diff --git "a/2522.jsonl" "b/2522.jsonl" new file mode 100644--- /dev/null +++ "b/2522.jsonl" @@ -0,0 +1,722 @@ +{"seq_id":"613162013","text":"\nfrom graphs.utils import random_graph_generator\nfrom itertools import combinations\nfrom copy import deepcopy\n\nnodes = random_graph_generator(7)\n\n\n# Algorithms\ndef min_kpartite(nodes, max_indep_set_size=None):\n graph = deepcopy(nodes)\n p_graphs = list(combinations(graph, len(nodes)))\n max_greedy = -1\n mis = None\n for i, graph in enumerate(p_graphs):\n graph_greedy, max_greedy_new = first_fit(graph)\n if max_indep_set_size:\n if max_greedy_new >= max_indep_set_size:\n mis = graph_greedy\n max_greedy = max_greedy_new\n break\n else:\n if max_greedy_new >= max_greedy:\n max_greedy = max_greedy_new\n mis = graph_greedy\n return mis, max_greedy\n\n\ndef first_fit(nodes):\n graph = deepcopy(nodes)\n available_color = len(graph) * [True]\n\n graph[0].color = 0\n for i, node in enumerate(graph[1:]):\n for ad in node.adjacent:\n if ad.color != -1:\n available_color[ad.color] = False\n ic = next(idx for idx, c in enumerate(available_color) if c == True)\n node.color = ic\n available_color = len(graph) * [True]\n colors = [n.color for n in graph]\n max_size = max([colors.count(i) for i in set(colors)])\n return graph, max_size\n\n\ndef show_result(nodes, max_size):\n print('Graph with #{} nodes has maximum independent set of size #{}\\n'.format(len(nodes), max_size))\n for n in nodes:\n print(\"ID=\", n.id, \", color=\", n.color)\n\n\nshow_result(*min_kpartite(nodes))\n","sub_path":"Tarjan_BF_Greedy_Kpartite/kpartite.py","file_name":"kpartite.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452757562","text":"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport wave\nimport sys\nimport argparse\nfrom collections import OrderedDict\nfrom scipy import signal\nfrom scipy.signal import find_peaks_cwt\nfrom tuner import BandPassFilter\n\n'''\n open 1st fret 2nd fret 3rd fret 4th fret\n6th string E F F♯/G♭ G G♯/A♭\n5th string\tA A♯/B♭\t B\t C\t C♯/D♭\n4th string\tD\t D♯/E♭\t E\t F\t F♯/G♭\n3rd string\tG\t G♯/A♭\t A\t A♯/B♭\t B\n2nd string\tB\t C\t C♯/D♭\t D\t D♯/E♭\n1st string\tE\t F\t F♯/G♭\t G\t G♯/A♭\n\nString\tFrequency\tScientific pitch notation\n1 (E)\t329.63 Hz\tE4\n2 (B)\t246.94 Hz\tB3\n3 (G)\t196.00 Hz\tG3\n4 (D)\t146.83 Hz\tD3\n5 (A)\t110.00 Hz\tA2\n6 (E)\t82.41 Hz\tE2\n'''\n\nnoteFreqs=OrderedDict(\n [\n ('E2', 82.41),\n ('F2', 87.31),\n ('F2S', 92.50),\n ('G2', 98.00),\n ('G2B', 103.83),\n ('A2', 110.00),\n ('A2S', 116.54),\n ('B2', 123.47),\n ('C3', 130.81),\n ('C3S', 138.59),\n ('D3', 146.83),\n ('D3S', 155.56),\n ('E3', 164.81),\n ('F3', 174.61),\n ('F3S', 185.00),\n ('G3', 196.00),\n ('G3S', 207.65),\n ('A3', 220.00),\n ('A3S', 233.88),\n ('B3', 246.94),\n ('C4', 261.63),\n ('C4S', 277.18),\n ('D4', 293.66),\n ('D4S', 311.13),\n ('E4', 329.63),\n ('F4', 349.23),\n ('F4S', 369.99),\n ('G4', 392.00)\n ]\n)\n\nnoteBins={\n 'E4':[],\n 'B3':[],\n 'G3':[],\n 'D3':[],\n 'A2':[],\n 'E2':[]\n}\n\nnoteHarmonics={\n 'E4':[],\n 'B3':[],\n 'G3':[],\n 'D3':[],\n 'A2':[],\n 'E2':[]\n}\n\ndef matchHarmonics(peaks):\n\n res = None\n if len(peaks) < 3:\n return res\n p = peaks[0:3]\n\n d_min = 99.\n note_min = 'E2'\n notes = noteFreqs.keys()\n for note in notes:\n d = np.linalg.norm(p - np.array(noteBins[note]))\n if d < d_min:\n d_min = d\n res = note\n\n if d_min < 2.0:\n return res\n else:\n return None\n\ndef getN(minFreq, maxFreq, bins, fs):\n\n Q= 1/(2**(1/bins)-1)\n numFreqs = np.ceil(bins*np.log2(maxFreq/minFreq))\n numFreqs = np.int(numFreqs)\n freqs = minFreq*2**(np.arange(0,numFreqs)/bins)\n N = np.zeros((numFreqs,),np.int)\n for k in np.arange(0,numFreqs):\n N[k] = np.round(Q*fs/(minFreq*2**(k/bins)))\n N[k] = np.int(N[k])\n\n return N,freqs\n\ndef getHarmonicBins( freq_in, minFreq, binsPerOctave, numBins):\n\n bins = []\n freq = freq_in\n while True:\n bin = np.int(binsPerOctave*np.log2(freq/minFreq))\n if bin >= numBins:\n break\n bins.append(bin)\n if len(bins) >= 3:\n break\n freq += freq_in\n return(bins)\n\ndef bins2freq(bins,minFreq,binsPerOctave):\n freqs = []\n for bin in bins:\n f = minFreq*2**(bin/binsPerOctave)\n freqs.append(f)\n return freqs\n\ndef slowQ(x, minFreq, maxFreq, bins, fs):\n Q= 1/(2**(1/bins)-1)\n\n numFreqs = np.ceil(bins*np.log2(maxFreq/minFreq))\n numFreqs = np.int(numFreqs)\n\n freqs = minFreq*2**(np.arange(0,numFreqs)/bins)\n\n cq = np.zeros(freqs.shape,freqs.dtype)\n for k in np.arange(0,numFreqs):\n N = np.round(Q*fs/(minFreq*2**(k/bins)))\n N = np.int(N)\n basis = np.exp( -2*np.pi*1j*Q*np.arange(0,N)/N)\n\n temp = np.zeros((N,),dtype=np.float)\n xLen = min(N,len(x))\n temp[0:xLen] = x[0:xLen]*np.hamming(xLen)\n cq[k]= abs(temp.dot( basis) / N)\n\n return cq,freqs\n\ndef find_peaks(x,width,thresh_dB,snr_dB):\n\n\n xMax = 20*np.log10(np.max(x));\n thresh = np.maximum(xMax-30,thresh_dB)\n\n thresh = 10**(thresh/20)\n snr = 10**(snr_dB/20)\n peaks=[]\n vals=[]\n for i in range(width,len(x)-width):\n if x[i] < thresh:\n continue\n if x[i] > x[i-1] and x[i] > x[i+1]:\n if x[i] > x[i-width] and x[i] > x[i+width]:\n if x[i] > snr*(x[i-width]+x[i+width])/2:\n peaks.append(i)\n vals.append(x[i])\n ind = np.argsort(vals)\n\n return peaks\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Test the Tuner Class')\n parser.add_argument('--note', help='guitar note, args.dbgtime and time < args.dbgtime + args.dbglen:\n plt.figure()\n plt.plot(20*np.log10(abs(cq)),'b*-')\n plt.show()\n\n sampleCount += blockSize/4\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"constq.py","file_name":"constq.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"377931287","text":"import time\nfrom calendar import month_name\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.forms import ModelForm\nfrom django.core.context_processors import csrf\nfrom life.models import Event, EventForm, Categories, CategoriesForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import RequestContext\n\ndef login(request):\n\tif request.method != 'POST':\n\t\traise HTTP404('Only POSTs are allowed')\n\ttry:\n\t\tm = Member.objects.get(username=request.POST['username'])\n\t\tif m.password == request.POST['password']:\n\t\t\trequest.session['member_id'] = m.id\n\t\t\treturn HttpResponseRedirect('/life/?logged_in=yes')\n\texcept Member.DoesNotExist:\n\t\treturn HttpResponse('Your username and password did not match.')\n\ndef logout(request):\n\tlogout(request)\n\treturn HttpResponseRedirect('/life/')\n\ndef lifeEvent(request):\n\ttitle = Event.objects.order_by('-timestamp')\n\n\treturn render_to_response('event.html', dict(title=title), context_instance=RequestContext(request))\n\n@login_required(login_url='/login/')\ndef add_event(request):\n\tif request.method == \"POST\":\n\t\t\tform = EventForm(request.POST, request.FILES)\n\t\t\tif form.is_valid():\n\t\t\t\tevent = Event.objects.create(\n\t\t\t\t\ttitle=form.cleaned_data['title'],\n\t\t\t\t\tcategory=form.cleaned_data['category'],\n\t\t\t\t\tlength=form.cleaned_data['length'],\n\t\t\t\t\tcounter=form.cleaned_data['counter'],\n\t\t\t\t\tcounterUnit=form.cleaned_data['counterUnit'],\n\t\t\t\t\turl=form.cleaned_data['url'],\n\t\t\t\t\tdescription=form.cleaned_data['description'],\n\t\t\t\t\timage=form.cleaned_data['image'],\n\t\t\t\t\ttimestamp=form.cleaned_data['timestamp'],\n\t\t\t\t\t)\n\t\t\t\treturn HttpResponseRedirect('/life/')\n\telse:\n\t\tform = EventForm()\n\n\td = dict(form=form)\n\td.update(csrf(request))\n\treturn render_to_response('add_event.html', d, context_instance=RequestContext(request))\n\n@login_required(login_url='/login/')\ndef add_category(request):\n\tif request.method == \"POST\":\n\t\t\tform = CategoriesForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tcategory = Categories.objects.create(\n\t\t\t\t\ttitle=form.cleaned_data['category'],\n\t\t\t\t\t)\n\t\t\t\treturn HttpResponseRedirect('/add/')\n\telse:\n\t\tform = CategoriesForm()\n\n\td = dict(form=form)\n\td.update(csrf(request))\n\treturn render_to_response('add_category.html', d, context_instance=RequestContext(request))","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"519598927","text":"\"\"\"\n import_mnist.py converts the dataset of handwritten characters into a numpy array of pixel data\n that we can actually work with in Python\n\"\"\"\n\nimport pickle\nimport gzip\nimport numpy as np\n\n\n\"\"\"\n Python module for importing the MNIST data set. It returns an iterator\n of 2-tuples with the first element being the label and the second element\n being a numpy.uint8 2D array of pixel data for the given image.\n\"\"\"\n\ndef read() :\n\n \"\"\"\n For those following along -- you will need to change the path to wherever you downloaded your MNIST data\n to.\n \"\"\"\n\n path = 'D:\\Programming\\Python\\DPUDS\\DPUDS_Projects\\Fall_2017\\MNIST\\mnist.pkl.gz'\n\n # There are two different datasets: one for training, and one for testing\n # The validation set isn't important for the first version of the network -- we'll use it later\n f = gzip.open(path, 'rb')\n training_data, validation_data, test_data = pickle.load(f, encoding='latin1')\n f.close()\n return (training_data, validation_data, test_data)\n\n\"\"\"\n Return a tuple containing (training_data, validation_data,\n test_data)\n\n training_data is a list containing 50,000\n 2-tuples (x, y). x is a 784-dimensional numpy.ndarray\n containing the input image. y is a 10-dimensional\n numpy.ndarray representing the unit vector corresponding to the\n correct digit for x.\n\n validation_data and test_data are lists containing 10,000\n 2-tuples (x, y). In each case, x is a 784-dimensional\n numpy.ndarry containing the input image, and y is the\n corresponding classification, i.e., the digit values (integers)\n corresponding to x.\n\n Obviously, this means we're using slightly different formats for\n the training data and the validation / test data. These formats\n turn out to be the most convenient for use in our neural network\n code.\n\"\"\"\ndef load_data_wrapper() :\n\n tr_d, va_d, te_d = read()\n training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n training_results = [vectorized_result(y) for y in tr_d[1]]\n training_data = zip(training_inputs, training_results)\n validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n validation_data = zip(validation_inputs, va_d[1])\n test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n test_data = zip(test_inputs, te_d[1])\n return (training_data, validation_data, test_data)\n\n\"\"\"\n Return a 10-dimensional unit vector with a 1.0 in the jth\n position and zeroes elsewhere. This is used to convert a digit\n (0...9) into a corresponding desired output from the neural\n network.\n\"\"\"\ndef vectorized_result(j):\n\n e = np.zeros((10, 1))\n e[j] = 1.0\n return e\n\n","sub_path":"Fall_2017/MNIST/import_mnist.py","file_name":"import_mnist.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"36456550","text":"#Goal: Calculate the specified power of a specified base\n#Method: Exponentiation by squaring \n\ndef power_function (base, power):\n #Case 1: Power is a negative number\n if (power<0):\n base = 1/base\n power = -power\n\n #Case 2: Power is equal to 0\n if (power==0):\n return 1\n \n #Case 3: Power is equal to 1\n if (power==1):\n return base\n \n #Case 4: Power is a positive number greater than 1\n result=1\n while(power>1):\n if(power%2==0):\n base=(base*base)\n power=power/2\n else: \n result=base*result\n base=base*base\n power=(power-1)/2\n \n return base*result","sub_path":"Functions/Power_Function.py","file_name":"Power_Function.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"197773480","text":"import cv2\nimport os\nimport argparse\nimport glob\nfrom torch.autograd import Variable\nfrom utils import *\nfrom model.net import SMNet\n\n# python test_rgb.py -c 40 --mode S --test_noiseL 15 --test_data McMaster\nparser = argparse.ArgumentParser(description=\"SMNet_rgb Test\")\nparser.add_argument(\"--checkpoint\", \"-c\", type=int, default=\"40\", help='checkpoint of model')\nparser.add_argument(\"--test_data\", type=str, default='McMaster', choices=[\"McMaster\", \"CBSD68\", \"Kodak24\"], help='test on McMaster,CBSD68 or Kodak24')\nparser.add_argument(\"--test_noiseL\", type=float, default=15, help='noise level used on test set')\nparser.add_argument(\"--mode\", type=str, default=\"S\", choices=['S', 'B'], help='with known noise level (S) or blind training (B)')\nopt = parser.parse_args()\n\ndef normalize(data):\n return data/255.\n\ndef main():\n # Build model\n print('Loading model ...\\n')\n net = SMNet(in_channels=3)\n model = torch.nn.DataParallel(net, device_ids=[0]).cuda()\n if opt.mode == 'S':\n model.load_state_dict(torch.load(os.path.join(\"weights\",\"model_rgb_L%d_%d.pth\" %(opt.test_noiseL, opt.checkpoint))))\n else:\n model.load_state_dict(torch.load(os.path.join(\"weights\", \"model_rgb_B_%d.pth\" % (opt.checkpoint))))\n model.eval()\n\n # load data info\n print('Loading data info ...\\n')\n files_source = glob.glob(os.path.join('data', opt.test_data, '*'))\n files_source.sort()\n\n # process data\n psnr_test = 0\n for f in files_source:\n # image\n Img = cv2.imread(f)\n Img = cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)\n Img = torch.tensor(Img)\n\n Img = Img.permute(2,0,1)\n Img = Img.numpy()\n Img = np.tile(Img,(3,1,1,1)) #expand the dimensional\n Img = np.float32(normalize(Img))\n ISource = torch.Tensor(Img)\n\n # noise\n torch.manual_seed(12) \n noise = torch.FloatTensor(ISource.size()).normal_(mean=0, std=opt.test_noiseL/255.)\n # noisy image\n INoisy = ISource + noise\n ISource = Variable(ISource)\n INoisy = Variable(INoisy)\n ISource= ISource.cuda() \n INoisy = INoisy.cuda() \n with torch.no_grad(): # this can save much memory\n Out = torch.clamp(model(INoisy), 0., 1.)\n psnr = batch_PSNR(Out, ISource, 1.)\n psnr_test += psnr\n print(\"%s PSNR %f\" % (f, psnr))\n psnr_test /= len(files_source)\n print(\"\\nPSNR on test data %f\" % psnr_test)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test_rgb.py","file_name":"test_rgb.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"223059564","text":"# Copyright (c) 2016-2017 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nimport os\nimport logging\nimport collections\nimport time\n\nfrom collections import OrderedDict\n\nfrom yardstick import ssh\nfrom yardstick.network_services.utils import get_nsb_option\nfrom yardstick.network_services.utils import provision_tool\nfrom yardstick.benchmark.contexts.base import Context\nfrom yardstick.benchmark.contexts.standalone.model import Libvirt\nfrom yardstick.benchmark.contexts.standalone.model import StandaloneContextHelper\nfrom yardstick.benchmark.contexts.standalone.model import Server\nfrom yardstick.benchmark.contexts.standalone.model import OvsDeploy\nfrom yardstick.network_services.utils import PciAddress\n\nLOG = logging.getLogger(__name__)\n\n\nclass OvsDpdkContext(Context):\n \"\"\" This class handles OVS standalone nodes - VM running on Non-Managed NFVi\n Configuration: ovs_dpdk\n \"\"\"\n\n __context_type__ = \"StandaloneOvsDpdk\"\n\n SUPPORTED_OVS_TO_DPDK_MAP = {\n '2.6.0': '16.07.1',\n '2.6.1': '16.07.2',\n '2.7.0': '16.11.1',\n '2.7.1': '16.11.2',\n '2.7.2': '16.11.3',\n '2.8.0': '17.05.2'\n }\n\n DEFAULT_OVS = '2.6.0'\n\n PKILL_TEMPLATE = \"pkill %s %s\"\n\n def __init__(self):\n self.file_path = None\n self.sriov = []\n self.first_run = True\n self.dpdk_nic_bind = \"\"\n self.vm_names = []\n self.name = None\n self.nfvi_host = []\n self.nodes = []\n self.networks = {}\n self.attrs = {}\n self.vm_flavor = None\n self.servers = None\n self.helper = StandaloneContextHelper()\n self.vnf_node = Server()\n self.ovs_properties = {}\n self.wait_for_vswitchd = 10\n super(OvsDpdkContext, self).__init__()\n\n def init(self, attrs):\n \"\"\"initializes itself from the supplied arguments\"\"\"\n\n self.name = attrs[\"name\"]\n self.file_path = attrs.get(\"file\", \"pod.yaml\")\n\n self.nodes, self.nfvi_host, self.host_mgmt = \\\n self.helper.parse_pod_file(self.file_path, 'OvsDpdk')\n\n self.attrs = attrs\n self.vm_flavor = attrs.get('flavor', {})\n self.servers = attrs.get('servers', {})\n self.vm_deploy = attrs.get(\"vm_deploy\", True)\n self.ovs_properties = attrs.get('ovs_properties', {})\n # add optional static network definition\n self.networks = attrs.get(\"networks\", {})\n\n LOG.debug(\"Nodes: %r\", self.nodes)\n LOG.debug(\"NFVi Node: %r\", self.nfvi_host)\n LOG.debug(\"Networks: %r\", self.networks)\n\n def setup_ovs(self):\n vpath = self.ovs_properties.get(\"vpath\", \"/usr/local\")\n xargs_kill_cmd = self.PKILL_TEMPLATE % ('-9', 'ovs')\n\n create_from = os.path.join(vpath, 'etc/openvswitch/conf.db')\n create_to = os.path.join(vpath, 'share/openvswitch/vswitch.ovsschema')\n\n cmd_list = [\n \"chmod 0666 /dev/vfio/*\",\n \"chmod a+x /dev/vfio\",\n \"pkill -9 ovs\",\n xargs_kill_cmd,\n \"killall -r 'ovs*'\",\n \"mkdir -p {0}/etc/openvswitch\".format(vpath),\n \"mkdir -p {0}/var/run/openvswitch\".format(vpath),\n \"rm {0}/etc/openvswitch/conf.db\".format(vpath),\n \"ovsdb-tool create {0} {1}\".format(create_from, create_to),\n \"modprobe vfio-pci\",\n \"chmod a+x /dev/vfio\",\n \"chmod 0666 /dev/vfio/*\",\n ]\n for cmd in cmd_list:\n self.connection.execute(cmd)\n bind_cmd = \"{dpdk_nic_bind} --force -b {driver} {port}\"\n phy_driver = \"vfio-pci\"\n for key, port in self.networks.items():\n vpci = port.get(\"phy_port\")\n self.connection.execute(bind_cmd.format(dpdk_nic_bind=self.dpdk_nic_bind,\n driver=phy_driver, port=vpci))\n\n def start_ovs_serverswitch(self):\n vpath = self.ovs_properties.get(\"vpath\")\n pmd_nums = int(self.ovs_properties.get(\"pmd_threads\", 2))\n ovs_sock_path = '/var/run/openvswitch/db.sock'\n log_path = '/var/log/openvswitch/ovs-vswitchd.log'\n\n pmd_mask = hex(sum(2 ** num for num in range(pmd_nums)) << 1)\n socket0 = self.ovs_properties.get(\"ram\", {}).get(\"socket_0\", \"2048\")\n socket1 = self.ovs_properties.get(\"ram\", {}).get(\"socket_1\", \"2048\")\n\n ovs_other_config = \"ovs-vsctl {0}set Open_vSwitch . other_config:{1}\"\n detach_cmd = \"ovs-vswitchd unix:{0}{1} --pidfile --detach --log-file={2}\"\n\n cmd_list = [\n \"mkdir -p /usr/local/var/run/openvswitch\",\n \"ovsdb-server --remote=punix:/{0}/{1} --pidfile --detach\".format(vpath,\n ovs_sock_path),\n ovs_other_config.format(\"--no-wait \", \"dpdk-init=true\"),\n ovs_other_config.format(\"--no-wait \", \"dpdk-socket-mem='%s,%s'\" % (socket0, socket1)),\n detach_cmd.format(vpath, ovs_sock_path, log_path),\n ovs_other_config.format(\"\", \"pmd-cpu-mask=%s\" % pmd_mask),\n ]\n\n for cmd in cmd_list:\n LOG.info(cmd)\n self.connection.execute(cmd)\n time.sleep(self.wait_for_vswitchd)\n\n def setup_ovs_bridge_add_flows(self):\n dpdk_args = \"\"\n dpdk_list = []\n vpath = self.ovs_properties.get(\"vpath\", \"/usr/local\")\n version = self.ovs_properties.get('version', {})\n ovs_ver = [int(x) for x in version.get('ovs', self.DEFAULT_OVS).split('.')]\n ovs_add_port = \\\n \"ovs-vsctl add-port {br} {port} -- set Interface {port} type={type_}{dpdk_args}\"\n ovs_add_queue = \"ovs-vsctl set Interface {port} options:n_rxq={queue}\"\n chmod_vpath = \"chmod 0777 {0}/var/run/openvswitch/dpdkvhostuser*\"\n\n cmd_dpdk_list = [\n \"ovs-vsctl del-br br0\",\n \"rm -rf /usr/local/var/run/openvswitch/dpdkvhostuser*\",\n \"ovs-vsctl add-br br0 -- set bridge br0 datapath_type=netdev\",\n ]\n\n ordered_network = OrderedDict(self.networks)\n for index, (key, vnf) in enumerate(ordered_network.items()):\n if ovs_ver >= [2, 7, 0]:\n dpdk_args = \" options:dpdk-devargs=%s\" % vnf.get(\"phy_port\")\n dpdk_list.append(ovs_add_port.format(br='br0', port='dpdk%s' % vnf.get(\"port_num\", 0),\n type_='dpdk', dpdk_args=dpdk_args))\n dpdk_list.append(ovs_add_queue.format(port='dpdk%s' % vnf.get(\"port_num\", 0),\n queue=self.ovs_properties.get(\"queues\", 4)))\n\n # Sorting the array to make sure we execute dpdk0... in the order\n list.sort(dpdk_list)\n cmd_dpdk_list.extend(dpdk_list)\n\n # Need to do two for loop to maintain the dpdk/vhost ports.\n for index, _ in enumerate(ordered_network):\n cmd_dpdk_list.append(ovs_add_port.format(br='br0', port='dpdkvhostuser%s' % index,\n type_='dpdkvhostuser', dpdk_args=\"\"))\n\n for cmd in cmd_dpdk_list:\n LOG.info(cmd)\n self.connection.execute(cmd)\n\n # Fixme: add flows code\n ovs_flow = \"ovs-ofctl add-flow br0 in_port=%s,action=output:%s\"\n\n network_count = len(ordered_network) + 1\n for in_port, out_port in zip(range(1, network_count),\n range(network_count, network_count * 2)):\n self.connection.execute(ovs_flow % (in_port, out_port))\n self.connection.execute(ovs_flow % (out_port, in_port))\n\n self.connection.execute(chmod_vpath.format(vpath))\n\n def cleanup_ovs_dpdk_env(self):\n self.connection.execute(\"ovs-vsctl del-br br0\")\n self.connection.execute(\"pkill -9 ovs\")\n\n def check_ovs_dpdk_env(self):\n self.cleanup_ovs_dpdk_env()\n\n version = self.ovs_properties.get(\"version\", {})\n ovs_ver = version.get(\"ovs\", self.DEFAULT_OVS)\n dpdk_ver = version.get(\"dpdk\", \"16.07.2\").split('.')\n\n supported_version = self.SUPPORTED_OVS_TO_DPDK_MAP.get(ovs_ver, None)\n if supported_version is None or supported_version.split('.')[:2] != dpdk_ver[:2]:\n raise Exception(\"Unsupported ovs '{}'. Please check the config...\".format(ovs_ver))\n\n status = self.connection.execute(\"ovs-vsctl -V | grep -i '%s'\" % ovs_ver)[0]\n if status:\n deploy = OvsDeploy(self.connection,\n get_nsb_option(\"bin_path\"),\n self.ovs_properties)\n deploy.ovs_deploy()\n\n def deploy(self):\n \"\"\"don't need to deploy\"\"\"\n\n # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.\n if not self.vm_deploy:\n return\n\n self.connection = ssh.SSH.from_node(self.host_mgmt)\n self.dpdk_nic_bind = provision_tool(\n self.connection,\n os.path.join(get_nsb_option(\"bin_path\"), \"dpdk-devbind.py\"))\n\n # Check dpdk/ovs version, if not present install\n self.check_ovs_dpdk_env()\n # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.\n StandaloneContextHelper.install_req_libs(self.connection)\n self.networks = StandaloneContextHelper.get_nic_details(self.connection,\n self.networks,\n self.dpdk_nic_bind)\n\n self.setup_ovs()\n self.start_ovs_serverswitch()\n self.setup_ovs_bridge_add_flows()\n self.nodes = self.setup_ovs_dpdk_context()\n LOG.debug(\"Waiting for VM to come up...\")\n self.nodes = StandaloneContextHelper.wait_for_vnfs_to_start(self.connection,\n self.servers,\n self.nodes)\n\n def undeploy(self):\n\n if not self.vm_deploy:\n return\n\n # Cleanup the ovs installation...\n self.cleanup_ovs_dpdk_env()\n\n # Bind nics back to kernel\n bind_cmd = \"{dpdk_nic_bind} --force -b {driver} {port}\"\n for key, port in self.networks.items():\n vpci = port.get(\"phy_port\")\n phy_driver = port.get(\"driver\")\n self.connection.execute(bind_cmd.format(dpdk_nic_bind=self.dpdk_nic_bind,\n driver=phy_driver, port=vpci))\n\n # Todo: NFVi undeploy (sriov, vswitch, ovs etc) based on the config.\n for vm in self.vm_names:\n Libvirt.check_if_vm_exists_and_delete(vm, self.connection)\n\n def _get_server(self, attr_name):\n \"\"\"lookup server info by name from context\n\n Keyword arguments:\n attr_name -- A name for a server listed in nodes config file\n \"\"\"\n node_name, name = self.split_name(attr_name)\n if name is None or self.name != name:\n return None\n\n matching_nodes = (n for n in self.nodes if n[\"name\"] == node_name)\n try:\n # A clone is created in order to avoid affecting the\n # original one.\n node = dict(next(matching_nodes))\n except StopIteration:\n return None\n\n try:\n duplicate = next(matching_nodes)\n except StopIteration:\n pass\n else:\n raise ValueError(\"Duplicate nodes!!! Nodes: %s %s\",\n (node, duplicate))\n\n node[\"name\"] = attr_name\n return node\n\n def _get_network(self, attr_name):\n if not isinstance(attr_name, collections.Mapping):\n network = self.networks.get(attr_name)\n\n else:\n # Don't generalize too much Just support vld_id\n vld_id = attr_name.get('vld_id', {})\n # for standalone context networks are dicts\n iter1 = (n for n in self.networks.values() if n.get('vld_id') == vld_id)\n network = next(iter1, None)\n\n if network is None:\n return None\n\n result = {\n # name is required\n \"name\": network[\"name\"],\n \"vld_id\": network.get(\"vld_id\"),\n \"segmentation_id\": network.get(\"segmentation_id\"),\n \"network_type\": network.get(\"network_type\"),\n \"physical_network\": network.get(\"physical_network\"),\n }\n return result\n\n def configure_nics_for_ovs_dpdk(self):\n portlist = OrderedDict(self.networks)\n for key, ports in portlist.items():\n mac = StandaloneContextHelper.get_mac_address()\n portlist[key].update({'mac': mac})\n self.networks = portlist\n LOG.info(\"Ports %s\" % self.networks)\n\n def _enable_interfaces(self, index, vfs, cfg):\n vpath = self.ovs_properties.get(\"vpath\", \"/usr/local\")\n vf = self.networks[vfs[0]]\n port_num = vf.get('port_num', 0)\n vpci = PciAddress.parse_address(vf['vpci'].strip(), multi_line=True)\n # Generate the vpci for the interfaces\n slot = index + port_num + 10\n vf['vpci'] = \\\n \"{}:{}:{:02x}.{}\".format(vpci.domain, vpci.bus, slot, vpci.function)\n Libvirt.add_ovs_interface(vpath, port_num, vf['vpci'], vf['mac'], str(cfg))\n\n def setup_ovs_dpdk_context(self):\n nodes = []\n\n self.configure_nics_for_ovs_dpdk()\n\n for index, (key, vnf) in enumerate(OrderedDict(self.servers).items()):\n cfg = '/tmp/vm_ovs_%d.xml' % index\n vm_name = \"vm_%d\" % index\n\n # 1. Check and delete VM if already exists\n Libvirt.check_if_vm_exists_and_delete(vm_name, self.connection)\n\n vcpu, mac = Libvirt.build_vm_xml(self.connection, self.vm_flavor, cfg, vm_name, index)\n # 2: Cleanup already available VMs\n for idx, (vkey, vfs) in enumerate(OrderedDict(vnf[\"network_ports\"]).items()):\n if vkey == \"mgmt\":\n continue\n self._enable_interfaces(index, vfs, cfg)\n\n # copy xml to target...\n self.connection.put(cfg, cfg)\n\n # FIXME: launch through libvirt\n LOG.info(\"virsh create ...\")\n Libvirt.virsh_create_vm(self.connection, cfg)\n\n # 5: Tunning for better performace\n Libvirt.pin_vcpu_for_perf(self.connection, vm_name, vcpu)\n self.vm_names.append(vm_name)\n\n # build vnf node details\n nodes.append(self.vnf_node.generate_vnf_instance(self.vm_flavor,\n self.networks,\n self.host_mgmt.get('ip'),\n key, vnf, mac))\n\n return nodes\n","sub_path":"TaskManagement/yardstick/benchmark/contexts/standalone/ovs_dpdk.py","file_name":"ovs_dpdk.py","file_ext":"py","file_size_in_byte":15307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316936354","text":"import random\r\n\r\nfrom mcpi.minecraft import Minecraft\r\n\r\nmc = Minecraft.create()\r\nWe = [\r\n \"Tom\",\r\n \"Colin\",\r\n \"HW\",\r\n \"Mamahaha\",\r\n \"Lzm\",\r\n \"Cat\",\r\n \"Dog\",\r\n \"Alice\",\r\n \"Kizuna AI\",\r\n \"Apple\",\r\n \"God\",\r\n]\r\n\r\n\r\nclass House:\r\n def __init__(self, name, length, width, height, pos):\r\n self.name = name\r\n self.length = length\r\n self.width = width\r\n self.height = height\r\n self.pos = pos\r\n self.once = True\r\n self.build()\r\n\r\n def build(self):\r\n mc.postToChat(\"Created %s's house located at: (%s, %s, %s).\" % (self.name, self.pos.x, self.pos.y, self.pos.z))\r\n self.__buildWall__()\r\n self.__buildFloor__()\r\n self.__buildRoof__()\r\n self.__buildDoor__()\r\n self.__buildWindow__()\r\n\r\n def __buildWall__(self):\r\n for i in range(1, self.height):\r\n for j in range(self.length - 1):\r\n mc.setBlock(self.pos.x + j, self.pos.y + i, self.pos.z, 5)\r\n for j in range(self.width - 1):\r\n mc.setBlock(\r\n self.pos.x + self.length - 1, self.pos.y + i, self.pos.z + j, 5)\r\n for j in range(self.length - 1):\r\n mc.setBlock(\r\n self.pos.x + self.length - j - 1,\r\n self.pos.y + i,\r\n self.pos.z + self.width - 1,\r\n 5,\r\n )\r\n for j in range(self.width - 1):\r\n mc.setBlock(\r\n self.pos.x, self.pos.y + i, self.pos.z + self.width - j - 1, 5\r\n )\r\n\r\n def __buildFloor__(self):\r\n for i in range(self.length): # floor\r\n for j in range(self.width):\r\n mc.setBlock(self.pos.x + i, self.pos.y, self.pos.z + j, 100)\r\n\r\n def __buildRoof__(self):\r\n for i in range(self.length):\r\n for j in range(self.width):\r\n mc.setBlock(\r\n self.pos.x + i, self.pos.y + self.height - 1, self.pos.z + j, 5\r\n )\r\n\r\n def __buildDoor__(self):\r\n for i in range(2):\r\n for j in range(3):\r\n mc.setBlock(\r\n self.pos.x + self.length / 2 + i, self.pos.y + 1 + j, self.pos.z, 0\r\n )\r\n\r\n def __buildWindow__(self):\r\n for i in range(2):\r\n for j in range(2):\r\n mc.setBlock(\r\n self.pos.x + self.length / 2 + i,\r\n self.pos.y + self.height / 2 + j,\r\n self.pos.z,\r\n 101,\r\n )\r\n\r\n def IsInHome(self, pos):\r\n if not self.pos.x < pos.x < self.pos.x + self.length - 1:\r\n return False\r\n if not self.pos.y < pos.y < self.pos.y + self.height - 1:\r\n return False\r\n if not self.pos.z < pos.z < self.pos.z + self.width - 1:\r\n return False\r\n return True\r\n\r\n\r\nHouses = []\r\nfor name in We:\r\n pos = mc.player.getTilePos()\r\n length = random.randint(10, 15)\r\n width = random.randint(5, 10)\r\n height = random.randint(15, 20)\r\n house = House(name, length, width, height, pos)\r\n Houses.append(house)\r\n mc.player.setTilePos(pos.x + 2 * length, pos.y, pos.z + 2 * width)\r\n\r\nwhile True:\r\n pos = mc.player.getTilePos()\r\n for house in Houses:\r\n if house.IsInHome(pos) and house.once:\r\n mc.postToChat(\"Welcome to %s's house!\" % house.name)\r\n house.once = False\r\n break\r\n elif not house.IsInHome(pos):\r\n house.once = True\r\n","sub_path":"circle/MCBuildHouse/setBlock.py","file_name":"setBlock.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"67411487","text":"# This is a sample Python script.\nimport csv\n\ncars_list = [{\"id\":1, \"Brand\":\"Hyundai\", \"Model\":\"Santa_Fe\", \"hp\":189, \"price\":30000},\n {\"id\":2, \"Brand\":\"Kia\", \"Model\":\"Sorento\", \"hp\":140, \"price\":20000}]\n\nkeys = cars_list[0].keys()\n\ncar_file = open(\"/home/hastatus/git_environment/car_file.csv\", \"w\")\ncar_writer = csv.DictWriter(car_file, keys)\ncar_writer.writeheader()\ncar_writer.writerows(cars_list)\ncar_file.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"430650792","text":"# patternC.py\n# January 12th, 2013\n#\n# Mischa Lewis-Norelle\n\ndef main():\n endNum = eval(input(\"What level of the pattern would you like me to show you? \"))\n for i in range(1, endNum + 1):\n for j in range(i, endNum + 1):\n print(j, \" \", end='', sep='')\n print()\n\nmain()","sub_path":"lab02/mlewisno/patternC.py","file_name":"patternC.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567991134","text":"import scipy as sp\r\nfrom metrics import metrics\r\nfrom batcher import batcher\r\nfrom parser import parser\r\n\r\nclass kernel:\r\n\r\n def __init__(self, file_name, camp_dist): #maybe folder name instead of file_name\r\n self.camp_dist_array = camp_dist\r\n self.parser = parser('../data/xlsx/start.xlsx', '../data/csv/out.csv')\r\n self.pars()\r\n self.data = sp.genfromtxt(file_name, delimiter=',', dtype='|S10')\r\n self.metrics = metrics()\r\n self.batcher = batcher(self.data)\r\n self.tth = self.batcher.tth_create()\r\n\r\n def pars(self):\r\n self.parser.load_translit()\r\n self.parser.expand()\r\n self.parser.split()\r\n\r\n def comput_first(self):\r\n self.dist = self.metrics.first_metrics(self.camp_dist_array, self.tth)\r\n return self.dist\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n camp_dist = sp.genfromtxt('../data/camp_dist.tsv', delimiter= '\\t')\r\n krn = kernel('../data/data.tsv', camp_dist)\r\n krn.comput_first()\r\n print(krn.batcher.name_list)\r\n print(krn.metrics.distance)\r\n","sub_path":"scripts/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"232952025","text":"from selenium import webdriver\nfrom datetime import date, timedelta\nimport re\nimport time\n\ndriver = webdriver.Chrome(\"/Users/kupriyandrey/PROJECTS/smart_card/Selenium_Python/chromedriver\")\ndriver.set_page_load_timeout(10000000)\n\ndriver.get(\"https://ua.sinoptik.ua\")\ndriver.set_page_load_timeout(100000)\n\n## Search city\ndriver.find_element_by_id(\"search_city\").send_keys(\"Дніпро\")\ndriver.set_page_load_timeout(100000)\ndriver.find_element_by_class_name(\"search_city-submit\").click()\ndriver.set_page_load_timeout(100000)\n\n## get today's sinoptik date\ndate_class = driver.find_element_by_xpath('//*[@id=\"bd1\"]/p[1]')\ndriver.set_page_load_timeout(100000)\ndate_url = driver.find_element_by_xpath('//*[@id=\"bd1\"]/p[1]').get_attribute(\"data-link\")\ndriver.set_page_load_timeout(100000)\nprint(\"Dnipro, This is a date url\", date_url)\n\n## function that separate date from the link\ndef extract_today_date(url):\n return re.findall(r'/(\\d{4})-(\\d{1,2})-(\\d{1,2})', url)\n\nurl1 = date_url\ntuple_date = extract_today_date(url1)\ncurrent_sinoptik_date = '-'.join(tuple_date[0])\nprint(\"Current sinoptik date:\", current_sinoptik_date)\n\n## Get current calendar date\n\ncurrent_calendar_date = date.today()\nprint(\"Current calendar date:\", current_calendar_date)\ncurrent_calendar_date_str = current_calendar_date.strftime(\"%F\")\n\n## Compare date from sinoptik and current dates and add 4 days\nif current_sinoptik_date == current_calendar_date_str:\n new_date = current_calendar_date + timedelta(days=4)\n new_date_str = new_date.strftime(\"%F\")\n print(new_date_str)\nelse:\n print(\"Error\")\n quit()\n\n\n## concat new day to the end of the link\nfuture_day_link_concat = \"//ua.sinoptik.ua/погода-дніпро/{}\".format(new_date_str)\nprint(\"This is a future day link concat:\", future_day_link_concat)\n## find tab with future date\nfuture_day_class = driver.find_element_by_xpath('//*[@id=\"bd5\"]/p[1]/a')\ndriver.set_page_load_timeout(1000000)\nfuture_day_link = future_day_class.get_attribute(\"data-link\")\ndriver.set_page_load_timeout(1000000)\nprint(\"This is a future day link:\", future_day_link)\n\n## check that future day link from tab == link generated by timedelta(days=4) and click on tab:\nif future_day_link_concat == future_day_link:\n tabs = driver.find_element_by_id('bd5').click()\n driver.set_page_load_timeout(100000)\n print(\"Link is the same\")\nelse:\n print(\"link is not the same\")\n\nlist_day_temp = []\n\ndriver.set_page_load_timeout(1000000)\nday_parts_temp = driver.find_elements_by_xpath('//*[@id=\"bd5c\"]//table/tbody/tr[3]/td')\ndriver.set_page_load_timeout(1000000)\n\nday_parts = driver.find_elements_by_xpath('//*[@id=\"bd5c\"]/div[1]/div[2]/table/thead/tr/td')\ni = 0\nfor element in day_parts_temp:\n list_day_temp.append('{}: {}'.format(day_parts[i].text, element.text))\n i += 1\n\nprint(\"list day temp:\", list_day_temp)\nfinal_string = ' \\n'.join(list_day_temp)\nprint(\"final string:\", final_string)\nsinoptik_txt = '/Users/kupriyandrey/PROJECTS/smart_card/Selenium_Python/sinoptik.txt'\nwith open(sinoptik_txt, 'w') as infile:\n date_weather = ' \\n'.join([new_date_str, final_string])\n infile.write(date_weather)\nprint('Weather in Dnipro was written to a file: {}'.format(sinoptik_txt))\ntime.sleep(2)\ndriver.close()\n\n","sub_path":"scripts/sinoptik.py","file_name":"sinoptik.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"535421096","text":"\n# A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].\n# By this logic, we say a sequence of brackets is balanced if the following conditions are met:\n\n# It contains no unmatched brackets.\n# The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets.\n# Given N strings of brackets, determine whether each sequence of brackets is balanced.\n# If a string is balanced, return YES. Otherwise, return NO.\n\n\nclass MyStackImpl():\n\tdef __init__(self):\n\t\tself.stack = []\n\t\tself.top = -1\n\t## END\n\n\tdef push(self, ch):\n\t\tself.top += 1\n\t\tself.stack.append(ch)\n\t## END\n\n\tdef pop(self):\n\t\tif(self.top == -1):\n\t\t\treturn None\n\t\t## END\n\t\tvalue = self.stack[self.top]\n\t\tdel self.stack[self.top]\n\t\tself.top -= 1\n\t\treturn value\n\t## END\n\n\tdef peek(self):\n\t\treturn self.stack[self.top]\n\t## END\n\n\tdef removeTheTop(self):\n\t\tdel self.stack[self.top]\n\t\tself.top -= 1\n\t## END\n\n\tdef isEmpty(self):\n\t\treturn self.top == -1\n\t## END\n\n\tdef getSize(self):\n\t\treturn (self.top + 1)\n\t## END\n## END\n\n\ndef isBalanced(string):\n\tif(len(string)%2 != 0):\n\t\treturn 'NO'\n\t## END\n\n\tstack = MyStackImpl()\n\n\tfor ch in string:\n\t\tif(ch == '[' or ch == '{' or ch == '('):\n\t\t\tstack.push(ch)\n\t\telse:\n\t\t\tif(stack.getSize() > 0):\n\t\t\t\tif(ch == ')'):\n\t\t\t\t\tif(stack.peek() != '('):\n\t\t\t\t\t\treturn 'NO'\n\t\t\t\t\telse:\n\t\t\t\t\t\tstack.removeTheTop()\n\t\t\t\t\t## END\n\t\t\t\t## END\n\t\t\t\tif(ch == '}'):\n\t\t\t\t\tif(stack.peek() != '{'):\n\t\t\t\t\t\treturn 'NO'\n\t\t\t\t\telse:\n\t\t\t\t\t\tstack.removeTheTop()\n\t\t\t\t\t## END\n\t\t\t\t## END\n\t\t\t\tif(ch == ']'):\n\t\t\t\t\tif(stack.peek() != '['):\n\t\t\t\t\t\treturn 'NO'\n\t\t\t\t\telse:\n\t\t\t\t\t\tstack.removeTheTop()\n\t\t\t\t\t## END\n\t\t\t\t## END\n\t\t\t## END\n\t\t## END\n\t## END\n\tif(stack.isEmpty()):\n\t\treturn 'YES'\n\telse:\n\t\treturn 'NO'\n\t## END\n## END\n\n\nif __name__ == '__main__':\n\n\t# test_cases = int(input())\n\ttest_cases = 1\n\tfor _ in range(test_cases):\n\t\t# string = input()\n\t\t# string = '{[()]}'\n\t\tstring = '{[(])}'\n\t\tresult = isBalanced(string)\n\t\tprint(result)\n\t## END\n## END\n\n","sub_path":"miscellaneous/BalancedBrackets.py","file_name":"BalancedBrackets.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451737474","text":"import argparse\n\nimport math\n\nimport torchtext\nfrom torchtext.vocab import Vectors, GloVe\n\nimport torch\nfrom torch.autograd import Variable as V\nfrom torch.nn.parameter import Parameter\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom torch.nn.utils import clip_grad_norm\n\nfrom tqdm import tqdm\n\nfrom IPython import embed\nimport numpy as np\n\nNBWEIGHT = 1\ntorch.manual_seed(1111)\n#torch.cuda.manual_seed_all(1111)\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-model\", choices=['NB', 'NB2', \"LR\", \"LR2\", \"CBoW\", \"CNN\", \"CNNLOL\", \"CNNLSTM\", \"LSTM\"])\n parser.add_argument(\"-gpu\", type=int, default=-1)\n parser.add_argument(\"-lr\", type=float, default=1)\n parser.add_argument(\"-lrd\", type=float, default=0.9)\n parser.add_argument(\"-epochs\", type=int, default=10)\n parser.add_argument(\"-dropout\", type=float, default=0.5)\n parser.add_argument(\"-bsz\", type=int, default=32)\n parser.add_argument(\"-mom\", type=float, default=0.9)\n parser.add_argument(\"-dm\", type=float, default=0)\n parser.add_argument(\"-wd\", type=float, default=1e-4)\n parser.add_argument(\"-nonag\", action=\"store_true\", default=False)\n parser.add_argument(\"-binarize_nb\", action=\"store_true\")\n\n parser.add_argument(\"-clip\", type=float, default=0.1)\n parser.add_argument(\"-optim\", type=str, required=False, default=\"SGD\")\n parser.add_argument(\"-output_file\", type=str, default=\"ensemble.out\")\n parser.add_argument(\"-model_dir\", type=str, required=False, default=\"model/\")\n parser.add_argument(\"-model_name\", type=str, required=False, default=\"tmp\")\n parser.add_argument(\"-load_model\", type=bool, required=False, default=False)\n args = parser.parse_args()\n return args\n\nargs = parse_args()\n\n\n\n# Our input $x$\nTEXT = torchtext.data.Field()\n\n# Our labels $y$\nLABEL = torchtext.data.Field(sequential=False)\ntrain, valid, test = torchtext.datasets.SST.splits(\n TEXT, LABEL,\n filter_pred=lambda ex: ex.label != 'neutral')\n\nprint('len(train)', len(train))\nprint('vars(train[0])', vars(train[0]))\n\nTEXT.build_vocab(train)\nLABEL.build_vocab(train)\nLABEL.vocab.itos = ['positive', 'negative']\nLABEL.vocab.stoi['positive'] = 0\nLABEL.vocab.stoi['negative'] = 1\n\nprint('len(TEXT.vocab)', len(TEXT.vocab))\nprint('len(LABEL.vocab)', len(LABEL.vocab))\n\nlabels = [ex.label for ex in train.examples]\n\ntrain_iter, _, _ = torchtext.data.BucketIterator.splits(\n (train, valid, test), batch_size=args.bsz, device=args.gpu, repeat=False)\n\n_, valid_iter, test_iter = torchtext.data.BucketIterator.splits(\n (train, valid, test), batch_size=10, device=args.gpu)\n\n\n# Build the vocabulary with word embeddings\nurl = 'https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.simple.vec'\nTEXT.vocab.load_vectors(vectors=Vectors('wiki.simple.vec', url=url))\nsimple_vec = TEXT.vocab.vectors.clone()\n\nurl = 'https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.en.vec'\nTEXT.vocab.load_vectors(vectors=Vectors('wiki.en.vec', url=url))\ncomplex_vec = TEXT.vocab.vectors\n\nloss = nn.BCEWithLogitsLoss()\n\n\ndef output_test_nb(model):\n \"All models should be able to be run with following command.\"\n upload = []\n for batch in test_iter:\n # Your prediction data here (don't cheat!)\n probs = model(batch.text)\n _, argmax = probs.max(1)\n upload += list(argmax.data)\n\n with open(args.output_file, \"w\") as f:\n f.write(\"Id,Cat\\n\")\n for i,u in enumerate(upload):\n f.write(str(i) + \",\" + str(u+1) + \"\\n\")\n\ndef output_test(model):\n \"All models should be able to be run with following command.\"\n upload = []\n for batch in test_iter:\n # Your prediction data here (don't cheat!)\n yhat = F.sigmoid(model(batch.text)) > 0.5\n upload += yhat.tolist()\n\n with open(args.output_file, \"w\") as f:\n f.write(\"Id,Cat\\n\")\n for i,u in enumerate(upload):\n f.write(str(i) + \",\" + str(u+1) + \"\\n\")\n\n# TODO: fix this; forward no longer returns # of correct example\ndef validate_nb(model, valid):\n correct = 0.\n total = 0.\n ugh = iter(valid)\n for i in tqdm(range(len(valid))):\n batch = next(ugh)\n x = batch.text\n y = batch.label\n correct += model(x, y)\n total += y.size(0)\n return correct , total, correct / total\n\ndef train_nb(nb):\n ugh = iter(train_iter)\n for i in range(len(train_iter)):\n batch = next(ugh)\n x = batch.text\n y = batch.label\n nb.update_counts(x, y)\n if args.model == \"NB2\":\n nb.get_probs()\n return nb\n \n\ndef validate(model, valid):\n model.eval()\n correct = 0.\n total = 0.\n if True:\n #with torch.no_grad():\n for batch in valid:\n x = batch.text\n y = batch.label\n yhat = F.sigmoid(model(x)) > 0.5\n results = yhat.long() == y\n correct += results.float().sum().data[0]\n total += results.size(0)\n return correct, total, correct / total\n\nclass NB2(nn.Module):\n # See http://www.aclweb.org/anthology/P/P12/P12-2.pdf#page=118\n def __init__(self, vocab, dropout, alpha=1.):\n super(NB2, self).__init__()\n self.vsize = len(vocab.itos)\n self.nclass = 2\n self.alpha = alpha\n self.ys = list(range(self.nclass))\n self.p = torch.zeros((self.vsize))\n self.q = torch.zeros((self.vsize))\n self.N = torch.zeros((self.nclass))\n\n self.w = torch.zeros((self.vsize))\n\n def output_dict(self):\n f = open(\"NB.dict\",\"w\")\n f.write(\"======== NB2 ========\\n\")\n for i in range(self.vsize):\n try:\n f.write(\"NBword(%s): %.3lf\\n\" % (TEXT.vocab.itos[i], self.w[i]))\n except:\n f.write(\"skip - unicode error\\n\")\n f.write(\"======== NB2 ======== \\n\")\n f.close()\n\n def transform(self, x):\n length, batch_size = x.size()\n f = torch.zeros((self.vsize, batch_size))\n for i in range(batch_size): # TODO: make it more efficient\n f[:,i][x[:,i]] += 1 \n f = (f > 0).float()\n return f\n\n def get_probs(self):\n self.p += self.alpha\n self.q += self.alpha\n p_normed = self.p / torch.norm(self.p, p=1)\n q_normed = self.q / torch.norm(self.q, p=1)\n self.w = torch.log(p_normed / q_normed)\n self.b = np.log(self.N[1] / self.N[0])\n\n def _score(self, x, y):\n length, batch_size = x.size()\n f = self.transform(x)\n predict = torch.sign(torch.matmul(self.w, f) + self.b)\n predict = (predict > 0).long()\n #print(\"in score\")\n #embed()\n correct = torch.sum(predict == y)\n\n return correct\n \n def get_score(self, x, y): # of correct examples,\n x = x.data\n y = y.data\n return self._score(x, y)\n \n def forward(self, x):\n x = x.data\n length, batch_size = x.size()\n f = self.transform(x)\n predict = torch.sign(torch.matmul(self.w, f) + self.b)\n predict = (predict > 0).long()\n return predict\n\n def update_counts(self, x, y):\n xd = x.data # (length, batch_size)\n yd = y.data.ne(0) # (batch_size)\n length, batch_size = xd.size()\n f = self.transform(xd)\n for i in range(batch_size):\n if yd[i] == 1:\n self.p += f[:,i]\n self.N[1] += 1\n else:\n self.q += f[:,i]\n self.N[0] += 1\n\n\nclass LR2(nn.Module):\n def __init__(self, vocab, dropout, binarize=True):\n super(LR2, self).__init__()\n self.vsize = len(vocab.itos)\n # Since this is binary LRRwe can just use BCEWithLogitsLoss\n self.lut = nn.Linear(self.vsize, 1)\n self.bias = Parameter(torch.zeros(1))\n self.dropout = nn.Dropout(dropout) if dropout > 0 else None\n self.binarize = binarize\n \n def output_dict(self):\n f = open(\"LR.dict\",\"w\")\n f.write(\"======== LR2 ======== \\n\")\n for i in range(self.vsize):\n try:\n f.write(\"LRword(%s): %.3lf\\n\" % (TEXT.vocab.itos[i], self.lut.weight[0][i].data[0]))\n except:\n f.write(\"skip - unicode error\\n\")\n f.write(\"======== LR2 ======== \\n\")\n f.close()\n \n def transform(self, x):\n length, batch_size = x.size()\n f = torch.zeros((self.vsize, batch_size))\n for i in range(batch_size): # TODO: make it more efficient\n f[:,i][x[:,i].data] += 1 \n f = (f > 0).float()\n return V(f)\n\n def forward(self, input):\n # input will be seqlen x bsz, so we want to use the weights from the lut\n # and sum them up to get the logits.\n x = self.transform(input) # vsize, batch_size\n x = torch.transpose(x, 0, 1) # batch_size, vsize\n if self.binarize:\n x = (x > 0).float()\n if self.dropout is not None:\n x = self.dropout(x)\n output = self.lut(x).view(input.size(1))\n return output + self.bias\n\nclass CBoW(nn.Module):\n def __init__(self, vocab, dropout=0, binarize=True, average=False):\n super(CBoW, self).__init__()\n self.vsize = len(vocab.itos)\n self.binarize = binarize\n self.average = average\n self.static_lut = nn.Embedding(self.vsize, vocab.vectors.size(1))\n self.static_lut.weight.data.copy_(vocab.vectors)\n self.static_lut.requires_grad = False\n self.lut = nn.Embedding(self.vsize, vocab.vectors.size(1))\n self.lut.weight.data.copy_(vocab.vectors)\n self.lut.weight.data += self.lut.weight.data.new(self.lut.weight.data.size()).normal_(0, 0.01)\n self.dropout = nn.Dropout(dropout) if dropout > 0 else None\n self.proj = nn.Sequential(\n nn.Linear(600, 600),\n nn.ReLU(),\n nn.Linear(600, 1)\n )\n\n def forward(self, input):\n if self.average:\n hidden = torch.cat([self.lut(input).sum(0), self.static_lut(input).mean(0)], -1)\n else:\n hidden = torch.cat([self.lut(input).sum(0), self.static_lut(input).sum(0)], -1)\n if self.dropout:\n hidden = self.dropout(hidden)\n return self.proj(hidden).squeeze(-1)\n\nclass CNNLOL(nn.Module):\n def __init__(self, vocab, dropout=0.):\n super(CNNLOL, self).__init__()\n self.vsize = len(vocab.itos)\n self.static_lut = nn.Embedding(self.vsize, vocab.vectors.size(1))\n self.static_lut.weight.data.copy_(vocab.vectors)\n self.static_lut.requires_grad = False\n self.lut = nn.Embedding(self.vsize, vocab.vectors.size(1))\n self.lut.weight.data.copy_(simple_vec)\n #self.lut.requires_grad = False\n self.convs = nn.ModuleList([\n nn.Conv1d(600, 200, 3, padding=1),\n nn.Conv1d(600, 200, 5, padding=2),\n ])\n self.proj = nn.Sequential(\n nn.Linear(1000, 500),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(500, 1)\n )\n\n def forward(self, input):\n word_rep = torch.cat([self.lut(input), self.static_lut(input)], -1).permute(1, 2, 0)\n cnns, _ = torch.cat([conv(word_rep) for conv in self.convs] + [word_rep], 1).max(2)\n return self.proj(cnns).squeeze(-1)\n\nclass LSTM(nn.Module):\n def __init__(self, vocab, dropout=0):\n super(LSTM, self).__init__()\n self.vsize = len(vocab.itos)\n self.dropout = dropout\n self.static_lut = nn.Embedding(self.vsize, vocab.vectors.size(1))\n self.static_lut.weight.data.copy_(vocab.vectors)\n self.static_lut.requires_grad = False\n self.lut = nn.Embedding(self.vsize, vocab.vectors.size(1))\n self.lut.weight.data.copy_(simple_vec)\n self.lut.requires_grad = False\n self.lstm = nn.LSTM(600, 300, 2, bidirectional=True, dropout=dropout)\n self.proj = nn.Sequential(\n nn.Dropout(dropout),\n #nn.Linear(1200 * 2, 1)\n nn.Linear(2400, 1200),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(1200, 1)\n )\n\n def forward(self, input):\n word_rep = torch.cat([self.lut(input), self.static_lut(input)], -1)\n _, (h, c) = self.lstm(word_rep)\n z = torch.cat([h.permute(1,0,2), c.permute(1,0,2)], -1).view(input.size(1), -1)\n return self.proj(z).squeeze(-1)\n\ndef validate_ensemble(models, data_iter, out=True):\n for model in models:\n model.eval()\n correct = 0.\n total = 0.\n def output_text(xlist):\n word_list = [TEXT.vocab.itos[idx] for idx in xlist]\n sentence = \" \".join(word_list)\n return sentence\n\n from sets import Set\n stop_words = []\n\n if True: # HACK\n #with torch.no_grad():\n for batch in tqdm(data_iter):\n x = batch.text\n y = batch.label\n\n batch_size = y.size(0)\n\n yhats = torch.zeros((len(models), batch_size)).long()\n for i, model in enumerate(models):\n if i != 0:\n yhat = (F.sigmoid(model(x)) > 0.5).long().data\n else: # NB: assume models[0] = NB2\n yhat = (1 - model(x).long()) * NBWEIGHT # NB: for NB2, labels are opposite\n yhats[i] = yhat\n #embed()\n agg_yhat = torch.sum(yhats, dim=0)\n agg_yhat = agg_yhat >= ((len(models) + NBWEIGHT - 1) / 2)\n results = V(agg_yhat).long() == y\n if out:\n for i in tqdm(range(batch_size), desc=\"output_bad\"):\n #embed()\n if agg_yhat[i] != y[i].data[0]:\n xlist = x[:,i].data.tolist()\n sent = output_text(xlist)\n print(\"--------- BAD START --------\")\n print(\"sent: %s\" % sent)\n nb_values = []\n lr_values = []\n for v in xlist:\n nb_values.append(\"%.3lf\" % (-models[0].w[v])) \n lr_values.append(\"%.3lf\" % models[1].lut.weight[0][v].data[0])\n print(\"nb_values: %s\" % \" \".join(nb_values))\n print(\"lr_values: %s\" % \" \".join(lr_values))\n\n # argmin negative values -> positive (label=0)\n # argmax positive values -> negative (label=1)\n if y[i].data[0] == 0:\n idx = np.argmax(nb_values)\n else:\n idx = np.argmin(nb_values)\n #embed()\n vid = xlist[idx]\n stop_words.append(TEXT.vocab.itos[vid])\n print(\"add %s | idx %d | vid %d\" % (TEXT.vocab.itos[vid], idx, vid))\n print(\"our: %d | true: %d\" % (agg_yhat[i], y[i].data[0]))\n print(\"all yhats: %s\" % str(yhats[:,i]))\n print(\"--------- BAD END--------\\n\\n\")\n\n correct += results.float().sum().data[0]\n total += results.size(0)\n print(\"list=\", stop_words)\n newf = open(\"stop_words.greedy\", \"w\")\n\n for word in stop_words:\n newf.write(\"%s\\n\" % word)\n newf.close()\n\n\n return correct, total, correct / total\n\ndef output_ensemble(models):\n \"All models should be able to be run with following command.\"\n upload = []\n\n for model in models:\n model.eval()\n correct = 0.\n total = 0.\n if True: # HACK\n #with torch.no_grad():\n for batch in test_iter:\n x = batch.text\n y = batch.label\n\n #print(\"x=%s\", str(x))\n batch_size = y.size(0)\n\n yhats = torch.zeros((len(models), batch_size)).long()\n for i, model in enumerate(models):\n if i != 0:\n yhat = (F.sigmoid(model(x)) > 0.5).long().data\n else: # NB: assume models[0] = NB2\n yhat = (1 - model(x).long()) * NBWEIGHT # NB: for NB2, labels are opposite\n yhats[i] = yhat\n #embed()\n agg_yhat = torch.sum(yhats, dim=0)\n agg_yhat = agg_yhat >= ((len(models) + NBWEIGHT - 1) / 2)\n upload += agg_yhat.tolist()\n\n with open(args.output_file, \"w\") as f:\n f.write(\"Id,Cat\\n\")\n for i,u in enumerate(upload):\n f.write(str(i) + \",\" + str(u+1) + \"\\n\")\n\ndef load_model(model, filename):\n checkpoint = torch.load(filename)\n model.load_state_dict(checkpoint[\"state_dict\"])\n print(\"Model Loaded from %s\" % filename)\n\n\nmodels = []\n# store all model in model/final/\n\n# NB2\nmodel_nb2 = NB2(TEXT.vocab, len(LABEL.vocab.itos))\ncheckpoint = torch.load(\"model/final/NB2\")\nmodel_nb2.w = checkpoint[\"w\"]\nmodel_nb2.b = checkpoint[\"b\"]\n#model_nb2.output_dict()\nmodels.append(model_nb2)\n\n# LR\nmodel_lr2 = LR2(TEXT.vocab, args.dropout)\nload_model(model_lr2, \"model/final/LR2\")\n#model_lr2.output_dict()\n\nmodels.append(model_lr2)\n\n\n# CBOW\nmodel_cbow = CBoW(TEXT.vocab)\ncheckpoint = torch.load(\"model/final/CBoW\")\nmodel_cbow.load_state_dict(checkpoint)\nmodels.append(model_cbow)\n\n\n\n# CNNLOL\nmodel_cnnlol = CNNLOL(TEXT.vocab)\nprint(\"start loading\")\ncheckpoint = torch.load(\"model/final/CNNLOL\")\nmodel_cnnlol.load_state_dict(checkpoint)\nprint(\"finish loading cnnlol\")\nmodels.append(model_cnnlol)\n\n# LSTM\nmodel_lstm = LSTM(TEXT.vocab)\ncheckpoint = torch.load(\"model/final/LSTM\")\nmodel_lstm.load_state_dict(checkpoint)\nmodels.append(model_lstm)\n\ntrain_acc = validate_ensemble(models, train_iter, out=True) \nprint(\"Train ACC:\", train_acc)\n#valid_acc = validate_ensemble(models, valid_iter, out=True)\n#print(\"Valid ACC:\", valid_acc)\ntest_acc = validate_ensemble(models, test_iter, out=False)\nprint(\"Test ACC:\" , test_acc)\n\n\n\noutput_ensemble(models)\n\n\n","sub_path":"hw1/ensemble-test.py","file_name":"ensemble-test.py","file_ext":"py","file_size_in_byte":17813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521018046","text":"import warnings\nfrom contextlib import contextmanager\n\nimport numpy as np\nfrom gym.spaces import Box, Discrete, Space\nfrom gym.wrappers import TimeAwareObservation\n\n\ndef assert_continuous(space: Space, client, nome: str = \"observação\"):\n assert isinstance(space, Box), f\"{type(client)} requer espaço de {nome} contínuo\"\n \n\ndef assert_discrete(space: Space, client, nome: str = \"ação\"):\n assert isinstance(space, Discrete), f\"{type(client)} requer espaço de {nome} discreto\"\n \n\n@contextmanager\ndef suppress_box_precision_warning():\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\", message=\".*Box bound precision.*\", module=\"gym.logger\"\n )\n yield\n\n\nclass TimeAwareWrapper(TimeAwareObservation):\n \"\"\"Add relative timestep specific to CartPole.\"\"\"\n\n @suppress_box_precision_warning()\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n high = np.array(\n [\n self.x_threshold * 2,\n np.inf,\n self.theta_threshold_radians * 2,\n np.inf,\n 1.0,\n ],\n dtype=np.float32,\n )\n low = -high.copy()\n low[-1] = 0\n\n self.observation_space = Box(low, high, dtype=np.float32)\n\n def observation(self, observation: np.ndarray) -> np.ndarray:\n return np.append(observation, self.t / self.spec.max_episode_steps)\n","sub_path":"notebooks/aula2/utils/gym_util.py","file_name":"gym_util.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176265945","text":"# -*- coding: utf-8 -*-\r\n# MLToolkit (mltoolkit)\r\n\r\n__name__=\"mltk\"\r\n\r\n\"\"\"\r\nMLToolkit - a verstile helping library for machine learning\r\n===========================================================\r\n'MLToolkit' is a Python package providing a set of user-friendly functions to \r\nhelp building machine learning models in data science research or production \r\nfocused projects. It is compatible with and interoperate with popular data \r\nanalysis, manipulation and machine learning libraries Pandas, Sci-kit Learn, \r\nTensorflow, Statmodels, Catboost, XGboost, etc.\r\n\r\nMain Features\r\n-------------\r\n- Data Extraction (SQL, Flatfiles, Images, etc.)\r\n- Exploratory data analysis (statistical summary, univariate analysis, etc.)\r\n- Feature Extraction and Engineering\r\n- Model performance analysis, Explain Predictions and comparison between models\r\n- Cross Validation and Hyper parameter tuning\r\n- JSON input script for executing model building and scoring tasks.\r\n- Model Building UI\r\n- Auto ML (automated machine learning)\r\n- Model Deploymet and Serving via RESTful API\r\n\r\nAuthor\r\n------\r\n- Sumudu Tennakoon\r\n\r\nLinks\r\n-----\r\nWebsite: http://sumudu.tennakoon.net/projects/MLToolkit\r\nGithub: https://mltoolkit.github.io/MLToolKit\r\n\r\nLicense\r\n-------\r\nApache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport shap\r\nimport lime\r\nimport traceback\r\nimport time \r\nimport matplotlib.pyplot as plt\r\n\r\nclass MLExplainer():\r\n def __init__(self, model_id=None, explainer_object=None, explainer_config=None, model_parameters=None):\r\n self.model_id = model_id\r\n self.explainer_object = explainer_object\r\n self.explainer_config = explainer_config\r\n self.model_parameters = model_parameters\r\n\r\n def get_explainer_object(self):\r\n return self.explainer_object\r\n\r\n def get_explainer_config(self):\r\n return self.explainer_config\r\n\r\n def get_model_parameters(self):\r\n return self.model_parameters\r\n\r\n def get_model_parameter(self, param):\r\n return self.model_parameters[param]\r\n \r\n def get_explainer_config_item(self, item):\r\n return self.explainer_config[item]\r\n \r\n def get_explainer_method(self):\r\n return self.explainer_config['Method'] \r\n \r\n def get_model_variables(self):\r\n return self.model_parameters['ModelVariables'] \r\n \r\n def get_base_value(self, class_number=None):\r\n try:\r\n if class_number == None:\r\n class_number = self.explainer_config['ClassNumber']\r\n else:\r\n class_number = 0\r\n return self.explainer_object.expected_value[class_number]\r\n except:\r\n print('Base Value calculating Error !\\n{}'.format(traceback.format_exc())) \r\n return None\r\n\r\ndef load_object(file_name):\r\n try:\r\n import pickle\r\n pickle_in = open(file_name,'rb')\r\n print('Loading explainer from file {}'.format(file_name))\r\n object = pickle.load(pickle_in)\r\n pickle_in.close()\r\n return object\r\n except:\r\n print('ERROR in loading explainer: {}'.format(traceback.format_exc()))\r\n return None\r\n \r\ndef save_object(object_to_save, file_name):\r\n try:\r\n import pickle\r\n pickle_out = open(file_name,'wb')\r\n print('Saving explainer to file {}'.format(file_name))\r\n pickle.dump(object_to_save, pickle_out)\r\n pickle_out.close()\r\n except:\r\n print('ERROR in saving explainer: {}'.format(traceback.format_exc()))\r\n\r\ndef save_explainer(Explainer, file_path):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n Explainer : mltk.MLExplainer\r\n file_path : str, dafault ''\r\n Path to file including the file name. \r\n \r\n Returns\r\n -------\r\n None\r\n \"\"\" \r\n save_object(Explainer, file_path)\r\n\r\ndef load_explainer(file_path):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n file_path : str, dafault ''\r\n Path to file including the file name. \r\n \r\n Returns\r\n -------\r\n Explainer : mltk.MLExplainer\r\n \"\"\"\r\n Explainer = load_object(file_path)\r\n return Explainer\r\n \r\ndef build_explainer(Model, explainer_config={'Method':'shap'}, train_variable_values=None):\r\n \"\"\" \r\n Parameters\r\n ---------- \r\n Model : mltk.MLModel \r\n explainer_config : dict or json, optional \r\n train_variable_values : pd.DataFrame (optional for Linear Explainer)\r\n \r\n Returns\r\n ------- \r\n Explainer : mltk.MLExplainer\r\n \"\"\"\r\n try:\r\n model_id = Model.get_model_id()\r\n ml_algorithm = Model.get_model_algorithm()\r\n model = Model.get_model_object()\r\n model_type = Model.get_model_type()\r\n model_variables = Model.get_model_variables()\r\n predicted_value_column = Model.get_score_variable()\r\n except:\r\n print('Error in processing Model\\n{}'.format(traceback.format_exc()))\r\n return None\r\n \r\n method = explainer_config['Method']\r\n \r\n if 'IdColumns' not in explainer_config:\r\n explainer_config['IdColumns'] = [] \r\n\r\n if 'ClassNumber' not in explainer_config:\r\n explainer_config['ClassNumber'] = 0\r\n \r\n model_parameters = {\r\n 'ModelType':model_type,\r\n 'ModelVariables':model_variables,\r\n 'PredictedValueColumn':predicted_value_column\r\n }\r\n \r\n try:\r\n if method=='shap':\r\n if ml_algorithm in ['RF']:\r\n explainer_object = shap.TreeExplainer(model)\r\n elif ml_algorithm in ['LGR']:\r\n explainer_object = shap.LinearExplainer(model, train_variable_values[model_variables].values, feature_dependence=\"independent\")\r\n elif ml_algorithm in ['NN']:\r\n explainer_object = shap.DeepExplainer(model, train_variable_values[model_variables].values) \r\n else:\r\n explainer_object = None\r\n print('Model not supported')\r\n elif method=='lime':\r\n explainer_object = None\r\n # Not implemented\r\n print('Explainer created ...') \r\n except:\r\n print('Explainer Create Error !\\n{}'.format(traceback.format_exc()))\r\n return None\r\n \r\n Explainer = MLExplainer(model_id, explainer_object, explainer_config, model_parameters)\r\n \r\n return Explainer \r\n \r\n \r\ndef get_explainer_values_task(DataFrame, Explainer=None, Model=None, explainer_config={'Method':'shap'}, verbose=False):\r\n \"\"\" \r\n Parameters\r\n ---------- \r\n DataFrame : pandas.DataFrame\r\n Explainer : mltk.MLExplainer\r\n Model : mltk.MLModel\r\n explainer_config : dict or json \r\n \r\n Returns\r\n ------- \r\n ShapValues : pandas.DataFrame\r\n VariableValues : pandas.DataFrame\r\n \r\n \"\"\"\r\n \r\n if Explainer==None and Model!=None:\r\n Explainer = build_explainer(Model, explainer_config)\r\n elif Explainer!=None and Model==None:\r\n Explainer = Explainer\r\n else:\r\n print('explainer or materials to create explainer not provided !')\r\n \r\n model_variables = Explainer.get_model_parameter('ModelVariables')\r\n model_type = Explainer.get_model_parameter('ModelType')\r\n predicted_value_column = Explainer.get_model_parameter('PredictedValueColumn') \r\n id_columns = Explainer.get_explainer_config_item('IdColumns')\r\n class_number = Explainer.get_explainer_config_item('ClassNumber')\r\n method = Explainer.get_explainer_config_item('Method')\r\n explainer = Explainer.get_explainer_object()\r\n fill_missing = Explainer.get_explainer_config_item('FillMissing')\r\n \r\n # Blanck columns for non-existance variables\r\n missing_variables = list(set(model_variables) - set(DataFrame.columns)) # Find columns not found in the dataset\r\n \r\n for f in missing_variables:\r\n DataFrame[f]=fill_missing\r\n if verbose:\r\n print('Column [{}] does not exist in the dataset. Created new column and set to {}...\\n'.format(f,missing_variables))\r\n \r\n \r\n if method == 'shap':\r\n ImpactValues, VariableValues = get_shap_values(DataFrame, explainer, \r\n model_variables=model_variables, \r\n id_columns=id_columns, \r\n model_type=model_type, \r\n class_number=class_number, \r\n predicted_value_column=predicted_value_column\r\n )\r\n else:\r\n ImpactValues = None\r\n VariableValues = None\r\n \r\n return ImpactValues, VariableValues\r\n\r\ndef get_explainer_visual(ImpactValues, VariableValues, Explainer, visual_config={'figsize':[20,4]}):\r\n \"\"\" \r\n Parameters\r\n ---------- \r\n ImpactValues : pandas.DataFrame\r\n VariableValues : pandas.DataFrame\r\n Explainer : mltk.MLExplainer\r\n visual_config : dict\r\n \r\n Returns\r\n ------- \r\n explainer_visual : matplotlib.figure.Figure\r\n \"\"\"\r\n \r\n base_value = Explainer.get_base_value()\r\n model_variables = Explainer.get_model_variables()\r\n method = Explainer.get_explainer_method()\r\n \r\n if method == 'shap':\r\n figsize = visual_config['figsize']\r\n text_rotation = visual_config['text_rotation']\r\n explainer_visual = get_shap_force_plot(ImpactValues, VariableValues, model_variables, base_value, figsize=figsize, text_rotation=text_rotation)\r\n else:\r\n explainer_visual = None\r\n print('method {} not implemented'.format(method))\r\n \r\n return explainer_visual\r\n\r\ndef get_shap_values(DataFrame, explainer, model_variables, id_columns=[], model_type='classification', class_number=0, predicted_value_column=None):\r\n \"\"\" \r\n Parameters\r\n ---------- \r\n DataFrame : pandas.DataFrame\r\n explainer : shap.Explainer\r\n model_variables : list(str)\r\n id_columns : list(str)\r\n model_type : {'regression', 'classification'}\r\n class_number : int\r\n predicted_value_column : str\r\n \r\n Returns\r\n ------- \r\n ShapValues : pandas.DataFrame\r\n VariableValues : pandas.DataFrame\r\n \"\"\"\r\n \r\n DataFrame = DataFrame.reset_index(drop=True)\r\n \r\n try:\r\n if model_type=='classification':\r\n shap_values = explainer.shap_values(DataFrame[model_variables])[class_number] \r\n base_value = explainer.expected_value[class_number]\r\n elif model_type=='regression':\r\n shap_values = explainer.shap_values(DataFrame[model_variables])\r\n base_value = explainer.expected_value[0]\r\n # To DataFrame\r\n ShapValues = pd.DataFrame(data=shap_values, columns=model_variables)\r\n ShapValues['BaseValue'] = base_value\r\n del(shap_values)\r\n except:\r\n print('Error creating Shap Values\\n{}'.format(traceback.format_exc())) \r\n return None\r\n \r\n try:\r\n for c in id_columns:\r\n ShapValues[c] = DataFrame[c].values\r\n except:\r\n print('Error creating Id columns\\n{}'.format(traceback.format_exc())) \r\n \r\n try:\r\n ShapValues['OutputValue'] = DataFrame[predicted_value_column].values\r\n except:\r\n ShapValues['OutputValue'] = None\r\n print('Error creating OutputValue columns\\n{}'.format(traceback.format_exc())) \r\n \r\n return ShapValues[id_columns+model_variables+['BaseValue', 'OutputValue']], DataFrame[id_columns+model_variables]#Pandas Dataframe\r\n\r\n\r\ndef get_shap_force_plot(ShapValues, VariableValues, model_variables, base_value, figsize=(20, 3), text_rotation=90):\r\n \"\"\"\r\n Parameters\r\n ---------- \r\n ShapValues : pandas.DataFrame\r\n VariableValues : pandas.DataFrame\r\n model_variables : list(str)\r\n figsize : (int, int), default (20, 3)\r\n text_rotation : float, default 90\r\n \r\n Returns\r\n ------- \r\n shap_force_plot : matplotlib.figure.Figure\r\n \"\"\"\r\n\r\n shap_force_plot = shap.force_plot(\r\n base_value=base_value,\r\n shap_values=ShapValues[model_variables].values,\r\n features=VariableValues[model_variables].values,\r\n feature_names=model_variables,\r\n out_names=None,\r\n link='identity',\r\n plot_cmap='RdBu',\r\n matplotlib=True,\r\n show=False,\r\n figsize=figsize,\r\n ordering_keys=None,\r\n ordering_keys_time_format=None,\r\n text_rotation=text_rotation,\r\n )\r\n \r\n return shap_force_plot\r\n\r\ndef get_shap_impact_plot(ShapValues, VariableValues, model_variables, iloc=0, top_n=5):\r\n \"\"\"\r\n Parameters\r\n ---------- \r\n ShapValues : pandas.DataFrame\r\n VariableValues : pandas.DataFrame\r\n model_variables : list(str)\r\n iloc : int, default 0\r\n top_n : int, default 5\r\n \r\n Returns\r\n ------- \r\n figure : matplotlib.figure.Figure\r\n \"\"\" \r\n \r\n impact_values = ShapValues[model_variables].iloc[iloc]\r\n variable_values = VariableValues[model_variables].iloc[iloc]\r\n variable_values.name = 'Value'\r\n \r\n posivite_impact_values = impact_values[impact_values>=0.0].sort_values(ascending=False)\r\n posivite_impact_values.name = 'Impact'\r\n\r\n negative_impact_values = impact_values[impact_values<=0.0].sort_values(ascending=True)\r\n negative_impact_values.name = 'Impact'\r\n\r\n figure, axes = plt.subplots(nrows=1, ncols=2)\r\n negative_impact_values.head(top_n)[::-1].plot(kind='barh', ax=axes[0], color='r', legend=False)\r\n posivite_impact_values.head(top_n)[::-1].plot(kind='barh', ax=axes[1], color='g', legend=False)\r\n axes[1].yaxis.tick_right()\r\n \r\n return figure\r\n\r\ndef get_shap_impact_summary(ShapValues, VariableValues, model_variables, base_value=None, iloc=0, top_n=None, show_plot=False):\r\n \"\"\"\r\n Parameters\r\n ---------- \r\n ShapValues : pandas.DataFrame\r\n VariableValues : pandas.DataFrame\r\n model_variables : list(str)\r\n iloc : int, default 0\r\n top_n : int, default None\r\n \r\n Returns\r\n ------- \r\n ImpactSummary : pandas.DataFrame\r\n \"\"\" \r\n impact_values = ShapValues[model_variables].iloc[iloc]\r\n variable_values = VariableValues[model_variables].iloc[iloc]\r\n variable_values.name = 'Value'\r\n \r\n posivite_impact_values = impact_values[impact_values>=0.0].sort_values(ascending=False)\r\n posivite_impact_values.name = 'Impact'\r\n\r\n negative_impact_values = impact_values[impact_values<=0.0].sort_values(ascending=True)\r\n negative_impact_values.name = 'Impact'\r\n\r\n sum_posivite_impact_values = posivite_impact_values.sum()\r\n sum_negative_impact_values = negative_impact_values.sum()\r\n\r\n norm_posivite_impact_values = posivite_impact_values/sum_posivite_impact_values\r\n norm_negative_impact_values = negative_impact_values/sum_negative_impact_values\r\n norm_posivite_impact_values.name = 'NormalizedImpact'\r\n norm_negative_impact_values.name = 'NormalizedImpact'\r\n\r\n if base_value != None:\r\n output_value = sum_posivite_impact_values + sum_negative_impact_values + base_value\r\n else:\r\n output_value = None\r\n \r\n out_posivite_impact_values = pd.concat([posivite_impact_values, norm_posivite_impact_values, variable_values], join='inner', axis=1)\r\n out_posivite_impact_values['Sign'] = 'P'\r\n out_posivite_impact_values['Rank'] = np.arange(out_posivite_impact_values.shape[0])+1\r\n out_posivite_impact_values['Output'] = output_value\r\n\r\n out_negative_impact_values = pd.concat([negative_impact_values, norm_negative_impact_values, variable_values], join='inner', axis=1) \r\n out_negative_impact_values['Sign'] = 'N'\r\n out_negative_impact_values['Rank'] = np.arange(out_negative_impact_values.shape[0])+1\r\n out_negative_impact_values['Output'] = output_value\r\n\r\n print('sum_posivite_impact_values', sum_posivite_impact_values)\r\n print('sum_negative_impact_values', sum_negative_impact_values)\r\n\r\n if show_plot:\r\n get_shap_impact_plot(ShapValues, VariableValues, model_variables, iloc=iloc, top_n=top_n)\r\n \r\n if top_n==None: \r\n return out_posivite_impact_values.append(out_negative_impact_values)\r\n else:\r\n return out_posivite_impact_values.head(top_n).append(out_negative_impact_values.head(top_n))\r\n \r\ndef get_explainer_report(DataFrame, Explainer, top_n=5, show_plot=False, return_type='frame'):\r\n \"\"\" \r\n Parameters\r\n ---------- \r\n DataFrame : pandas.DataFrame\r\n Explainer : mltk.MLExplainer\r\n top_n : int, default 5\r\n show_plot : bool, defualt False\r\n return_type : {'frame', 'json'}, defua;t 'frame'\r\n \r\n Returns\r\n ------- \r\n ImpactSummary : pandas.DataFrame\r\n impact_plot : matplotlib.figure.Figure (optional)\r\n \"\"\"\r\n\r\n ImpactValues, VariableValues = get_explainer_values_task(DataFrame, Explainer=Explainer)\r\n \r\n model_variables = Explainer.get_model_variables()\r\n base_value = Explainer.get_base_value()\r\n \r\n ImpactSummary = get_shap_impact_summary(ImpactValues, VariableValues, model_variables, base_value=base_value, iloc=0, top_n=top_n)\r\n\r\n if show_plot:\r\n impact_plot = get_shap_impact_plot(ImpactValues, VariableValues, model_variables, iloc=0, top_n=top_n)\r\n\r\n if return_type=='frame':\r\n if show_plot:\r\n return ImpactSummary, impact_plot\r\n else:\r\n return ImpactSummary\r\n elif return_type=='json':\r\n if show_plot:\r\n return ImpactSummary.to_json(orient='columns'), impact_plot\r\n else:\r\n return ImpactSummary.to_json(orient='columns')\r\n else:\r\n print(\"return type is set to 'frame'. use 'json' to return json output\")\r\n if show_plot:\r\n ImpactSummary, impact_plot\r\n else:\r\n return ImpactSummary","sub_path":"MLToolkit/explain.py","file_name":"explain.py","file_ext":"py","file_size_in_byte":17772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"398200842","text":"#attach the training data header\n# 00 '' 01 'PassengerId' 02 'Survived' 03 'Pclass' 04 'Name' 05 'Sex'\n# 06 'Age' 07 'SibSp' 08 'Parch' 09 'Ticket' 10 'Fare' 11 'Cabin'\n# 12 'Embarked' 13 'Gender' 14 'Embark']\n\n#attach the testing data header\n# 01 PassengerId 02 Pclass 03 Name 04 Sex\n# 05 Age 06 SibSp 07 Parch 08 Ticket\n# 09 Fare 10 Cabin 11 Embarked\n\n#calculate the average age 5 6\ndef calculate_average_age(sample_matrix,index_of_age):\n\n\n totalAge = 0\n totalCount = 0\n\n for row in sample_matrix:\n if(row[index_of_age] != \"NA\"):\n totalAge+=(float(row[index_of_age]))\n totalCount+=1\n\n averageAge = int(totalAge/totalCount)\n\n for row in sample_matrix:\n if(row[index_of_age] == \"NA\"):\n row[index_of_age] = averageAge\n","sub_path":"1.Titanic/Python/CleanData.py","file_name":"CleanData.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"563118436","text":"# cross platform home folder\nfrom pathlib import Path\nhome = str(Path.home())\n\n# constants\nPORT = 14908\nENCODING = 'utf-8'\n\n# Database\nDB_PROTOCOL = 'sqlite:///'\nDB_NAME = '/client_contacts.db'\nDB_PATH = DB_PROTOCOL + home + DB_NAME\n","sub_path":"aiogbserver/server_config.py","file_name":"server_config.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576950854","text":"\nimport random\nimport numpy as np\nimport math\nimport itertools\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n have_matplotlib = False\nelse:\n have_matplotlib = True\n # plt.ion()\n\nfrom my_link_search import LinkSearch\nls = LinkSearch()\n\ndef create_new_path(map_orig, rand_list):\n ls.map = map_orig.copy()\n\n # Create new rand list\n # for _ in range(1):\n a = random.randrange(0, 64)\n b = random.randrange(0, 64)\n rand_list[a], rand_list[b] = rand_list[b], rand_list[a]\n\n score = 0\n path = []\n\n for x, y in rand_list:\n num = ls.map[x, y]\n if num == 0:\n continue\n\n sl, pl = [], []\n for p in np.argwhere(ls.map == num):\n s = ls.search_link(x, y, *p)\n if s is not None:\n sl.append(s)\n pl.append(p)\n\n if len(sl):\n idx = sl.index(max(sl))\n path.append([x-1, y-1, pl[idx][0]-1, pl[idx][1]-1])\n ls.link(x, y, pl[idx][0], pl[idx][1])\n score += sl[idx]\n # 第4次,第8次,第16次,第28,29,30,31,32次配对\n if len(path) in (4, 8, 16, 28, 29, 30, 31, 32) and sl[idx] == 50:\n score += 50\n \n if ls.is_all_empty():\n return score, path, rand_list\n else:\n return None\n\n\nscore_list = []\ndef simulated_annealing(map_orig, q = 0.975, T_begin = 200, T_end = 1, mapkob_len = 50):\n\n map_orig = np.pad(map_orig, ((1,1),(1,1)),'constant',constant_values = (0,0)) \n\n best_path = None\n best_score = 0\n T = T_begin\n rand_list = [(x, y) for x in range(1, 10) for y in range(1, 10)]\n score = 0\n\n last_ret = None\n ret = None\n\n while T > T_end:\n for _ in range(mapkob_len):\n \n while ret is None or ret == last_ret:\n ret = create_new_path(map_orig, rand_list.copy())\n last_ret = ret\n new_score, new_path, new_rand_list = ret\n\n df = score - new_score\n\n if df < 0:\n path = new_path\n score = new_score\n rand_list = new_rand_list\n\n if score > best_score:\n best_score, best_path = score, path\n\n elif math.exp(-df/T) > random.random():\n path = new_path\n score = new_score\n rand_list = new_rand_list\n \n score_list.append(score)\n \n if have_matplotlib:\n plt.clf()\n plt.plot(score_list)\n plt.pause(0.05)\n else:\n print(score)\n # print(best_score)\n T *= q\n\n return best_score, best_path\n\ndef generate_map():\n sample_list = random.choices(range(1, 30), k=32) * 2\n return np.array(sample_list, dtype=np.int).reshape(8, 8)\n\nif __name__ == \"__main__\":\n map_orig = generate_map()\n simulated_annealing(map_orig)\n","sub_path":"my_code/planner/sa.py","file_name":"sa.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"127003020","text":"from unittest import skip\nfrom unittest.mock import Mock, patch\n\nfrom django.core import mail\nfrom django.urls import reverse\nfrom django.test import TestCase\nfrom guardian.shortcuts import assign_perm, get_user_perms\nfrom django.db.models import Count\nfrom feder.cases.factories import CaseFactory\nfrom feder.cases.models import Case\nfrom feder.domains.factories import DomainFactory\nfrom feder.institutions.factories import InstitutionFactory\nfrom feder.letters.factories import IncomingLetterFactory, DraftLetterFactory\nfrom feder.letters.factories import OutgoingLetterFactory\nfrom feder.main.tests import PermissionStatusMixin\nfrom feder.monitorings.filters import MonitoringFilter\nfrom feder.parcels.factories import IncomingParcelPostFactory, OutgoingParcelPostFactory\nfrom feder.teryt.factories import JSTFactory\nfrom feder.records.factories import RecordFactory\nfrom feder.users.factories import UserFactory\nfrom .factories import MonitoringFactory\nfrom .forms import MonitoringForm\nfrom .models import Monitoring\nfrom .tasks import send_letter_for_mass_assign, handle_mass_assign\n\nEXAMPLE_DATA = {\n \"name\": \"foo-bar-monitoring\",\n \"description\": \"xyz\",\n \"notify_alert\": True,\n \"subject\": \"example subject\",\n \"template\": \"xyz {{EMAIL}}\",\n \"email_footer\": \"X\",\n \"domain\": 1,\n}\n\n\nclass MonitoringFormTestCase(TestCase):\n def setUp(self):\n self.user = UserFactory(username=\"john\")\n\n def test_form_save_user(self):\n form = MonitoringForm(EXAMPLE_DATA.copy(), user=self.user)\n self.assertTrue(form.is_valid(), msg=form.errors)\n obj = form.save()\n self.assertEqual(obj.user, self.user)\n\n def test_form_template_validator(self):\n data = EXAMPLE_DATA.copy()\n data[\"template\"] = \"xyzyyz\"\n form = MonitoringForm(data, user=self.user)\n self.assertFalse(form.is_valid())\n self.assertIn(\"template\", form.errors)\n\n\nclass MonitoringFilterTestCase(TestCase):\n @skip(\"Need to discovery way to mock QuerySet\")\n def test_respect_disabling_fields(self):\n mock_qs = Mock()\n voivodeship = JSTFactory(category__level=1)\n county = JSTFactory(parent=voivodeship, category__level=2)\n\n filter = MonitoringFilter(\n data={\"voivodeship\": voivodeship.pk, \"county\": county.pk}, queryset=mock_qs\n )\n\n _ = filter.qs # Fire mock\n # [call.area()]\n self.assertEqual(len(mock_qs.all().mock_calls), 1, mock_qs.all().mock_calls)\n\n\nclass ObjectMixin:\n def setUp(self):\n super().setUp()\n self.user = UserFactory(username=\"john\")\n self.monitoring = self.permission_object = MonitoringFactory(subject=\"Wniosek\")\n\n\nclass MonitoringCreateViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n url = reverse(\"monitorings:create\")\n permission = [\"monitorings.add_monitoring\"]\n\n def get_permission_object(self):\n return None\n\n def test_template_used(self):\n assign_perm(\"monitorings.add_monitoring\", self.user)\n self.client.login(username=\"john\", password=\"pass\")\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"monitorings/monitoring_form.html\")\n\n def test_assign_perm_for_creator(self):\n assign_perm(\"monitorings.add_monitoring\", self.user)\n self.client.login(username=\"john\", password=\"pass\")\n data = EXAMPLE_DATA.copy()\n response = self.client.post(self.get_url(), data=data)\n self.assertEqual(response.status_code, 302)\n monitoring = Monitoring.objects.get(name=\"foo-bar-monitoring\")\n self.assertTrue(self.user.has_perm(\"monitorings.reply\", monitoring))\n\n\nclass MonitoringListViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n status_anonymous = 200\n status_no_permission = 200\n permission = []\n\n def get_url(self):\n return reverse(\"monitorings:list\")\n\n def test_list_display(self):\n response = self.client.get(self.get_url())\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, self.monitoring)\n\n def test_filter_by_voivodship(self):\n self.case = (\n CaseFactory()\n ) # creates a new monitoring (and institution, JST, too)\n\n response = self.client.get(\n reverse(\"monitorings:list\")\n + \"?voivodeship={}\".format(self.case.institution.jst.id)\n )\n self.assertContains(response, self.case.monitoring)\n self.assertNotContains(response, self.monitoring)\n\n\nclass IncomingParcelFactory:\n pass\n\n\nclass MonitoringDetailViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n status_anonymous = 200\n status_no_permission = 200\n permission = []\n\n def get_url(self):\n return self.monitoring.get_absolute_url()\n\n def test_details_display(self):\n response = self.client.get(self.get_url())\n self.assertContains(response, self.monitoring)\n\n def test_display_case(self):\n case = CaseFactory(monitoring=self.monitoring)\n response = self.client.get(self.get_url())\n self.assertContains(response, case)\n\n def test_display_letter(self):\n letter = OutgoingLetterFactory(record__case__monitoring=self.monitoring)\n response = self.client.get(self.get_url())\n self.assertContains(response, letter)\n\n def test_display_parcel(self):\n ipp = IncomingParcelPostFactory(record__case__monitoring=self.monitoring)\n opp = OutgoingParcelPostFactory(record__case__monitoring=self.monitoring)\n response = self.client.get(self.get_url())\n self.assertContains(response, ipp)\n self.assertContains(response, opp)\n\n def test_display_invalid_record(self):\n # see following issues regarding details of source of inconsistency:\n # https://github.com/watchdogpolska/feder/issues/748\n # https://github.com/watchdogpolska/feder/issues/769\n RecordFactory(case__monitoring=self.monitoring)\n response = self.client.get(self.get_url())\n self.assertEqual(response.status_code, 200)\n\n\nclass LetterListMonitoringViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n status_anonymous = 200\n status_no_permission = 200\n permission = []\n\n def get_url(self):\n return reverse(\"monitorings:letters\", kwargs={\"slug\": self.monitoring.slug})\n\n def test_list_display(self):\n response = self.client.get(self.get_url())\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, self.monitoring)\n\n def test_display_letter(self):\n letter = IncomingLetterFactory(record__case__monitoring=self.monitoring)\n response = self.client.get(self.get_url())\n self.assertContains(response, letter.body)\n self.assertContains(response, letter.note)\n\n\nclass DraftListMonitoringViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n status_anonymous = 200\n status_no_permission = 200\n permission = []\n\n def get_url(self):\n return reverse(\"monitorings:drafts\", kwargs={\"slug\": self.monitoring.slug})\n\n def test_list_display(self):\n response = self.client.get(self.get_url())\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, self.monitoring)\n\n def test_hide_draft(self):\n outgoing_letter = OutgoingLetterFactory(\n record__case__monitoring=self.monitoring\n )\n incoming_letter = IncomingLetterFactory(\n record__case__monitoring=self.monitoring\n )\n draft_letter = DraftLetterFactory(record__case__monitoring=self.monitoring)\n response = self.client.get(self.get_url())\n self.assertNotContains(\n response,\n outgoing_letter.body,\n msg_prefix=\"Response contains outgoing letter. \",\n )\n self.assertNotContains(\n response,\n incoming_letter.body,\n msg_prefix=\"Response contains incoming letter. \",\n )\n\n self.assertContains(response, draft_letter.body)\n self.assertContains(response, draft_letter.note)\n\n\nclass MonitoringUpdateViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"monitorings.change_monitoring\"]\n\n def get_url(self):\n return reverse(\"monitorings:update\", kwargs={\"slug\": self.monitoring.slug})\n\n def test_template_used(self):\n assign_perm(\"monitorings.change_monitoring\", self.user, self.monitoring)\n self.client.login(username=\"john\", password=\"pass\")\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"monitorings/monitoring_form.html\")\n\n\nclass MonitoringDeleteViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"monitorings.delete_monitoring\"]\n\n def get_url(self):\n return reverse(\"monitorings:delete\", kwargs={\"slug\": self.monitoring.slug})\n\n def test_template_used(self):\n assign_perm(\"monitorings.delete_monitoring\", self.user, self.monitoring)\n self.client.login(username=\"john\", password=\"pass\")\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"monitorings/monitoring_confirm_delete.html\")\n\n\nclass PermissionWizardTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"monitorings.manage_perm\"]\n\n def get_url(self):\n return reverse(\"monitorings:perm-add\", kwargs={\"slug\": self.monitoring.slug})\n\n def test_template_used(self):\n assign_perm(\"monitorings.manage_perm\", self.user, self.monitoring)\n self.client.login(username=\"john\", password=\"pass\")\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"monitorings/permission_wizard.html\")\n\n def test_set_permissions(self):\n normal_user = UserFactory(username=\"barney\")\n\n assign_perm(\"monitorings.manage_perm\", self.user, self.monitoring)\n self.client.login(username=\"john\", password=\"pass\")\n\n # First step - selecting user to set permissions to\n data = {\"0-user\": normal_user.pk, \"permission_wizard-current_step\": \"0\"}\n response = self.client.post(self.get_url(), data=data)\n self.assertEqual(response.status_code, 200)\n\n # Second step - updating user's permissions\n granted_permission = [\"add_case\", \"add_draft\", \"add_letter\"]\n data = {\n \"1-permissions\": granted_permission,\n \"permission_wizard-current_step\": \"1\",\n }\n response = self.client.post(self.get_url(), data=data)\n self.assertEqual(response.status_code, 302)\n self.assertCountEqual(\n get_user_perms(normal_user, self.monitoring), granted_permission\n )\n\n\nclass MonitoringPermissionViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"monitorings.manage_perm\"]\n\n def get_url(self):\n return reverse(\"monitorings:perm\", kwargs={\"slug\": self.monitoring.slug})\n\n def test_template_used(self):\n assign_perm(\"monitorings.manage_perm\", self.user, self.monitoring)\n self.client.login(username=\"john\", password=\"pass\")\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"monitorings/monitoring_permissions.html\")\n\n\nclass MonitoringUpdatePermissionViewTestCase(\n ObjectMixin, PermissionStatusMixin, TestCase\n):\n permission = [\"monitorings.manage_perm\"]\n\n def get_url(self):\n return reverse(\n \"monitorings:perm-update\",\n kwargs={\"slug\": self.monitoring.slug, \"user_pk\": self.user.pk},\n )\n\n def test_template_used(self):\n self.grant_permission()\n self.client.login(username=\"john\", password=\"pass\")\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"monitorings/monitoring_form.html\")\n\n\nclass MonitoringAssignViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"monitorings.change_monitoring\"]\n\n def get_url(self):\n return reverse(\"monitorings:assign\", kwargs={\"slug\": self.monitoring.slug})\n\n def send_all_pending(self):\n ids = list(\n {\n x\n for x in Case.objects.annotate(count=Count(\"record\"))\n .filter(count=0)\n .all()\n .values_list(\"mass_assign\", flat=True)\n }\n )\n for mass_assign in ids:\n handle_mass_assign.now(str(mass_assign))\n for mass_assign in ids:\n send_letter_for_mass_assign.now(str(mass_assign))\n\n def test_assign_display_institutions(self):\n self.login_permitted_user()\n institution_1 = InstitutionFactory()\n institution_2 = InstitutionFactory()\n response = self.client.get(self.get_url())\n self.assertContains(response, institution_1.name)\n self.assertContains(response, institution_2.name)\n\n def test_send_to_all(self):\n self.login_permitted_user()\n InstitutionFactory(name=\"Office 1\")\n InstitutionFactory(name=\"Office 2\")\n InstitutionFactory()\n self.client.post(self.get_url() + \"?name=Office\", data={\"all\": \"yes\"})\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 2)\n\n def test_force_filtering_before_assign(self):\n self.login_permitted_user()\n InstitutionFactory(name=\"Office 1\")\n InstitutionFactory(name=\"Office 2\")\n InstitutionFactory()\n response = self.client.post(self.get_url(), data={\"all\": \"yes\"})\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 0)\n self.assertRedirects(response, self.get_url())\n\n def test_send_to_selected(self):\n self.login_permitted_user()\n institution_1 = InstitutionFactory(name=\"Office 1\")\n institution_2 = InstitutionFactory(name=\"Office 2\")\n InstitutionFactory()\n to_send_ids = [institution_1.pk, institution_2.pk]\n self.client.post(self.get_url() + \"?name=\", data={\"to_assign\": to_send_ids})\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 2)\n self.assertEqual(mail.outbox[0].to[0], institution_1.email)\n self.assertEqual(mail.outbox[1].to[0], institution_2.email)\n for x in (0, 1):\n self.assertEqual(mail.outbox[x].subject, \"Wniosek\")\n\n def test_update_email_after_send(self):\n self.login_permitted_user()\n institution = InstitutionFactory(name=\"Office 1\")\n to_send_ids = [institution.pk]\n self.client.post(self.get_url() + \"?name=\", data={\"to_assign\": to_send_ids})\n self.send_all_pending()\n case = Case.objects.filter(\n monitoring=self.monitoring, institution=institution\n ).get()\n self.assertTrue(case.email)\n\n def test_constant_increment_local_id(self):\n self.login_permitted_user()\n institution_1 = InstitutionFactory(name=\"Office 1\")\n institution_2 = InstitutionFactory(name=\"Office 2\")\n institution_3 = InstitutionFactory(name=\"Office 3\")\n self.client.post(\n self.get_url() + \"?name=Office\", data={\"to_assign\": [institution_1.pk]}\n )\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 1)\n\n self.assertTrue(\n Case.objects.latest().name.endswith(\" #1\"), msg=Case.objects.latest().name\n )\n\n self.client.post(\n self.get_url() + \"?name=Office\",\n data={\"to_assign\": [institution_2.pk, institution_3.pk]},\n )\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 3)\n self.assertTrue(institution_2.case_set.all()[0].name.endswith(\" #2\"))\n self.assertTrue(institution_3.case_set.all()[0].name.endswith(\" #3\"))\n\n for x in (0, 1, 2):\n self.assertEqual(mail.outbox[x].subject, \"Wniosek\")\n\n @patch(\n \"feder.monitorings.views.MonitoringAssignView.get_limit_simultaneously\",\n Mock(return_value=10),\n )\n def test_limit_number_of_letters_sent_simultaneously(self):\n self.login_permitted_user()\n InstitutionFactory.create_batch(size=25, name=\"Office\")\n\n response = self.client.post(\n self.get_url() + \"?name=Office\", data={\"all\": \"yes\"}\n )\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 0)\n self.assertRedirects(response, self.get_url())\n\n def test_assing_using_custom_domain(self):\n self.monitoring.domain = DomainFactory(name=\"custom-domain.com\")\n self.monitoring.save()\n self.login_permitted_user()\n InstitutionFactory(name=\"Office 1\")\n InstitutionFactory(name=\"Office 2\")\n InstitutionFactory()\n self.client.post(self.get_url() + \"?name=Office\", data={\"all\": \"yes\"})\n self.send_all_pending()\n self.assertEqual(len(mail.outbox), 2)\n self.assertTrue(mail.outbox[0].from_email.endswith(\"custom-domain.com\"))\n\n\nclass SitemapTestCase(ObjectMixin, TestCase):\n def test_monitorings(self):\n url = reverse(\"sitemaps\", kwargs={\"section\": \"monitorings\"})\n needle = reverse(\"monitorings:details\", kwargs={\"slug\": self.monitoring.slug})\n response = self.client.get(url)\n self.assertContains(response, needle)\n\n def test_monitorings_pages(self):\n url = reverse(\"sitemaps\", kwargs={\"section\": \"monitorings_pages\"})\n needle = reverse(\n \"monitorings:details\", kwargs={\"slug\": self.monitoring.slug, \"page\": 1}\n )\n response = self.client.get(url)\n self.assertContains(response, needle)\n","sub_path":"feder/monitorings/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":17560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"131413580","text":"import pytest\n\nfrom lhotse import CutSet\nfrom lhotse.dataset.sampling import BucketingSampler, CutPairsSampler, SingleCutSampler\nfrom lhotse.dataset.transforms import concat_cuts\nfrom lhotse.testing.dummies import DummyManifest, dummy_cut\n\n\n@pytest.fixture\ndef libri_cut_set():\n cs = CutSet.from_json('test/fixtures/libri/cuts.json')\n return CutSet.from_cuts([\n cs[0],\n cs[0].with_id('copy-1'),\n cs[0].with_id('copy-2'),\n cs[0].append(cs[0])\n ])\n\n\ndef test_single_cut_sampler_shuffling():\n # The dummy cuts have a duration of 1 second each\n cut_set = DummyManifest(CutSet, begin_id=0, end_id=100)\n\n sampler = SingleCutSampler(\n cut_set,\n shuffle=True,\n # Set an effective batch size of 10 cuts, as all have 1s duration == 100 frames\n # This way we're testing that it works okay when returning multiple batches in\n # a full epoch.\n max_frames=1000\n )\n sampler_cut_ids = []\n for batch in sampler:\n sampler_cut_ids.extend(batch)\n\n # Invariant 1: we receive the same amount of items in a dataloader epoch as there we in the CutSet\n assert len(sampler_cut_ids) == len(cut_set)\n # Invariant 2: the items are not duplicated\n assert len(set(sampler_cut_ids)) == len(sampler_cut_ids)\n # Invariant 3: the items are shuffled, i.e. the order is different than that in the CutSet\n assert sampler_cut_ids != [c.id for c in cut_set]\n\n\ndef test_single_cut_sampler_low_max_frames(libri_cut_set):\n sampler = SingleCutSampler(libri_cut_set, shuffle=False, max_frames=2)\n # Check that it does not crash\n for batch in sampler:\n # There will be only a single item in each batch as we're exceeding the limit each time.\n assert len(batch) == 1\n\n\ndef test_cut_pairs_sampler():\n # The dummy cuts have a duration of 1 second each\n cut_set = DummyManifest(CutSet, begin_id=0, end_id=100)\n\n sampler = CutPairsSampler(\n source_cuts=cut_set,\n target_cuts=cut_set,\n shuffle=True,\n # Set an effective batch size of 10 cuts, as all have 1s duration == 100 frames\n # This way we're testing that it works okay when returning multiple batches in\n # a full epoch.\n max_source_frames=1000,\n max_target_frames=500,\n )\n sampler_cut_ids = []\n for batch in sampler:\n sampler_cut_ids.extend(batch)\n\n # Invariant 1: we receive the same amount of items in a dataloader epoch as there we in the CutSet\n assert len(sampler_cut_ids) == len(cut_set)\n # Invariant 2: the items are not duplicated\n assert len(set(sampler_cut_ids)) == len(sampler_cut_ids)\n # Invariant 3: the items are shuffled, i.e. the order is different than that in the CutSet\n assert sampler_cut_ids != [c.id for c in cut_set]\n\n\ndef test_concat_cuts():\n cuts = [\n dummy_cut(0, duration=30.0),\n dummy_cut(1, duration=20.0),\n dummy_cut(2, duration=10.0),\n dummy_cut(3, duration=5.0),\n dummy_cut(4, duration=4.0),\n dummy_cut(5, duration=3.0),\n dummy_cut(6, duration=2.0),\n ]\n concat = concat_cuts(cuts, gap=1.0)\n assert [c.duration for c in concat] == [\n 30.0,\n 20.0 + 1.0 + 2.0 + 1.0 + 3.0, # == 27.0\n 10.0 + 1.0 + 4.0 + 1.0 + 5.0, # == 21.0\n ]\n\n\ndef test_bucketing_sampler_single_cuts():\n cut_set = DummyManifest(CutSet, begin_id=0, end_id=1000)\n sampler = BucketingSampler(cut_set, sampler_type=SingleCutSampler)\n cut_ids = []\n for batch in sampler:\n cut_ids.extend(batch)\n assert set(cut_set.ids) == set(cut_ids)\n\n\ndef test_bucketing_sampler_shuffle():\n cut_set = DummyManifest(CutSet, begin_id=0, end_id=10)\n sampler = BucketingSampler(cut_set, sampler_type=SingleCutSampler, shuffle=True, num_buckets=2, max_frames=200)\n\n sampler.set_epoch(0)\n batches_ep0 = []\n for batch in sampler:\n # Convert List[str] to Tuple[str, ...] so that it's hashable\n batches_ep0.append(tuple(batch))\n assert set(cut_set.ids) == set(cid for batch in batches_ep0 for cid in batch)\n\n sampler.set_epoch(1)\n batches_ep1 = []\n for batch in sampler:\n batches_ep1.append(tuple(batch))\n assert set(cut_set.ids) == set(cid for batch in batches_ep1 for cid in batch)\n\n # BucketingSampler ordering may be different in different epochs (=> use set() to make it irrelevant)\n # Internal sampler (SingleCutSampler) ordering should be different in different epochs\n assert set(batches_ep0) != set(batches_ep1)\n\n\ndef test_bucketing_sampler_cut_pairs():\n cut_set1 = DummyManifest(CutSet, begin_id=0, end_id=1000)\n cut_set2 = DummyManifest(CutSet, begin_id=0, end_id=1000)\n sampler = BucketingSampler(cut_set1, cut_set2, sampler_type=CutPairsSampler)\n\n cut_ids = []\n for batch in sampler:\n cut_ids.extend(batch)\n assert set(cut_set1.ids) == set(cut_ids)\n assert set(cut_set2.ids) == set(cut_ids)\n\n\ndef test_bucketing_sampler_buckets_have_different_durations():\n cut_set_1s = DummyManifest(CutSet, begin_id=0, end_id=10)\n cut_set_2s = DummyManifest(CutSet, begin_id=10, end_id=20)\n for c in cut_set_2s:\n c.duration = 2.0\n cut_set = cut_set_1s + cut_set_2s\n\n # The bucketing sampler should return 5 batches with two 1s cuts, and 10 batches with one 2s cut.\n sampler = BucketingSampler(\n cut_set,\n sampler_type=SingleCutSampler,\n max_frames=200,\n num_buckets=2\n )\n batches = list(sampler)\n assert len(batches) == 15\n\n # All cuts have the same durations (i.e. are from the same bucket in this case)\n for batch in batches:\n batch_durs = [cut_set[cid].duration for cid in batch]\n assert all(d == batch_durs[0] for d in batch_durs)\n\n batches = sorted(batches, key=len)\n assert all(len(b) == 1 for b in batches[:10])\n assert all(len(b) == 2 for b in batches[10:])\n","sub_path":"test/dataset/test_sampling.py","file_name":"test_sampling.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504558216","text":"import math\n\ndef rpy2rv(roll,pitch,yaw):\n\n alpha = yaw\n\n beta = pitch\n\n gamma = roll\n\n\n ca = math.cos(alpha)\n\n cb = math.cos(beta)\n\n cg = math.cos(gamma)\n\n sa = math.sin(alpha)\n\n sb = math.sin(beta)\n\n sg = math.sin(gamma)\n\n \n\n r11 = ca*cb\n\n r12 = ca*sb*sg-sa*cg\n\n r13 = ca*sb*cg+sa*sg\n\n r21 = sa*cb\n\n r22 = sa*sb*sg+ca*cg\n\n r23 = sa*sb*cg-ca*sg\n\n r31 = -sb\n\n r32 = cb*sg\n\n r33 = cb*cg\n\n \n\n theta = math.acos((r11+r22+r33-1)/2)\n\n sth = math.sin(theta)\n\n kx = (r32-r23)/(2*sth)\n\n ky = (r13-r31)/(2*sth)\n\n kz = (r21-r12)/(2*sth)\n\n \n\n return [(theta*kx),(theta*ky),(theta*kz)]\n\n end\n\n \n\ndef rv2rpy(rx,ry,rz):\n\n #\n\n theta = math.sqrt(rx*rx + ry*ry + rz*rz)\n\n kx = rx/theta\n\n ky = ry/theta\n\n kz = rz/theta\n\n cth = math.cos(theta)\n\n sth = math.sin(theta)\n\n vth = 1-math.cos(theta)\n\n \n\n r11 = kx*kx*vth + cth\n\n r12 = kx*ky*vth - kz*sth\n\n r13 = kx*kz*vth + ky*sth\n\n r21 = kx*ky*vth + kz*sth\n\n r22 = ky*ky*vth + cth\n\n r23 = ky*kz*vth - kx*sth\n\n r31 = kx*kz*vth - ky*sth\n\n r32 = ky*kz*vth + kx*sth\n\n r33 = kz*kz*vth + cth\n\n \n\n beta = math.atan2(-r31,math.sqrt(r11*r11+r21*r21))\n\n \n\n if beta > math.radians(89.99):\n\n beta = math.radians(89.99)\n\n alpha = 0\n\n gamma = math.atan2(r12,r22)\n\n elif beta < -math.radians(89.99):\n\n beta = -math.radians(89.99)\n\n alpha = 0\n\n gamma = -math.atan2(r12,r22)\n\n else:\n\n cb = math.cos(beta)\n\n alpha = math.atan2(r21/cb,r11/cb)\n\n gamma = math.atan2(r32/cb,r33/cb)\n\n\n \n\n return [gamma,beta,alpha]\n\n\n\n\n\n\n\n\n\n\nprint(rpy2rv(3.1166, 0.0250, -3.1411))\nprint(rv2rpy(-0.0012544807064647876, 3.1163570520210695, 0.038954640875551304))","sub_path":"Robotics/rotation_vector_conversion.py","file_name":"rotation_vector_conversion.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587604993","text":"from bs4 import BeautifulSoup\n\nhtml = \"\"\"\n \n \n \n \n \n \n \n \n \n \n
100200
300400
\n \n\"\"\"\n\nbs_obj = BeautifulSoup(html,\"html.parser\")\n\n#100\ntd_first = bs_obj.find(\"td\",{\"class\",\"first\"})\n#print(td_first)\n\n#200\ntable = bs_obj.find(\"table\")\ntr = bs_obj.find(\"tr\")\ntds = tr.findAll(\"td\")\n#print(tds[1].text)\n\n#300\ntable = bs_obj.find(\"table\")\ntrs = bs_obj.findAll(\"tr\")\ntds = trs[1].findAll(\"td\")\nprint(tds[0].text)\n","sub_path":"python_crawler_example_01/com/18_pr_findAll.py","file_name":"18_pr_findAll.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"575216280","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/9\n# @Author : CHEN Li and ZENG Yanru\n# @Email : 595438103@qq.com\n# @File : SumobindingModel.py\n# @Software: PyCharm\nimport tensorflow as tf\nimport math\nimport numpy as np\nfrom sklearn import metrics\nimport copy\n\n\nclass CNN_SUMO:\n def __init__(self, all_id=None ,input_data=None,input_target=None,valid_data=None,valid_target=None,keep_prob=0.7,\n bp_num=1, model_mode='train',mode='onehot',batch_size=20,epochs=100,learning_rate=0.01,\n model_path=None,model_name=\"model\",display_step=10,early_stop_thresh=0.000001,verbose=True,train_length=5):\n self.bp_num = bp_num # unknown parameters\n self.epochs = epochs\n self.learning_rate = learning_rate\n self.beta = 0.0001 # didn't use\n self.batch_size = batch_size\n self.all_id=all_id # of same length of input_data, mapping exactly to the input data's protein\n self.est = early_stop_thresh\n\n self.keep_prob_rate = keep_prob\n self.train_data= input_data\n self.train_target = input_target # this will be leave as None if the model mode is \"predict\"\n self.valid_data = valid_data # surveilance on the performance of model on each display step\n self.valid_target = valid_target\n\n self.dim = (train_length * 2 + 5) * 21\n self.dim2 = 30\n\n # well there will be a situation like this: we don't input train data\n if self.train_data is None:\n self.train_data = np.zeros([1, self.dim+self.dim2])\n # self.train_data = np.zeros([1, self.dim3])\n self.train_target = np.zeros([1,2])\n self.train_data_target = np.hstack([self.train_data,self.train_target])\n\n\n self.Size = self.train_data.shape # the shape of input data\n self.sample_num, self.dim_all = self.Size[0], int(self.Size[1] / self.bp_num)\n # if mode == 'onehot': # though we don't know what will be else, we leave it here in case there is some correction in the future\n self.total_dim = int(self.Size[1] / self.bp_num)\n\n self.train_data_target_cp = copy.deepcopy(self.train_data_target)\n self.pos_train = self.train_data_target_cp[np.where(self.train_data_target_cp[:, -2] == 1), :].reshape(-1,\n self.dim_all + 2)\n self.neg_train = self.train_data_target_cp[np.where(self.train_data_target_cp[:, -2] == 1), :].reshape(-1,\n self.dim_all + 2)\n\n\n\n self.onehot = self.train_data[:,0:self.dim]\n self.knn = self.train_data[:,self.dim:self.dim + self.dim2]\n\n self.epoch_train_err, self.epoch_valid_err = [], []\n\n self.model_mode = model_mode # to train or to predict new data from saved model\n self.test_outs = None\n self.model_path = model_path\n self.sess = None\n self.display_step = display_step # show result at each display_step when training model\n\n # all placeholders we need\n self.xs = tf.placeholder(tf.float32, [None, self.bp_num * self.dim], name=\"xs\") # onehot\n self.ys = tf.placeholder(tf.float32, [None, 2], name=\"ys\")\n self.xs2 = tf.placeholder(tf.float32, [None, self.bp_num * self.dim2], name=\"xs2\") # knn\n self.keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n\n # whether to show details of training process\n self.verbose = verbose\n self.model_name = model_name\n\n def model_initialize(self): # TODO: this function is redundant! we will delete it later\n self.model = self.conf_model()\n self.config_trainer()\n # return # actually we don't need to return anything\n\n def pick_batch(self,iteration,batch_data,rs_shape=False,new_shape=None):\n # inorder to calculate loss or for other purposes, rs_shape means whether we need to reshape the output\n # if true, then we need to set new_shape to a list of shape\n begin = iteration * self.batch_size\n end = (iteration+1) * self.batch_size\n if end >= self.sample_num:\n end = self.sample_num - 1\n if rs_shape is False:\n return batch_data[begin:end]\n else:\n return batch_data[begin:end].reshape(new_shape)\n\n def pick_batch_reg(self,iteration,batch_data,extra_pos,extra_neg,rs_shape=False,new_shape=None,balace_sp=False,close_ratio=1):\n # inorder to calculate loss or for other purposes, rs_shape means whether we need to reshape the output\n # if true, then we need to set new_shape to a list of shape\n # batch_data means something different from that of the above function. It contains both X and Y\n # close ratio is the ratio pos:neg that we want to pick\n begin = iteration * self.batch_size\n end = (iteration+1) * self.batch_size\n if end >= self.sample_num:\n end = self.sample_num - 1\n if rs_shape is False:\n x = batch_data[begin:end,0:self.dim_all]\n y = batch_data[begin:end,self.dim_all:]\n else:\n x = batch_data[begin:end,0:self.dim_all].reshape(new_shape)\n y = batch_data[begin:end,self.dim_all:]\n if balace_sp is False:\n pos_sp = list(y[:,0]).count(1)\n neg_sp = len(y[:,0]) - pos_sp\n # dif_pn = abs(pos_sp - neg_sp)\n if pos_sp < neg_sp:\n extra_pick = extra_pos\n dif_pn = int(neg_sp * close_ratio - pos_sp) # to construct a sample with specific combination of pos and neg samples\n else:\n extra_pick = extra_neg\n dif_pn = int(pos_sp * close_ratio - neg_sp)\n if dif_pn > 0:\n np.random.shuffle(extra_pick)\n more_x,more_y = extra_pick[0:dif_pn,0:self.dim_all],extra_pick[0:dif_pn,self.dim_all:]\n x = np.vstack([x,more_x])\n y = np.vstack([y,more_y])\n return x, y\n else:\n return x, y\n\n def conf_model(self):\n x_matrix = tf.reshape(self.xs,[-1,int(self.dim/21),21]) # dim/21 * 21(row * col)\n x_matrix = tf.transpose(x_matrix,perm=[0,2,1])\n x_matrix = tf.reshape(x_matrix, [-1, int(self.bp_num * 21), int(self.dim / 21), 1]) # 21 * dim/21 (row * col)\n\n x_matrix2 = tf.reshape(self.xs2, [-1, self.bp_num, self.dim2, 1]) # original knn sequence, like a bargraph in the meaning of a graph\n\n # TODO: change strides or filters length (in col axis) to fit a better model\n # onehot\n hidden_conv1 = tf.layers.conv2d(inputs=x_matrix,filters=8,kernel_size=[21,5],strides=[self.bp_num*21,1],padding=\"same\",\n activation=tf.nn.relu) # kernel_regularizer=tf.contrib.layers.l2_regularizer(0.0001)\n pool_conv2 = self.max_pool(inputs=hidden_conv1, ksize=[1, 1, 2, 1], strides=[1, 1, 2, 1])\n\n hidden_conv2 = tf.layers.conv2d(inputs=pool_conv2, filters=16, kernel_size=[1, 3], strides=[1, 1],\n padding=\"same\", activation=tf.nn.relu)\n pool_conv2 = self.max_pool(inputs=hidden_conv2, ksize=[1, 1, 2, 1], strides=[1, 1, 2, 1])\n\n # knn\n hidden_conv21 = tf.layers.conv2d(inputs=x_matrix2, filters=8, kernel_size=[1, 3], strides=[1, 1],\n padding=\"same\", activation=tf.nn.relu,\n kernel_regularizer=tf.contrib.layers.l2_regularizer(0.0001))\n pool_conv21 = self.max_pool(inputs=hidden_conv21, ksize=[1, 1, 2, 1], strides=[1, 1, 2, 1])\n\n conv_all = tf.reshape(pool_conv2, [-1, pool_conv2.shape[1]*pool_conv2.shape[2]*pool_conv2.shape[3]])\n conv_all2 = tf.reshape(pool_conv21, [-1, pool_conv21.shape[1]*pool_conv21.shape[2]*pool_conv21.shape[3]])\n ################ zyr added in 190604, just try to get a better model ###########\n h_fc_drop = tf.concat([conv_all,conv_all2],1)\n ##############################################################\n # fully connected network\n first_unit = int((self.dim/21+self.dim2))\n second_unit = int(first_unit/4)\n\n fc4 = tf.layers.dense(inputs=h_fc_drop, units=first_unit, activation=tf.nn.relu,kernel_regularizer=tf.contrib.layers.l2_regularizer(0.0001)) # fully-connection can be more precise\n h_fc1_drop2 = tf.nn.dropout(fc4, self.keep_prob)\n\n fc4 = tf.layers.dense(inputs=h_fc1_drop2, units=second_unit, activation=tf.nn.relu)\n\n model = tf.layers.dense(inputs=fc4, units=2, activation=tf.nn.softmax)\n\n return model\n\n\n def run(self): # train model and output a sess or make sess an attribute\n # model, loss and optimizer\n model = tf.reshape(self.conf_model(), [-1, 2], name=\"model_output\")\n lossFunc = -tf.reduce_mean(self.ys * tf.log(model))\n optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(lossFunc)\n\n # begin running or the so call training\n sess = tf.Session()\n # TODO:if it doesn't succeed, drop the following codes\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n sess.run(tf.global_variables_initializer())\n\n total_batch = int(self.sample_num / self.batch_size)\n\n prev_c = 0\n best_val_auc = 0\n best_train_auc = 0\n for epochs in range(self.epochs):\n for i in range(total_batch):\n batch_xs = self.pick_batch(i,batch_data=self.train_data)\n batch_ys = self.pick_batch(i,batch_data=self.train_target)\n # batch_xs,batch_ys = self.pick_batch_reg(i,batch_data=self.train_data_target,extra_pos=self.pos_train,extra_neg=self.neg_train,close_ratio=1)\n train_data1 = batch_xs[:,0:self.dim]\n train_data2 = batch_xs[:,self.dim:(self.dim+self.dim2)]\n\n _, c = sess.run([optimizer, lossFunc], feed_dict={self.xs:train_data1,self.xs2:train_data2,\n self.ys: batch_ys,self.keep_prob: self.keep_prob_rate})\n if epochs % self.display_step == 0:\n # print(\"Epoch: %d\" % (epochs + 1), \"cost=\", \"{:.9f}\".format(c))\n self.sess = sess\n if self.verbose is True:\n if self.valid_data is not None and self.valid_target is not None:\n vd1,vd2 = self.valid_data[:,0:self.dim], self.valid_data[:,self.dim:(self.dim2+self.dim)] # self.valid_data[:,(self.dim2+self.dim):(self.dim2+self.dim+self.dim3)]\n # vd1,vd2 = self.valid_data[:,0:self.dim],self.valid_data[:,self.dim:(self.dim2+self.dim)]\n pred = sess.run(model,feed_dict={self.xs:vd1,self.xs2:vd2,self.keep_prob:self.keep_prob_rate})\n # pred = sess.run(model, feed_dict={self.xs:vd1,self.xs2:vd2, self.keep_prob: self.keep_prob_rate})\n pred_train = sess.run(model,feed_dict={self.xs:self.onehot,self.xs2:self.knn,self.keep_prob:self.keep_prob_rate})\n loss = -np.mean(self.valid_target * np.log(pred))\n print(\"Epoch: %d\" % (epochs + 1), \"cost=\", \"{:.9f}\".format(c),\", Valid Data Loss:\",\"{:.9f}\".format(loss))\n AUC_valid = self.GetAUCFromPredAndActual(self.valid_target,pred)\n AUC_train = self.GetAUCFromPredAndActual(self.train_target,pred_train)\n if AUC_valid > best_val_auc:\n best_val_auc = AUC_valid\n self.restore_model(path=self.model_path,modelname=self.model_name) # save model in every display_step\n print(\"AUC of validation data is:\",AUC_valid,\"and of training data is:\",AUC_train)\n else:\n print(\"Epoch: %d\" % (epochs + 1), \"cost=\", \"{:.9f}\".format(c))\n else: # save the model with best auc in training data\n pred_train = sess.run(model, feed_dict={self.xs: self.onehot,self.xs2:self.knn,\n self.keep_prob: self.keep_prob_rate})\n AUC_train = self.GetAUCFromPredAndActual(self.train_target, pred_train)\n if best_val_auc < AUC_train:\n self.restore_model(path=self.model_path,modelname=self.model_name) # save model in every display_step\n\n if abs(prev_c-c) <= self.est:\n break\n print(\"Optimization Finished!\")\n\n # inheritage the info above\n coord.request_stop()\n coord.join(threads=threads)\n\n def restore_model(self, path=None,modelname=None):\n # path should contains os.sep in the end of the string\n self.saver = tf.train.Saver(save_relative_paths=True)\n if path is None:\n path = self.model_path\n if modelname is None:\n modelname = self.model_name\n if self.model_mode != \"train\":\n # self.saver.restore(self.sess, PATH+\"model.ckpt\") # TODO: high chance to change ckpt into meta\n self.saver.restore(self.sess, path + modelname + \".meta\") # actually this sentence if of no use or it is useless\n else:\n self.saver.save(self.sess, path + modelname)\n\n def predict(self,other_data=None,model_path=None,modelname=None):\n tf.reset_default_graph() # in case newly input graph contaminates the last one\n if model_path is None:\n model_path = self.model_path\n if other_data is None:\n other_data = self.train_data\n # divide other data into three part\n onehot_data = other_data[:,0:self.dim]\n knn_data = other_data[:,self.dim:(self.dim+self.dim2)]\n\n if modelname is None:\n modelname = \"model\"\n\n # get saved sess and predict\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n new_saver = tf.train.import_meta_graph(model_path + modelname + \".meta\")\n new_saver.restore(sess, tf.train.latest_checkpoint(model_path))\n # new_saver.restore(sess, save_path=model_path)\n graph = tf.get_default_graph()\n xs = graph.get_tensor_by_name(\"xs:0\")\n xs2 = graph.get_tensor_by_name(\"xs2:0\")\n keep_prob = graph.get_tensor_by_name(\"keep_prob:0\")\n model_out = graph.get_tensor_by_name(\"model_output:0\")\n\n pred = sess.run([model_out], feed_dict={xs:onehot_data,xs2:knn_data,keep_prob: self.keep_prob_rate})\n return pred[0]\n\n\n def GetAUCFromPredAndActual(self,true_label,pred_score):\n # presume that both label and pred score are 2 dimension\n try:\n pred_score = [i[0] for i in pred_score]\n except:\n pred_score = pred_score\n true_score = [i[0] for i in true_label]\n AUC = metrics.roc_auc_score(y_true=true_score, y_score=pred_score)\n return AUC\n\n def GetStatisticPred(self,pred,y_new,cutoff=0.5):\n ppn = []\n for i in pred:\n if isinstance(i,float) or isinstance(i,int):\n i = [i,0.5]\n if i[0] >= cutoff:\n ppn.append(1)\n else:\n ppn.append(0)\n tp, tn, fp, fn = 0, 0, 0, 0\n for idx, j in enumerate(ppn):\n if j == 1 and y_new[idx][0] == 1:\n tp += 1\n elif j == 1 and y_new[idx][0] == 0:\n fp += 1\n elif j == 0 and y_new[idx][0] == 0:\n tn += 1\n elif j == 0 and y_new[idx][0] == 1:\n fn += 1\n ac = (tp + tn) / (tp + tn + fp + fn)\n sn = tp / (tp + fn)\n sp = tn / (tn + fp)\n mcc = (tp * tn - fp * fn) / (((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) ** 0.5)\n print(\"ac,sn,sp,mcc,tp,fp,tn,fn:\",ac, sn, sp, mcc,tp,fp,tn,fn)\n\n def filter_variable(self, shape):\n initial = tf.truncated_normal(shape=shape, stddev=0.1)\n return tf.Variable(initial)\n\n def bias_variable(self, shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n def conv2d(self, inputs, filter, strides):\n return tf.nn.conv2d(inputs, filter=filter, strides=strides, padding='SAME')\n\n def max_pool(self, inputs, ksize, strides):\n return tf.nn.max_pool(value=inputs, ksize=ksize, strides=strides, padding='SAME')\n\n def relu(self, inputs):\n return tf.nn.relu(inputs)","sub_path":"SumobindingModel.py","file_name":"SumobindingModel.py","file_ext":"py","file_size_in_byte":16589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"616134809","text":"#1723682\n#David van Vliet\n\n#Het textbestand openen in leesmodus en alle regels lezen\ninfile = open('kaartnummers.txt', 'r')\nlijst = infile.readlines()\nkaartnummer_lijst = []\n\n#De getallen splitsen met een , om hier aparte nummers van te maken\nfor nummer in lijst:\n getal = nummer.split(',')\n kaartnummer_lijst.append(int(getal[0]))\n\n#De hoogste en lengte uitrekenen\nhoogste = max(kaartnummer_lijst)\n\nregels = len(lijst)\n\n\nprint(\"Deze file telt\", regels, \"regels.\")\nprint(\"Het grootste kaartnummer is:\", hoogste, \"en dat staat op regel\", kaartnummer_lijst.index(hoogste) + 1)\n\n","sub_path":"Python/les5/pe5_3.py","file_name":"pe5_3.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"620016709","text":"\nimport numpy as np\nimport tensorflow as tf\nimport kaleido as kld\n\n##### TRAINERBASE\nclass TrainerBase( kld.Algorithm ):\n\n ### __INIT__\n def __init__( self , args ):\n self.preInit()\n\n self.args = args\n self.sess = tf.Session()\n self.load_network()\n\n args.image_style = kld.prepare_image_dict( args.image_style )\n args.image_content = kld.prepare_image_dict( args.image_content )\n\n self.ysL = self.load_image( args.style_dir , args.image_style )\n self.ycL = kld.get_dir_files( args.content_dir )\n args.num_iters = len( self.ycL ) // args.batch_size\n\n self.style_layers = kld.ordered_sorted_dict( args.style_layer_ids )\n self.content_layers = kld.ordered_sorted_dict( args.content_layer_ids )\n\n self.build( args )\n self.train( args )\n\n ### TRAIN\n def train( self , args ):\n self.preTrain()\n\n trainable_variables = tf.trainable_variables()\n grads = tf.gradients( self.L_full , trainable_variables )\n\n self.lr = kld.plchf( None , 'learn_rate' )\n optimizer = tf.train.AdamOptimizer( self.lr )\n optim = optimizer.apply_gradients( zip( grads , trainable_variables ) )\n\n yc = np.zeros( [ args.batch_size ] + args.image_content['shape'] , dtype = np.float32 )\n\n epoch = self.load_model()\n for epoch in range( epoch , args.num_epochs ):\n\n kld.shuffle_list( self.ysL )\n kld.shuffle_list( self.ycL )\n lr = self.calc_learn_rate( epoch )\n\n# for iter in range( args.num_iters ):\n for iter in range( int( args.num_iters / 2 ) ):\n\n curr , last = self.next_idxs( iter )\n for j , path in enumerate( self.ycL[ curr:last ] ):\n yc[j] = self.load_image( path , args.image_content )\n ys = self.ysL[ iter % len( self.ysL ) ]\n\n pars_dict = {}\n pars = self.sess.run( args.net.pars_calc , feed_dict = { self.yc : yc } )\n for i in range( len( pars ) ): pars_dict[ args.net.pars_eval[i] ] = pars[i]\n self.sess.run( [ optim ] ,\n feed_dict = { **{ self.yc : yc , self.ys : ys ,\n self.lr : lr } , **pars_dict } )\n\n# self.sess.run( [ optim ] ,\n# feed_dict = { self.yc : yc , self.ys : ys ,\n# self.lr : lr } )\n\n if self.time_to_eval( iter ):\n L_full , L_style , L_content , L_totvar = self.sess.run(\n [ self.L_full , self.L_style , self.L_content , self.L_totvar ] ,\n feed_dict = { **{ self.yc : yc , self.ys : ys } , **pars_dict } )\n self.print_counters( epoch , iter )\n print( '|| L_full : %3.5e | L_style : %3.5e | L_content : %3.5e | L_totvar : %3.5e' %\n ( L_full , L_style , L_content , L_totvar ) , end = '' )\n self.values.append( [ epoch , iter , L_full , L_style , L_content , L_totvar ] )\n self.print_time( epoch , iter )\n\n self.save_model()\n\n","sub_path":"style/ZZZ/fst/code/trainers/trainer2.py","file_name":"trainer2.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"31939423","text":"# Data Parallel Control (dpctl)\n#\n# Copyright 2020-2021 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Defines unit test cases for the SyclQueueManager class.\n\"\"\"\n\nimport unittest\n\nimport dpctl\n\nfrom ._helper import has_cpu, has_gpu, has_sycl_platforms\n\n\n@unittest.skipIf(not has_sycl_platforms(), \"No SYCL platforms available\")\nclass TestIsInDeviceContext(unittest.TestCase):\n def test_is_in_device_context_outside_device_ctxt(self):\n self.assertFalse(dpctl.is_in_device_context())\n\n @unittest.skipUnless(has_gpu(), \"No OpenCL GPU queues available\")\n def test_is_in_device_context_inside_device_ctxt(self):\n with dpctl.device_context(\"opencl:gpu:0\"):\n self.assertTrue(dpctl.is_in_device_context())\n\n @unittest.skipUnless(has_gpu(), \"No OpenCL GPU queues available\")\n @unittest.skipUnless(has_cpu(), \"No OpenCL CPU queues available\")\n def test_is_in_device_context_inside_nested_device_ctxt(self):\n with dpctl.device_context(\"opencl:cpu:0\"):\n with dpctl.device_context(\"opencl:gpu:0\"):\n self.assertTrue(dpctl.is_in_device_context())\n self.assertTrue(dpctl.is_in_device_context())\n self.assertFalse(dpctl.is_in_device_context())\n\n\n@unittest.skipIf(not has_sycl_platforms(), \"No SYCL platforms available\")\n@unittest.skipUnless(has_gpu(), \"No OpenCL GPU queues available\")\nclass TestGetCurrentDevice(unittest.TestCase):\n def test_get_current_device_type_outside_device_ctxt(self):\n self.assertNotEqual(dpctl.get_current_device_type(), None)\n\n def test_get_current_device_type_inside_device_ctxt(self):\n self.assertNotEqual(dpctl.get_current_device_type(), None)\n\n with dpctl.device_context(\"opencl:gpu:0\"):\n self.assertEqual(\n dpctl.get_current_device_type(), dpctl.device_type.gpu\n )\n\n self.assertNotEqual(dpctl.get_current_device_type(), None)\n\n @unittest.skipUnless(has_cpu(), \"No OpenCL CPU queues available\")\n def test_get_current_device_type_inside_nested_device_ctxt(self):\n self.assertNotEqual(dpctl.get_current_device_type(), None)\n\n with dpctl.device_context(\"opencl:cpu:0\"):\n self.assertEqual(\n dpctl.get_current_device_type(), dpctl.device_type.cpu\n )\n\n with dpctl.device_context(\"opencl:gpu:0\"):\n self.assertEqual(\n dpctl.get_current_device_type(), dpctl.device_type.gpu\n )\n self.assertEqual(\n dpctl.get_current_device_type(), dpctl.device_type.cpu\n )\n\n self.assertNotEqual(dpctl.get_current_device_type(), None)\n\n\n@unittest.skipIf(not has_sycl_platforms(), \"No SYCL platforms available\")\nclass TestGetCurrentQueueInMultipleThreads(unittest.TestCase):\n def test_num_current_queues_outside_with_clause(self):\n self.assertEqual(dpctl.get_num_activated_queues(), 0)\n\n @unittest.skipUnless(has_gpu(), \"No OpenCL GPU queues available\")\n @unittest.skipUnless(has_cpu(), \"No OpenCL CPU queues available\")\n def test_num_current_queues_inside_with_clause(self):\n with dpctl.device_context(\"opencl:cpu:0\"):\n self.assertEqual(dpctl.get_num_activated_queues(), 1)\n with dpctl.device_context(\"opencl:gpu:0\"):\n self.assertEqual(dpctl.get_num_activated_queues(), 2)\n self.assertEqual(dpctl.get_num_activated_queues(), 0)\n\n @unittest.skipUnless(has_gpu(), \"No OpenCL GPU queues available\")\n @unittest.skipUnless(has_cpu(), \"No OpenCL CPU queues available\")\n def test_num_current_queues_inside_threads(self):\n from threading import Thread\n\n def SessionThread(self):\n self.assertEqual(dpctl.get_num_activated_queues(), 0)\n with dpctl.device_context(\"opencl:gpu:0\"):\n self.assertEqual(dpctl.get_num_activated_queues(), 1)\n\n Session1 = Thread(target=SessionThread(self))\n Session2 = Thread(target=SessionThread(self))\n with dpctl.device_context(\"opencl:cpu:0\"):\n self.assertEqual(dpctl.get_num_activated_queues(), 1)\n Session1.start()\n Session2.start()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"dpctl/tests/test_sycl_queue_manager.py","file_name":"test_sycl_queue_manager.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636521833","text":"import requests\nimport json\nimport time\nimport logging\n\nclass JudgeBase:\n \"\"\"\n JudgeMethod base class , implement judge method\n All of subclass only accept two parameters\n \"\"\"\n\n def judge(self, post):\n pass\n\n\nclass WordsBag(JudgeBase):\n \"\"\"\n Read word from file and detect if word is in post\n \"\"\"\n\n def judge(self, post):\n wordbag = []\n with open('wordsbag.txt') as f:\n wordbag = f.read().split()\n\n content = post.get_title() + post.get_content()\n\n for word in wordbag:\n if word in content:\n return True\n return False\n\n\nclass TxnlpTextJudge(JudgeBase):\n \"\"\"\n Text emotion analyze provided by Tencent\n Page:http://nlp.qq.com/semantic.cgi#page4\n \"\"\"\n\n def judge(self, post):\n url = \"http://nlp.qq.com/public/wenzhi/api/common_api.php\"\n body = {'url_path': 'http://10.209.0.215:55000/text/sentiment',\n 'body_data': \"\"}\n\n logging.info(\"Judging {0} {1}\".format(post.get_title(), post.get_content()))\n\n content = json.dumps({'content': post.get_title() + post.get_content()})\n body['body_data'] = content\n\n response = requests.post(url, data=body).json()\n\n time.sleep(1)\n\n return response['negative'] > 0.75\n\n\nif __name__ == \"__main__\":\n title = '求送'\n","sub_path":"judgemethods.py","file_name":"judgemethods.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"262086523","text":"# _*_ coding:utf-8 _*_\nimport os\nimport sys\nimport socket\nimport threading\nBASE_DIR = os.path.dirname(os.path.dirname(__file__)).replace('/', '\\\\')\nsys.path.append(BASE_DIR)\nimport config.setting as config\nfrom core.command import Command\n\n\nclass Connect(object):\n\n def __init__(self, addr, port, listen):\n self.addr = addr\n self.port = port\n self.listen = listen\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server.bind((self.addr, self.port))\n self.server.listen(self.listen)\n\n def link(self):\n print(\"Accept new connection from %s:%s \" % self.addr)\n self.conn.send(b'Welcome!')\n c = Command()\n chroot_path = self.conn.recv(1024)\n os.chdir(chroot_path)\n try:\n while True:\n cmd = self.conn.recv(1024)\n if not cmd: continue\n if cmd.decode('utf-8') == 'exit': break\n cmd_list = cmd.decode().strip().split(' ')\n if hasattr(c, cmd_list[0]):\n cmd_res = getattr(c, cmd_list[0])(cmd_list, self.conn)\n else:\n msg = \"cmd error\"\n self.conn.send(msg.encode())\n self.conn.close()\n print(\"Connection from %s:%s closed.\" % self.addr)\n except ConnectionResetError:\n self.conn.close()\n print(\"Connection from %s:%s closed.\" % self.addr)\n\n def init_connect(self):\n while True:\n self.conn, self.addr = self.server.accept()\n t = threading.Thread(target=self.link)\n t.start()","sub_path":"learning/stage3/ftp/core/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627488636","text":"import random\n\nclass Carreer:\n def __init__(self, name, home_territory):\n self.name = name\n self.home = home_territory\n self.territories = set()\n self.__front_lines = set()\n\n @property\n def front_lines(self):\n for territory in self.territories:\n for neighbor_territory in territory.neighbors:\n if neighbor_territory.carrer != self:\n self.__front_lines.add(territory)\n break\n return self.__front_lines\n\n def choose_opponent(self):\n territory = random.sample(self.front_lines)\n return random.sample(filter(lambda x : x.carreer != self\n , territory.neighbors))\n\n def attack(self, territory):\n territory.carreer.territories.remove(territory)\n territory.carreer = self\n self.territories.add(territory)\n","sub_path":"carreer.py","file_name":"carreer.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"55237729","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom wxpy import *\n\nclass PM25:\n def __init__(self, city):\n #city用拼音,这个网站支持很多城市\n self.url = \"http://www.pm25.com/\" + str(city) + \".html/\"\n self.web = requests.get(self.url).text\n self.soup = BeautifulSoup(self.web, \"html.parser\")\n self.aqi = self.soup.find(name=\"a\", attrs={\"class\": \"bi_aqiarea_num\"}).text\n self.weather = self.soup.find(name=\"p\", attrs= {\"class\": \"bi_info_weather\"}).text\n\n def show_aqi(self):\n city_aqi = self.aqi\n return city_aqi\n\n def show_weather(self):\n city_weather = self.weather[1:]\n return city_weather\n\ndef wechat(groupName, cityName):\n '''\n wxpy的文档:https://wxpy.readthedocs.io/zh/latest/index.html\n Bot()方法的几个参数:\n console_qr=2:在终端显示二维码,命令行必用\n cache_pate=True:一次登陆以后缓存一定时间\n '''\n bot = Bot(cache_path=True, console_qr=2)\n\n group = bot.groups().search(groupName)[0]\n @bot.register(group, TEXT)\n def reply_api(msg):\n if msg.text == \"天气\":\n pM25 = PM25(cityName)\n aqi = pM25.show_aqi()\n weather = pM25.show_weather()\n\n air_index = int(aqi)\n message = {\"good\":\"空气很好,适宜出门!\",\n \"normal\":\"空气一般,户外时间不宜过长。\",\n \"bad\":\"空气不好,不建议出门。\",\n \"worse\":\"空气很糟糕,不要出门,家里开空气净化器!\"}\n if air_index <= 40:\n air_msg = message[\"good\"]\n elif 40 < air_index <= 70:\n air_msg = message[\"normal\"]\n elif 70 < air_index <= 100:\n air_msg = message[\"bad\"]\n elif air_index > 100:\n air_msg = message[\"worse\"]\n group.send(\"当前重庆空气质量指数:\" + aqi + \"@\" + air_msg +\"@ 本日天气:\" + weather)\n \n embed()\n\n\nwechat(\"groupName\", \"city\")\n","sub_path":"pm25.py","file_name":"pm25.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442057519","text":"def collatz(num):\n\tif num%2==0:\n\t\tprint(num//2)\n\t\treturn (num//2)\n\telif num %2==1:\n\t\tprint(3*num+1)\n\t\treturn(3*num+1)\n\n\nprint(\"give a number:\")\ntry:\n\tn=input(int())\nexcept:\n\tprint(\"That's not a valid answer, please enter a valid number\")\n\texit()\n\nwhile n!=1:\n\tn=collatz(int(n))\n\n\n\n\n\n\t\t\n\n","sub_path":"collatz,nr1988.py","file_name":"collatz,nr1988.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"426825657","text":"try:\n from urllib.parse import urljoin\n from urllib.parse import urlencode\n import urllib.request as urlrequest\nexcept ImportError:\n from urlparse import urljoin\n from urllib import urlencode\n import urllib2 as urlrequest\nimport json\n\n\nclass Slack(object):\n\n def __init__(self, url=\"\", cfg=None):\n self.url = url\n if cfg is not None:\n self.username = cfg.get('slack', 'username')\n self.markdown = cfg.get('slack', 'markdown')\n else:\n self.username = 'barn2'\n self.markdown = 'true'\n self.opener = urlrequest.build_opener(urlrequest.HTTPHandler())\n\n\n\n def info(self, text):\n self._notify(text, 'BARN2 INFO Message', 'good')\n\n def error(self, text):\n self._notify(text, 'BARN2 ERROR Message', 'danger')\n pass\n\n def _notify(self, text, title, type):\n \"\"\"\n Send message to slack API\n \"\"\"\n attachments = []\n attachment = {\n 'title': title,\n 'color': type,\n 'text': text,\n }\n attachments.append(attachment)\n return self._send(attachments=attachments)\n\n def _send(self, **payload):\n \"\"\"\n Send payload to slack API\n \"\"\"\n payload_json = json.dumps(payload)\n data = urlencode({\"payload\": payload_json})\n req = urlrequest.Request(self.url)\n response = self.opener.open(req, data.encode('utf-8')).read()\n return response.decode('utf-8')\n\n def close(self):\n try:\n self.opener.close()\n except:\n pass\n\n\n# slack = Slack(url='https://hooks.slack.com/services/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')\n# slack.error(text='Test message to *Wenyu*')","sub_path":"barn2/errorhandlers/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"280149191","text":"from scipy.integrate import OdeSolver, DenseOutput\nfrom copy import copy\nimport numpy as np\nfrom poliastro import integrator_params\nfrom scipy.integrate._ivp.common import (warn_extraneous, validate_max_step, validate_tol, select_initial_step)\nfrom poliastro.jit import jit\n\n\ndef validate_max_nsteps(max_nsteps):\n if max_nsteps <= 0:\n raise ValueError(\"`max_nsteps` must be positive.\")\n return max_nsteps\n\n\ndef validate_safety_factor(safety_factor):\n if safety_factor >= 1.0 or safety_factor <= 1e-4:\n raise ValueError(\"`safety_factor` must lie within 1e-4 and 1.0.\")\n return safety_factor\n\n\ndef validate_beta_stabilizer(beta_stabilizer):\n if beta_stabilizer < 0 or beta_stabilizer > 0.2:\n raise ValueError(\"`beta_stabilizer` must lie within 0 and 0.2.\")\n return beta_stabilizer\n\n\nclass DOP835(OdeSolver):\n A = integrator_params.A\n C = integrator_params.C\n B = integrator_params.B\n E = integrator_params.E\n BHH = integrator_params.BHH\n D = integrator_params.D\n\n def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,\n rtol=1e-7, atol=1e-12, safety_factor=0.9,\n min_step_change=0.333, max_step_change=6.0,\n beta_stabilizer=0.00, max_nsteps=100000,\n vectorized=False, **extraneous):\n warn_extraneous(extraneous)\n super().__init__(fun, t0, y0, t_bound, vectorized,\n support_complex=True)\n self.y_old = None\n self.max_step = validate_max_step(max_step)\n self.beta_stabilizer = validate_beta_stabilizer(beta_stabilizer)\n self.max_nsteps = validate_max_nsteps(max_nsteps)\n self.safety_factor = validate_safety_factor(safety_factor)\n self.rtol, self.atol = validate_tol(rtol, atol, self.n)\n self.min_step_change = min_step_change\n self.max_step_change = max_step_change\n self.order = 8\n\n self.f = self.fun(self.t, self.y)\n self.h_abs = select_initial_step(self.fun, self.t, self.y, self.f, self.direction,\n self.order, self.rtol, self.atol)\n self.nfev += 2\n\n self.n_steps = 0\n self.n_accepted = 0\n self.n_rejected = 0\n self.factor_old = 1e-4 # Lund-stabilization factor\n self.K = np.zeros((16, self.n))\n self.interpolation = np.zeros((8, self.n))\n\n def _step_impl(self):\n t = self.t\n y = self.y\n f = self.f\n K = self.K\n\n max_step = self.max_step\n rtol = self.rtol\n atol = self.atol\n\n min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)\n\n if self.h_abs > max_step:\n h_abs = max_step\n elif self.h_abs < min_step:\n h_abs = min_step\n else:\n h_abs = self.h_abs\n\n order = self.order\n step_accepted = False\n\n while not step_accepted:\n if self.h_abs < min_step:\n return False, self.TOO_SMALL_STEP\n\n h = self.h_abs * self.direction\n t_new = t + h\n\n if self.direction * (t_new - self.t_bound) > 0:\n t_new = self.t_bound\n\n h = t_new - t\n h_abs = np.abs(h)\n\n K[0] = f\n for s in range(1, 12):\n a, c = self.A[s], self.C[s]\n dy = np.dot(K[:s].T, a) * h\n K[s] = self.fun(t + c * h, y + dy)\n self.nfev += 11\n\n f_B = np.dot(K[:12].T, self.B)\n y_final = y + h * f_B\n\n scale = atol + np.maximum(np.abs(y), np.abs(y_final)) * rtol\n err_BHH = f_B - self.BHH[0] * K[0] - self.BHH[1] * K[8] - self.BHH[2] * K[11]\n err_BHH = np.sum((err_BHH / scale) ** 2)\n\n err_E = np.dot(K[:12].T, self.E)\n err_E = np.sum((err_E / scale) ** 2)\n\n denominator = err_E + 1e-2 * err_BHH\n err_E = h_abs * err_E / np.sqrt(self.n * denominator)\n\n err_exp = err_E ** (0.125 - self.beta_stabilizer * 0.2)\n dh_factor = err_exp / (self.factor_old ** self.beta_stabilizer)\n dh_factor = np.max([1.0 / self.max_step_change,\n np.min([1.0 / self.min_step_change,\n dh_factor / self.safety_factor])])\n h_new_abs = h_abs / dh_factor\n\n if err_E < 1.0:\n step_accepted = True\n self.factor_old = np.max([err_E, 1e-4])\n self.n_accepted += 1\n K[12] = self.fun(t + h, y_final)\n\n for s in range(13, 16):\n a, c = self.A[s], self.C[s]\n dy = np.dot(K[:s].T, a) * h\n K[s] = self.fun(t + c * h, y + dy)\n self.nfev += 4\n\n # prepare the dense output\n self.interpolation[0] = y\n self.interpolation[1] = y_final - y\n self.interpolation[2] = h * K[0] - self.interpolation[1]\n self.interpolation[3] = self.interpolation[1] - h * K[12] - self.interpolation[2]\n for n in range(4, 8):\n self.interpolation[n] = h * np.dot(K[:16].T, self.D[n])\n\n self.y_old = y\n self.t = t_new\n self.y = y_final\n self.f = K[12]\n self.h_abs = h_new_abs\n\n return True, None\n else:\n self.n_rejected += 1\n self.h_abs /= np.min([1.0 / self.min_step_change,\n err_exp / self.safety_factor])\n\n def _dense_output_impl(self):\n return DOP835DenseOutput(self.t_old, self.t, self.y_old, self.interpolation)\n\n\ndef get_coeffs(s):\n coeffs = np.zeros((8))\n s_back = 1.0 - s\n coeffs[0] = 1.0\n for i in range(7):\n if i % 2 == 0:\n coeffs[i + 1] = coeffs[i] * s\n else:\n coeffs[i + 1] = coeffs[i] * s_back\n return np.array(coeffs)\n\n\nclass DOP835DenseOutput(DenseOutput):\n def __init__(self, t_old, t_new, y_old, interpolation):\n super().__init__(t_old, t_new)\n self.h = t_new - t_old\n self.interpolation = copy(interpolation)\n self.y_old = y_old\n\n def _call_impl(self, t_eval):\n s = (t_eval - self.t_old) / self.h\n coeffs = get_coeffs(s)\n return np.dot(self.interpolation.T, coeffs)\n","sub_path":"src/poliastro/integrators.py","file_name":"integrators.py","file_ext":"py","file_size_in_byte":6375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"397130222","text":"#\n# Project 1, starter code part b\n#\nimport math\nimport tensorflow as tf\nimport numpy as np\nimport pylab as plt\n\n# initialization routines for bias and weights\ndef init_bias(n = 1):\n return(tf.Variable(np.zeros(n), dtype=tf.float32))\n\ndef init_weights(n_in=1, n_out=1):\n return (tf.Variable(tf.truncated_normal([n_in, n_out], stddev=1.0/math.sqrt(float(n_in))), name='weights'))\n\n# scale data\ndef scale(X):\n return (X - np.mean(X, axis=0))/np.std(X, axis=0)\n\n\nNUM_FEATURES = 8\nlearning_rate = 0.5*(10**-6)\nbeta = 10**-3\nepochs = 1000\nbatch_size = 32\nnum_neurons = [20,40,60,80,100]\nseed = 10\nnp.random.seed(seed)\nnum_folds = 5\n\n#read and divide data into test and train sets\ncal_housing = np.loadtxt('cal_housing.data', delimiter=',')\nX_data, Y_data = cal_housing[:,:8], cal_housing[:,-1]\nX_data = scale(X_data)\nY_data = (np.asmatrix(Y_data)).transpose()\n\nidx = np.arange(X_data.shape[0])\nnp.random.shuffle(idx)\nX_data, Y_data = X_data[idx], Y_data[idx]\n\ntest_size = 3* X_data.shape[0] // 10\ntrain_size = X_data.shape[0]-test_size\ntrain_X, train_Y = X_data[test_size:], Y_data[test_size:]\ntestX, testY = X_data[:test_size], Y_data[:test_size]\n\n# experiment with small datasets\n# train_X = train_X[:1000]\n# train_Y = train_Y[:1000]\n# train_size = train_X.shape[0]\n\n# Create the model\nx = tf.placeholder(tf.float32, [None, NUM_FEATURES])\ny_ = tf.placeholder(tf.float32, [None, 1])\n\n# Build the graph for the deep net\n\n\nerrors = []\nsizeof_fold = train_size//num_folds\nfor number in num_neurons:\n\tprint('Starting training for number of neurons: %d'%number)\n\t#Create the gradient descent optimizer with the given learning rate.\n\tV = init_weights(NUM_FEATURES, number)\n\tc = init_bias(number)\n\tW = init_weights(number)\n\tb = init_bias()\n\th = tf.nn.relu(tf.matmul(x, V) + c)\n\ty = tf.matmul(h, W) + b\n\n\tsquare_error = tf.square(y_ - y)\n\tregularization = tf.nn.l2_loss(V) + tf.nn.l2_loss(W)\n\tloss = tf.reduce_mean(square_error + beta *regularization)\n\n\toptimizer = tf.train.GradientDescentOptimizer(learning_rate)\n\ttrain_op = optimizer.minimize(loss)\n\terror = tf.reduce_mean(tf.square(y_ - y))\n\n\terrs=[]\n\tfor fold in range(num_folds):\n\t\tstart, end = fold * sizeof_fold, (fold+1)* sizeof_fold\n\t\tvalidX = train_X[start:end]\n\t\tvalidY = train_Y[start:end]\n\t\ttrainX = np.append(train_X[:start],train_X[end:],axis=0)\n\t\ttrainY = np.append(train_Y[:start],train_Y[end:],axis=0)\n\t\twith tf.Session() as sess:\n\t\t\tsess.run(tf.global_variables_initializer())\n\t\t\tfor i in range(epochs):\n\t\t\t\trand_array = np.arange(trainX.shape[0])\n\t\t\t\tnp.random.shuffle(rand_array)\n\t\t\t\ttrainX = trainX[rand_array]\n\t\t\t\ttrainY = trainY[rand_array]\n\t\t\t\t# implementing mini-batch GD\n\t\t\t\tfor s in range(0, trainX.shape[0]-batch_size, batch_size):\n\t\t\t\t\ttrain_op.run(feed_dict={x: trainX[s:s+batch_size], y_: trainY[s:s+batch_size]})\n\t\t\t\tif i % 100 == 0:\n\t\t\t\t\tprint('finished training iter %d'%i)\n\t\t\tfold_err = error.eval(feed_dict={x: validX, y_: validY})\n\t\t\tprint(\"start and end are %d and %d\" %(start, end))\n\t\t\tprint(\"%d fold test error is: %g\" %(fold, fold_err))\n\t\t\terrs.append(fold_err)\n\tprint('mean error = %g'% np.mean(errs))\n\terrors.append(np.mean(errs))\nprint(errors)\n# plot learning curves\nfig = plt.figure(1)\nplt.xlabel('Learning Rates')\nplt.xscale(\"log\")\nplt.ylabel('Test Data Error')\nplt.plot(learning_rate, errs)\nplt.savefig('./figures/B3_Fig1.png')\nplt.show()\n","sub_path":"Assignment 1/TY&AY to be submitted/B3a.py","file_name":"B3a.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"161530889","text":"#!/usr/bin/python3\nfrom sys import stdin\n\ndef main ():\n read = stdin.readline\n mul_mem = dict ()\n hits = [[] for i in range (1002)]\n for i in range (1, 1001):\n for j in range (1, i + 1):\n if i ^ j == i - j:\n hits [i].append (j)\n t = int (read ())\n for t_ in range (t):\n n = int (read ())\n a = list (map (int, read ().split ()))\n ct = [0] * 1001\n for v in a:\n ct [v] += 1\n ans = 0\n for i in range (1, 1001):\n for j in hits [i]: ans += ct [i] * ct [j]\n print (ans)\n\nif __name__ == \"__main__\": main ()","sub_path":"_a_bitwise_pair.py","file_name":"_a_bitwise_pair.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"190071831","text":"import logging\n\nfrom app import books\n\n\nlogger = logging.getLogger('scraping.manu')\n\nUSER_CHOICE = ''' Enter one of the following\n\n- 'b' to look at 5-star books\n- 'c' to look at the cheapest books\n- 'n' to just get the next available book on the catalogue\n- 'q' to exit\n\nEnter your choice: '''\n\n\ndef print_best_books():\n logger.info('Finding best books by rating...')\n best_books = sorted(books, key=lambda x: x.rating * -1)[:10]\n # sorted --> Organiza a lista de acordo com a KEY (no caso de acordo com as estrelas)\n # Multiplicar por -1 faz com que seja organizado de forma DESCENDENTE, ou seja, ...\n # De 5 estrelas para 1 e não de 1 para 5.\n # [:10] Pega apenas 10 livros (slice) --> 0 até o 9\n for book in best_books:\n print(book)\n\n\ndef print_cheapest_books():\n logger.info('Finding best books by price...')\n cheapest_books = sorted(books, key=lambda x: x.price)[:10]\n for book in cheapest_books:\n print(book)\n\n# Caso se queira organizar de acordo com múltiplas características. Por exemplo, Organizar primeiro\n# de acordo com as estrelas e dentre os que possuem o mesmo número de estrelas, organizar\n# de acordo com o preço. Para isso, usa-se uma TUPLA, em que o primeiro elemento é o que será\n# primeiro organizado (estrelas no caso abaixo) e o segundo será o segundo elemento a ser\n# organizado (preço no caso abaixo)\n\n\ndef print_best_cheapest_books():\n best_books = sorted(books, key=lambda x: (x.rating * -1, x.price))\n for book in best_books:\n print(book)\n\n\n# Tupla usada para a função GENERATOR get_next_book()\nbooks_generator = (x for x in books)\n\n\ndef get_next_book():\n logger.info('Getting next book from generator of all books...')\n print(next(books_generator))\n\n\nuser_choices = {\n 'b': print_best_books,\n 'c': print_cheapest_books,\n 'n': get_next_book\n}\n\n\ndef menu():\n user_input = input(USER_CHOICE)\n while user_input != 'q':\n if user_input in ('b', 'c', 'n'):\n user_choices[user_input]()\n else:\n print('Please choose a valid command.')\n user_input = input(USER_CHOICE)\n logger.debug('Terminatng program...')\n\n\nmenu()\n","sub_path":"completePythonCourse/13_Asynchronous_Development/12_Asynchronous_Book_Scraper/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594132102","text":"import numpy as np \nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef fun1():\n #绘制函数图形\n x = np.linspace(0,20,1000) #作图的自变量x\n y = np.sin(x) + 1 #因变量y\n z = np.cos(x**3) + 1 #因变量z\n plt.figure(figsize=(8,4)) #设置图像大小\n plt.xlabel('Times(s)') #x轴名称\n plt.ylabel('Volt') #y轴名称\n plt.title('函数图像') #标题\n plt.ylim(0,2.2) #y轴的范围\n plt.legend() #显示图例\n plt.show() #显示作图结果\n\n## f(x,y) = (x**2)/2 + (y**2)/2\ndef fun_200():\n t = np.linspace(0, 5, 100)\n x = t\n y = t\n z = (t**2)/2 + (t**2)/2\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n ax.plot_surface(x, y, z, cmap='xxx')\n plt.show()\n\n\nif __name__ == \"__main__\":\n fun_200()\n\n\n\n","sub_path":"pythonrc/matplotlib/function3D.py","file_name":"function3D.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"448652357","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ninfermedica_api.webservice\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis module contains classes and function responsible for making API requests.\n\"\"\"\n\nimport json\nimport platform\n\nimport requests\nfrom . import __version__, exceptions, models, API_CONFIG, DEFAULT_API_VERSION\n\nif platform.python_version_tuple()[0] == '3':\n basestring = (str,bytes)\n\n\nclass SearchFilters(object):\n \"\"\"Simple class to hold search filter constants.\"\"\"\n SYMPTOMS = \"symptom\"\n RISK_FACTORS = \"risk_factor\"\n LAB_TESTS = \"lab_test\"\n\n ALL = [SYMPTOMS, RISK_FACTORS, LAB_TESTS]\n\nSEARCH_FILTERS = SearchFilters()\n\n\nclass API(object):\n \"\"\"Class which handles requests to the Infermedica API.\"\"\"\n\n # User-Agent for HTTP request\n library_details = \"requests %s; python %s\" % (requests.__version__, platform.python_version())\n user_agent = \"Infermedica-API-Python %s (%s)\" % (__version__, library_details)\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize API object.\n\n Usage::\n >>> import infermedica_api\n >>> api = infermedica_api.API(app_id='YOUR_APP_ID', app_key='YOUR_APP_KEY')\n \"\"\"\n self.api_version = kwargs.get(\"api_version\", DEFAULT_API_VERSION)\n self.app_id = kwargs[\"app_id\"] # Mandatory parameter, so not using `dict.get`\n self.app_key = kwargs[\"app_key\"] # Mandatory parameter, so not using `dict.get`\n self.default_headers = self.__calculate_headers(kwargs)\n\n if self.api_version in kwargs.get(\"api_definitions\", {}) or {}:\n self.endpoint = kwargs[\"api_definitions\"][self.api_version]['endpoint']\n self.api_methods = kwargs[\"api_definitions\"][self.api_version]['methods']\n else:\n self.endpoint = API_CONFIG[self.api_version]['endpoint']\n self.api_methods = API_CONFIG[self.api_version]['methods']\n\n def __calculate_headers(self, parameters):\n headers = parameters.get(\"default_headers\", {})\n if parameters.get(\"model\", None):\n headers.update({\n \"Model\": parameters[\"model\"]\n })\n\n if parameters.get(\"dev_mode\", None) and parameters[\"dev_mode\"] == True:\n headers.update({\n \"Dev-Mode\": \"true\"\n })\n\n return headers\n\n def __get_url(self, method):\n return self.endpoint + self.api_version + method\n\n def __get_headers(self, override):\n \"\"\"Returns default HTTP headers.\"\"\"\n headers = {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n \"User-Agent\": self.user_agent,\n \"app_id\": self.app_id,\n \"app_key\": self.app_key\n }\n headers.update(self.default_headers)\n headers.update(override)\n return headers\n\n def __api_call(self, url, method, **kwargs):\n\n kwargs['headers'] = self.__get_headers(kwargs['headers'] or {})\n\n response = requests.request(method, url, **kwargs)\n\n return self.__handle_response(response)\n\n def __handle_response(self, response):\n \"\"\"\n Validates HTTP response, if response is correct decode json data and returns dict object.\n If response is not correct raise appropriate exception.\n\n :returns: dict or list with response data\n :rtype: dict or list\n :raises:\n infermedica_api.exceptions.BadRequest,\n infermedica_api.exceptions.UnauthorizedAccess,\n infermedica_api.exceptions.ForbiddenAccess,\n infermedica_api.exceptions.ResourceNotFound,\n infermedica_api.exceptions.MethodNotAllowed,\n infermedica_api.exceptions.ServerError,\n infermedica_api.exceptions.ConnectionError\n \"\"\"\n status = response.status_code\n content = response.content.decode('utf-8')\n\n if 200 <= status <= 299:\n return json.loads(content) if content else {}\n elif status == 400:\n raise exceptions.BadRequest(response, content)\n elif status == 401:\n raise exceptions.UnauthorizedAccess(response, content)\n elif status == 403:\n raise exceptions.ForbiddenAccess(response, content)\n elif status == 404:\n raise exceptions.ResourceNotFound(response, content)\n elif status == 405:\n raise exceptions.MethodNotAllowed(response, content)\n elif 500 <= status <= 599:\n raise exceptions.ServerError(response, content)\n else:\n raise exceptions.ConnectionError(response, content)\n\n def __get(self, method, params=None, headers=None):\n \"\"\"Wrapper for a GET API call.\"\"\"\n return self.__api_call(self.__get_url(method), \"GET\", headers=headers, params=params)\n\n def __post(self, method, data, headers=None):\n \"\"\"Wrapper for a GET API call.\"\"\"\n return self.__api_call(self.__get_url(method), \"POST\", headers=headers, data=data)\n\n def info(self):\n \"\"\"Makes an API request and returns basic API model information.\"\"\"\n try:\n return self.__get(self.api_methods['info'])\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'info')\n\n def search(self, phrase, sex=None, max_results=8, filters=None):\n \"\"\"\n Makes an API search request and returns list of dicts containing keys: 'id', 'label' and 'type'.\n Each dict represent an evidence (symptom, lab test or risk factor).\n By default only symptoms are returned, to include other evidence types use filters.\n\n :param phrase: Phrase to look for.\n :type phrase: str\n\n :param sex: Sex of the patient 'female' or 'male'.\n :type sex: str\n\n :param max_results: Maximum number of result to return, default is 8.\n :type max_results: int\n\n :param filters: List of search filters, taken from SEARCH_FILTERS variable.\n :type filters: list\n\n :returns: A List of dicts with 'id' and 'label' keys.\n :rtype: list\n \"\"\"\n try:\n params = {\n 'phrase': phrase,\n 'max_results': max_results\n }\n\n if sex:\n params['sex'] = sex\n\n if filters:\n if isinstance(filters, (list, tuple)):\n params['type'] = filters\n elif isinstance(filters, basestring):\n params['type'] = [filters]\n\n for filter in params['type']:\n if filter not in SEARCH_FILTERS.ALL:\n raise exceptions.InvalidSearchFilter(filter)\n\n return self.__get(self.api_methods['search'], params=params)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'search')\n\n def lookup(self, phrase, sex=None):\n \"\"\"\n Makes an API lookup request and returns evidence details object.\n\n :param phrase: Phrase to look for.\n :type phrase: str\n\n :param sex: Sex of the patient 'female' or 'male'.\n :type sex: str\n\n :returns: Dictionary with details.\n :rtype: dict\n \"\"\"\n try:\n params = {\n 'phrase': phrase\n }\n if sex:\n params['sex'] = sex\n return self.__get(self.api_methods['lookup'], params=params)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'lookup')\n\n def diagnosis(self, diagnosis_request, case_id=None):\n \"\"\"\n Makes an diagnosis API request with provided diagnosis data\n and returns diagnosis question with possible conditions.\n\n :param diagnosis_request: Diagnosis request object or json request for diagnosis method.\n :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict\n\n :param case_id: Unique case id for diagnosis\n :type case_id: str\n\n :returns: A Diagnosis object with api response\n :rtype: :class:`infermedica_api.models.Diagnosis`\n \"\"\"\n try:\n method = self.api_methods['diagnosis']\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'diagnosis')\n\n headers = {}\n if case_id:\n headers['Case-Id'] = case_id\n\n if isinstance(diagnosis_request, models.Diagnosis):\n if not case_id and diagnosis_request.case_id:\n headers['Case-Id'] = diagnosis_request.case_id\n\n response = self.__post(method, json.dumps(diagnosis_request.get_api_request()), headers=headers)\n diagnosis_request.update_from_api(response)\n\n return diagnosis_request\n\n return self.__post(method, json.dumps(diagnosis_request), headers=headers)\n\n def explain(self, diagnosis_request, target_id):\n \"\"\"\n Makes an explain API request with provided diagnosis data and target condition.\n Returns explain results with supporting and conflicting evidences.\n\n :param diagnosis_request: Diagnosis request object or json request for diagnosis method.\n :type diagnosis_request: :class:`infermedica_api.models.Diagnosis` or dict\n\n :param target_id: Condition id for which explain shall be calculated.\n :type target_id: str\n\n :returns: A Diagnosis object with api response\n :rtype: :class:`infermedica_api.models.Diagnosis`\n \"\"\"\n try:\n if isinstance(diagnosis_request, models.Diagnosis):\n request = diagnosis_request.get_explain_request(target_id)\n else:\n request = dict(diagnosis_request, **{'target': target_id})\n\n response = self.__post(self.api_methods['explain'], json.dumps(request))\n\n return models.ExplainResults.from_json(response)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'explain')\n\n def observation_details(self, _id):\n \"\"\"\n Makes an API request and returns observation details object.\n\n :param _id: Observation id\n :type _id: str\n\n :returns: A Observation object\n :rtype: :class:`infermedica_api.models.Observation`\n \"\"\"\n try:\n url = self.api_methods['observation_details'].format(**{'id': _id})\n response = self.__get(url)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'observation_details')\n\n return models.Observation.from_json(response)\n\n def observations_list(self):\n \"\"\"\n Makes an API request and returns list of observation details objects.\n\n :returns: A ObservationList list object with Observation objects\n :rtype: :class:`infermedica_api.models.ObservationList`\n \"\"\"\n try:\n response = self.__get(self.api_methods['observations'])\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'observations_list')\n\n return models.ObservationList.from_json(response)\n\n def condition_details(self, _id):\n \"\"\"\n Makes an API request and returns condition details object.\n\n :param _id: Condition id\n :type _id: str\n\n :returns:A Condition object\n :rtype: :class:`infermedica_api.models.Condition`\n \"\"\"\n try:\n url = self.api_methods['condition_details'].format(**{'id': _id})\n response = self.__get(url)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'condition_details')\n\n return models.Condition.from_json(response)\n\n def conditions_list(self):\n \"\"\"\n Makes an API request and returns list of condition details objects.\n\n :returns: A ConditionList list object with Condition objects\n :rtype: :class:`infermedica_api.models.ConditionList`\n \"\"\"\n try:\n response = self.__get(self.api_methods['conditions'])\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'conditions_list')\n\n return models.ConditionList.from_json(response)\n\n def symptom_details(self, _id):\n \"\"\"\n Makes an API request and returns symptom details object.\n\n :param _id: Symptom id\n :type _id: str\n\n :returns: A Symptom object\n :rtype: :class:`infermedica_api.models.Symptom`\n \"\"\"\n try:\n url = self.api_methods['symptom_details'].format(**{'id': _id})\n response = self.__get(url)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'symptom_details')\n\n return models.Symptom.from_json(response)\n\n def symptoms_list(self):\n \"\"\"\n Makes an API request and returns list of symptom details objects.\n\n :returns: A SymptomList list object with Symptom objects\n :rtype: :class:`infermedica_api.models.SymptomList`\n \"\"\"\n try:\n response = self.__get(self.api_methods['symptoms'])\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'symptoms_list')\n\n return models.SymptomList.from_json(response)\n\n def lab_test_details(self, _id):\n \"\"\"\n Makes an API request and returns lab_test details object.\n\n :param _id: LabTest id\n :type _id: str\n\n :returns: A LabTest object\n :rtype: :class:`infermedica_api.models.LabTest`\n \"\"\"\n try:\n url = self.api_methods['lab_test_details'].format(**{'id': _id})\n response = self.__get(url)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'lab_test_details')\n\n return models.LabTest.from_json(response)\n\n def lab_tests_list(self):\n \"\"\"\n Makes an API request and returns list of lab_test details objects.\n\n :returns: A LabTestList list object with LabTest objects\n :rtype: :class:`infermedica_api.models.LabTestList`\n \"\"\"\n try:\n response = self.__get(self.api_methods['lab_tests'])\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'lab_tests_list')\n\n return models.LabTestList.from_json(response)\n\n def risk_factor_details(self, _id):\n \"\"\"\n Makes an API request and returns risk factor details object.\n\n :param _id: risk factor id\n :type _id: str\n\n :returns: A RiskFactor object\n :rtype: :class:`infermedica_api.models.RiskFactor`\n \"\"\"\n try:\n url = self.api_methods['risk_factor_details'].format(**{'id': _id})\n response = self.__get(url)\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'risk_factor_details')\n\n return models.RiskFactor.from_json(response)\n\n def risk_factors_list(self):\n \"\"\"\n Makes an API request and returns list of risk factors details objects.\n\n :returns: A RiskFactorList list object with RiskFactor objects\n :rtype: :class:`infermedica_api.models.RiskFactorList`\n \"\"\"\n try:\n response = self.__get(self.api_methods['risk_factors'])\n except KeyError as e:\n raise exceptions.MethodNotAvailableInAPIVersion(self.api_version, 'risk_factors_list')\n\n return models.RiskFactorList.from_json(response)\n\n\n__api__ = None\n__api_aliased__ = {}\n\n\ndef get_api(alias=None):\n \"\"\"\n Returns global API object and if present,\n otherwise raise MissingConfiguration exception.\n\n :param alias: Alias of the API to retrieve\n :type alias: str\n\n :returns: An API object\n :rtype: :class:`infermedica_api.webservice.API`\n :raises: :class:`infermedica_api.exceptions.MissingConfiguration`\n \"\"\"\n global __api__\n global __api_aliased__\n\n if isinstance(alias, basestring):\n try:\n return __api_aliased__[alias]\n except KeyError:\n raise exceptions.MissingConfiguration(alias)\n\n if __api__ is None:\n raise exceptions.MissingConfiguration()\n\n return __api__\n\n\ndef configure(options=None, **config):\n \"\"\"\n Configure and create new global API object with given configuration.\n Configuration can be passed as a dict or separate arguments.\n Returns newly created object.\n\n Usage:\n >>> import infermedica_api\n >>> infermedica_api.configure({'app_id': 'YOUR_APP_ID', 'app_key': 'YOUR_APP_KEY'})\n\n ... or:\n >>> import infermedica_api\n >>> infermedica_api.configure(app_id='YOUR_APP_ID', app_key='YOUR_APP_KEY')\n\n :param options: Dict with configuration data\n :type options: dict\n\n :returns: An API object\n :rtype: :class:`infermedica_api.webservice.API`\n \"\"\"\n global __api__\n global __api_aliased__\n\n configuration = dict(options or {}, **config)\n\n if 'alias' in configuration and isinstance(configuration['alias'], basestring):\n __api_aliased__[configuration['alias']] = API(**configuration)\n\n if configuration.get('default', False):\n __api__ = __api_aliased__[configuration['alias']]\n\n return __api_aliased__[configuration['alias']]\n\n __api__ = API(**configuration)\n\n return __api__\n","sub_path":"app/main/infermedica_api/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":17445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"533849217","text":"import numpy as np\nimport sncosmo\nfrom astropy.table import Table, Column\n\n\ndef read_des_datfile(datafile):\n \"\"\" Read in a SN data table that was written in the old \n SNANA format, modify it, and return an astropy Table object \n that can be handled by sncosmo functions.\n \"\"\"\n metadata, datatable = sncosmo.read_snana_ascii(\n datafile, default_tablename='OBS')\n sntable = standardize_snana_data(datatable['OBS'])\n return metadata, sntable\n\n\ndef standardize_data(data):\n \"\"\"Standardize photometric data by converting to a structured numpy array\n with standard column names (if necessary) and sorting entries in order of\n increasing time.\n\n Parameters\n ----------\n data : `~astropy.table.Table` or `~numpy.ndarray` or `dict`\n\n Returns\n -------\n standardized_data : `~numpy.ndarray`\n \"\"\"\n\n #warn_once('standardize_data', '1.5', '2.0',\n # 'This function not intended for public use; open an issue at '\n # 'https://github.com/sncosmo/sncosmo/issues if you need this '\n # 'functionality.')\n\n if isinstance(data, Table):\n data = np.asarray(data)\n\n if isinstance(data, np.ndarray):\n colnames = data.dtype.names\n\n # Check if the data already complies with what we want\n # (correct column names & ordered by date)\n if (set(colnames) == set(PHOTDATA_ALIASES.keys())\n and np.all(np.ediff1d(data['time']) >= 0.)):\n return data\n\n elif isinstance(data, dict):\n colnames = data.keys()\n\n else:\n raise ValueError('Unrecognized data type')\n\n # Create mapping from lowercased column names to originals\n lower_to_orig = dict([(colname.lower(), colname) for colname in colnames])\n\n # Set of lowercase column names\n lower_colnames = set(lower_to_orig.keys())\n\n orig_colnames_to_use = []\n for aliases in PHOTDATA_ALIASES.values():\n i = lower_colnames & aliases\n if len(i) != 1:\n raise ValueError('Data must include exactly one column from {0} '\n '(case independent)'.format(', '.join(aliases)))\n orig_colnames_to_use.append(lower_to_orig[i.pop()])\n\n if isinstance(data, np.ndarray):\n new_data = data[orig_colnames_to_use].copy()\n new_data.dtype.names = list(PHOTDATA_ALIASES.keys())\n\n else:\n new_data = OrderedDict()\n for newkey, oldkey in zip(PHOTDATA_ALIASES.keys(),\n orig_colnames_to_use):\n new_data[newkey] = data[oldkey]\n\n new_data = dict_to_array(new_data)\n\n # Sort by time, if necessary.\n if not np.all(np.ediff1d(new_data['time']) >= 0.):\n new_data.sort(order=['time'])\n\n return new_data\n\n\ndef standardize_snana_data(sn, headfile=None):\n \"\"\" Modify a SN data table that was written in the old \n SNANA format so that it can be handled by sncosmo\n \"\"\"\n if 'MJD' in sn.colnames:\n sn['MJD'].name = 'time'\n timedata = sn['time']\n timecolumn = Column(data=timedata, name='time')\n\n if 'FLT' in sn.colnames and 'FILTER' not in sn.colnames:\n filterdata = np.where(sn['FLT'] == 'g', 'desg',\n np.where(sn['FLT'] == 'r', 'desr',\n np.where(sn['FLT'] == 'i', 'desi',\n np.where(\n sn['FLT'] == 'z', 'desz',\n '?'))))\n filtercolumn = Column(data=filterdata, name='band')\n sn.add_column(filtercolumn)\n sn.remove_column('FLT')\n sn.remove_column('FIELD')\n if 'MAG' in sn.colnames:\n sn.remove_column('MAG')\n sn.remove_column('MAGERR')\n\n if 'ZEROPT' in sn.colnames and 'ZPT' not in sn.colnames:\n sn['ZEROPT'].name = 'zp'\n if 'ZPT' not in sn.colnames:\n sn['zp'] = 27.5 * np.ones(len(sn))\n\n if 'FLUXCAL' in sn.colnames and 'FLUX' not in sn.colnames:\n fluxdata = sn['FLUXCAL'] * 10**(0.4 * (sn['zp'] - 27.5))\n fluxerrdata = sn['FLUXCALERR'] * 10**(0.4 * (sn['zp'] - 27.5))\n fluxcolumn = Column(data=fluxdata, name='flux')\n sn.add_column(fluxcolumn)\n fluxerrcolumn = Column(data=fluxerrdata, name='fluxerr')\n sn.add_column(fluxerrcolumn)\n sn.remove_column('FLUXCAL')\n sn.remove_column('FLUXCALERR')\n sn.remove_column('zp')\n\n if 'ZEROPT' in sn.colnames and 'ZPT' not in sn.colnames:\n sn['ZEROPT'].name = 'zp'\n if 'ZPT' not in sn.colnames:\n sn['zp'] = 27.5 * np.ones(len(sn))\n\n if 'MAGSYS' not in sn.colnames:\n abVals = ['ab' for i in range(len(sn))]\n magsyscol = Column(data=abVals, name='zpsys')\n sn.add_column(magsyscol)\n\n #snstd = sncosmo._deprecated.standardize_data(sn)\n snstd = sn\n\n if headfile:\n sn.meta['HEADFILE'] = headfile\n sn.meta['PHOTFILE'] = headfile.replace('HEAD', 'PHOT')\n\n return Table(snstd, meta=sn.meta, copy=False)\n","sub_path":"stardust/classTest/read_des_datfile.py","file_name":"read_des_datfile.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"257679014","text":"from collections import defaultdict\nimport urllib\nimport xml.etree.cElementTree as ET\nfrom datetime import date\nfrom bs4 import SoupStrainer, BeautifulSoup\nimport nltk\nfrom dateutil.rrule import rrule,DAILY\nfrom nltk.corpus import stopwords\n\ndef main_parser():\n a = b = date(2014, 3, 27)\n articles = ET.Element(\"articles\")\n for dt in rrule(DAILY, dtstart=a, until=b):\n url = \"http://www.reuters.com/resources/archive/us/\" + dt.strftime(\"%Y\") + dt.strftime(\"%m\") + dt.strftime(\n \"%d\") + \".html\"\n\n links = SoupStrainer(\"div\", \"headlineMed\")\n soup = BeautifulSoup(urllib.urlopen(url), \"lxml\", parse_only=links)\n\n article_date = ET.SubElement(articles, \"article_date\")\n article_date.text = str(dt)\n for link in soup.find_all('a'):\n if not 'video' in link['href']:\n try:\n article_time = ET.SubElement(article_date, \"article_time\")\n article_time.text = str(link.text[-11:])\n\n article_header = ET.SubElement(article_time, \"article_name\")\n article_header.text = str(link.text)\n\n article_link = ET.SubElement(article_time, \"article_link\")\n article_link.text = str(link['href']).encode('utf-8')\n\n try:\n article_text = ET.SubElement(article_time, \"article_text\")\n article_text.text = str(remove_stop_words(extract_article(link['href']))).encode('ascii','ignore')\n except Exception:\n pass\n except Exception:\n pass\n\n tree = ET.ElementTree(articles)\n tree.write(\"~/Documents/test.xml\", \"utf-8\")\n\n\ndef extract_article(url):\n paragraphs = SoupStrainer('p')\n soup = BeautifulSoup(urllib.urlopen(url), \"html5lib\", parse_only=paragraphs)\n return soup.text\n\n\ndef remove_stop_words(text):\n text = nltk.word_tokenize(text)\n filtered_words = [w for w in text if not w in stopwords.words('english')]\n return ' '.join(filtered_words)\n\ndef merger_with_similar_root():\n text_to_merge=\"\"\n tree=ET.parse(\"/Users/tarasmurzenkov/Documents/test.xml\")\n root=tree.getroot()\n data=defaultdict(list)\n root = ET.Element('articles')\n article_date = ET.SubElement(root, 'article_date')\n article_date.text = tree.find('.//article_date').text\n\n data = defaultdict(list)\n for article_time in tree.findall('.//article_time'):\n if (not(article_time.find('./article_name') is None)) and (not (article_time.find('./article_link') is None)) and (not (article_time.find('./article_text') is None)):\n time = article_time.text.strip()\n name = article_time.find('./article_name').text\n link = article_time.find('./article_link').text\n text = article_time.find('./article_text').text\n data[time].append((name, link, text))\n\n for time_value, items in data.iteritems():\n buff=\"\"\n article_time = ET.SubElement(article_date, 'article_time')\n article_name = ET.SubElement(article_time, 'article_name')\n article_link = ET.SubElement(article_time, 'article_link')\n article_text = ET.SubElement(article_time, 'article_text')\n\n article_time.text = time_value\n article_name.text = ' '.join(name for (name, _ , _) in items)\n article_link.text = ' '.join(link for (_, link , _) in items)\n for (_ , _ ,text) in items:\n try:\n buff +=str(text)+\" \"\n except Exception:\n pass\n article_text.text=buff\n\n tree = ET.ElementTree(root)\n tree.write(\"/Users/tarasmurzenkov/Documents/test1.xml\",\"utf-8\")\n print (ET.tostring(root))\n\nmain_parser()","sub_path":"Python/Sentiment_analysis_python/parse_reuters.py","file_name":"parse_reuters.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"456619109","text":"# vim: set fileencoding=utf-8 :\n#\n# Copyright (c) 2013 Daniel Truemper \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\nfrom __future__ import (absolute_import, division, print_function,\n with_statement)\n\nimport sys\nfrom unittest import TestCase\nfrom unittest import skipIf\n\nimport tornado\nfrom tornado import httputil\nfrom tornado.web import Application, RequestHandler\n\nfrom supercell.environment import Environment\n\n\nclass EnvironmentTest(TestCase):\n\n def test_simple_app_creation(self):\n env = Environment()\n app = env.get_application()\n self.assertIsInstance(app, Application)\n if tornado.version < '4.5':\n self.assertEqual(len(app.handlers), 2)\n else:\n self.assertEqual(len(app.default_router.rules), 2)\n\n def test_config_file_paths(self):\n env = Environment()\n self.assertEqual(len(env.config_file_paths), 0)\n\n @skipIf(tornado.version < '4.5', 'test requires tornado.routing')\n def test_add_handler(self):\n env = Environment()\n self.assertEqual(len(env._handlers), 0)\n\n class MyHandler(RequestHandler):\n def get(self):\n self.write({'ok': True})\n\n env.add_handler('/test', MyHandler, {})\n\n self.assertEqual(len(env._handlers), 1)\n\n app = env.get_application()\n\n request = httputil.HTTPServerRequest(uri='/test')\n handler_delegate = app.default_router.find_handler(request)\n self.assertIsNotNone(handler_delegate)\n self.assertEqual(handler_delegate.handler_class, MyHandler)\n\n def test_managed_object_access(self):\n env = Environment()\n\n managed = object()\n env.add_managed_object('i_am_managed', managed)\n self.assertEqual(managed, env.i_am_managed)\n\n def test_no_overwriting_of_managed_objects(self):\n env = Environment()\n managed = object()\n env.add_managed_object('i_am_managed', managed)\n\n self.assertEqual(managed, env.i_am_managed)\n with self.assertRaises(AssertionError):\n env.add_managed_object('i_am_managed', object())\n\n def test_finalizing(self):\n env = Environment()\n managed = object()\n env.add_managed_object('i_am_managed', managed)\n env._finalize()\n\n with self.assertRaises(AssertionError):\n env.add_managed_object('another_managed', object())\n","sub_path":"test/test_environment.py","file_name":"test_environment.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"604545855","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rango', '0069_auto_20150120_2328'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='education',\n name='degree',\n field=models.CharField(blank=True, max_length=200, choices=[(b'1', b'Ph. D'), (b'2', b'BA'), (b'3', b'BS'), (b'4', b\"Master's\"), (b'5', b'AA')]),\n ),\n ]\n","sub_path":"tango_with_django_project/rango/migrations/0070_auto_20150121_1808.py","file_name":"0070_auto_20150121_1808.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88813299","text":"from pyplasm import *\nimport window\n#8\n\nx_lato = QUOTE([3,-1.5,0.5,-2,0.5,-1.5,3]) #lato che combacera con con sette\nx_latoc = QUOTE([3,-6,3])\ny_lato = QUOTE([3])\n\nyt = R([1,2])(PI/2)(y_lato)\nxc = T([2])([3])(x_latoc)\n\nwind2 = window.window2 #contorno finestra\nwind2r = R([2,3])(PI/2)(wind2)\nwind2rr = R([1,2])(PI/2)(wind2r)\nwind2rrt = T([1,2,3])([12,1,2])(wind2rr)\nwind2rrt2 = T([1,2,3])([0,1,2])(wind2rr)\n\ncontorno = COLOR(BLACK)(SKELETON(1)(STRUCT([x_lato,T([1])([12])(yt),yt,xc])))\n\ncontprod = STRUCT([(PROD)([contorno,Q(4)]),wind2rrt,wind2rrt2])\n\n\nVIEW(STRUCT([wind2rrt,contprod,wind2rrt2]))","sub_path":"2014-03-21/python/exercise2/alae.py","file_name":"alae.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"274419227","text":"# -*- coding: utf-8 -*-\nfrom salmon.server.models import Cluster, SrvGroup, ServerFilter\nfrom salmon.package.status import PackageExtensionType\nfrom salmon.config.status import FileType, OperateResult\nfrom salmon.deployment.status import OnlineStatus, UpgradeStatus, PublicationStatus\nfrom salmon.mastersite.jsonhelper import BFEResult\nfrom salmon.mastersite.processorbase import click_page_jump\nfrom salmon.mastersite.login import sessionManager\nimport salmon.mastersite.config as config\n\nimport logging\nlogger = logging.getLogger(__package__)\n\n\ndef json_common_detail(req, e_target):\n args = req.POST\n vd = click_page_jump(req, e_target, False)\n if args['action'] == 'onlineStatus':\n vd.tdata.json_set_data(OnlineStatus.getlist(), restype=BFEResult.Raw) \n elif args['action'] == 'upgradeStatus':\n vd.tdata.json_set_data(UpgradeStatus.getlist(), restype=BFEResult.Raw) \n elif args['action'] == 'publishStatus':\n vd.tdata.json_set_data(PublicationStatus.getlist(), restype=BFEResult.Raw) \n elif args['action'] == 'serverStatus':\n vd.tdata.json_set_data(ServerFilter.getlist(), restype=BFEResult.Raw) \n elif args['action'] == 'packageType':\n vd.tdata.json_set_data(PackageExtensionType.getlist(), restype=BFEResult.Raw) \n elif args['action'] == 'fileType':\n filetypes = FileType.getlist()\n #filetypes.remove(FileType.TYPE_CHOICES[FileType.BINARY])\n vd.tdata.json_set_data(filetypes, restype=BFEResult.Raw) \n elif args['action'] == 'operateResult':\n vd.tdata.json_set_data(OperateResult.getlist(), restype=BFEResult.Raw) \n elif args['action'] == 'publishGroups':\n results = []\n for cluobj in Cluster.objects.all():\n for srvgobj in SrvGroup.objects.all():\n results.append(\"%s_%s\"%(cluobj.verbose_name,srvgobj.name))\n vd.tdata.json_set_data(results, restype=BFEResult.Raw) \n return vd\n\n\ndef json_common_permission(req, e_target):\n args = req.POST\n vd = click_page_jump(req, e_target, False)\n from django.contrib.auth.models import Permission\n results = {}\n perms = None\n if req.user == \"administrator\":\n perms = Permission.objects.filter()\n else:\n perms = Permission.objects.filter(group__user__username=req.user)\n for perm in perms:\n results[perm.codename] = True\n #view层 使用诸如 ng-show='show_package_delete' 来控制 控件 状态\n if args['action'] == 'profile':\n desclist = []\n for k,v in results.items():\n desc = config.get_perm_desc(k)\n if desc!='' and not results.has_key(k.rsplit('_',1)[0]) and (desc not in desclist):\n desclist.append(desc)\n else:\n results.pop(k)\n desclist.sort()\n vd.tdata.json_set_data({\"permissions\": desclist}) \n else:\n results[\"session_changed\"] = sessionManager.check_session_inactive(req.user, req.session._session_key) \n vd.tdata.json_set_data(results) \n return vd\n\n\n\n","sub_path":"mastersite/modules/common2.py","file_name":"common2.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"163317414","text":"__author__ = 'qgw'\nfrom multiprocessing import Process,Manager\nimport os\n\ndef run(d, l):\n d[os.getpid()] = os.getpid()\n # d[1] = '1'\n # d['2'] = 2\n\n l.append(os.getpid())\n print(l)\n\nif __name__ == '__main__':\n with Manager() as managers:\n d = managers.dict()\n l = managers.list(range(5))\n p_list = []\n for i in range(10):\n p = Process(target=run, args=(d, l,))\n p.start()\n p_list.append(p)\n\n for res in p_list:\n res.join()\n\n print(d)\n print(l)\n","sub_path":"OLDBOY/day10/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"502448733","text":"\"\"\" Systemd based service\n\"\"\"\nimport glob\nimport logging\nimport os\nimport pwd\nimport subprocess\n\nimport service\n\n\nlog = logging.getLogger(__name__)\n\n\nclass LinuxInit(service.Service):\n \"\"\"Parent class for all Linux based init systems.\n \"\"\"\n def enable(self):\n \"\"\"Does user/group directory creation.\n \"\"\"\n # Create user/group if needed\n try:\n user = pwd.getpwnam(self.username)\n except KeyError:\n subprocess.check_call(['useradd', '-r', self.username])\n user = pwd.getpwnam(self.username)\n\n # Create dirs\n # todo log dir is hardcoded\n for path in (self.log_dir, self.config_dir, '%s/conf.d' % self.config_dir):\n if not os.path.exists(path):\n os.makedirs(path, 0o755)\n os.chown(path, 0, user.pw_gid)\n # the log dir needs to be writable by the user\n os.chown(self.log_dir, user.pw_uid, user.pw_gid)\n\n def start(self, restart=True):\n if not self.is_enabled():\n log.error('The service is not enabled')\n return False\n\n def stop(self):\n if not self.is_enabled():\n log.error('The service is not enabled')\n return True\n\n def is_enabled(self):\n \"\"\"Returns True if monasca-agent is setup to start on boot, false otherwise.\n\n \"\"\"\n raise NotImplementedError\n\n\nclass Systemd(LinuxInit):\n def enable(self):\n \"\"\"Sets monasca-agent to start on boot.\n\n Generally this requires running as super user\n \"\"\"\n LinuxInit.enable(self)\n\n # Write the systemd script\n init_path = '/etc/systemd/system/{0}.service'.format(self.name)\n with open(os.path.join(self.template_dir, 'monasca-agent.service.template'), 'r') as template:\n with open(init_path, 'w') as service_script:\n service_script.write(template.read().format(prefix=self.prefix_dir, monasca_user=self.username,\n config_dir=self.config_dir))\n os.chown(init_path, 0, 0)\n os.chmod(init_path, 0o644)\n\n # Enable the service\n subprocess.check_call(['systemctl', 'daemon-reload'])\n subprocess.check_call(['systemctl', 'enable', '{0}.service'.format(self.name)])\n log.info('Enabled {0} service via systemd'.format(self.name))\n\n def start(self, restart=True):\n \"\"\"Starts monasca-agent.\n\n If the agent is running and restart is True, restart\n \"\"\"\n LinuxInit.start(self)\n log.info('Starting {0} service via systemd'.format(self.name))\n if restart:\n subprocess.check_call(['systemctl', 'restart', '{0}.service'.format(self.name)])\n else:\n subprocess.check_call(['systemctl', 'start', '{0}.service'.format(self.name)])\n\n return True\n\n def stop(self):\n \"\"\"Stops monasca-agent.\n \"\"\"\n LinuxInit.stop(self)\n log.info('Stopping {0} service'.format(self.name))\n subprocess.check_call(['systemctl', 'stop', '{0}.service'.format(self.name)])\n return True\n\n def is_enabled(self):\n \"\"\"Returns True if monasca-agent is setup to start on boot, false otherwise.\n \"\"\"\n try:\n subprocess.check_output(['systemctl', 'is-enabled', '{0}.service'.format(self.name)])\n except subprocess.CalledProcessError:\n return False\n\n return True\n\n\nclass SysV(LinuxInit):\n\n def __init__(self, prefix_dir, config_dir, log_dir, template_dir, username, name='monasca-agent'):\n \"\"\"Setup this service with the given init template.\n\n \"\"\"\n service.Service.__init__(self, prefix_dir, config_dir, log_dir, template_dir, name, username)\n self.init_script = '/etc/init.d/%s' % self.name\n self.init_template = os.path.join(template_dir, 'monasca-agent.init.template')\n\n def enable(self):\n \"\"\"Sets monasca-agent to start on boot.\n\n Generally this requires running as super user\n \"\"\"\n LinuxInit.enable(self)\n # Write the init script and enable.\n with open(self.init_template, 'r') as template:\n with open(self.init_script, 'w') as conf:\n conf.write(template.read().format(prefix=self.prefix_dir, monasca_user=self.username,\n config_dir=self.config_dir))\n os.chown(self.init_script, 0, 0)\n os.chmod(self.init_script, 0o755)\n\n for runlevel in ['2', '3', '4', '5']:\n link_path = '/etc/rc%s.d/S10monasca-agent' % runlevel\n if not os.path.exists(link_path):\n os.symlink(self.init_script, link_path)\n\n log.info('Enabled {0} service via SysV init script'.format(self.name))\n\n def start(self, restart=True):\n \"\"\"Starts monasca-agent.\n\n If the agent is running and restart is True, restart\n \"\"\"\n LinuxInit.start(self)\n\n log.info('Starting {0} service via SysV init script'.format(self.name))\n if restart:\n subprocess.check_call([self.init_script, 'restart']) # Throws CalledProcessError on error\n else:\n subprocess.check_call([self.init_script, 'start']) # Throws CalledProcessError on error\n return True\n\n def stop(self):\n \"\"\"Stops monasca-agent.\n\n \"\"\"\n LinuxInit.stop(self)\n\n log.info('Stopping {0} service via SysV init script'.format(self.name))\n subprocess.check_call([self.init_script, 'stop']) # Throws CalledProcessError on error\n return True\n\n def is_enabled(self):\n \"\"\"Returns True if monasca-agent is setup to start on boot, false otherwise.\n\n \"\"\"\n if not os.path.exists(self.init_script):\n return False\n\n if len(glob.glob('/etc/rc?.d/S??monasca-agent')) > 0:\n return True\n else:\n return False\n","sub_path":"monasca_setup/service/linux.py","file_name":"linux.py","file_ext":"py","file_size_in_byte":5913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"384060187","text":"import pytest\n\nfrom type_registry import load_yaml_str, register\n\n\n@register('yaml-simple', x=10)\nclass Simple:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\ndef test_load_yaml_str_raises_exception_if_type_is_not_found():\n test_config = '''\nbase:\n __factory__: no-one\n '''\n\n with pytest.raises(ValueError):\n load_yaml_str(test_config)\n\n\ndef test_load_yaml_str_returns_constructed_type():\n test_config = '''\nbase:\n __factory__: yaml-simple\n y: 20\n '''\n\n actual = load_yaml_str(test_config)\n assert 'base' in actual\n assert type(actual['base']) is Simple\n\n\ndef test_load_yaml_str_constructs_with_correct_values():\n test_config = '''\nbase:\n __factory__: yaml-simple\n y: 20\n '''\n\n actual = load_yaml_str(test_config)\n base = actual['base']\n assert base.x == 10\n assert base.y == 20\n","sub_path":"tests/test_yaml_constructor.py","file_name":"test_yaml_constructor.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335791341","text":"def get_sr_and_score(imset, model, aposterior_gt, num_frames, min_L=16):\n '''\n Super resolves an imset with a given model.\n Args:\n imset: imageset\n model: HRNet, pytorch model\n min_L: int, pad length\n Returns:\n sr: tensor (1, C_out, W, H), super resolved image\n scPSNR: float, shift cPSNR score\n '''\n\n if imset.__class__ is ImageSet:\n collator = collateFunction(num_frames, min_L)\n lrs, alphas, hrs, hr_maps, names = collator([imset])\n elif isinstance(imset, tuple): # imset is a tuple of batches\n lrs, alphas, hrs, hr_maps, names = imset\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # alphas = torch.from_numpy(np.zeros((1, min_L))) # torch.tensor\n # sr = np.zeros((imset[0].shape[0] * 3, imset[0].shape[1] * 3, 3))\n\n # for i in range(3):\n # cur_lrs = np.zeros((1, min_L, imset[0].shape[0], imset[0].shape[1]))\n\n # for j in range(min_L):\n # cur_lrs[0][j] = imset[j][:, :, i]\n\n # cur_lrs = torch.from_numpy(cur_lrs)\n # cur_lrs = cur_lrs.float().to(device)\n\n # cur_sr = model(cur_lrs, alphas)[:, 0]\n # cur_sr = cur_sr.detach().cpu().numpy()[0]\n\n # sr[:, :, i] = cur_sr[:, :]\n\n lrs = lrs[:, :min_L, :, :].float().to(device)\n alphas = alphas[:, :min_L].float().to(device)\n\n print(\"LRS SHAPEE: \", lrs.shape)\n print(\"ALPHAS SHAPEE: \", alphas.shape)\n\n sr = model(lrs, alphas)[:, 0]\n sr = sr.detach().cpu().numpy()[0]\n\n if len(hrs) > 0:\n scPSNR = shift_cPSNR(sr=np.clip(sr, 0, 1),\n hr=hrs.numpy()[0],\n hr_map=hr_maps.numpy()[0])\n else:\n scPSNR = None\n\n ssim = cSSIM(sr=np.clip(sr, 0, 1), hr=hrs.numpy()[0])\n\n # print(\"APGT SHAPE: \", aposterior_gt.shape)\n # print(\"APGT: \", aposterior_gt)\n\n if (str(type(aposterior_gt)) == \"\"):\n aposterior_ssim = 1.0\n else:\n aposterior_ssim = cSSIM(sr=np.clip(sr, 0, 1), hr=np.clip(aposterior_gt, 0, 1))\n\n return sr, scPSNR, ssim, aposterior_ssim","sub_path":"deprecated/get_sr_and_score.py","file_name":"get_sr_and_score.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"382213550","text":"###\n# Uses https://github.com/CheckPointSW/cp_mgmt_api_python_sdk\n# Connecting to remote CheckPoint MGMT server\n#\n#\n##\n# A package for reading passwords without displaying them on the console\nfrom __future__ import print_function\n# cpapi is a library that handles the communication with the Check Point management server.\nfrom cpapi import APIClient, APIClientArgs\n\nimport json\nimport os\nimport sys\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\n\ndef main():\n # Login to the Server\n # getting details from the support files\n #\n\n with open('./auth/mycpapi.json') as json_file:\n server = json.load(json_file)\n\n api_server = server['chkp']['host']\n\n with open('./auth/mycpauth.json') as json_file:\n auth = json.load(json_file)\n\n username = auth['user']\n password = auth['password']\n\n client_args = APIClientArgs(server=api_server)\n\n with APIClient(client_args) as client:\n\n # create debug file. The debug file will hold all the communication between the python script and\n # Check Point's management server.\n client.debug_file = \"api_calls.json\"\n\n # The API client, would look for the server's certificate SHA1 fingerprint in a file.\n # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.\n # In case the user does not accept the fingerprint, exit the program.\n if client.check_fingerprint() is False:\n print(\"Could not get the server's fingerprint - Check connectivity with the server.\")\n exit(1)\n\n # login to server:\n login_res = client.login(username, password)\n # print(login_res.data.get(\"sid\"))\n # sid = login_res.data.get(\"sid\")\n # print(sid)\n\n if login_res.success is False:\n print(\"Login failed:\\n{}\".format(login_res.error_message))\n exit(1)\n\n ### Actual Code Starts here ###\n\n print(\"Processing. Please wait...\")\n show_access_layers_res = client.api_query(\"show-access-layers\", \"standard\")\n if show_access_layers_res.success is False:\n print(\"Failed to get the list of all host objects:\\n{}\".format(show_access_layers_res.error_message))\n exit(1)\n\n layerarr = []\n\n # print(show_access_layers_res.data)\n layers = show_access_layers_res.data['access-layers']\n\n for layer in layers:\n ##print(layer['name'])\n layerarr.append(layer['name'])\n\n print(layerarr)\n\n print(\"************************\")\n\n awrulebase = {}\n\n cmddata = {'name': \"\", 'use-object-dictionary': 'true', 'show-hits': 'true'}\n\n for layer in layerarr:\n cmddata['name'] = layer\n cmddata['offset'] = 0\n show_access_rulebase_res = client.api_call(\"show-access-rulebase\", cmddata)\n awrulearr = show_access_rulebase_res.data['rulebase']\n while show_access_rulebase_res.data['total'] > show_access_rulebase_res.data['to']:\n cmddata['offset'] = show_access_rulebase_res.data['to']\n show_access_rulebase_res = client.api_call(\"show-access-rulebase\", cmddata)\n awrulearr += show_access_rulebase_res.data['rulebase']\n\n awrulebase[layer] = awrulearr\n\n awrulebase_pretty = json.dumps(awrulebase, indent=2)\n print(awrulebase_pretty)\n\n with open('awpyrules.json', 'w') as outfile:\n outfile.write(awrulebase_pretty)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"awrules.py","file_name":"awrules.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"561251116","text":"COLUMN_TEMPLATE = '{column_name} {column_type}'\n\n\nclass TableColumn(object):\n def __init__(self, column_name, column_type, is_not_null=True, has_index=False):\n self.column_name = column_name.upper()\n self.column_type = column_type.upper()\n self.is_not_null = is_not_null\n self.has_index = has_index\n\n def __cmp__(self, other):\n return self.column_name == other.column_name\n\n '''\n Returns the column signature (used also for the table creation statement)\n '''\n def __str__(self):\n signature = COLUMN_TEMPLATE.format(column_name=self.column_name, column_type=self.column_type)\n if self.is_not_null:\n signature += ' NOT NULL'\n if self.has_index:\n signature += ', INDEX ({})'.format(self.column_name)\n return signature\n","sub_path":"py/RuleRefinement/RSAData/db_builder/infra/table_column.py","file_name":"table_column.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"35244380","text":"def Auto_Outside_System(caller, owner, whenst, where):\r\n thistime = whenst + 2\r\n whenfin = whenst + 3\r\n print(\"Time now : \", thistime)\r\n print(\"Hi,\",caller, \"Sorry to say you this sad sentences\")\r\n print(owner, \"is gone to \", where, \" from \", whenst, \" to \", whenfin)\r\n print(\"Or will you leave your phone number to him??(y, n) : \")\r\n answer = input()\r\n if (answer == \"y\"):\r\n number = input(\"번호 입력 : \")\r\n print(\"Is this your number??(y, n) -> \", number)\r\n ans2 = input()\r\n if (ans2 == \"y\"):\r\n print(\"Ok, Thanks! I will give your number to my boss\")\r\n else:\r\n print(\"Sorry, I am busy now. Please call back\")\r\n else:\r\n print(\"Ok! Then call later,please^^\")\r\n print(\"===========================================\")\r\nowner = \"JoSungSu\"\r\ncaller = str(input(\"What is your name, sir??\"))\r\nwhenst = random.choice([9, 12, 15, 17, 20])\r\nwhere = [\"GangNam\", \"DongJak\", \"Jongro\"]\r\nwhereIndex = random.randrange(0, len(where))\r\nif (whereIndex == 0):\r\n where = \"GangNam\"\r\nif (whereIndex == 1):\r\n where = \"DongJak\"\r\nif (whereIndex == 2):\r\n where = \"Jongro\"\r\nAuto_Outside_System(caller, owner, whenst, where)\r\n","sub_path":"Auto_Outside_System.py","file_name":"Auto_Outside_System.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534251625","text":"import os\nimport urllib.parse\n\nimport airflow\nimport pendulum\nfrom airflow import models\nfrom airflow.configuration import conf\nfrom airflow.models.baseoperator import BaseOperatorLink\nfrom airflow.plugins_manager import AirflowPlugin\nfrom airflow.settings import STORE_SERIALIZED_DAGS\nfrom airflow.utils.db import provide_session\nfrom airflow.utils.log.file_task_handler import FileTaskHandler\nfrom airflow.www import utils as wwwutils\nfrom airflow.www.forms import DateTimeForm\nfrom flask import Blueprint, request\nfrom flask_appbuilder import expose, BaseView as AppBuilderBaseView\n\nairflow.load_login()\nlogin_required = airflow.login.login_required\n\n# Creating a flask appbuilder BaseView\nclass WorkerLogsBaseView(AppBuilderBaseView):\n\n default_view = \"render\"\n\n @expose(\"/\")\n @login_required\n @wwwutils.action_logging\n @provide_session\n def render(self, session=None):\n dag_id = request.args.get(\"dag_id\")\n task_id = request.args.get(\"task_id\")\n execution_date = request.args.get(\"execution_date\")\n\n if not dag_id or not task_id or not execution_date:\n return self.render_template(\n \"airflow/circles.html\", hostname=\"readact\" # Airflow 404 template\n )\n\n dttm = pendulum.parse(execution_date)\n form = DateTimeForm(data={\"execution_date\": dttm})\n dagbag = models.DagBag(\n os.devnull, # to initialize an empty dag bag\n store_serialized_dags=STORE_SERIALIZED_DAGS,\n )\n dag = dagbag.get_dag(dag_id)\n ti = (\n session.query(models.TaskInstance)\n .filter(\n models.TaskInstance.dag_id == dag_id,\n models.TaskInstance.task_id == task_id,\n models.TaskInstance.execution_date == dttm,\n )\n .first()\n )\n ti.task = dag.get_task(ti.task_id)\n\n file_task_handler = FileTaskHandler(\n base_log_folder=conf.get(\"core\", \"BASE_LOG_FOLDER\"),\n filename_template=conf.get(\"core\", \"LOG_FILENAME_TEMPLATE\"),\n )\n logs, metadatas = file_task_handler.read(ti, None, None)\n return self.render_template(\n \"worker_logs_plugin/template.html\",\n logs=logs,\n dag=dag,\n title=\"Logs from worker\",\n dag_id=dag.dag_id,\n task_id=task_id,\n execution_date=execution_date,\n form=form,\n root=\"\",\n wrapped=conf.getboolean(\"webserver\", \"default_wrap\"),\n )\n\n\nv_appbuilder_view = WorkerLogsBaseView()\nv_appbuilder_package = {\n \"name\": \"Worker Logs\",\n \"category\": \"Browse\",\n \"view\": v_appbuilder_view,\n}\n\n# Creating a flask blueprint to integrate the templates and static folder\nbp = Blueprint(\n \"worker_logs_plugin\",\n __name__,\n template_folder=\"templates\",\n static_folder=\"static\",\n static_url_path=\"/static/template\",\n)\n\n# An extra button link in task page that redirect to logs from worker\nclass WorkerLogsLink(BaseOperatorLink):\n name = \"Worker Logs\"\n\n def get_link(self, operator, dttm):\n return (\n f'{os.getenv(\"AIRFLOW__WEBSERVER__BASE_URL\")}'\n f\"/workerlogsbaseview\"\n f\"?task_id={operator.task_id}&dag_id={operator.dag_id}\"\n f\"&execution_date={urllib.parse.quote(str(dttm))},\"\n )\n\n\n# Defining the plugin class\nclass AirflowWorkerLogsPlugin(AirflowPlugin):\n name = \"worker_logs_plugin\"\n flask_blueprints = [bp]\n appbuilder_views = [v_appbuilder_package]\n global_operator_extra_links = [\n WorkerLogsLink(),\n ]\n","sub_path":"plugins/WorkerLogFetcher.py","file_name":"WorkerLogFetcher.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540408236","text":"print('To samo co Laboratorium 2 -> Zadanie 2')\nprint('')\n\n# Utwórz program, który wczytuje komunikat użytkownika, a następnie wypisuje go\n# w odwrotnej kolejności.\n\n#string=input(\"Podaj tekst do odwrócenia\")\ndef reverse(string):\n length = len(string)\n str2 = ''\n for x in range(0, length).__reversed__():\n str2 = str2+string[x]\n return str2\n\nprint(reverse(string=input(\"Podaj tekst do odwrócenia\")))\n\n","sub_path":"Laboratorium1/Zadania Prostrze/Zadanie10.py","file_name":"Zadanie10.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"506879736","text":"from .utils import get_latest_rpe, get_number_of_submissions, get_date_first_submission\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.views import generic\nfrom django.contrib import messages\nimport datetime\nfrom django.utils.translation import ugettext as _\n\n\nclass DashboardView(generic.TemplateView):\n template_name = 'player_dashboard/index.html'\n\n def get_template_names(self):\n \"\"\"\n Returns a list of template names to be used for the request. Must return\n a list. May not be called if render_to_response is overridden.\n \"\"\"\n if self.template_name is None:\n raise ImproperlyConfigured(\n \"TemplateResponseMixin requires either a definition of \"\n \"'template_name' or an implementation of 'get_template_names()'\"\n )\n else:\n if self.request.user.is_authenticated():\n group = self.request.user.groups.values_list('name', flat=True)\n if 'Club' in group:\n messages.add_message(self.request, messages.INFO, _('Please login with your Player Account.'))\n return ['registration/login.html']\n elif 'Coach' in group:\n messages.add_message(self.request, messages.INFO, _('Please login with your Player Account.'))\n return ['registration/login.html']\n elif 'Player' in group:\n return [self.template_name]\n else:\n messages.add_message(self.request, messages.INFO, _('Please login with your Player Account.'))\n return ['registration/login.html']\n else:\n return ['registration/login.html']\n\n def get_context_data(self, **kwargs):\n context = super(DashboardView, self).get_context_data(**kwargs)\n if not self.request.user.is_authenticated():\n return {}\n group = self.request.user.groups.values_list('name', flat=True)\n\n if 'Club' in group:\n return {}\n elif 'Coach' in group:\n return {}\n elif 'Player' in group:\n context['menu_item'] = 'index'\n context['latest_rpe'] = get_latest_rpe(self.request.user.player)\n context['count_training_session'] = get_number_of_submissions(self.request.user.player, 'exercise-diary')\n context['count_daily_wellbeing'] = get_number_of_submissions(self.request.user.player, 'daily-wellbeing-u15')\n context['completion_daily_wellbeing'] = int((context['count_daily_wellbeing'] / (\n datetime.date.today() - get_date_first_submission(self.request.user.player, 'daily-wellbeing-u15')\n ).days) * 100)\n return context\n else:\n return {}\n","sub_path":"apps/player_dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"475133424","text":"import os\n\nfrom .base import PROJECT_ROOT_DIR\n\n# Static settings\nSTATIC_URL = '/static/'\n\nSTATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n\n 'pipeline.finders.PipelineFinder',\n)\n\nSTATIC_ROOT = os.path.join(PROJECT_ROOT_DIR, \"dist\", \"static\")\n\nPIPELINE = {\n 'STYLESHEETS': {\n 'chacha_dabang': {\n 'source_filenames': (\n 'css/*.css',\n 'fonts/*.css'\n ),\n 'output_filename': 'css/chacha_dabang.css',\n },\n },\n 'JAVASCRIPT': {\n 'chacha_dabang': {\n 'source_filenames': (\n 'js/owl.carousel.min.js',\n 'js/viewport-units-buggyfill.js',\n 'js/scripts.js',\n ),\n 'output_filename': 'js/chacha_dabang.js',\n },\n 'jquery': {\n 'source_filenames': (\n 'js/jquery/jquery.min.js',\n 'js/jquery/jquery.easing.1.3.min.js',\n 'js/jquery/jquery.form.js',\n 'js/jquery/jquery.validate.min.js',\n 'js/jquery/jquery.isotope.min.js',\n 'js/jquery/jquery.easytabs.min.js',\n ),\n 'output_filename': 'js/jquery.js',\n },\n 'bootstrap': {\n 'source_filenames': (\n 'js/bootstrap/bootstrap.min.js',\n 'js/bootstrap/bootstrap-hover-dropdown.min.js',\n ),\n 'output_filename': 'js/bootstrap.js',\n },\n 'waypoints': {\n 'source_filenames': (\n 'js/waypoints/waypoints.min.js',\n 'js/waypoints/waypoints-sticky.min.js',\n ),\n 'output_filename': 'js/waypoints.js',\n },\n 'skrollr': {\n 'source_filenames': (\n 'js/skrollr/*.js',\n 'js/skrollr/skrollr.min.js',\n 'js/skrollr/skrollr.stylesheets.min.js',\n ),\n 'output_filename': 'js/skrollr.js',\n },\n 'comments': {\n 'source_filenames': (\n 'js/posts/comments.js',\n ),\n 'output_filename': 'js/comments.js',\n }\n }\n}\n\n# Media settings\nMEDIA_ROOT = os.path.join(\n PROJECT_ROOT_DIR,\n 'dist',\n 'media',\n)\nMEDIA_URL = \"/media/\"\n","sub_path":"chacha_dabang/chacha_dabang/settings/partials/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143509493","text":"#!/bin/python\n\n\"\"\"\nCollect packet-drop statistics, and optionally, net-stats, from an ESX host\nOutput is printed to console, and is also written to file '/tmp/vmaperf1.out'\n\nUsage examples:\n\n 1. Collect drop counts\n ./vmaperf.py --swport \n\n 2. Collect drop counts and net-stats\n ./vmaperf.py --swport --netstats\n\n 3. Collect drop counts and net-stats for 100 seconds, at 4-second intervals\n ./vmaperf.py --swport --netstats --tsec 100 --duration 4\n\n Default is to collect for 300 seconds, at 5-second intervals\n\n CAUTION: Running this monitoring program does cost CPU cycles and memory.\n Consider the overhead of running it.\n When running with default parameters (as in example #1), the overhead is negligible.\n When running with --netstats, esp with small values of --duration, or with large values of --tsec, overhead can be significant.\n\nQuestions and bug reports: please email vabidi@vmware.com\n\"\"\"\nimport sys\nimport os\nimport time\nimport subprocess\nimport argparse\nimport signal\n\n\npc_fname = \"/tmp/vmaperf1.out\"\nns_fname = \"/tmp/ns1.out\"\nMAX_SECONDS = 300\nDFLT_INTERVAL = 5\n\nvmnic_rxd, vmx_rxd, nioc_txd, rxpkts = 0, 0, 0, 0\ni = 0\nrdrops, rpkts = [], []\n\n\ndef parseArgs(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--tsec\", help=\"time in secs\", type=int, default=MAX_SECONDS)\n parser.add_argument(\"--duration\", help=\"duration in secs\", type=int, default=DFLT_INTERVAL)\n parser.add_argument(\"--swport\", help=\"switchport number\", required=True)\n parser.add_argument(\"--netstats\", help=\"collect net-stats\", action=\"store_true\")\n args = parser.parse_args()\n return args\n\n\ndef endit():\n global pcfile\n # compute drop percent\n dp = sum(rdrops) * 100.0 / sum(rpkts)\n line = \"Total drops = %d rxpkts = %d Drop Percentage is %.3f\" % (sum(rdrops), sum(rpkts), dp)\n\n print(line)\n pcfile.write(line + \"\\n---------\\n\")\n pcfile.close()\n if argt.netstats:\n time.sleep(2)\n pcfile = open(pc_fname, 'a')\n nsfile = open(ns_fname)\n pcfile.write(nsfile.read())\n pcfile.close()\n nsfile.close()\n\n sys.exit()\n\ndef sighandler(frame, signum):\n endit()\n\n\ndef start_netstats(argt):\n ival = argt.duration\n num = argt.tsec/ival\n cmd = \"net-stats -A -t WwQqi -i %d -n %d -o %s\" % (ival, num, ns_fname)\n print(cmd)\n subprocess.Popen(cmd.split())\n\n\ndef get_kw_value(cli, name):\n res = subprocess.check_output(cli, shell=True)\n res = str(res)\n for line in res.split('\\\\n'):\n if name in line:\n return int(line.split(':')[-1])\n\n # I considered return None below, but decided that would increase caller complexity, with questionable benefit\n return 0\n\n\nargt = parseArgs(sys.argv)\nsignal.signal(signal.SIGINT, sighandler)\nswport = argt.swport\nduration = argt.duration\n\ncli1 = \"localcli --plugin-dir /usr/lib/vmware/esxcli/int networkinternal nic privstats get -n vmnic0\"\n\ncli2 = \"vsish -e get /net/portsets/DvsPortset-0/ports/%s/vmxnet3/rxSummary\" % swport\n\ncli3 = \"vsish -e get /vmkModules/netsched_hclk/devs/vmnic0/qleaves/netsched.pools.vm.%s/info\" % swport\n\ncli_line = cli1 + \"\\n\" + cli2 + \"\\n\" + cli3 + \"\\n\"\n\ntitle = \"\\nSecs\\tvmnic0-rxdrops\\tvmxnet3-rxdrops\\thclk-txdrops\\trxpkts\\t%drops\\n\"\ntitle += \"-\"*70 + \"\\n\"\npcfile = open(pc_fname, 'w')\npcfile.write(cli_line)\npcfile.write(title)\nprint(cli_line)\nprint(title)\n\n# Start net-stats if required\nif argt.netstats:\n start_netstats(argt)\n\n\nwhile i <= argt.tsec:\n val = get_kw_value(cli1, 'rx_pkts')\n del_rxpkts = (val - rxpkts)\n rxpkts = val\n\n val = get_kw_value(cli1, 'rx_drops')\n del_vmnic_rxd = (val - vmnic_rxd)\n vmnic_rxd = val\n\n val = get_kw_value(cli2, 'running out of buffers')\n del_vmx_rxd = (val - vmx_rxd)\n vmx_rxd = val\n\n val = get_kw_value(cli3, 'pktsDropped')\n del_nioc_txd = (val - nioc_txd)\n nioc_txd = val\n\n if i > 0:\n drops = del_vmnic_rxd + del_vmx_rxd + del_nioc_txd\n drop_percent = drops * 100.0 / del_rxpkts\n rdrops.append(drops)\n rpkts.append(del_rxpkts)\n else:\n drop_percent = 0.0\n\n line = \"%d \\t %d \\t %d \\t %d \\t %d \\t %.3f\\n\" % \\\n (i, del_vmnic_rxd, del_vmx_rxd, del_nioc_txd, del_rxpkts,\n drop_percent)\n\n pcfile.write(line)\n print(line)\n i += duration\n time.sleep(duration)\nendit()\n","sub_path":"perftools/vmaperf.py","file_name":"vmaperf.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183238139","text":"from sklearn.datasets import load_files\nfrom keras.utils import np_utils\nimport numpy as np\nfrom glob import glob\nimport cv2\nimport os\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.models import Model, load_model, Sequential\nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\nfrom keras.layers import Dropout, Flatten, Dense\n\nfrom helper import paths_to_tensor, path_to_tensor, load_dataset\n\n\nclass Classifer_Dog_Breed():\n def __init__(self, model_name='Resnet50'):\n ''' '''\n self.model_name = model_name\n\n def create_data_set(self, pathname='dogImages/'):\n ''' '''\n self.train_files, self.train_targets = load_dataset(pathname + 'train')\n self.valid_files, self.valid_targets = load_dataset(pathname + 'valid')\n self.test_files, self.test_targets = load_dataset(pathname + 'test')\n self.data_set_size = len(self.train_files)\n self.dog_names = [item[20:-1] for item in sorted(glob(pathname + \"train/*/\"))]\n\n def preprocess_data(self, size=None):\n ''' '''\n if size is not None:\n self.data_set_size = size\n # pre-process the data for Keras\n self.train_tensors = paths_to_tensor(\n train_files[:self.data_set_size]).astype('float32')/255\n self.valid_tensors = paths_to_tensor(\n valid_files[:self.data_set_size]).astype('float32')/255\n self.test_tensors = paths_to_tensor(\n test_files[:self.data_set_size]).astype('float32')/255\n\n def create_bottleneck_features(self):\n ''' '''\n pathname = 'bottleneck_features/Dog' + self.model_name + 'Data.npz'\n bottleneck_features = np.load(pathname)\n self.train_bottleneck_features = bottleneck_features['train']\n self.valid_bottleneck_features = bottleneck_features['valid']\n self.test_bottleneck_features = bottleneck_features['test']\n\n def create_model(self):\n \"\"\" \"\"\"\n self.model = Sequential()\n self.model.add(GlobalAveragePooling2D(\n input_shape=self.train_bottleneck_features.shape[1:]))\n self.model.add(Dense(133, activation='softmax'))\n\n def model_summery(self):\n \"\"\" shows the architecture of the model \"\"\"\n print(self.model.summary())\n\n def train(self, save_path=None):\n ''' transfer learning saves the trained model to the given path '''\n save_path = 'saved_models/weights.best.' + self.model_name + '.hdf5'\n if save_path is not None:\n save_path = save_path\n checkpointer = ModelCheckpoint(filepath=save_path, verbose=1, save_best_only=True)\n self.model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n self.model.fit(\n self.train_bottleneck_features, self.train_targets,\n validation_data=(self.valid_bottleneck_features, self.valid_targets),\n epochs=30, batch_size=128, callbacks=[checkpointer], verbose=1)\n\n def load_model(self, path_name=None):\n \"\"\" is load the model of the given pathname \"\"\"\n load_path = 'saved_models/weights.best.' + self.model_name + '.hdf5'\n if path_name is not None:\n load_path = path_name\n self.create_bottleneck_features()\n print(load_path)\n self.create_model()\n if os.path.isfile(load_path): \n self.model.load_weights(load_path)\n\n def predict(self, image_path):\n \"\"\" \"\"\"\n tensor = path_to_tensor(image_path)\n preprocess_tensor = preprocess_input(tensor)\n model = InceptionV3(include_top=False)\n bottleneck_shape = model.predict(preprocess_tensor)\n self.y_predict = self.model.predict(bottleneck_shape)\n return self.dog_names[np.argmax(self.y_predict)]\n\n\nif __name__ == \"__main__\":\n model = Classifer_Dog_Breed(model_name='InceptionV3')\n model.load_model()\n model.create_data_set()\n model.train()\n model.predict(model.test_files[1])\n","sub_path":"dogbreed_prediction/dog_prediction.py","file_name":"dog_prediction.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212571451","text":"def isLeave(a,b,c):\r\n if a in c and b in c:\r\n return True\r\n else:\r\n return False\r\n \r\n\r\n\r\nif __name__=='__main__':\r\n t = int(input())\r\n for _ in range(t):\r\n arr = input().strip().split()\r\n if isLeave(arr[0], arr[1], arr[2]):\r\n print(1)\r\n else:\r\n print(0)\r\n\r\n\r\n","sub_path":"Interleaving Strings (SUdo Geeks).py","file_name":"Interleaving Strings (SUdo Geeks).py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"216726312","text":"import validators\n\nfrom apps.authentication.models import ResortOauthApp\nfrom apps.custom_user.models import UserRoles\nfrom apps.incidents.utils import get_template\nfrom apps.resorts.models import Resort\nfrom apps.resorts.models import UserResortMap\nfrom apps.resorts.serializers import ResortSerializer\nfrom apps.resorts.serializers import UserResortListSerializer\nfrom apps.resorts.serializers import UserResortMapSerializer\nfrom apps.routing.models import Domains\nfrom helper_functions import delete_keys_from_dict\nimport urllib\n\n\ndef get_resort_by_name(resort_name):\n \"\"\"\n Returns resort object based resort name\n \"\"\"\n return Resort.objects.filter(resort_name=resort_name).first()\n\n\ndef get_resort_by_network_key(key):\n return Resort.objects.filter(network_key=key).first()\n\n\ndef get_resort_by_resort_id(key):\n return Resort.objects.filter(resort_id=key).first()\n\n\ndef get_user_resort_map(user, resort):\n return UserResortMap.objects.filter(user=user, resort=resort).first()\n\n\ndef get_resort_for_user(user):\n try:\n user_resort = UserResortMap.objects.filter(user=user).first()\n return user_resort.resort\n except:\n return None\n\n\ndef get_userrole_for_resort(resort, method, user):\n if user.user_connected == 1:\n user_resort_role = UserResortMap.objects.filter(resort=resort, user__user_connected=1, user__is_active=True)\n else:\n user_resort_role = UserResortMap.objects.filter(resort=resort, user=user, user__is_active=True)\n\n if len(user_resort_role) != 0:\n if method == 'get':\n user_resort_data = UserResortMapSerializer(user_resort_role, fields=('user', 'role'), many=True)\n return user_resort_data.data\n elif method == 'list':\n user_resort_data = UserResortListSerializer(user_resort_role, fields=('user', 'role'), many=True)\n return user_resort_data.data\n\n\ndef get_userrole_for_list(resort):\n user_resort_role = UserResortMap.objects.filter(resort=resort)\n\n if len(user_resort_role) != 0:\n user_resort_data = UserResortMapSerializer(user_resort_role, fields=('user', 'role'), many=True)\n return user_resort_data.data\n\n\ndef user_resort_map(user, resort, role_id):\n role = UserRoles(role_id=role_id)\n user_resort_exists = UserResortMap.objects.filter(user=user, resort=resort, role=role).first()\n\n if user_resort_exists is None:\n new_user_resort = UserResortMap(user=user, resort=resort, role=role)\n new_user_resort.save()\n\n return True\n\n\n# Updates template of resort during creation and updation of resort\ndef template_update(resort, created):\n template = {}\n if created:\n template = get_template()\n if resort.print_on_device == 0:\n template = delete_keys_from_dict(template, ['print_button'])\n else:\n template = resort.incident_template\n if resort.print_on_device == 0:\n template = delete_keys_from_dict(template, ['print_button'])\n else:\n try:\n print_template = template['DashboardItems']['print_button']\n except:\n template['DashboardItems'].update({\"print_button\": {\n \"Label\": \"print\",\n \"Placeholder\": \"\",\n \"Type\": \"\",\n \"Required\": \"false\",\n \"Order\": \"9998\",\n \"Values\": \"\"\n }})\n return template\n\n\ndef get_setting_data_for_resort(resort):\n return_data = {}\n resort_data = ResortSerializer(resort, fields=('map_kml', 'default_unit_paper', 'map_lat', 'map_lng',\n 'network_key', 'licenses', 'report_form',\n 'unit_format', 'timezone', 'resort_logo', 'domain_id',\n 'datetime_format', 'dispatch_field_choice', 'initial_map_zoom_level'))\n return_data.update(resort_data.data)\n\n user_count = UserResortMap.objects.filter(resort=resort, user__user_connected=1, user__is_active=True).count()\n return_data.update({\"user_count\": user_count})\n\n try:\n app = ResortOauthApp.objects.get(resort=resort)\n return_data.update({'client_id': app.oauth_app.client_id, 'client_secret': app.oauth_app.client_secret})\n except:\n return_data.update({'client_id': '', 'client_secret': ''})\n\n\n return return_data\n\n\ndef transform_resort_settings_request(incoming_data):\n field_to_remove = []\n for key, value in incoming_data.iteritems():\n if key in ['resort_logo', 'map_kml', 'report_form']:\n if validators.url(value) or (not value):\n field_to_remove.append(key)\n\n for field in field_to_remove:\n del incoming_data[field]\n\n domain_id = incoming_data.get('domain_id')\n if domain_id is not None:\n domains = Domains.objects.filter(domain=domain_id)\n if len(domains) > 0:\n incoming_data['domain_id'] = domains[0].domain_id\n\n return incoming_data","sub_path":"project/apps/resorts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"234306739","text":"\"\"\"Constantes of the game MacGyver Labyrinth\"\"\"\r\n\r\n#Window settings\r\nsize_sprite = 40\r\nx_number_sprites = 15\r\ny_number_sprites = 16\r\nx_size_window = size_sprite * x_number_sprites\r\ny_size_window = size_sprite * y_number_sprites\r\n\r\n#Customizing the window\r\nname_window = \"MacGyver Labyrinth\"\r\nimage_icon = \"images/player.png\"\r\n\r\n#List of the images\r\nimage_floor = \"images/floor.png\"\r\nimage_guard = \"images/guardian.png\"\r\nimage_tube = \"images/tube.png\"\r\nimage_needle = \"images/needle.png\"\r\nimage_ether = \"images/ether.png\"\r\nimage_macgyver = \"images/player.png\"\r\nimage_escaped = \"images/escaped.png\"\r\nimage_died = \"images/died.png\"\r\nimage_legend = \"images/legend.png\"","sub_path":"constantes.py","file_name":"constantes.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500180508","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 18 18:37:53 2018\n\n@author: Prodipta\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport quandl\nimport json\nimport sys\nimport re\nimport requests\nfrom StringIO import StringIO\nimport nsepy\n\n# TODO: This is a hack, install the correct version\nzp_path = \"C:/Users/academy.academy-72/Documents/python/zipline/\"\nsys.path.insert(0, zp_path)\n# TODO: End of hack part\n\nfrom zipline.data import bundles as bundles_module\nfrom zipline.data.bundles import register\nfrom zipline.data.bundles.XNSE import xnse_equities\nfrom zipline.data.bundles.ingest_utilities import read_big_csv,split_csvs,unzip_to_directory,clean_up,get_ohlcv, find_interval, upsert_pandas, update_ticker_change, if_csvs_in_dir, ensure_data_between_dates\n\ndef subset_adjustment(dfr, meta_data):\n meta_data['start_date'] = pd.to_datetime(meta_data['start_date'])\n meta_data['end_date'] = pd.to_datetime(meta_data['end_date'])\n dfr.iloc[:,0] = pd.to_datetime(dfr.iloc[:,0])\n syms = dfr['symbol'].tolist()\n for s in syms:\n start_date = meta_data.loc[meta_data['symbol']==s,'start_date'].iloc[0]\n end_date = meta_data.loc[meta_data['symbol']==s,'end_date'].iloc[0]\n dfr = dfr[~((dfr.symbol == s) & (dfr.iloc[:,0] < start_date))]\n dfr = dfr[~((dfr.symbol == s) & (dfr.iloc[:,0] > end_date))]\n return dfr\n\n\ndef load_quandl_tickers(tickers_path):\n df = pd.read_csv(tickers_path, header=None)\n df.columns = ['Ticker','Name']\n df = df[df.Name.str.contains(\"\\(EQ(.+)\\) Unadjusted\")]\n tickers = [re.search(\"\\(EQ(.+)\\) Unadjusted\",s).group(1) for s in df.Name.tolist()]\n names = [s.split(' (EQ'+tickers[i])[0] for i,s in enumerate(df.Name.tolist())]\n names = [s.split(\"Ltd\")[0].strip() for s in names]\n quandl_tickers = df.Ticker.tolist()\n df_dict = {'symbol':tickers,'qsymbol':quandl_tickers, 'name':names}\n tickers = pd.DataFrame(df_dict,columns=['symbol','qsymbol','name'])\n return tickers\n\ndef nse_to_quandl_tickers(syms,tickers,strip_prefix=False, strip_suffix=False):\n tickers = tickers[~tickers.qsymbol.str.endswith(\"_1_UADJ\")]\n map_dict = dict(zip(tickers.symbol,tickers.qsymbol))\n qsyms = [map_dict[s] for s in syms]\n\n if strip_prefix:\n qsyms = [q.split(\"XNSE/\")[1] for q in qsyms]\n if strip_suffix:\n qsyms = [q.split(\"_UADJ\")[0] for q in qsyms]\n\n return qsyms\n\ndef quandl_to_nse_tickers(qsyms,tickers,add_prefix=False, add_suffix=False):\n if add_prefix:\n qsyms = [\"XNSE/\"+q for q in qsyms]\n if add_suffix:\n qsyms = [q+\"_UADJ\" for q in qsyms]\n\n map_dict = dict(zip(tickers.qsymbol,tickers.symbol))\n syms = [map_dict[q] for q in qsyms]\n\n return syms\n\ndef get_latest_symlist(url):\n try:\n r = requests.get(url)\n syms = pd.read_csv(StringIO(r.content))\n except:\n raise IOError(\"failed to download the latest NIFTY500 membership\")\n return syms['Symbol'].tolist()\n\ndef download_data(url, api_key, strpath):\n try:\n r = requests.get(url+api_key, stream=True)\n zipdata = StringIO()\n for chunk in r.iter_content(chunk_size=1024):\n if chunk:\n zipdata.write(chunk)\n unzip_to_directory(zipdata,strpath)\n except:\n raise IOError(\"failed to download latest data from Quandl\")\n\ndef adjustment_classifier(x):\n s = str(int(x))\n order = ['s','m','d']\n s = re.sub(r\"[1][7]|[1][8]|[2][0]\", \"d\", s)\n s = re.sub(r\"[6]\",\"m\",s)\n s = re.sub(r\"[1-9]\",\"s\",s)\n s = re.sub(r\"[0]\",\"\",s)\n s = \"\".join(set(s))\n s = reduce((lambda x,y: x\n if order.index(x) < order.index(y) else y), s)\n if len(s) != 1:\n raise ValueError('Undefined adjustment type, please check input {}'.format(x))\n return s\n\nclass IngestLoop:\n\n def __init__(self, configpath):\n with open(configpath) as configfile:\n config = json.load(configfile)\n quandl.ApiConfig.api_key = config[\"QUANDL_API_KEY\"]\n self.config_path = configpath\n self.api_key = config[\"QUANDL_API_KEY\"]\n self.quandl_table_name = config[\"QUANDL_TABLE_NAME\"]\n self.bundle_name=config[\"BUNDLE_NAME\"]\n self.bundle_path=config[\"BUNDLE_PATH\"]\n self.calendar_name=config[\"CALENDAR_NAME\"]\n self.calendar_tz=config[\"CALENDAR_TZ\"]\n self.meta_path=config[\"META_PATH\"]\n self.daily_path=config[\"DAILY_PATH\"]\n self.download_path=config[\"DOWNLOAD_PATH\"]\n self.bizdays_file=config[\"BIZDAYLIST\"]\n self.symlist_file=config[\"SYMLIST\"]\n self.sym_directory=config[\"SYM_DIRECTORY\"]\n self.sym_url = config['SYMBOLS_DOWNLOAD_URL']\n self.data_url = config['DATA_DOWNLOAD_URL']\n self.code_url = config['CODE_DOWNLOAD_URL']\n self.benchmark_file = config['BENCHMARKDATA']\n self.benchmark_sym = config['BENCHMARK_SYM']\n self.benchmark_download_sym = config['BENCHMARK_DOWNLOAD_SYM']\n self.code_file = config[\"QUANDLE_TICKER_MAP\"]\n self.ticker_change_file = config[\"TICKER_CHANGE_FILE\"]\n self.ensure_codes()\n self.ensure_data()\n self.tickers = load_quandl_tickers(os.path.join(self.meta_path,config[\"QUANDLE_TICKER_MAP\"]))\n self.last_data_dt = self.get_last_data_date()\n\n def get_last_data_date(self):\n dts = []\n files = os.listdir(self.download_path)\n try:\n dts = [pd.to_datetime(f.split(\"XNSE_\")[1].split(\".csv\")[0]) for f in files]\n except:\n pass\n if dts:\n return dts[-1].tz_localize(tz=self.calendar_tz)\n\n return None\n\n def ensure_codes(self):\n if not os.path.isfile(os.path.join(self.meta_path,self.code_file)):\n print(\"code file missing, downloading...\")\n download_data(self.code_url,self.api_key,self.meta_path)\n print(\"code file download complete\")\n\n def ensure_data(self):\n items = os.listdir(self.download_path)\n files = [f for f in items if f.endswith(\".csv\") and \"XNSE\" in f]\n if not files:\n print(\"data file missing, downloading...\")\n download_data(self.data_url,self.api_key,self.download_path)\n print(\"data file download complete\")\n\n def ensure_latest_data(self, date):\n if date > self.last_data_dt:\n print(\"data file stale, downloading...\")\n download_data(self.data_url,self.api_key,self.download_path)\n print(\"data file download complete\")\n self.last_data_dt = self.get_last_data_date()\n if self.last_data_dt is None:\n raise ValueError(\"no data available\")\n\n def ensure_benchmark(self, date):\n dts = self.get_bizdays()\n if not os.path.isfile(os.path.join(self.meta_path,self.benchmark_file)):\n print(\"benchmark data missing, downloading...\")\n benchmark = nsepy.get_history(symbol=self.benchmark_download_sym, start=dts[0], end=dts[-1],index=True)\n print(\"benchmark data download complete\")\n benchmark.index = pd.to_datetime(benchmark.index)\n benchmark = benchmark.dropna()\n benchmark.to_csv(os.path.join(self.meta_path,self.benchmark_file))\n\n benchmark = pd.read_csv(os.path.join(self.meta_path,self.benchmark_file),index_col=[0], parse_dates=[0])\n last_date = benchmark.index[-1]\n last_date = last_date.tz_localize(tz=self.calendar_tz)\n if date > last_date:\n print(\"benchmark data stale, updating from {} to {}\".format(last_date.strftime(\"%Y-%m-%d\"),date.strftime(\"%Y-%m-%d\")))\n increment = nsepy.get_history(symbol=self.benchmark_download_sym, start=last_date, end=date,index=True)\n print(\"benchmark data download complete\")\n benchmark = pd.concat([benchmark,increment])\n benchmark.index = pd.to_datetime(benchmark.index)\n\n benchmark = benchmark.dropna()\n benchmark = benchmark[~benchmark.index.duplicated(keep='last')]\n benchmark.to_csv(os.path.join(self.meta_path,self.benchmark_file))\n benchmark.columns = benchmark.columns.str.lower()\n benchmark = get_ohlcv(benchmark)\n if len(benchmark) == 0:\n raise ValueError(\"benchmark data does not exist\")\n benchmark.to_csv(os.path.join(self.daily_path,self.benchmark_sym+\".csv\"))\n\n def _read_symlist(self,strpath):\n sym_list = pd.read_csv(strpath)\n return sym_list\n\n def ensure_latest_sym_list(self,date):\n dts = [dt.split(\".csv\")[0].split(\"members_\")[1] for dt in os.listdir(os.path.join(self.meta_path,self.sym_directory))]\n dts = pd.to_datetime(sorted(dts))\n dts = dts.tz_localize(tz=self.calendar_tz)\n\n if date > dts[-1]:\n print(\"membership data stale, updating...\")\n symbols = get_latest_symlist(self.sym_url)\n print(\"membership data download complete\")\n if symbols:\n symfile = \"members_\"+pd.to_datetime(date,format='%d%m%Y').date().strftime('%Y%m%d')+\".csv\"\n pd.DataFrame(symbols,columns=['symbol']).to_csv(os.path.join(self.meta_path,self.sym_directory,symfile))\n else:\n raise ValueError(\"failed to download the symbols list\")\n\n def create_bizdays_list(self, dts):\n strpathmeta = os.path.join(self.meta_path,self.bizdays_file)\n dts = pd.to_datetime(sorted(set(dts)))\n dts = [d for d in dts if d.weekday()<5]\n bizdays = pd.DataFrame(sorted(set(dts)),columns=['dates'])\n if len(bizdays) == 0:\n raise ValueError(\"empty business days list\")\n bizdays.to_csv(strpathmeta,index=False)\n\n def get_bizdays(self):\n strpathmeta = os.path.join(self.meta_path,self.bizdays_file)\n bizdays = pd.read_csv(strpathmeta)\n return pd.to_datetime(bizdays['dates'].tolist())\n\n def ensure_membership_maps(self):\n if os.path.isfile(os.path.join(self.meta_path,self.symlist_file)):\n membership_maps = pd.read_csv(os.path.join(self.meta_path,self.symlist_file))\n last_date = sorted(set(pd.to_datetime(membership_maps.end_date.tolist())))[-1]\n else:\n membership_maps = pd.DataFrame(columns=['symbol','asset_name','start_date','end_date'])\n last_date = pd.to_datetime(0)\n\n dts = [dt.split(\".csv\")[0].split(\"members_\")[1] for dt in os.listdir(os.path.join(self.meta_path,self.sym_directory))]\n dts = pd.to_datetime(sorted(dts))\n ndts = [d.value/1E9 for d in dts]\n ndate = last_date.value/1E9\n dts = dts[find_interval(ndate,ndts):]\n\n print(\"updating membership data...\")\n names_dict = dict(zip(self.tickers.symbol,self.tickers.name))\n for dt in dts:\n fname = \"members_\"+dt.date().strftime(\"%Y%m%d\")+\".csv\"\n print('reading {}'.format(fname))\n syms = pd.read_csv(os.path.join(self.meta_path,self.sym_directory,fname))['symbol'].tolist()\n for sym in syms:\n upsert_pandas(membership_maps, 'symbol', sym, 'end_date', dt, names_dict)\n\n if len(membership_maps) == 0:\n raise ValueError(\"empty membership data\")\n\n print(\"checking for ticker change\")\n tickers_list = pd.read_csv(os.path.join(self.meta_path,self.ticker_change_file))\n membership_maps = update_ticker_change(membership_maps,tickers_list)\n print(\"updating membership complete\")\n membership_maps.to_csv(os.path.join(self.meta_path,self.symlist_file),index=False)\n self.symlist = membership_maps\n\n def create_csvs(self, date):\n #clean_up(self.daily_path)\n colnames=['ticker','date','open','high','low','close',\n 'volume','adj_factor','adj_type']\n print(\"reading data from disk...\")\n syms = nse_to_quandl_tickers(self.symlist['symbol'],self.tickers,strip_prefix=True)\n dfr = read_big_csv(self.download_path, syms,\"XNSE\", header=None)\n dfr.columns = colnames\n qsyms = dfr.ticker.tolist()\n dfr.ticker = quandl_to_nse_tickers(qsyms,self.tickers,add_prefix=True, add_suffix=False)\n print(\"saving csvs to disk for ingestion...\")\n split_csvs(dfr,self.daily_path, maps=self.symlist)\n dts = dfr['date']\n print(\"updating date lists...\")\n self.create_bizdays_list(dts)\n print(\"creating adjustments data...\")\n dfr['prev_close'] = dfr.close.shift(1)\n dfr['match'] = dfr.ticker.eq(dfr.ticker.shift())\n self.make_adjustments_maps(dfr)\n print(\"adjustment data creation complete.\")\n\n def ensure_data_range(self):\n if not if_csvs_in_dir(self.daily_path):\n raise IOError(\"csv data files are not available\")\n\n files = [s for s in os.listdir(self.daily_path) if s.endswith(\".csv\")]\n\n for f in files:\n sym = f.split('.csv')[0]\n if sym == self.benchmar_symbol:\n continue\n start_date = self.symlist.start_date[self.symlist.symbol==sym].tolist()[0]\n end_date = self.symlist.end_date[self.symlist.symbol==sym].tolist()[0]\n ensure_data_between_dates(os.path.join(self.daily_path,f),\n start_date, end_date)\n\n def update_membership_maps(self):\n if not if_csvs_in_dir(self.daily_path):\n raise IOError(\"csv data files are not available\")\n\n syms = [s.split(\".csv\")[0] for s in os.listdir(self.daily_path) if s.endswith(\".csv\")]\n membership_maps = self.symlist\n membership_maps = membership_maps[membership_maps.symbol.isin(syms)]\n self.symlist = membership_maps\n membership_maps.to_csv(os.path.join(self.meta_path,self.symlist_file),index=False)\n\n def make_adjustments_maps(self,dfr):\n dts = list(self.get_bizdays())\n meta_data = pd.read_csv(os.path.join(self.meta_path,self.symlist_file))\n adj_dfr = dfr.dropna()\n adj_dfr.adj_type = adj_dfr.adj_type.apply(adjustment_classifier)\n adj_dfr.loc[adj_dfr['match']==False,'prev_close'] = np.nan\n\n splits = adj_dfr.loc[adj_dfr.adj_type=='s',['date','ticker','adj_factor']]\n splits.columns = ['effective_date','symbol','ratio']\n splits.effective_date = pd.to_datetime(splits.effective_date)\n splits = subset_adjustment(splits,meta_data)\n splits = splits.sort_values(by=['effective_date'])\n\n mergers = adj_dfr.loc[adj_dfr.adj_type=='m',['date','ticker','adj_factor']]\n mergers.columns = ['effective_date','symbol','ratio']\n mergers.effective_date = pd.to_datetime(mergers.effective_date)\n mergers = subset_adjustment(mergers,meta_data)\n mergers = mergers.sort_values(by=['effective_date'])\n\n divs = adj_dfr.loc[adj_dfr.adj_type=='d',['date','ticker','adj_factor','prev_close']]\n divs['amount'] = (1 - divs.adj_factor)*divs.prev_close\n divs = divs.drop(['adj_factor','prev_close'],axis=1)\n divs.columns = ['ex_date','symbol','amount']\n divs.ex_date = pd.to_datetime(divs.ex_date)\n divs['declared_date'] = [dts[max(0,dts.index(e)-1)] for e in list(divs.ex_date)]\n divs['record_date'] = [dts[min(len(dts)-1,dts.index(e)+2)] for e in list(divs.ex_date)]\n divs['pay_date'] = divs['record_date']\n divs.declared_date = pd.to_datetime(divs.ex_date)\n divs.record_date = pd.to_datetime(divs.ex_date)\n divs.pay_date = pd.to_datetime(divs.ex_date)\n divs = subset_adjustment(divs,meta_data)\n divs = divs.sort_values(by=['ex_date'])\n\n splits.to_csv(os.path.join(self.meta_path,'splits.csv'),index=False)\n mergers.to_csv(os.path.join(self.meta_path,'mergers.csv'),index=False)\n divs.to_csv(os.path.join(self.meta_path,'dividends.csv'),index=False)\n\n\n def register_bundle(self):\n dts = (self.get_bizdays()).tz_localize(self.calendar_tz)\n register(self.bundle_name, xnse_equities(self.config_path),calendar_name=self.calendar_name,\n start_session=None,end_session=None,\n create_writers=False)\n\n def call_ingest(self):\n clean_up(os.path.join(self.bundle_path,\"minute\"))\n clean_up(os.path.join(self.bundle_path,\"daily\"))\n print(\"calling ingest function\")\n self.register_bundle()\n bundles_module.ingest(self.bundle_name,os.environ,pd.Timestamp.utcnow())\n print(\"ingestion complete\")\n\n def run(self, date, update_codes=False):\n if update_codes:\n download_data(self.code_url,self.api_key,self.meta_path)\n self.ensure_latest_sym_list(date)\n self.ensure_membership_maps()\n self.ensure_latest_data(date)\n self.create_csvs(date)\n self.ensure_benchmark(date)\n self.call_ingest()\n\n#config_path = \"C:/Users/academy.academy-72/Desktop/dev platform/data/XNSE/meta/config.json\"\n#ingest_loop = IngestLoop(config_path)\n\ndef main():\n assert len(sys.argv) == 4, (\n 'Usage: python {} '\n ' '.format(os.path.basename(__file__)))\n\n print(sys.argv[1])\n dt = pd.Timestamp(sys.argv[1],tz='Etc/UTC')\n config_file = sys.argv[2]\n update_codes = sys.argv[3]\n\n ingest_looper = IngestLoop(config_file)\n ingest_looper.run(dt, update_codes)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"zipline/data/bundles/xnse_ingest_loop.py","file_name":"xnse_ingest_loop.py","file_ext":"py","file_size_in_byte":17355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"5289048","text":"from orcsome import get_wm\nfrom orcsome.actions import *\n\n#################################################################################\n# Some from: https://github.com/BlaineEXE/window-layout\n#################################################################################\nimport argparse\nimport os\nimport os.path as path\nimport pickle\nimport re\nimport statistics as stat\nimport subprocess\n\ndef RunCommand(command):\n res = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if res.returncode != 0:\n raise Exception(\"could not run command: \" + command + \"\\nresult: \" + res)\n return(res.stdout.decode(\"utf8\"))\n\nclass Window:\n def __init__(self):\n return\n\n def NewFromWmctrlListLine(self, line):\n fields = line.split()\n self.id = fields[0]\n self.desktop = int(fields[1])\n self.x, self.y, self.w, self.h= getWindowXYWH(self.id)\n\ndef GetWindows():\n rawWins = RunCommand([\"wmctrl\", \"-pl\"])\n wins = []\n for line in rawWins.splitlines(0):\n w = Window()\n w.NewFromWmctrlListLine(line)\n if w.desktop < 0:\n continue\n wins += [w]\n return(wins)\n\ndef getWindowXYWH(windowID):\n rawInfo = RunCommand([\"xwininfo\", \"-id\", windowID])\n x = extractValueFromXwininfoLine(\"Absolute upper-left X\", rawInfo)\n y = extractValueFromXwininfoLine(\"Absolute upper-left Y\", rawInfo)\n w = extractValueFromXwininfoLine(\"Width\", rawInfo)\n h = extractValueFromXwininfoLine(\"Height\", rawInfo)\n return int(x), int(y), int(w), int(h)\n\ndef extractValueFromXwininfoLine(fullFieldText, multilineText):\n matcher = re.compile(r\"{}\\:\\s+(-?\\d+)\".format(fullFieldText))\n match = matcher.search(multilineText)\n return match.group(1)\n\n# saved 总是0 current 总是1\ndef Matches(savedWins, currentWins):\n winMatches = []\n for i in savedWins:\n for j in currentWins:\n if i.id == j.id:\n if i.x==j.x and i.y==j.y and i.w==j.w and i.h==j.h:\n continue\n winMatches += [[i, j]]\n return winMatches\n\ndef IsDiff(savedWins, currentWins):\n for i in currentWins:\n _diff = True\n for j in savedWins:\n if i.id == j.id:\n if i.x==j.x and i.y==j.y and i.w==j.w and i.h==j.h:\n _diff = False\n if _diff is True:\n return True\n return False\n\ndef UnExist(savedWins, currentWins):\n unExist = []\n for i in currentWins:\n _unexist = True\n for j in savedWins:\n if i.id == j.id:\n _unexist = False\n if _unexist is True:\n unExist += [i]\n return unExist\n\ndef SetGeometry(windowMatch):\n saved = windowMatch[0]\n currID = windowMatch[1].id\n RunCommand([\"wmctrl\", \"-i\", \"-r\", currID,\n \"-e\", \"0,{},{},{},{}\".format(saved.x , saved.y , saved.w, saved.h)])\n\ndef HideWindow(window):\n currID = window.id\n print(currID)\n RunCommand([\"xdotool\", \"windowminimize\", currID])\n#################################################################################\n\nwm = get_wm()\n\n_back = []\n_forward = []\n\n@wm.on_property_change('_NET_WM_STATE')\ndef property():\n append_wins()\n\n@wm.on_create\ndef create():\n append_wins()\n\ndef append_wins():\n global _forward, _back\n wins = GetWindows()\n if len(_back)==0 or IsDiff(_back[-1], wins):\n _back.append(wins)\n _forward.clear()\n\n@wm.on_key('Mod+u')\ndef forward_wins():\n global _forward, _back\n savedWins = _forward.pop()\n _back.append(savedWins)\n change_wins(savedWins)\n\n@wm.on_key('Mod+d')\ndef back_wins():\n global _forward, _back\n savedWins = _back.pop()\n _forward.append(savedWins)\n change_wins(savedWins)\n\ndef change_wins(savedWins):\n currentWins = GetWindows()\n matches = Matches(savedWins, currentWins)\n unexists = UnExist(savedWins, currentWins)\n\n for m in matches:\n SetGeometry(m)\n for u in unexists:\n HideWindow(u)\n \n","sub_path":"orcsome/rc.py","file_name":"rc.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332509714","text":"\n\"\"\"Simple travelling salesman problem between cities.\"\"\"\n\nfrom ortools.constraint_solver import routing_enums_pb2\nfrom ortools.constraint_solver import pywrapcp\nfrom WarehouseMapping import WarehouseMapping\n\n\ndef create_data_model(mapping, map):\n \"\"\"Stores the data for the problem.\"\"\"\n data = {}\n data['distance_matrix'] = map\n data['num_vehicles'] = 1\n data['starts'] = [0]\n data['ends'] = [len(map)-1]\n return data\n\ndef get_route(manager, routing, solution, index_to_locs):\n # Get vehicle routes and store them in a two dimensional array whose\n # i,j entry is the jth location visited by vehicle i along its route.\n index = routing.Start(0)\n route = [index_to_locs.get(manager.IndexToNode(index))]\n while not routing.IsEnd(index):\n index = solution.Value(routing.NextVar(index))\n route.append(index_to_locs.get(manager.IndexToNode(index)))\n route.pop(0)\n route.pop(-1)\n return route\n\ndef print_solution(manager, routing, solution, index_to_locs):\n index = routing.Start(0)\n plan_output = 'Best route found:\\n'\n route_distance = 0\n while not routing.IsEnd(index):\n plan_output += ' {} ->'.format(index_to_locs.get(manager.IndexToNode(index)))\n previous_index = index\n index = solution.Value(routing.NextVar(index))\n route_distance += routing.GetArcCostForVehicle(previous_index, index, 0)\n plan_output += ' {}\\n'.format(index_to_locs.get(manager.IndexToNode(index)))\n plan_output += 'Route walking distance: {} meters\\n'.format(route_distance)\n print(plan_output)\n\ndef main(locs):\n \"\"\"Entry point of the program.\"\"\"\n # Instantiate the data problem.\n mapping = WarehouseMapping(calculate_loc2Dmatrix=True)\n\n map, index_to_locs = mapping.getLoc2DMapForTSP(locs)\n\n data = create_data_model(mapping, map)\n\n # Create the routing index manager.\n manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),\n data['num_vehicles'], data['starts'], data['ends'])\n\n # Create Routing Model.\n routing = pywrapcp.RoutingModel(manager)\n\n\n def distance_callback(from_index, to_index):\n \"\"\"Returns the distance between the two nodes.\"\"\"\n # Convert from routing variable Index to distance matrix NodeIndex.\n from_node = manager.IndexToNode(from_index)\n to_node = manager.IndexToNode(to_index)\n return data['distance_matrix'][from_node][to_node]\n\n transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n\n # Define cost of each arc.\n routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n\n # Setting first solution heuristic.\n search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n search_parameters.first_solution_strategy = (\n routing_enums_pb2.FirstSolutionStrategy.AUTOMATIC)\n\n # Solve the problem.\n solution = routing.SolveWithParameters(search_parameters)\n\n # Print solution on console.\n route = None\n if solution:\n print_solution(manager, routing, solution, index_to_locs)\n route = get_route(manager, routing, solution, index_to_locs)\n return route\n\ndef TSPsolver(locs):\n best_route = main(locs)\n return best_route\n\nif __name__ == '__main__':\n locs = [1, 101, 200, 705, 303, 55, 755, 455, 630, 350, 230]\n route = main(locs)\n assert(len(route) == len(locs)-2)\n","sub_path":"TSP.py","file_name":"TSP.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"40948620","text":"#####################################################################################################################\r\n#Program: Doc bao theo tu khoa (keyword-based online journalism reader)\r\n#Author: hailoc12\r\n#Version: 1.4.0\r\n#Date: 22/12/2018 (Dec, 15 2018)\r\n#Repository: http://github.com/hailoc12/docbao\r\n#Donation is welcomed if you feel this program useful\r\n#Bank: Vietcombank (Vietnam)\r\n#Account: DANG HAI LOC\r\n#Number: 0491000010179\r\n#####################################################################################################################\r\n\r\n# IMPORT LIB\r\nimport xlsxwriter\r\nfrom lib import *\r\n\r\n# CHECK IF ANOTHER SESSION IS RUNNING\r\n\r\n#Because unknown reason, os.remove() can't delete docbao.lock\r\n#if is_another_session_running():\r\n# print(\"ANOTHER SESSION IS RUNNING !\")\r\n# print(\"If you believe this is error, please delete docbao.lock file\")\r\n# exit()\r\n#else:\r\n# new_session()\r\n\r\n# GLOBAL OBJECT\r\n\r\nconfig_manager = ConfigManager(get_independent_os_path(['input', 'config.txt'])) #config object\r\ndata_manager = ArticleManager(config_manager, get_independent_os_path([\"data\", \"article.dat\"]),get_independent_os_path([\"data\",\"blacklist.dat\"]) ) #article database object\r\nkeyword_manager = KeywordManager(data_manager, config_manager, get_independent_os_path([\"data\", \"keyword.dat\"]), get_independent_os_path([\"input\", \"collocation.txt\"]), get_independent_os_path([\"input\", \"keywords_to_remove.txt\"])) #keyword analyzer object\r\n\r\ndef export_result():\r\n\r\n # export database in excel format\r\n print(\"Exporting database to %s\" % get_independent_os_path([\"export\", \"csdl_bao_chi_ngay_\" + datetime.now().strftime(\"%d-%m-%Y\") + '.xlsx']))\r\n\r\n workbook = xlsxwriter.Workbook(get_independent_os_path([\"export\", \"csdl_bao_chi_ngay_\" + datetime.now().strftime(\"%d-%m-%Y\") + '.xlsx']))\r\n worksheet = workbook.add_worksheet()\r\n worksheet.write(0, 0, \"STT\")\r\n worksheet.write(0, 1, \"Bài viết\")\r\n worksheet.write(0, 2, \"Link\")\r\n worksheet.write(0, 3, \"Báo\")\r\n worksheet.write(0, 4, \"Ngày xuất bản\")\r\n worksheet.write(0, 5, \"Sapo\")\r\n row = 1\r\n col = 0\r\n\r\n count = 0\r\n for article in data_manager.get_sorted_article_list():\r\n count+=1\r\n worksheet.write(row, col, count )\r\n worksheet.write(row, col+1, article.get_topic())\r\n worksheet.write(row, col+2, article.get_href())\r\n worksheet.write(row, col+3, article.get_newspaper())\r\n worksheet.write(row, col+4, article.get_date_string())\r\n worksheet.write(row, col+5, article.get_summary())\r\n row+=1\r\n workbook.close()\r\n\r\n # local frontend as index.html file\r\n print(\"Exporting database to %s\" % get_independent_os_path([\"export\", \"local_html\",\"index.html\"]))\r\n\r\n html_begin = '''\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n '''\r\n html_end = '''\r\n \r\n \r\n \r\n '''\r\n\r\n with open_utf8_file_to_write(get_independent_os_path([\"export\", \"local_html\", \"index.html\"])) as stream:\r\n stream.write(html_begin)\r\n stream.write(\"

ĐỌC BÁO THEO TỪ KHÓA

\")\r\n stream.write(\"

Cập nhật: \" + datetime.now().strftime(\"%d/%m/%Y %H:%M\") +\r\n \"

\")\r\n stream.write(\"

Trích tự động từ \" + str(config_manager.get_newspaper_count()) + \" trang báo với \" + str(\r\n data_manager.count_database()) + \" bài xuất bản trong ngày hôm nay.\" +\r\n \" Click để đọc

\")\r\n # write hot tag list\r\n\r\n # write keyword list to json file\r\n keyword_manager.write_trending_keyword_to_json_file()\r\n keyword_manager.write_keyword_dicts_to_json_files()\r\n #tag_extract.write_tag_dict_to_file() # to create word cloud\r\n #tag_extract.write_hot_keyword_to_text_file() # to create facebook status\r\n\r\n stream.write('')\r\n stream.write('')\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n \r\n for category in config_manager.get_categories():\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n tag_string = \"\"\r\n for keyword, count in keyword_manager.get_hot_keyword_dict_by_category(category).items():\r\n if keyword != '': # chua biet tai sao lai co ca tag trang\r\n tag_string = tag_string + '''' + \\\r\n '' + keyword + '' + \\\r\n '' + \"\" + str(count) + \"\" \"\" + \"\" + '' +\" • \"\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write('
Chuyên mụcKeyword nổi bật
\" + category.get_name() + \"\")\r\n stream.write(tag_string)\r\n stream.write(\"
')\r\n stream.write('
')\r\n\r\n keyword_manager.write_uncategoried_keyword_to_text_file() # for crowdsource\r\n # search input\r\n stream.write(\"

Lọc bài theo từ khóa của bạn:\")\r\n stream.write('

')\r\n\r\n stream.write(\"

Lọc tiếp bài theo nguồn báo (nếu cần)\")\r\n stream.write(\"
\")\r\n for newspaper in config_manager.get_newspaper_list():\r\n stream.write('' +\r\n \" \" + newspaper.get_webname() + \" \" + '')\r\n stream.write('
')\r\n stream.write('')\r\n stream.write(\"

\")\r\n\r\n stream.write('

Hãy góp sức bổ sung thêm từ khóa'\r\n ' hoặc phân nhóm chuyên mục cho từ khóa '\r\n 'để hệ thống phục vụ cộng đồng hiệu quả hơn

')\r\n\r\n\r\n stream.write('Trở về đầu trang ')\r\n\r\n stream.write(\"
\")\r\n\r\n\r\n stream.write('')\r\n stream.write('')\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n\r\n json_article_list=[]\r\n count = 0\r\n for article in data_manager.get_sorted_article_list():\r\n count += 1\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n update_time = int((datetime.now() - article.get_creation_date()).total_seconds() / 60)\r\n update_time_string=\"\"\r\n if update_time >= 720:\r\n update_time = int(update_time / 720)\r\n update_time_string = str(update_time) + \" ngày trước\"\r\n else:\r\n if update_time >= 60:\r\n update_time = int(update_time / 60)\r\n update_time_string = str(update_time) + \" giờ trước\"\r\n else:\r\n update_time_string = str(update_time) + \" phút trước\"\r\n\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n stream.write(\"\")\r\n\r\n json_article_list.append({'stt':str(count),\r\n 'topic':article.get_topic(),\r\n 'href':article.get_href(),\r\n 'newspaper': article.get_newspaper(),\r\n 'update_time': update_time_string, \r\n 'publish_time': article.get_date_string()})\r\n stream.write(\"
STTBàiBáoCập nhậtNgày xuất bản
\" + str(count) + \"\" + '' + article.get_topic() + \"\" + article.get_newspaper() +\"\" + update_time_string + \"\" + article.get_date_string()+\"
\")\r\n\r\n stream.write(html_end)\r\n stream.close()\r\n\r\n # export article database to json file\r\n with open_utf8_file_to_write(get_independent_os_path([\"export\", \"article_data.json\"])) as stream:\r\n stream.write(jsonpickle.encode({'article_list': json_article_list}))\r\n stream.close()\r\n\r\n # in keyword freq series to json file\r\n keyword_manager.write_keyword_freq_series_to_json_file()\r\n\r\ndef write_log_data_to_json():\r\n with open_utf8_file_to_write(get_independent_os_path([\"export\", \"log_data.json\"])) as stream:\r\n log_dict = dict()\r\n log_dict['update_time'] = datetime.now().strftime(\"%d/%m/%Y %H:%M\")\r\n log_dict['newspaper_count'] = str(config_manager.get_newspaper_count())\r\n log_dict['database_count'] = str(data_manager.count_database())\r\n stream.write(jsonpickle.encode(log_dict))\r\n stream.close()\r\n\r\n\r\n# MAIN PROGRAM\r\n# init data\r\nconfig_manager.load_data()\r\ndata_manager.load_data()\r\nkeyword_manager.load_data()\r\n\r\n# console output\r\nversion = \"1.0.0\"\r\nprint(\"DOC BAO VERSION \" + version + \" Days to crawl: \" + str(config_manager.get_maximum_day_difference()+1))\r\n\r\n# compress database\r\ndata_manager.compress_database(keyword_manager)\r\ndata_manager.compress_blacklist()\r\n\r\n# crawling data\r\nprint(\"PHASE I: CRAWLING DATA\")\r\nfor webconfig in config_manager.get_newspaper_list():\r\n data_manager.add_articles_from_newspaper(webconfig)\r\n\r\nprint(\"Number of articles in database: \" + str(data_manager.count_database()))\r\nprint(\"Number of link in blacklist database: \" + str(data_manager.count_blacklist()))\r\n\r\n# analyze keyword\r\nprint(\"PHASE II: ANALYZE KEYWORDS FROM ARTICLE DATABASE\")\r\nprint(\"\")\r\nkeyword_manager.build_keyword_list()\r\n\r\n# export data\r\nprint(\"PHASE III: EXPORT DATA IN EXCEL, HTML, JSON FORMAT\")\r\n\r\nexport_result()\r\nwrite_log_data_to_json()\r\n\r\nprint(\"PHASE IV: SAVE DATA\")\r\n# save data\r\ndata_manager.save_data()\r\nkeyword_manager.save_data()\r\n\r\n# close firefox browser\r\nquit_browser()\r\n\r\nprint(\"FINISH\")\r\n# clear lock file to finish this session\r\n# finish_session()\r\n","sub_path":"backend/backup/docbao.py","file_name":"docbao.py","file_ext":"py","file_size_in_byte":17402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"66324456","text":"__author__ = 'anna'\n\nf_handle = open('/home/anna/Documents/Test/first_file.txt', 'w')\n\nl = list(range(0, 10, 2))\n\nprint(l)\n\n\nfor item in l:\n f_handle.write(str(item) + '\\n')\n\nf_handle.close()\n\nf_handle = open('/home/anna/Documents/Test/first_file.txt', 'r')\n\nprint(f_handle.read())\n\nf_handle.seek(0, 0)\nprint('Using readline and for loop:')\nfor i in range(len(l)):\n print(f_handle.readline(), end='')\n\nf_handle.seek(0, 0)\n\nprint('Using readline and while loop')\n\nwhile True:\n line = f_handle.readline()\n if len(line) == 0:\n break\n print(line, end='')\n\nf_handle.seek(0, 0)\nprint('Using readlines:')\n\nfor line in f_handle.readlines():\n print(line, end='')\nf_handle.seek(0, 0)\n\nprint('The whole readlines object-list:')\n\nprint(f_handle.readlines())\n\nf_handle.seek(0, 0)\nprint('Iterating through a file:')\ni = 0\nfor line in f_handle:\n print(line, end='')\n i += 1\nprint('Total number of lines: {}'.format(i))\n\nf_handle.close()\n\nf_handle = open('/home/anna/Documents/Test/first_file.txt', 'w')\nf_handle.truncate()\nf_handle.close()\n\nprint('Second part:')\n\nfruits = ['apple', 'pear', 'watermelon', 'grape']\n\nf_handle = open('/home/anna/Documents/Test/fruits.txt', 'w')\n\nfor fruit in fruits:\n f_handle.write(str(fruit) + '\\n')\nf_handle.close()\n\nprint('Sorting the content with readlines:')\n\nf_handle = open('/home/anna/Documents/Test/fruits.txt', 'r')\n\nfor item in sorted(f_handle.readlines()):\n print(item, end='')\n\nf_handle.seek(0, 0)\n\nprint('Turning the whole file in one string, truncating spaces:')\n\nl = f_handle.read().split()\nprint(''.join(l))\n\nf_handle.seek(0, 0)\n\ns = f_handle.read().replace('\\n', '')\nprint(s)\n\n\nf_handle.close()\n","sub_path":"Udemy_python_anyone_can_code/files_practice.py","file_name":"files_practice.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"505513986","text":"# -*- coding:utf-8 -*-\n\n# ************************** Copyrights and license ***************************\n#\n# This file is part of gcovr 4.3, a parsing and reporting tool for gcov.\n# https://gcovr.com/en/stable\n#\n# _____________________________________________________________________________\n#\n# Copyright (c) 2013-2021 the gcovr authors\n# Copyright (c) 2013 Sandia Corporation.\n# This software is distributed under the BSD License.\n# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n# the U.S. Government retains certain rights in this software.\n# For more information, see the README.rst file.\n#\n# ****************************************************************************\n\nfrom argparse import ArgumentTypeError\nimport os\nimport re\nimport sys\nfrom contextlib import contextmanager\n\n\nclass LoopChecker(object):\n def __init__(self):\n self._seen = set()\n\n def already_visited(self, path):\n st = os.stat(path)\n key = (st.st_dev, st.st_ino)\n if key in self._seen:\n return True\n\n self._seen.add(key)\n return False\n\n\ndef search_file(predicate, path, exclude_dirs):\n \"\"\"\n Given a search path, recursively descend to find files that satisfy a\n predicate.\n \"\"\"\n if path is None or path == \".\":\n path = os.getcwd()\n elif not os.path.exists(path):\n raise IOError(\"Unknown directory '\" + path + \"'\")\n\n loop_checker = LoopChecker()\n for root, dirs, files in os.walk(os.path.abspath(path), followlinks=True):\n # Check if we've already visited 'root' through the magic of symlinks\n if loop_checker.already_visited(root):\n dirs[:] = []\n continue\n\n dirs[:] = [d for d in dirs\n if not any(exc.match(os.path.join(root, d))\n for exc in exclude_dirs)]\n root = os.path.realpath(root)\n\n for name in files:\n if predicate(name):\n yield os.path.realpath(os.path.join(root, name))\n\n\ndef commonpath(files):\n r\"\"\"Find the common prefix of all files.\n\n This differs from the standard library os.path.commonpath():\n - We first normalize all paths to a realpath.\n - We return a path with a trailing path separator.\n\n No common path exists under the following circumstances:\n - on Windows when the paths have different drives.\n E.g.: commonpath([r'C:\\foo', r'D:\\foo']) == ''\n - when the `files` are empty.\n\n Arguments:\n files (list): the input paths, may be relative or absolute.\n\n Returns: str\n The common prefix directory as a relative path.\n Always ends with a path separator.\n Returns the empty string if no common path exists.\n \"\"\"\n if not files:\n return ''\n\n if len(files) == 1:\n prefix_path = os.path.dirname(os.path.realpath(files[0]))\n else:\n split_paths = [os.path.realpath(path).split(os.path.sep)\n for path in files]\n # We only have to compare the lexicographically minimum and maximum\n # paths to find the common prefix of all, e.g.:\n # /a/b/c/d <- min\n # /a/b/d\n # /a/c/a <- max\n #\n # compare:\n # https://github.com/python/cpython/blob/3.6/Lib/posixpath.py#L487\n min_path = min(split_paths)\n max_path = max(split_paths)\n common = min_path # assume that min_path is a prefix of max_path\n for i in range(min(len(min_path), len(max_path))):\n if min_path[i] != max_path[i]:\n common = min_path[:i] # disproven, slice for actual prefix\n break\n prefix_path = os.path.sep.join(common)\n\n # make the path relative and add a trailing slash\n if prefix_path:\n prefix_path = os.path.join(os.path.relpath(prefix_path), '')\n return prefix_path\n\n\n#\n# Get global statistics\n#\ndef get_global_stats(covdata):\n lines_total = 0\n lines_covered = 0\n branches_total = 0\n branches_covered = 0\n\n keys = list(covdata.keys())\n\n for key in keys:\n (total, covered, _) = covdata[key].line_coverage()\n lines_total += total\n lines_covered += covered\n\n (total, covered, _) = covdata[key].branch_coverage()\n branches_total += total\n branches_covered += covered\n\n percent = calculate_coverage(lines_covered, lines_total)\n percent_branches = calculate_coverage(branches_covered, branches_total)\n\n return (lines_total, lines_covered, percent,\n branches_total, branches_covered, percent_branches)\n\n\ndef calculate_coverage(covered, total, nan_value=0.0):\n coverage = nan_value\n if total != 0:\n coverage = round(100.0 * covered / total, 1)\n # If we get 100.0% and not all branches are covered use 99.9%\n if (coverage == 100.0) and (covered != total):\n coverage = 99.9\n\n return coverage\n\n\nclass FilterOption(object):\n def __init__(self, regex, path_context=None):\n self.regex = regex\n self.path_context = os.getcwd() if path_context is None else path_context\n\n def build_filter(self, logger):\n # Try to detect unintended backslashes and warn.\n # Later, the regex engine may or may not raise a syntax error.\n # An unintended backslash is a literal backslash r\"\\\\\",\n # or a regex escape that doesn't exist.\n (suggestion, bs_count) = re.subn(\n r'\\\\\\\\|\\\\(?=[^\\WabfnrtuUvx0-9AbBdDsSwWZ])', '/', self.regex)\n if bs_count:\n logger.warn(\"filters must use forward slashes as path separators\")\n logger.warn(\"your filter : {}\", self.regex)\n logger.warn(\"did you mean: {}\", suggestion)\n\n if os.path.isabs(self.regex):\n return AbsoluteFilter(self.regex)\n else:\n return RelativeFilter(self.path_context, self.regex)\n\n\nclass NonEmptyFilterOption(FilterOption):\n def __init__(self, regex, path_context=None):\n if not regex:\n raise ArgumentTypeError(\"filter cannot be empty\")\n super(NonEmptyFilterOption, self).__init__(regex, path_context)\n\n\nFilterOption.NonEmpty = NonEmptyFilterOption\n\n\nclass Filter(object):\n def __init__(self, pattern):\n cwd = os.getcwd()\n # Guessing if file system is case insensitive.\n # The working directory is not the root and accessible in upper and lower case.\n is_fs_case_insensitive = (cwd != os.path.sep) and os.path.exists(cwd.upper()) and os.path.exists(cwd.lower())\n flags = re.IGNORECASE if is_fs_case_insensitive else 0\n self.pattern = re.compile(pattern, flags)\n\n def match(self, path):\n os_independent_path = path.replace(os.path.sep, '/')\n return self.pattern.match(os_independent_path)\n\n def __str__(self):\n return \"{name}({pattern})\".format(\n name=type(self).__name__, pattern=self.pattern.pattern)\n\n\nclass AbsoluteFilter(Filter):\n def match(self, path):\n abspath = os.path.realpath(path)\n return super(AbsoluteFilter, self).match(abspath)\n\n\nclass RelativeFilter(Filter):\n def __init__(self, root, pattern):\n super(RelativeFilter, self).__init__(pattern)\n self.root = root\n\n def match(self, path):\n abspath = os.path.realpath(path)\n try:\n relpath = os.path.relpath(abspath, self.root)\n except ValueError:\n relpath = abspath\n return super(RelativeFilter, self).match(relpath)\n\n def __str__(self):\n return \"RelativeFilter({} root={})\".format(\n self.pattern.pattern, self.root)\n\n\nclass AlwaysMatchFilter(Filter):\n def __init__(self):\n super(AlwaysMatchFilter, self).__init__(\"\")\n\n def match(self, path):\n return True\n\n\nclass DirectoryPrefixFilter(Filter):\n def __init__(self, directory):\n abspath = os.path.realpath(directory)\n os_independent_dir = abspath.replace(os.path.sep, '/')\n pattern = re.escape(os_independent_dir + '/')\n super(DirectoryPrefixFilter, self).__init__(pattern)\n\n def match(self, path):\n normpath = os.path.normpath(path)\n return super(DirectoryPrefixFilter, self).match(normpath)\n\n\nclass Logger(object):\n def __init__(self, verbose=False):\n self.verbose = verbose\n\n def warn(self, pattern, *args, **kwargs):\n \"\"\"Write a formatted warning to STDERR.\n\n pattern: a str.format pattern\n args, kwargs: str.format arguments\n \"\"\"\n pattern = \"(WARNING) \" + pattern + \"\\n\"\n sys.stderr.write(pattern.format(*args, **kwargs))\n\n def error(self, pattern, *args, **kwargs):\n \"\"\"Write a formatted error to STDERR.\n\n pattern: a str.format pattern\n args, kwargs: str.format parameters\n \"\"\"\n pattern = \"(ERROR) \" + pattern + \"\\n\"\n sys.stderr.write(pattern.format(*args, **kwargs))\n\n def msg(self, pattern, *args, **kwargs):\n \"\"\"Write a formatted message to STDOUT.\n\n pattern: a str.format pattern\n args, kwargs: str.format arguments\n \"\"\"\n pattern = pattern + \"\\n\"\n sys.stdout.write(pattern.format(*args, **kwargs))\n\n def verbose_msg(self, pattern, *args, **kwargs):\n \"\"\"Write a formatted message to STDOUT if in verbose mode.\n\n see: self.msg()\n \"\"\"\n if self.verbose:\n self.msg(pattern, *args, **kwargs)\n\n\ndef sort_coverage(covdata, show_branch,\n by_num_uncovered=False, by_percent_uncovered=False):\n \"\"\"Sort a coverage dict.\n\n covdata (dict): the coverage dictionary\n show_branch (bool): select branch coverage (True) or line coverage (False)\n by_num_uncovered, by_percent_uncovered (bool):\n select the sort mode. By default, sort alphabetically.\n\n returns: the sorted keys\n \"\"\"\n def num_uncovered_key(key):\n cov = covdata[key]\n (total, covered, _) = \\\n cov.branch_coverage() if show_branch else cov.line_coverage()\n uncovered = total - covered\n return uncovered\n\n def percent_uncovered_key(key):\n cov = covdata[key]\n (total, covered, _) = \\\n cov.branch_coverage() if show_branch else cov.line_coverage()\n if covered:\n return -1.0 * covered / total\n elif total:\n return total\n else:\n return 1e6\n\n if by_num_uncovered:\n key_fn = num_uncovered_key\n elif by_percent_uncovered:\n key_fn = percent_uncovered_key\n else:\n key_fn = None # default key, sort alphabetically\n\n return sorted(covdata, key=key_fn)\n\n\n@contextmanager\ndef open_text_for_writing(filename=None, default_filename=None, **kwargs):\n \"\"\"Context manager to open and close a file for text writing.\n\n Stdout is used if `filename` is None or '-'.\n \"\"\"\n if filename is not None and filename.endswith(os.sep):\n filename += default_filename\n\n if filename is not None and filename != '-':\n fh = open(filename, 'w', **kwargs)\n close = True\n else:\n fh = sys.stdout\n close = False\n\n try:\n yield fh\n finally:\n if close:\n fh.close()\n\n\n@contextmanager\ndef open_binary_for_writing(filename=None, default_filename=None, **kwargs):\n \"\"\"Context manager to open and close a file for binary writing.\n\n Stdout is used if `filename` is None or '-'.\n \"\"\"\n if filename is not None and filename.endswith(os.sep):\n filename += default_filename\n\n if filename is not None and filename != '-':\n # files in write binary mode for UTF-8\n fh = open(filename, 'wb', **kwargs)\n close = True\n else:\n fh = sys.stdout.buffer\n close = False\n\n try:\n yield fh\n finally:\n if close:\n fh.close()\n\n\ndef presentable_filename(filename, root_filter):\n # type: (str, re.Regex) -> str\n \"\"\"mangle a filename so that it is suitable for a report\"\"\"\n\n normalized = root_filter.sub('', filename)\n if filename.endswith(normalized):\n # remove any slashes between the removed prefix and the normalized name\n if filename != normalized:\n while normalized.startswith(os.path.sep):\n normalized = normalized[len(os.path.sep):]\n else:\n # Do no truncation if the filter does not start matching\n # at the beginning of the string\n normalized = filename\n\n return normalized.replace('\\\\', '/')\n\n\ndef fixup_percent(percent):\n # output csv percent values in range [0,1.0]\n return percent / 100 if percent is not None else None\n\n\ndef summarize_file_coverage(coverage, root_filter):\n filename = presentable_filename(\n coverage.filename, root_filter=root_filter)\n\n branch_total, branch_covered, branch_percent = coverage.branch_coverage()\n line_total, line_covered, line_percent = coverage.line_coverage()\n return (filename, line_total, line_covered, fixup_percent(line_percent),\n branch_total, branch_covered, fixup_percent(branch_percent))\n","sub_path":"Tools/gcovr/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"469461982","text":"import sys\nimport sys\nimport os\nimport time\nimport re \nimport csv\nimport cv2\nimport glob\nimport tensorflow as tf\nimport numpy as np\nimport xml.dom.minidom\nfrom xml.dom.minidom import parse\nfrom xml.etree import ElementTree as ET\n#import pandas as pd\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\nfrom object_detection.utils import per_image_evaluation\nfrom object_detection.utils import metrics\n\ndef read_xml(f_path):\n xml_list = []\n filenames = []\n classes = []\n boxes = []\n label_s = {'plaque':1, 'sclerosis':2, 'pseudomorphism':3, 'normal':4}\n for xml_file in glob.glob(f_path):\n tree = ET.parse(xml_file)\n root = tree.getroot()\n for member in root.findall('object'):\n if member[0].text != 'vessel':\n label = label_s.get(member[0].text)\n value = [root.find('filename').text,\n # int(root.find('size')[0].text),\n # int(root.find('size')[1].text),\n label,\n float(member[4][0].text),\n float(member[4][1].text),\n float(member[4][2].text),\n float(member[4][3].text)\n ]\n xml_list.append(value)\n return xml_list\n \n\n\n\nif len(sys.argv) < 3:\n print('Usage: python {} test_image_path checkpoint_path'.format(sys.argv[0]))\n exit()\nPATH_TEST_IMAGE = sys.argv[1]\nPATH_TO_CKPT = sys.argv[2]\nPATH_TO_LABELS = 'annotations/label_map.pbtxt'\nNUM_CLASSES = 4\nIMAGE_SIZE = (48, 32)\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\nprint(category_index)\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph, config=config) as sess:\n start_time = time.time()\n print(time.ctime())\n #single_label = 'plaque'\n image = Image.open(PATH_TEST_IMAGE)\n \n print('---------')\n \n xml_list = read_xml('./images/verification/刘郑-右-斑块-横切.xml')\n print(xml_list, np.shape(xml_list)[0])\n gt_boxes = []\n gt_class_labels = []\n gt_is_difficult_list = []\n gt_is_group_of_list = []\n for i in range(np.shape(xml_list)[0]):\n gt_box = xml_list[i][2:]\n gt_class_label = xml_list[i][1]\n gt_boxes.append(gt_box)\n gt_class_labels.append(gt_class_label)\n gt_is_difficult_list.append(True)\n gt_is_group_of_list.append(True)\n gt_boxes = np.array(gt_boxes)\n gt_class_labels = np.array(gt_class_labels)\n gt_is_difficult_list = np.array(gt_is_difficult_list)\n gt_is_group_of_list = np.array(gt_is_group_of_list)\n print(gt_boxes, '-----', gt_class_labels)\n \n\n image_np = np.array(image).astype(np.uint8)\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n use_time = time.time() - start_time\n # vis_util.visualize_boxes_and_labels_on_image_array(\n # image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores),\n # category_index, use_normalized_coordinates=True, min_score_thresh=0.8, line_thickness=2)\n eval_dicts = {'boxes':boxes, 'scores':scores, 'classes':classes, 'num_detections':num_detections}\n scores, tp_fp_labels, is_class_correctly_detected_in_image = per_image_evaluation.PerImageEvaluation().compute_object_detection_metrics(detected_boxes=np.squeeze(boxes), \n detected_scores = np.squeeze(scores), detected_class_labels = np.squeeze(classes).astype(np.int32), groundtruth_boxes=gt_boxes, groundtruth_class_labels=gt_class_labels,groundtruth_is_difficult_list=gt_is_difficult_list, groundtruth_is_group_of_list = gt_is_group_of_list)\n #scores=np.array(scores), \n tp_fp_labels=np.array(tp_fp_labels)\n precision, recall = metrics.compute_precision_recall(np.array(scores), tp_fp_labels[1].astype(float), 2)\n print(scores)\n print('---------')\n print(len(tp_fp_labels))\n #f_name = re.split('/',path_f)\n #print(category_index.get(value))\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)\n #plt.savefig(f_name[-1])\n #print('Image:{} Num: {} scores:{} Time: {:.3f}s'.format(PATH_TEST_IMAGE, num_detections, np.max(np.squeeze(scores)), use_time))\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)\n #plt.savefig('./test_result/predicted_' + f_name[-1])\n #cv2.imwrite('./test_result/predicted_' + f_name[-1], image_np)\n ","sub_path":"AcademicAN/TwoStage/eval_pr.py","file_name":"eval_pr.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"173435110","text":"from django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import redirect, render\n\nfrom goals.forms import NewGoal, NewObjective, NewTodo, GoalCompleted, ObjectiveCompleted, TodoCompleted\nfrom goals.models import Goal, Objective, Todo\n\n@login_required\ndef home_page(request, active_tab='goals'):\n if request.method == 'POST':\n # Check if it's a change of 'completed' status,\n if 'goal_id' in request.POST:\n goal = Goal.objects.get(id=request.POST['goal_id'])\n goal.change_completed_status(request.POST)\n goal.save()\n\n elif 'objective_id' in request.POST:\n objective = Objective.objects.get(id=request.POST['objective_id'])\n objective.change_completed_status(request.POST)\n objective.save()\n \n elif 'todo_id' in request.POST:\n todo = Todo.objects.get(id=request.POST['todo_id'])\n todo.change_completed_status(request.POST)\n todo.save()\n \n # or a new item creation.\n elif 'new_goal_text' in request.POST:\n new_goal_form = NewGoal(request.POST)\n if new_goal_form.is_valid():\n goal = Goal.objects.create(text = new_goal_form.cleaned_data['new_goal_text'], owner = request.user)\n \n elif 'new_objective_text' in request.POST:\n new_objective_form = NewObjective(request.POST)\n if new_objective_form.is_valid():\n objective = Objective(text = new_objective_form.cleaned_data['new_objective_text'], owner = request.user)\n objective.full_clean()\n objective.save()\n\n # Change 'active_tab'\n active_tab = 'objectives'\n\n elif 'new_todo_text' in request.POST:\n new_todo_form = NewTodo(request.POST)\n if new_todo_form.is_valid():\n todo = Todo(text = new_todo_form.cleaned_data['new_todo_text'], owner = request.user)\n todo.full_clean()\n todo.save()\n\n # Change 'active_tab'\n active_tab = 'todos'\n\n # Empty forms for a new items.\n new_goal_form = NewGoal()\n new_objective_form = NewObjective()\n new_todo_form = NewTodo()\n\n # Items in the database.\n goals = Goal.objects.filter(owner=request.user).order_by('id').reverse()\n objectives = Objective.objects.filter(owner=request.user, goal=None).order_by('id').reverse()\n todos = Todo.objects.filter(owner=request.user, goal=None, objective=None).order_by('id').reverse()\n\n goal_formset = [GoalCompleted(instance=goal, auto_id=str(goal.id) + \"_%s\") for goal in goals]\n objective_formset = [ObjectiveCompleted(instance=objective, auto_id=str(objective.id) + \"_%s\") for objective in objectives]\n todo_formset = [TodoCompleted(instance=todo, auto_id=str(todo.id) + \"_%s\") for todo in todos]\n\n return render(request, 'home.html', {\n 'new_goal_form': new_goal_form,\n 'new_objective_form': new_objective_form,\n 'new_todo_form': new_todo_form,\n 'goal_formset': goal_formset,\n 'objective_formset': objective_formset,\n 'todo_formset': todo_formset,\n 'goals_header_text': 'Goals', \n 'objectives_header_text': 'Objectives',\n 'todo_header_text': 'Todo',\n 'new_goal_label_text': 'New goal',\n 'new_objective_label_text': 'New objective',\n 'new_todo_label_text': 'New todo',\n active_tab: 'active',\n })\n\n@login_required\ndef goal(request, goal_id, active_tab='objectives'):\n\n goal = Goal.objects.get(id = goal_id)\n\n if request.method == 'POST':\n # Check if it's a change of objective's\n # 'completed' status,\n if 'objective_id' in request.POST:\n objective = Objective.objects.get(id=request.POST['objective_id'])\n objective.change_completed_status(request.POST)\n objective.save()\n\n elif 'todo_id' in request.POST:\n todo = Todo.objects.get(id=request.POST['todo_id'])\n todo.change_completed_status(request.POST)\n todo.save()\n\n # or a new objective creation.\n elif 'new_objective_text' in request.POST:\n new_objective_form = NewObjective(request.POST)\n if new_objective_form.is_valid():\n objective = Objective.objects.create(\n text = new_objective_form.cleaned_data['new_objective_text'], \n owner=request.user, \n goal=goal\n )\n\n elif 'new_todo_text' in request.POST:\n new_todo_form = NewTodo(request.POST)\n if new_todo_form.is_valid():\n todo = Todo(\n text=new_todo_form.cleaned_data['new_todo_text'], \n owner = request.user, \n goal=goal\n )\n todo.full_clean()\n todo.save()\n\n # Change 'active_tab'\n active_tab = 'todos'\n\n # Empty forms for a new items.\n new_objective_form = NewObjective()\n new_todo_form = NewTodo()\n \n # Items in the database.\n try:\n objectives = Objective.objects.filter(goal = goal).order_by('id').reverse()\n except ObjectDoesNotExist:\n objectives = None\n \n try:\n todos = Todo.objects.filter(goal=goal, objective=None).order_by('id').reverse()\n except ObjectDoesNotExist:\n todos = None\n\n objective_formset = [ObjectiveCompleted(instance=objective, auto_id=str(objective.id) + '_%s') for objective in objectives]\n todo_formset = [TodoCompleted(instance=todo, auto_id=str(todo.id) + '_%s') for todo in todos]\n\n # Navigation ribbon.\n items = []\n items.append(goal)\n \n return render(request, 'goal.html', {\n 'items': items, \n 'objectives_header_text': goal.text, \n 'todo_header_text': goal.text,\n 'objective_formset': objective_formset, \n 'todo_formset': todo_formset,\n 'new_objective_form': new_objective_form, \n 'new_todo_form': new_todo_form,\n 'new_objective_label_text': 'New objective',\n 'new_todo_label_text': 'New todo',\n active_tab: 'active',\n })\n\n@login_required\ndef objective(request, objective_id):\n\n objective = Objective.objects.get(id = objective_id)\n goal = objective.goal\n\n if request.method == 'POST':\n if 'todo_id' in request.POST:\n todo = Todo.objects.get(id=request.POST['todo_id']) \n todo.change_completed_status(request.POST)\n todo.save()\n elif 'new_todo_text' in request.POST:\n new_todo_form = NewTodo(request.POST)\n if new_todo_form.is_valid():\n todo = Todo(\n text = new_todo_form.cleaned_data['new_todo_text'], \n goal=goal, \n objective=objective, \n owner=request.user\n )\n todo.full_clean()\n todo.save()\n\n new_todo_form = NewTodo()\n\n try:\n todos = Todo.objects.filter(objective = objective)\n except ObjectDoesNotExist:\n todos = None\n\n todo_formset = [TodoCompleted(instance=todo, auto_id=str(todo.id)+'_%s') for todo in todos] \n\n # Data for navigation ribbon.\n items = []\n if objective.goal:\n items.append(objective.goal)\n items.append(objective)\n\n # Link for an 'Objectives' tab.\n if objective.goal:\n objectives_link = objective.goal.get_absolute_url\n else:\n objectives_link = '/objectives'\n \n \n return render(request, 'objective.html', {\n 'todo_header_text': objective.text, \n 'items': items, \n 'todo_formset': todo_formset, \n 'new_todo_form': new_todo_form, \n 'new_todo_label_text': 'New to-do',\n 'objectives_link': objectives_link,\n })\n\n@login_required\ndef todo(request, todo_id):\n todo = Todo.objects.get(id = todo_id)\n items = []\n if todo.objective:\n if todo.objective.goal:\n items.append(todo.objective.goal)\n items.append(todo.objective)\n items.append(todo)\n return render(request, 'base.html', {'items': items, 'header_text': todo.text})\n\n","sub_path":"goals/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"261438410","text":"# 나머지와 몫이 같은 수 구하기\n# 숫자 n이 주어졌습니다.\n# n으로 나누었을 때 나머지와 몫이 같은 모든 자연수의 합이 얼마인지 찾는 문제를 풀어 봅시다.\n# 예를 들어서,\n# n이 1일 경우, 해당하는 자연수는 없기에 0으로 간주한다.\n# n = 2일 경우 3,\n# n = 3일 경우 12,\n# n = 4일 경우는 30이 정답으로 간주된다.\n\n# 자연수 n이 주어질 때 나머지와 몫이 같은 모든 자연수의 합을 출력하시오.\n\ndef question(n) :\n sum = 0\n d = []\n\n for i in range(1, n**2) :\n mok = i//n\n namerge = i%n\n\n if mok == namerge :\n sum += i\n d.append(i)\n \n print(f'답 : {sum} {d}')\n\n\ndef answer(n) :\n sum = 0\n\n for i in range(1,n) :\n sum += i*(n+1)\n \n print(f'답 : {sum}')\n\n\ndef another_answer(n) :\n sum = (n*(n+1)*(n-1))/2\n\n print(f'답 : {sum}')\n\n\nwhile True :\n # question(int(input()))\n # answer(int(input()))\n another_answer(int(input()))\n\n\n\n","sub_path":"6Period/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"150941781","text":"import sys, os\nfrom datetime import datetime, timedelta\n\n\ndisco_path = \"C:\\\\Users\\\\katie\\\\OneDrive\\\\Desktop\\\\DiscordChatExporter.CLI\\\\DiscordChatExporter.Cli.exe\"\ntoken = \"NDg1MTQ0NDgzNTI5NDkwNDQz.Xl7AOw.6F2mx05KDqxgOstohXHf2EqV8OQ\"\nguild = \"518199891982286858\"\nintro_id = \"654109188548591616\"\n\nstart = datetime.now() - timedelta(days=90)\n\nprint(start)\n\n# os.system(\"{exe} channels -t {t} -g {g}\".format(exe=disco_path, t=token, \n# g=guild, start=start.strftime(\"%m/%d/%Y\")))\n\nos.system(\"{exe} exportguild -t {t} -g {g} --after {start}\".format(exe=disco_path, t=token, \n g=guild, start=start.strftime(\"%m/%d/%Y\")))\n\nos.system(\"{exe} export -t {t} -c {i} -o introduce-all-time.html\".format(exe=disco_path, t=token, \n i=intro_id))","sub_path":"general/user-roster/get_files.py","file_name":"get_files.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"413619121","text":"\"\"\"\n读取Excel文件\n\"\"\"\nfrom openpyxl import load_workbook\n\nwb = load_workbook('./data/学生明细表.xlsx')\nprint(wb.sheetnames)\nsheet = wb[wb.sheetnames[0]]\nprint(sheet.title)\n\nfor row in range(2, 7):\n for col in range(65, 70):\n # A2 A3 A4 B2 B3 B4...\n cell_index = chr(col) + str(row)\n print(sheet[cell_index].value, end='\\t')\n print()\n","sub_path":"01-foundation/day15/04-excel.py","file_name":"04-excel.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567265890","text":"from django.urls import path\nfrom rest_framework import routers\n\nfrom whoweb.users.views import (\n SeatViewSet,\n DeveloperKeyViewSet,\n NetworkViewSet,\n UserViewSet,\n ManageUserAuthenticationAPIView,\n ImpersonatedTokenObtainSlidingView,\n)\n\napp_name = \"users\"\n\nrouter = routers.SimpleRouter()\nrouter.register(r\"users\", UserViewSet)\nrouter.register(r\"seats\", SeatViewSet)\nrouter.register(r\"networks\", NetworkViewSet)\nrouter.register(r\"developer_keys\", DeveloperKeyViewSet)\n\n\nurlpatterns = [\n path(\"set_password/\", ManageUserAuthenticationAPIView.as_view()),\n path(\"iadmin/\", ImpersonatedTokenObtainSlidingView.as_view()),\n]\n","sub_path":"whoweb/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"63290291","text":"import gym\n#env = gym.make('LunarLanderMarl-v2')\n#env.reset()\n#for _ in range(100):\n# env.render()\n# action = env.action_space.sample()\n# #print(\"action: %d\" % action)\n# env.step(action)\n\n\nenv = gym.make('LunarLanderContinuousMarl-v2')\n\nfor j in range(100):\n env.reset()\n for _ in range(100):\n env.render()\n action = env.action_space.sample()\n #print(\"action: %d\" % action)\n obs, rew, don, info = env.step(action)\n print(rew) \n","sub_path":"code_for_report/s3_modified_env_with_2actors/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"578118490","text":"import random\n\n\nclass Card:\n def __init__(self,suit=None,value=None):\n if suit is None or value is None:\n self.suit = random.choice([\"Spades\", \"Clubs\", \"Hearts\", \"Diamonds\"])\n self.value = random.choice(range(2,15))\n else:\n self.suit = suit\n self.value = value\n\n def __str__(self):\n \"\"\"\n prints a string representing the value and the suit of the card\n :return: no return value\n \"\"\"\n cards = list(range(2,11)) + [\"Jack\",\"Queen\",\"King\",\"Ace\"]\n val = cards[self.value - 2]\n return str(val) + \" of %s\" % (self.suit,)\n\n def __repr__(self):\n return \"Card(%d,%s)\" % (self.value,self.suit)\n","sub_path":"util/Card.py","file_name":"Card.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"413079847","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QIcon\n\n\nclass Ui_SellerList(object):\n def setupUi(self, SellerList,email,product_name):\n self.email = email\n self.product_name = product_name\n SellerList.setObjectName(\"SellerList\")\n SellerList.resize(490, 708)\n self.centralwidget = QtWidgets.QWidget(SellerList)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.label = QtWidgets.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(50, 20, 391, 71))\n font = QtGui.QFont()\n font.setFamily(\"B Nazanin\")\n font.setPointSize(24)\n self.label.setFont(font)\n self.label.setStyleSheet(\"color: rgb(61, 135, 255);\\n\"\n\"font-family: B Nazanin, Arial;\")\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(\"label\")\n self.sellers_list = QtWidgets.QListWidget(self.centralwidget)\n self.sellers_list.setGeometry(QtCore.QRect(55, 100, 381, 471))\n self.sellers_list.setObjectName(\"sellers_list\")\n self.confirm = QtWidgets.QPushButton(self.centralwidget)\n self.confirm.setGeometry(QtCore.QRect(160, 630, 171, 41))\n font = QtGui.QFont()\n font.setFamily(\"B Nazanin\")\n font.setPointSize(14)\n self.confirm.setFont(font)\n self.confirm.setStyleSheet(\"QPushButton\\n\"\n\"{\\n\"\n\"color:white;\\n\"\n\"background-color: rgb(0, 161, 5);\\n\"\n\"border-radius:30%;\\n\"\n\"border: 2px solid rgb(0, 161, 5);\\n\"\n\"font-family:B Nazanin, Arial\\n\"\n\"}\\n\"\n\"QPushButton::pressed\\n\"\n\"{\\n\"\n\"color:rgb(0, 161, 5);\\n\"\n\"background-color:white;\\n\"\n\"border-radius:30%;\\n\"\n\"border: 2px solid rgb(0, 161, 5);\\n\"\n\"font-family:B Nazanin, Arial\\n\"\n\"}\")\n self.confirm.setObjectName(\"confirm\")\n self.confirm.clicked.connect(self.buyproduct)\n self.not_enough = QtWidgets.QLabel(self.centralwidget)\n self.not_enough.setGeometry(QtCore.QRect(140, 590, 211, 21))\n font = QtGui.QFont()\n font.setFamily(\"B Nazanin\")\n font.setPointSize(12)\n self.not_enough.setFont(font)\n self.not_enough.setStyleSheet(\"color: red;\\n\"\n\"font-family: B Nazanin, Arial;\")\n self.not_enough.setText(\"\")\n self.not_enough.setAlignment(QtCore.Qt.AlignCenter)\n self.not_enough.setObjectName(\"not_enough\")\n SellerList.setCentralWidget(self.centralwidget)\n self.SellerList = SellerList\n\n products = open('products.txt','r')\n products = products.readlines()\n #print(products)\n #products = [product.replace(' ','') for product in products]\n products = [product.replace('\\n','').split(', ') for product in products]\n #print(products)\n seller_list = []\n for i in range(len(products)):\n if products[i][0] == self.product_name:\n seller_list.append([products[i][0],products[i][1],products[i][2]])\n for i in seller_list:\n item = ' - '.join(str(x) for x in i)\n self.sellers_list.addItem(item)\n\n self.retranslateUi(SellerList)\n QtCore.QMetaObject.connectSlotsByName(SellerList)\n\n def buyproduct(self):\n item = self.sellers_list.currentItem()\n txt = item.text()\n listed = txt.split(' - ')\n listed2 = listed\n #print(listed)\n customer_money = 0\n seller_money = 0\n new_info_seller = []\n new_info_customer = []\n with open('customer_wallet.txt','r') as cwallet:\n lines = cwallet.readlines()\n lines = [line.replace(' ','') for line in lines]\n lines = [line.replace('\\n','').split(':') for line in lines]\n lines2 = lines\n for i in range(len(lines)):\n if lines[i][0] == self.email:\n if int(lines[i][1]) >= int(listed[2]):\n customer_money = int(lines[i][1])-int(listed[2])\n eMail = lines[i][0]\n new_info_customer.append([eMail, customer_money])\n #lines[i].pop()\n #lines[i].append(deposite)\n lines2 = [lines[i] for i in range(len(lines)) if lines[i][0] != self.email]\n cWallet = open('customer_wallet.txt','a')\n cWallet.truncate(0)\n new_info_customer_str = \":\".join(str(x) for x in new_info_customer[0])\n cWallet.write(new_info_customer_str+'\\n')\n for i in range(len(lines2)):\n cWallet.write(':'.join(str(x) for x in lines2[i])+'\\n')\n #cWallet.close()\n with open('seller_wallet.txt','r') as swallet:\n slines = swallet.readlines()\n slines = [sline.replace(' ','') for sline in slines]\n slines = [sline.replace('\\n','').split(':') for sline in slines]\n slines2 = slines\n for j in range(len(slines)):\n if slines[j][0] == listed[1]:\n seller_money = int(slines[j][1])+int(listed[2])\n seMail = slines[j][0]\n new_info_seller.append([seMail,seller_money])\n slines2 = [slines[i] for i in range(len(slines)) if slines[i][0] != listed[1]]\n new_info_seller_str = \":\".join(str(x) for x in new_info_seller[0])\n #print(slines)\n #print(slines2)\n #print(new_info_seller)\n #print(new_info_customer)\n sWallet = open('seller_wallet.txt','a')\n sWallet.truncate(0)\n sWallet.write(new_info_seller_str+'\\n')\n for k in range(len(slines2)):\n sWallet.write(':'.join(slines2[k])+'\\n')\n sWallet.close()\n self.SellerList.close()\n else:\n self.not_enough.setText('موجودی کافی نیست')\n\n\n def retranslateUi(self, SellerList):\n _translate = QtCore.QCoreApplication.translate\n SellerList.setWindowTitle(_translate(\"SellerList\", \"Sellers\"))\n self.SellerList.setWindowIcon(QIcon('Images/null.png'))\n self.label.setText(_translate(\"SellerList\", \"فروشندگان این محصول\"))\n self.confirm.setText(_translate(\"SellerList\", \"تایید\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n SellerList = QtWidgets.QMainWindow()\n ui = Ui_SellerList()\n ui.setupUi(SellerList)\n SellerList.show()\n sys.exit(app.exec_())\n","sub_path":"Options/seller_list.py","file_name":"seller_list.py","file_ext":"py","file_size_in_byte":7078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"247895360","text":"import os\nimport glob\nimport re\nimport signal\nimport sys\nimport argparse\nimport threading\nimport time\nfrom random import shuffle\nimport random\nimport tensorflow as tf\nfrom PIL import Image\nimport numpy as np\nimport scipy.io\nfrom scipy import misc\nfrom MODEL import model\nfrom PSNR import psnr\nfrom TEST import test_VDSR\n\ndef get_train_list_mat(data_path):\n l = glob.glob(os.path.join(data_path, \"*\"))\n l = [f for f in l if re.search(\"^\\d+.mat$\", os.path.basename(f))]\n train_list = []\n for f in l:\n if os.path.exists(f):\n if os.path.exists(f[:-4] + \"_2.mat\"):\n train_list.append([f, f[:-4] + \"_2.mat\"])\n if os.path.exists(f[:-4] + \"_3.mat\"):\n train_list.append([f, f[:-4] + \"_3.mat\"])\n if os.path.exists(f[:-4] + \"_4.mat\"):\n train_list.append([f, f[:-4] + \"_4.mat\"])\n return train_list\n\n#image format: png\ndef get_train_list(data_path):\n l = glob.glob(os.path.join(data_path, \"*\"))\n l = [f for f in l if re.search(\"\\w+.png$\", os.path.basename(f))]\n train_list = []\n\n for f in l:\n train_list.append(f)\n\n return train_list\n\ndef get_image_batch(train_list, offset, batch_size, args):\n target_list = train_list[offset:offset + batch_size]\n input_list = []\n gt_list = []\n cbcr_list = []\n for pair in target_list:\n input_img = scipy.io.loadmat(pair[1])['patch']\n gt_img = scipy.io.loadmat(pair[0])['patch']\n input_list.append(input_img)\n gt_list.append(gt_img)\n input_list = np.array(input_list)\n input_list.resize([args.batch_size, args.image_size[1], args.image_size[0], 1])\n gt_list = np.array(gt_list)\n gt_list.resize([args.batch_size, args.image_size[1], args.image_size[0], 1])\n return input_list, gt_list, np.array(cbcr_list)\n\n\ndef get_test_image(test_list, offset, batch_size):\n target_list = test_list[offset:offset + batch_size]\n input_list = []\n gt_list = []\n for pair in target_list:\n mat_dict = scipy.io.loadmat(pair[1])\n input_img = None\n if \"img_2\" in mat_dict:\n input_img = mat_dict[\"img_2\"]\n elif \"img_3\" in mat_dict:\n input_img = mat_dict[\"img_3\"]\n elif \"img_4\" in mat_dict:\n input_img = mat_dict[\"img_4\"]\n else:\n continue\n gt_img = scipy.io.loadmat(pair[0])['img_raw']\n input_list.append(input_img[:, :, 0])\n gt_list.append(gt_img[:, :, 0])\n return input_list, gt_list\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n #directory\n parser.add_argument(\"--train_dir\", type=str, default='../data/train')\n parser.add_argument(\"--test_dir\", type=str, default='../data/test')\n parser.add_argument(\"--dataset\", type=str)\n parser.add_argument(\"--model_path\", type=str)\n\n #super resolution\n parser.add_argument(\"--image_size\", type=tuple, default=(41, 41))\n parser.add_argument(\"--scale\", type=int, default=2)\n\n #learning parameter\n parser.add_argument(\"--learning_rate\", type=float, default=0.1)\n parser.add_argument(\"--decay_rate\", type=float, default=0.5, help=\"decaying rate of lr\")\n parser.add_argument(\"--decay_step\", type=int, default=10000) #decay_step > epoch: not use decaying rate\n parser.add_argument(\"--max_epoch\", type=int, default=80)\n parser.add_argument(\"--batch_num\", type=int, default=128)\n\n #hardware\n parser.add_argument(\"--gpu_idx\", type=int, default=0, help=\"gpu index num for multi-gpu case\")\n\n #tensorflow config\n parser.add_argument(\"--queue_load\", type=bool, default=False)\n parser.add_argument(\"--saved_interval\", type=int, default=20) #TODO\n\n args = parser.parse_args()\n\n os.envision['CUDA_VISIBLE-DEVICES'] = args.gpu_idx\n\n #data upload\n train_data_path = str(args.train_dir) + \"/\" + str(args.dataset)\n\n if not args.queue_load:\n print(\"not use queue loading, just sequential loading...\")\n\n ### WITHOUT ASYNCHRONOUS DATA LOADING ###\n\n train_input = tf.placeholder(tf.float32, shape=(\n args.batch_size, args.img_size[0], args.img_size[1], 1))\n train_gt = tf.placeholder(tf.float32, shape=(\n args.batch_size, args.img_size[0], args.img_size[1], 1))\n\n ### WITHOUT ASYNCHRONOUS DATA LOADING ###\n\n sys.exit(-1)\n\n else:\n print(\"use queue loading\")\n\n ### WITH ASYNCHRONOUS DATA LOADING ###\n\n train_input_single = tf.placeholder(\n tf.float32, shape=(args.image_size[0], args.image_size[1], 1))\n train_gt_single = tf.placeholder(\n tf.float32, shape=(args.image_size[0], args.image_size[1], 1))\n q = tf.FIFOQueue(10000, [tf.float32, tf.float32], [\n [args.image_size[0], args.image_size[1], 1], [args.image_size[0], args.image_size[1], 1]])\n enqueue_op = q.enqueue([train_input_single, train_gt_single])\n\n train_input, train_gt = q.dequeue_many(args.batch_size)\n\n ### WITH ASYNCHRONOUS DATA LOADING ###\n\n shared_model = tf.make_template('shared_model', model)\n #train_output, weights \t= model(train_input)\n train_output, weights = shared_model(train_input)\n loss = tf.reduce_sum(tf.nn.l2_loss(tf.subtract(train_output, train_gt)))\n for w in weights:\n loss += tf.nn.l2_loss(w) * 1e-4\n tf.summary.scalar(\"loss\", loss)\n\n global_step = tf.Variable(0, trainable=False)\n learning_rate = tf.train.exponential_decay(\n args.learning_rate, global_step * args.batch_size, len(train_list) * args.decay_step, args.decay_rate, staircase=True)\n tf.summary.scalar(\"learning rate\", learning_rate)\n\n # tf.train.MomentumOptimizer(learning_rate, 0.9)\n optimizer = tf.train.AdamOptimizer(learning_rate)\n opt = optimizer.minimize(loss, global_step=global_step)\n\n saver = tf.train.Saver(weights, max_to_keep=0)\n\n shuffle(train_list)\n config = tf.ConfigProto()\n # config.operation_timeout_in_ms=10000\n\n model_path = args.model_path\n\n with tf.Session(config=config) as sess:\n # TensorBoard open log with \"tensorboard --logdir=logs\"\n if not os.path.exists('logs'):\n os.mkdir('logs')\n merged = tf.summary.merge_all()\n file_writer = tf.summary.FileWriter('logs', sess.graph)\n\n tf.initialize_all_variables().run()\n\n # restore model if exists\n if model_path:\n print(\"restore model...\")\n saver.restore(sess, model_path)\n print(\"Done\")\n\n ### WITH ASYNCHRONOUS DATA LOADING ###\n def load_and_enqueue(coord, file_list, enqueue_op, train_input_single, train_gt_single, idx=0, num_thread=1):\n count = 0\n length = len(file_list)\n try:\n while not coord.should_stop():\n i = count % length\n input_img = scipy.io.loadmat(file_list[i][1])['patch'].reshape([\n args.image_size[0], args.image_size[1], 1])\n gt_img = scipy.io.loadmat(file_list[i][0])['patch'].reshape(\n [args.image_size[0], args.image_size[1], 1])\n sess.run(enqueue_op, feed_dict={\n train_input_single: input_img, train_gt_single: gt_img})\n count += 1\n except Exception as e:\n print((\"stopping...\", idx, e))\n ### WITH ASYNCHRONOUS DATA LOADING ###\n threads = []\n\n def signal_handler(signum, frame):\n sess.run(q.close(cancel_pending_enqueues=True))\n coord.request_stop()\n coord.join(threads)\n print(\"Done\")\n sys.exit(1)\n original_sigint = signal.getsignal(signal.SIGINT)\n signal.signal(signal.SIGINT, signal_handler)\n\n if args.queue_load:\n # create threads\n num_thread = 20\n coord = tf.train.Coordinator()\n for i in range(num_thread):\n length = len(train_list) / num_thread\n t = threading.Thread(target=load_and_enqueue, args=(coord, train_list[i * length:(\n i + 1) * length], enqueue_op, train_input_single, train_gt_single, i, num_thread))\n threads.append(t)\n t.start()\n print((\"num thread:\", len(threads)))\n\n for epoch in range(0, args.max_epoch):\n max_step = len(train_list) // args.batch_size\n for step in range(max_step):\n _, l, output, lr, g_step, summary = sess.run(\n [opt, loss, train_output, learning_rate, global_step, merged])\n print((\"[epoch %2.4f] loss %.4f\\t lr %.5f\" % (epoch + (float(step) * args.batch_size / len(train_list)), np.sum(l) / args.batch_size, lr)))\n file_writer.add_summary(summary, step + epoch * max_step)\n # print \"[epoch %2.4f] loss %.4f\\t lr %.5f\\t norm %.2f\"%(epoch+(float(step)*args.batch_size/len(train_list)), np.sum(l)/args.batch_size, lr, norm)\n saver.save(sess, \"./checkpoints/VDSR_adam_epoch_%03d.ckpt\" %\n epoch, global_step=global_step)\n else:\n for epoch in range(0, args.max_epoch):\n for step in range(len(train_list) // args.batch_size):\n offset = step * args.batch_size\n #TODO: get_image_batch python version porting\n input_data, gt_data, cbcr_data = get_image_batch(\n train_list, offset, args.batch_size)\n feed_dict = {train_input: input_data, train_gt: gt_data}\n _, l, output, lr, g_step = sess.run(\n [opt, loss, train_output, learning_rate, global_step], feed_dict=feed_dict)\n print((\"[epoch %2.4f] loss %.4f\\t lr %.5f\" % (epoch + (float(step) * args.batch_size / len(train_list)), np.sum(l) / args.batch_size, lr)))\n #TODO: calculate PSNR rather than loss function\n\n del input_data, gt_data, cbcr_data\n\n if epoch % args.saved_interval == 0:\n saver.save(sess, \"./checkpoints/VDSR_const_clip_0.01_epoch_%03d.ckpt\" %\n epoch, global_step=global_step)\n\n #TODO: for debuggin, we need to test image PSNR, test image result\n","sub_path":"VDSR.py","file_name":"VDSR.py","file_ext":"py","file_size_in_byte":10316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"122045524","text":"from helmnet import IterativeSolver\nfrom helmnet.support_functions import fig_generic\nimport numpy as np\nimport torch\n\nsolver = IterativeSolver.load_from_checkpoint(\n \"checkpoints/trained_weights.ckpt\", strict=False\n)\nsolver.freeze() # To evaluate the model without changing it\nsolver.to(\"cuda:0\")\n\n# Setup problem\nsource_location = [30, 128]\nsos_map = np.ones((256, 256))\nsos_map[100:170, 30:240] = np.tile(np.linspace(2,1,210),(70,1))\n\n# Set model domain size (assumed square)\nsolver.set_domain_size(sos_map.shape[-1], source_location=source_location)\n\n# Run example in kWave and pytorch, and produce figure\nfig_generic(\n solver,\n sos_map,\n path=\"images/withgmres\",\n source_location=source_location,\n omega=1,\n min_sos=1,\n cfl=0.1,\n roundtrips=10.0,\n mode=\"normal\",\n)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289139335","text":"#modules\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageTk\r\nfrom assets.resources.colors import *\r\nfrom src.styles import *\r\n\r\n#####################\r\n#translations i guess\r\nfrom assets.resources.translations.english import *\r\n\r\n#####################\r\n#code\r\n\r\nroot = Tk()\r\nroot.title('BCFD desktop')\r\nroot.geometry(\"1300x700\")\r\n\r\n\r\nicon = PhotoImage(file =\"assets/BCFD-LOGO.png\")\r\nroot.iconphoto(True, icon)\r\n\r\ntitle = Label(root, text=bcfdText, anchor='w',bg = barColor, fg = white)\r\n\r\ntitle.pack(fill = \"x\")\r\n\r\nimg = ImageTk.PhotoImage(Image.open(\"assets/BCFD-Default-icon.png\"))\r\npanel = Label(root, anchor='n', image = img, bg=imgBackroundColor)\r\npanel.pack(fill = \"both\", expand = \"yes\")\r\n\r\ntokenBox = Entry(root, width=\"55\", text=tokenText)\r\ntokenBox.pack(expand = \"yes\", anchor=\"center\", side='top')\r\n\r\nroot.configure(bg=color)\r\n\r\n#######################\r\n#on\r\n\r\n\r\nroot.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"python/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544321013","text":"#!/usr/bin/env python\n\nimport sys\nsys.path.append('./')\nsys.path.append('../../')\n\nfrom lab_utils import (\n tf, os, np, plt, logger, ap, BooleanAction,\n debug, toc, auto_increment\n)\n\nap.add_argument('--epochs', type=int, default=10, help='number of epochs: 10*')\nap.add_argument('--batch', type=int, default=64, help='batch size: 64*')\nargs, extra_args = ap.parse_known_args()\nlogger.info(args)\n# logger.info(extra_args)\n\nif args.all:\n args.step = 0 # forced to 0\n\nif args.debug:\n import pdb\n import rlcompleter\n pdb.Pdb.complete=rlcompleter.Completer(locals()).complete\n # import code\n # code.interact(local=locals())\n debug = breakpoint\n\nimport time\nimport io\nimport re\nimport shutil\nimport string\n\nfrom tensorflow.keras import Sequential, Model, Input\nfrom tensorflow.keras.layers import Dense, Embedding, GlobalAveragePooling1D\nfrom tensorflow.keras.layers.experimental.preprocessing import TextVectorization\n\n\n### TOC\nif args.step == 0:\n toc(__file__)\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #1 - Representing text as numbers\nif args.step == 1: \n print(\"\\n### Step #1 - Representing text as numbers\")\n\n logger.info('One-hot encodings:')\n __doc__ ='''\n This approach is inefficient.\n A one-hot encoded vector is sparse (meaning, most indices are zero).\n Imagine you have 10,000 words in the vocabulary. To one-hot encode each word,\n you would create a vector where 99.99% of the elements are zero.\n '''\n print(__doc__)\n\n logger.info('Encode each word with a unique number:')\n __doc__='''\n This appoach is efficient. Instead of a sparse vector,\n you now have a dense one (where all elements are full).\n There are two downsides to this approach, however:\n - The integer-encoding is arbitrary\n (it does not capture any relationship between words).\n - An integer-encoding can be challenging for a model to interpret.\n A linear classifier, for example, learns a single weight for each\n feature. Because there is no relationship between the similarity\n of any two words and the similarity of their encodings, this feature-weight\n combination is not meaningful.\n '''\n print(__doc__)\n\n logger.info('Word embeddings:')\n __doc__='''\n Word embeddings give us a way to use an efficient, dense representation\n in which similar words have a similar encoding. Importantly, you do not\n have to specify this encoding by hand. An embedding is a dense vector of\n floating point values (the length of the vector is a parameter you specify).\n Instead of specifying the values for the embedding manually, they are\n trainable parameters (weights learned by the model during training).\n It is common to see word embeddings that are 8-dimensional (for small\n datasets), up to 1024-dimensions when working with large datasets.\n A higher dimensional embedding can capture fine-grained relationships\n between words, but takes more data to learn.\n '''\n print(__doc__)\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #2 - Setup: Download the IMDb Dataset\nif args.step in [2, 3, 5, 6, 7, 8]: \n print(\"\\n### Step #2 - Setup: Download the IMDb Dataset\")\n\n url = \"https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\"\n dataset = tf.keras.utils.get_file(\n \"aclImdb_v1.tar.gz\", \n url,\n untar=True\n )\n\n dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')\n train_dir = os.path.join(dataset_dir, 'train')\n remove_dir = os.path.join(train_dir, 'unsup')\n if os.path.exists(remove_dir):\n shutil.rmtree(remove_dir)\n \n batch_size = 1024\n seed = 123\n\n train_ds = tf.keras.preprocessing.text_dataset_from_directory(\n train_dir, batch_size=batch_size, validation_split=0.2,\n subset='training', seed=seed\n )\n val_ds = tf.keras.preprocessing.text_dataset_from_directory(\n train_dir, batch_size=batch_size, validation_split=0.2,\n subset='validation', seed=seed\n )\n\n if args.step == 2:\n print()\n logger.info(dataset_dir)\n print(*os.listdir(dataset_dir), sep='\\n')\n print()\n logger.info('samples:')\n for text_batch, label_batch in train_ds.take(1):\n for i in range(5):\n print(label_batch[i].numpy(), ':', text_batch.numpy()[i][:50])\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #3 - Setup: Configure the dataset for performance\nif args.step in [3, 5, 6, 7, 8]: \n print(\"\\n### Step #3 - Setup: Configure the dataset for performance\")\n\n AUTOTUNE = tf.data.AUTOTUNE\n\n train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)\n val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #4 - Using the Embedding layer\nif args.step == 4: \n print(\"\\n### Step #4 - Using the Embedding layer\")\n\n # Embed a 1,000 word vocabulary into 5 dimensions.\n embedding_layer = tf.keras.layers.Embedding(1000, 5)\n\n result = embedding_layer(tf.constant([1, 2, 3]))\n logger.info('embedding_layer(tf.constant([1, 2, 3])):')\n print(result.numpy(), '\\n')\n\n input_text = tf.constant([[0, 1, 2], [3, 4, 5]])\n result = embedding_layer(input_text)\n logger.info(f'shape of input_text: {input_text.shape}')\n logger.info(f'shape of embedding_layer: {result.shape}')\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #5 - Text preprocessing\nif args.step in [5, 6, 7, 8]: \n print(\"\\n### Step #5 - Text preprocessing\")\n\n # Create a custom standardization function to strip HTML break tags '
'.\n def custom_standardization(input_data):\n lowercase = tf.strings.lower(input_data)\n stripped_html = tf.strings.regex_replace(lowercase, '
', ' ')\n return tf.strings.regex_replace(\n stripped_html, '[%s]' % re.escape(string.punctuation), ''\n )\n\n # Vocabulary size and number of words in a sequence.\n vocab_size = 10000\n sequence_length = 100\n\n # Use the text vectorization layer to normalize, split, and map strings to\n # integers. Note that the layer uses the custom standardization defined above.\n # Set maximum_sequence length as all samples are not of the same length.\n vectorize_layer = TextVectorization(\n standardize=custom_standardization,\n max_tokens=vocab_size,\n output_mode='int',\n output_sequence_length=sequence_length\n )\n\n # Make a text-only dataset (no labels) and call adapt to build the vocabulary.\n text_ds = train_ds.map(lambda x, y: x)\n vectorize_layer.adapt(text_ds)\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #6 - Create a classification model\nif args.step in [6, 7, 8]: \n print(\"\\n### Step #6 - Create a classification model\")\n\n embedding_dim=16\n model = Sequential([\n vectorize_layer,\n Embedding(vocab_size, embedding_dim, name=\"embedding\"),\n GlobalAveragePooling1D(),\n Dense(16, activation='relu'),\n Dense(1)\n ])\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #7 - Compile and train the model\nif args.step in [7, 8]: \n print(\"\\n### Step #7 - Compile and train the model\")\n\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=\"tmp/tf2_t0701/logs\")\n\n model.compile(\n optimizer='adam',\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n metrics=['accuracy']\n )\n\n model.fit(\n train_ds,\n validation_data=val_ds,\n epochs=args.epochs, # 15\n callbacks=[tensorboard_callback],\n verbose=2 if args.step == 7 else 0\n )\n\n if args.step == 7:\n print()\n model.summary()\n print('\\ntensorboard --logdir tmp/tf2_t0701/logs --bind_all')\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #8 - Retrieve the trained word embeddings and save them to disk\nif args.step == 8: \n print(\"\\n### Step #8 - Retrieve the trained word embeddings and save them to disk\")\n\n weights = model.get_layer('embedding').get_weights()[0]\n vocab = vectorize_layer.get_vocabulary()\n\n out_v = io.open('tmp/tf2_t0701/vectors.tsv', 'w', encoding='utf-8')\n out_m = io.open('tmp/tf2_t0701/metadata.tsv', 'w', encoding='utf-8')\n\n for index, word in enumerate(vocab):\n if index == 0:\n continue # skip 0, it's padding.\n vec = weights[index]\n out_v.write('\\t'.join([str(x) for x in vec]) + \"\\n\")\n out_m.write(word + \"\\n\")\n out_v.close()\n out_m.close()\n\n\nargs.step = auto_increment(args.step, args.all)\n### Step #9 - Visualize the embeddings\nif args.step == 9:\n print(\"\\n### Step #9 - Visualize the embeddings\")\n\n __doc__ = '''\n To visualize the embeddings, upload them to the embedding projector.\n 1. Open the Embedding Projector[http://projector.tensorflow.org/]\n (this can also run in a local TensorBoard instance).\n 2. Click on \"Load data\".\n 3. Upload the two files you created above: vecs.tsv and meta.tsv.\n '''\n print(__doc__)\n\n\n\n### End of File\nprint()\nif args.plot:\n plt.show()\ndebug()\n\n\n","sub_path":"text/guide/lab.0102.concepts.word_embeddings.py","file_name":"lab.0102.concepts.word_embeddings.py","file_ext":"py","file_size_in_byte":9091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"109522306","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.impute import KNNImputer\nimport time\nimport profile\nimport pytest\n\n##################### THIS TEST SUITE WILL TAKE APPROXIMATELY 15 MINUTES, BUT VARIES BY MACHINE ############################\n\n# Initialise constants\nepsilon = 0.75 # Seconds of breathing room for smaller sized n tests\nperc = [0.1,0.5,0.9] # We want to test a varying amount of missing values to impute, each of these represent the precrentage of missing values in X\nsmall_n = [5,300,500]\nlarge_n = [1000,3000,5000]\n\n# generate random array of size x by y with (p*100)% missing values\ndef gen_matrix(x, y, p):\n np.random.seed(1)\n X = np.random.random([x, y])\n X = pd.DataFrame(X).mask(X <= p)\n return X\n\n# Run (simulated) old time or new time, return start and end times\ndef run_test(X, old=False):\n start = time.time()\n if (old):\n imputer = KNNImputer(n_neighbors=5, n_jobs=1)\n else:\n imputer = KNNImputer(n_neighbors=5)\n imputer.fit_transform(X)\n end = time.time()\n\n return start,end\n\ndef relative_assert(new, old):\n # Since smaller times will yield more sporatic results, an amount of seconds of amount epsilon are accounted for\n assert ((new == pytest.approx(old, abs=epsilon)) or (new < old))\n\ndef output_res(old_end,old_start,end,start):\n print(\"\\nOld time:\", round((old_end-old_start),4) ,\", New time:\", round((end-start),4),\",\", str(round(((old_end-old_start)/(end-start) - 1)*100, 2))+\"% improved\")\n\n# Test arrays of size 1 by a small n with varying missing values\n@pytest.mark.parametrize(\"n,p\",[(n, p) for p in perc for n in small_n])\ndef test_time_1_by_n(n,p):\n X = gen_matrix(1, n, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of size 1 by a large n with varying missing values\n@pytest.mark.parametrize(\"N,p\",[(N, p) for p in perc for N in large_n])\ndef test_time_1_by_N(N,p):\n X = gen_matrix(1, N, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of a small n by 1 with varying missing values\n@pytest.mark.parametrize(\"n,p\",[(n, p) for p in perc for n in small_n])\ndef test_time_n_by_1(n,p):\n X = gen_matrix(n, 1, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of a large n by 1 with varying missing values\n@pytest.mark.parametrize(\"N,p\",[(N, p) for p in perc for N in large_n])\ndef test_time_N_by_1(N,p):\n X = gen_matrix(N, 1, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of a small n by a small n with varying missing values\n@pytest.mark.parametrize(\"n1,n2,p\",[(n1,n2,p) for p in perc for n1 in small_n for n2 in small_n])\ndef test_time_n_by_n(n1,n2,p):\n X = gen_matrix(n1, n2, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of a small n by a large n with varying missing values\n@pytest.mark.parametrize(\"n,N,p\",[(n,N,p) for p in perc for n in small_n for N in large_n])\ndef test_time_n_by_N(n,N,p):\n X = gen_matrix(n, N, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of a large n by a small n with varying missing values\n### This is the most important test case since it is the most likely scenario for usage\n### (More likely to be testing a large number of features)\n@pytest.mark.parametrize(\"N,n,p\",[(N,n,p) for p in perc for n in small_n for N in large_n])\ndef test_time_N_by_n(N,n,p):\n X = gen_matrix(N, n, p)\n\n start, end = run_test(X)\n old_start, old_end = run_test(X, old=True)\n\n output_res(old_end,old_start,end,start)\n\n relative_assert(end-start, old_end-old_start)\n\n# Test arrays of a large n by a large n with varying missing values\n# (This takes a VERY long time to run, since they are more often called individually)\n## @pytest.mark.parametrize(\"N1,N2,p\",[(N1,N2,p) for p in perc for N1 in large_n for N2 in large_n])\n## def test_time_N_by_N(N1, N2, p):\n## X = gen_matrix(N1, N2, p)\n\n## start, end = run_test(X)\n## old_start, old_end = run_test(X, old=True)\n\n## output_res(old_end,old_start,end,start)\n\n## relative_assert(end-start, old_end-old_start)\n","sub_path":"sklearn/impute/tests/test_time.py","file_name":"test_time.py","file_ext":"py","file_size_in_byte":4773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576150362","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom time import sleep\n\ndef periodCalc (data, sumCrop=4.5, swingCrop=None, viewGraph=True):\n '''\n This function takes a pandas dataframe of period data and calculates the\n period from the zero crossings, by event numbers.\n\n input: dataframe with columns=['eventNumber', 'sumSignal',\n 'leftMinusRight', 'topMinusBotom',\n 'xField', 'yField', 'timeStamp']\n output: dataframe with columns=['eventNumber', 'avgPeriod',\n 'xField', 'yField']\n\n Variables=\n\n sumCrop: value for which all data be ignored if sumSignal is lower than it\n\n swingCrop: a +/- value to stop counting when the signal dampens out, checks\n backwards, until swingCrop or (-swingCrop) is met by\n leftMinusRight, and then crops off all data after that index.\n May not work if the data wanders high or low after good crossings.\n\n viewGraph: allows the user to see a graph of the leftMinusRight and sumSignal\n data, and then prompts for a last index value for analysis.\n Allows for wandering data, as people tend to be better at picking\n out bad wandering signals than computers.\n '''\n eventNumbers = data.eventNumber.unique() # checks for unique event numbers\n\n #set up for a couple of checks in the loop\n first=True\n\n for j,l in enumerate(eventNumbers): #goes through data by event number\n\n print('%s of %s'%(int(l), len(eventNumbers)))#prints which event number\n\n selectedData = data.loc[data.eventNumber == l] #only checks event number data\n selectedData = selectedData.reset_index()\n\n #crops end where data is no longer swinging consistantly\n if swingCrop != None:\n for i in reversed(selectedData.leftMinusRight.index):\n if selectedData.leftMinusRight[i] >= swingCrop \\\n or selectedData.leftMinusRight[i] <= -1*swingCrop:\n CropIndex = i\n break\n\n #shows users the data, and asks for index to crop after\n if viewGraph:\n repeat = True\n while repeat:\n x = selectedData.index\n y = selectedData.leftMinusRight\n z = selectedData.sumSignal\n plt.figure(figsize=(15,12))\n plt.plot(x,y, 'o')\n plt.plot(x,z, 'o')\n plt.xlabel('Index')\n plt.ylabel('Sum Signal and L-R Signal')\n plt.show()\n try:\n CropIndex = 1000*int(input('Please enter the end index value \\\n for analysis in thousands, \\n e.g. 13 for index \\\n 13,000 (0 for all): '))\n repeat = False\n except:\n pass \n \n if CropIndex == 0:\n CropIndex = max(selectedData.index)+1\n repeat = False\n\n #crops index\n selectedData = selectedData[selectedData.index <= CropIndex]\n\n crossingsIndex=[]\n #checks to see if the sign from one element to the next changes, and then\n #appends the value of the two that is closest to zero\n\n for i in range(1,len(selectedData.index)):\n if ((selectedData.leftMinusRight[i]>0.0 and selectedData.leftMinusRight[i-1]<0.0)\n or (selectedData.leftMinusRight[i]<0.0 and selectedData.leftMinusRight[i-1]>0.0)):\n if abs(selectedData.leftMinusRight[i]) < abs(selectedData.leftMinusRight[i-1]):\n crossingsIndex.append(i)\n else:\n crossingsIndex.append(i-1)\n\n #creates a boolean array to append to data DataFrame to show crossings\n crossings = np.zeros(len(selectedData.index))\n\n for i in crossingsIndex:\n crossings[i] = True\n\n #adds column to data of crossing value\n selectedData['crossings'] = pd.Series(crossings, index=selectedData.index)\n\n #crops data to only include crossings and high sum signal\n newdata = selectedData.loc[selectedData['sumSignal'] >= sumCrop]\n newdata = newdata.loc[newdata['crossings'] == True]\n\n\n #resets index\n newdata = newdata.reset_index()\n\n #gets periods of crossings\n periods = []\n for i in range(2, len(newdata.index)):\n periods.append(newdata.timeStamp[i]-newdata.timeStamp[i-2])\n\n #gets average period\n avgPeriod = np.mean(periods)\n stdPeriods = np.std(periods)\n numPeriods = len(periods)\n\n #if first time through loop (usually eventNumber = 0), sets up return\n #database\n if first:\n\n d = {'eventNumber':l, 'avgPeriod':avgPeriod,\n 'periodSTD': stdPeriods, 'numPeriods': numPeriods,\n 'xField':newdata.xField.mean(), 'yField':newdata.yField.mean()}\n periodList = pd.DataFrame(d, index=[0])\n\n first=False\n\n #adds to set up database from above\n else:\n\n tempdf = pd.DataFrame({'eventNumber':l, 'avgPeriod':avgPeriod,\n 'periodSTD':stdPeriods, 'numPeriods':numPeriods,\n 'xField':newdata.xField.mean(),\n 'yField':newdata.yField.mean()}, index=[0])\n periodList= pd.concat([periodList,tempdf], ignore_index=True)\n\n\n return periodList\n","sub_path":"period.py","file_name":"period.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"604425349","text":"class Morph:\n def __init__(self, surface, base, pos, pos1):\n self.surface = surface\n self.base = base\n self.pos = pos\n self.pos1 = pos1\n\n\none_sent = []\nsurf = \"abc\"\nitems = [0,1,2,3,4,5,6,7]\n\none_sent.append(Morph(surf, items[6], items[0], items[1]))\nprint(Morph(surf, items[6], items[0], items[1]))\nprint(one_sent)\nprint(Morph(surf, items[6], items[0], items[1]).surface)\nfor item in one_sent:\n print ('surface=%s\\tbase=%d\\tpos=%d\\tpos1=%d' % (item.surface, item.base, item.pos, item.pos1) )\n\n\"\"\"\nall_sent = []\n\nwith open('neko.txt.cabocha', encoding='utf-8') as cabochaed:\n for line in cabochaed:\n if line[0] == \"*\" :\n next\n if \"\\t\" in line:\n item = line.strip().split(\"\\t\")\n try: # 一文字目が空白で始まるものがうまく処理できなかったので、try - exceptを使うことにした\n surf = item[0]\n items = item[1].split(\",\")\n except IndexError: # 一文字目が空白だとIndexErrorを起こすみたい\n next\n if not item == ['記号,空白,*,*,*,*,\\u3000,\\u3000,']: # 空白の箇所の処理, \\u3000は空白、ここはかなりアドホックな処理をしている\n one_sent.append(Morph(surf, items[6], items[0], items[1]))\n elif \"EOS\" in line:\n if len(one_sent) > 0:\n all_sent.append(one_sent)\n one_sent = []\n\nfor item in all_sent[3]:\n print ('surface=%s\\tbase=%s\\tpos=%s\\tpos1=%s' % (item.surface, item.base, item.pos, item.pos1) )\n \"\"\"","sub_path":"Eguchi/chapter05/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610795174","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 22 15:59:00 2017\n\n\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.plotly as py\nimport numpy as np\nimport seaborn as sns\nsns.set_style('whitegrid')\n\ntrain = pd.read_csv('H:/GIM Strategy and Execution/Knowledge/Data and Python/titanic/train.csv')\ndel(train['Ticket'])\n\ndel(train['PassengerId'])\n\ntrain[['Pclass', 'Survived']].groupby(['Pclass']).mean()\ntrain[['Pclass', 'Survived']].plot()\n\nsns.countplot( x= 'Pclass', data = train)\nsns.countplot(x = 'Survived', hue = 'Embarked', data = train, order = [1,0])\n\nfig, (axis1,axis2,axis3) = plt.subplots(1,3,figsize=(15,5))\n\n#Plot to see % of people from each embarkment survived\nembarkedmean = train[['Survived', 'Embarked']].groupby(['Embarked'], as_index = False).mean()\nsns.barplot(x = 'Embarked', y = 'Survived', data = embarkedmean, ax = axis2)\n\n#Plot to see % of male / female survived\nsexmean = train[['Survived', 'Sex']].groupby(['Sex'], as_index = False).mean()\nsns.barplot('Sex', 'Survived', data = sexmean, ax = axis1)\n\n#plot scatter of age vs fare w/ survival as colors\nplt.scatter(train['Age'], train['Fare'], c= train['Survived'], cmap=plt.cm.coolwarm)\n\ntMale = train.loc[train['Sex']=='male']\nplt.scatter(tMale['Age'], tMale['Fare'], c= tMale['Survived'], cmap=plt.cm.coolwarm)\n","sub_path":"Titanic.py","file_name":"Titanic.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504976806","text":"import os, umap\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport h5py\nfrom scipy.sparse import csc_matrix\nfrom sklearn.decomposition import PCA\n\n#####################\n\n\ndef read_h5(path):\n \"\"\"\n Function takes data in h5 file format and returns pandas DataFrame\n Input: (string) file pathname\n Returns: (pd.DataFrame) pandas dataframe with RNA-seq data\n \"\"\"\n # Read h5 file\n h5_file = h5py.File(path)[\"mm10\"]\n\n #define tuple with data, indices, and indptr\n dat_ind_ptr = (h5_file.get('data')[:],\n h5_file.get('indices')[:], h5_file.get('indptr')[:])\n\n #decompress data from compressed matrix format\n csc = csc_matrix(dat_ind_ptr, h5_file.get('shape')[:])\n\n # return dataframe\n return pd.DataFrame(csc.toarray(),\n columns = list(h5_file.get('barcodes')[:]),\n index = list(h5_file.get('genes')[:]))\n\ndef main():\n files_to_plot = 5\n #initialize\n data_mat = None\n shapes = []\n for filename in os.listdir('../data/GSE115943_RAW/')[:files_to_plot]:\n #read data\n data = read_h5('../data/GSE115943_RAW/' + filename)\n #log transform and transpose data\n data = np.transpose(np.log2(data.to_numpy() + 1))\n if data_mat is None:\n data_mat = data\n else:\n data_mat = np.concatenate((data_mat, data))\n shapes.append(data.shape[0])\n\n # run PCA with top 30 svs\n pca = PCA(n_components=30)\n pca.fit(data_mat)\n mat_pca = pca.transform(data_mat)\n\n # Define UMAP\n rna_umap = umap.UMAP(n_neighbors=30, min_dist=.25)\n\n # Fit UMAP and extract latent vars 1-2\n embedding = pd.DataFrame(rna_umap.fit_transform(mat_pca),\n columns = ['UMAP1','UMAP2'])\n legend_hue = [str(i) for i in range(files_to_plot) for j in range(shapes[i])]\n\n # Produce sns.scatterplot and use file number as color\n sns_plot = sns.scatterplot(x='UMAP1', y='UMAP2', data=embedding,\n hue=legend_hue,\n alpha=1, linewidth=0, s=1)\n # Adjust legend\n sns_plot.legend(loc='center left', bbox_to_anchor=(1, .5))\n plt.show()\n # Save PNG\n sns_plot.figure.savefig('../figures/two_page_figure.png',\n bbox_inches='tight', dpi=500)\nmain()\n","sub_path":"code/generate_figures.py","file_name":"generate_figures.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"257097857","text":"class Solution:\n def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:\n totalNum = 0\n queue = [(i,j,0)]\n while len(queue):\n state = queue.pop(0)\n if state[2] < N:\n up = (state[0]-1, state[1], state[2]+1)\n down = (state[0]+1, state[1], state[2]+1)\n left = (state[0], state[1]-1, state[2]+1)\n right = (state[0], state[1]+1, state[2]+1)\n new_state = [up, down, left, right]\n inline = [x for x in new_state \\\n if (x[0] not in [-1, m] and x[1] not in [-1, n]) ]\n totalNum = totalNum + 4 - len(inline)\n for x in inline:\n queue.append(x)\n \n return totalNum % (1000000000 + 7)\n\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n print( solution.findPaths(7, 5, 10, 5, 0) )","sub_path":"LeetCode/576_出界的路径数/Traversal.py","file_name":"Traversal.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"192989238","text":"# coding=utf-8\n# python ${script_tools}/ApkBuild/apks_compile.py \n# ${JOB_NAME} ${WORKSPACE} ${SIGN_TYPE} ${BRANCH} ${BUILD_TOOL} ${Need_Test}\nimport shutil\nimport os\nimport sys\nimport subprocess\nimport datetime\nimport io\n\nlint_option = '''\n lintOptions {\n abortOnError false\n }\n'''\nmultiDexEnabled = '''\n multiDexEnabled true\n'''\ngradle_properties_contents_list = [\nu'org.gradle.jvmargs=-Xmx6144m -XX:MaxPermSize=5210m\\n'\nu'org.gradle.daemon=false\\n'\nu'org.gradle.parallel=false\\n'\n]\ngradle_properties_contents = '''\norg.gradle.jvmargs=-Xmx6144m -XX:MaxPermSize=5210m\norg.gradle.daemon=false\norg.gradle.parallel=false\n'''\ngrade_projectsEvaluated = '''\n tasks.withType(JavaCompile){\n options.sourcepath = files(\n '/this/directory/must/not/exits'\n )\n }\n'''\nCOVERITY_NO_PRELOAD_CLASSES ='export COVERITY_NO_PRELOAD_CLASSES=java.io.ObjectInputStream'\n\n# Initialize the gradle of project\ndef gradle_init(dir):\n build_gradle_path = dir + \"/build.gradle\" #path of project build.gradle\n settings_gradle_path = dir + \"/settings.gradle\" # path of Settings.gradle\n local_properties_path = dir + \"/local.properties\" # path of local.properties' path\n if os.path.exists(build_gradle_path):\n print (\"build.gradle path:\"+str(build_gradle_path))\n os.chdir(dir)\n list_content = []\n new_content = ''\n with io.open(build_gradle_path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n list_content.append(line)\n for content in list_content:\n if \"allprojects {\" in content:\n new_content = new_content + content + grade_projectsEvaluated\n continue\n new_content = new_content + content\n with io.open(build_gradle_path, 'r+', encoding='utf-8') as f:\n f.writelines(new_content)\n if os.path.exists(local_properties_path):\n os.chdir(dir)\n os.system(\"rm local.properties\")\n # Get all modules' name from reading the Setting.gradle\n #if prj_name == 'Camera' and branch not in 'Camera_steady':\n # module_name = ['Camera_Publish']\n # module_num = len(module_name)\n #else:\n module_name = get_module_name(settings_gradle_path)\n module_num = len(module_name)\n\n os.chdir(dir)\n if os.path.exists(dir + \"/gradle.properties\") :\n project_gradle_properties_path = dir + \"/gradle.properties\"\n if prj_name == 'ItelOS' :\n list_content = []\n new_content = ''\n with io.open(project_gradle_properties_path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n list_content.append(line)\n for content in list_content:\n if \"org.gradle.jvmargs\" in content:\n new_content += gradle_properties_contents\n continue\n new_content = new_content + content\n with io.open(project_gradle_properties_path, 'r+', encoding='utf-8') as f:\n f.writelines(new_content)\n else :\n os.system(\"rm gradle.properties;\")\n os.system(\"touch gradle.properties;\")\n with io.open(project_gradle_properties_path, 'r+', encoding='utf-8') as f:\n f.writelines(gradle_properties_contents_list)\n else :\n os.system(\"touch gradle.properties\")\n project_gradle_properties_path = dir + \"/gradle.properties\"\n with io.open(project_gradle_properties_path, 'r+', encoding='utf-8') as f:\n f.writelines(gradle_properties_contents_list)\n \n # modify the build.gradles of modules in project, add list_content to those build.gradles\n if module_num == 0:\n module_build_gradle_path = dir + \"/build.gradle\"\n print(module_build_gradle_path)\n list_content = []\n new_content = ''\n\n list_content.append(\"import java.text.SimpleDateFormat\\n\")\n # 在Gradle.build中添加new_content和build_time内容\n with io.open(module_build_gradle_path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n list_content.append(line)\n for content in list_content:\n if \"versionName\" in content and \"//\" not in content:\n version_name = content.split()[1].strip('\"')\n version_name_format = ' versionName \"' + version_name + '({0})\"\\n'.format(date_format2)\n new_content += version_name_format\n continue\n if \"defaultConfig {\" in content:\n new_content = new_content + lint_option + content\n continue\n if \"jackOptions {\" in content:\n new_content = new_content + multiDexEnabled + content\n continue\n new_content = new_content + content\n with io.open(module_build_gradle_path, 'r+', encoding='utf-8') as f:\n f.writelines(new_content)\n else:\n for i in range(0, len(module_name)):\n module_build_gradle_path = dir + \"/\" + module_name[i] + \"/build.gradle\"\n print(module_build_gradle_path)\n list_content = []\n new_content = ''\n\n list_content.append(\"import java.text.SimpleDateFormat\\n\")\n # 在Gradle.build中添加new_content和build_time内容\n with io.open(module_build_gradle_path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n list_content.append(line)\n for content in list_content:\n if \"versionName\" in content and \"//\" not in content:\n version_name = content.split()[1].strip('\"')\n version_name_format = ' versionName \"' + version_name + '({0})\"\\n'.format(date_format2)\n new_content += version_name_format\n continue\n if \"defaultConfig {\" in content:\n new_content = new_content + lint_option + content\n continue\n if \"jackOptions {\" in content:\n new_content = new_content + multiDexEnabled + content\n continue\n ##chb add for coverity start\n if \"apply plugin\" in content:\n new_content = new_content + content + grade_projectsEvaluated\n continue\n ##chb add for coverity end\n new_content = new_content + content\n os.chdir(dir +\"/\"+module_name[i])\n os.system(\"rm build.gradle;\")\n os.system(\"touch build.gradle\")\n with io.open(module_build_gradle_path, 'r+', encoding='utf-8') as f:\n f.writelines(new_content)\n \ndef get_module_name(setting_gradle_address):\n module_name_list = list()\n with io.open(setting_gradle_address, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n module_name = line\n module_name_list.append(module_name)\n #print (\"module_name_list:\"+str(module_name_list))\n real_module_name_list = []\n for i in range(len(module_name_list)):\n moudle_name_list_sub = module_name_list[i]\n #print ('moudle_name_list_sub:'+str(moudle_name_list_sub))\n app_module_list = moudle_name_list_sub.split(',')\n #print (\"app_module_list:\"+str(app_module_list))\n #print (\"lenth app_module_list:\"+str(len(app_module_list)))\n for j in range (len(app_module_list)):\n real_module_name_list.append(app_module_list[j].replace(\"'\", '').replace('include', '').replace(' ', '').replace(':', '').replace(\"\\n\", ''))\n print(\"real_module_name_list: \"+str(real_module_name_list))\n return real_module_name_list\n\n\ndef copy_tn_for_camera():\n workspace_dir = prj_dir + r\"/ModuleCamera\"\n build_gralde = workspace_dir + r\"/build.gradle\"\n build_tn_gradle = workspace_dir + r\"/build_tn.gradle\"\n build_bk_gradle = workspace_dir + r\"/build_backup.gradle\"\n if os.path.exists(build_tn_gradle):\n shutil.move(build_gralde, build_bk_gradle)\n shutil.move(build_tn_gradle, build_gralde)\n\n\ndef copy_tn_for_phonemanager():\n workspace_dir = prj_dir + r\"/app\"\n build_gralde = workspace_dir + r\"/build.gradle\"\n build_show_icon_gradle = workspace_dir + r\"/build_show_icon.gradle\"\n build_bk_gradle = workspace_dir + r\"/build_backup.gradle\"\n if os.path.exists(build_show_icon_gradle):\n shutil.move(build_gralde, build_bk_gradle)\n shutil.move(build_show_icon_gradle, build_gralde)\n\n\nif __name__ == '__main__':\n job_name = sys.argv[1]\n print ('job_name: '+str(job_name))\n prj_name =sys.argv[1].split('_')[0].replace(' ','').replace('\\n','').replace('\\r','').replace('\\t','').replace('{','').replace('}','').replace('\\'','').strip()\n print ('prj_name: '+str(prj_name))\n prj_dir = sys.argv[2]\n branch = sys.argv[3]\n is_tn = \"No\"\n submodule = ''\n if prj_name == \"Camera\":\n is_tn = sys.argv[4]\n if prj_name == \"SystemUI\":\n submodule = sys.argv[4]\n\n date = datetime.datetime.now()\n date_format1 = date.strftime(\"%Y.%m.%d_%H.%M\") # yy.mm.dd_HHMM格式的日期\n date_format2 = date.strftime(\"%Y%m%d_%H%M%S\") # yyMMdd.HHmmss格式的日期\n\n if is_tn == \"Yes\":\n copy_tn_for_camera()\n\n print(\"编译准备!!!\")\n gradle_init(prj_dir)\n os.system(COVERITY_NO_PRELOAD_CLASSES)\n","sub_path":"script/ApkBuild/pipeline/apk_build_ready_for_coverity.py","file_name":"apk_build_ready_for_coverity.py","file_ext":"py","file_size_in_byte":9388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486506005","text":"import sys\nimport PIL\nfrom PIL import Image\nimport numpy as np\nimport os\nsys.setrecursionlimit(50000)\nnp.set_printoptions(threshold=np.nan)\n\nglobal_image = []\nthreshold = 0.15\ndef thinning(image, root_path):\n im = Image.open(root_path + '/' + image)\n image = im.load()\n h, w = im.size\n #quantize image to 0 and 1 value\n quantitized_image = np.zeros((w + 2, h + 2), dtype=int)\n for i in range(w):\n for j in range(h):\n rgb_image = image[j, i]\n if(isinstance(rgb_image, int)):\n grayscale = rgb_image\n elif (len(rgb_image) == 4):\n if (rgb_image[3] > 0):\n grayscale = (rgb_image[0] + rgb_image[1] + rgb_image[2]) / 3\n else:\n grayscale = 9999\n else:\n grayscale = (rgb_image[0] + rgb_image[1] + rgb_image[2]) / 3\n\n if(grayscale < 120):\n quantitized_image[i + 1, j + 1] = 1\n #Algoritma Zhang-suen\n changing1 = changing2 = 1 # the points to be removed\n while changing1 or changing2: # iterates until no further changes occur in the image\n # Step 1\n changing1 = []\n rows, columns = quantitized_image.shape # x for rows, y for columns\n for x in range(1, rows - 1): # No. of rows\n for y in range(1, columns - 1): # No. of columns\n P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, quantitized_image)\n if (quantitized_image[x][y] == 1 and # Condition 0: Point P1 in the object regions \n 2 <= sum(n) <= 6 and # Condition 1: 2<= N(P1) <= 6\n transitions(n) == 1 and # Condition 2: S(P1)=1 \n P2 * P4 * P6 == 0 and # Condition 3 \n P4 * P6 * P8 == 0): # Condition 4\n changing1.append((x,y))\n for x, y in changing1: \n quantitized_image[x][y] = 0\n # Step 2\n changing2 = []\n for x in range(1, rows - 1):\n for y in range(1, columns - 1):\n P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, quantitized_image)\n if (quantitized_image[x][y] == 1 and # Condition 0\n 2 <= sum(n) <= 6 and # Condition 1\n transitions(n) == 1 and # Condition 2\n P2 * P4 * P8 == 0 and # Condition 3\n P2 * P6 * P8 == 0): # Condition 4\n changing2.append((x,y)) \n for x, y in changing2: \n quantitized_image[x][y] = 0\n\n return quantitized_image\n\n\ndef neighbours(x,y,image):\n # \"Return 8-neighbours of image point P1(x,y), in a clockwise order\"\n img = image\n x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1\n return [ img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], # P2,P3,P4,P5\n img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1] ] # P6,P7,P8,P9\n\ndef transitions(neighbours):\n #\"No. of 0,1 patterns (transitions from 0 to 1) in the ordered sequence\"\n n = neighbours + neighbours[0:1] # P2, P3, ... , P8, P9, P2\n return sum( (n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]) ) # (P2,P3), (P3,P4), ... , (P8,P9), (P9,P2)\n\ndef get_feature_from_bone(bone):\n h, w = bone.shape\n global global_image\n global_image = bone\n datas = []\n for i in range(h):\n for j in range(w):\n if(global_image[i, j] == 1): #jika bertemu titik yg belum diperiksa\n if(path_count(i, j, global_image) == 1): #jika titik di ujung\n corners = []\n corners.append([i,j])\n global_image[i, j] = 2\n circles, branchs, corner, chain_codes= check(i, j)\n corners = corners + corner\n data = []\n circles = circles/2\n data.extend([int(circles),branchs, corners, chain_codes])\n datas.append(data)\n elif(path_count(i, j, global_image) == 2): #jika titik di tengah\n corners = []\n global_image[i, j] = 2\n circles, branchs, corner, chain_codes = check(i, j)\n data = []\n corners = corners + corner\n circles = circles/2\n #hapus cabang palsu pada titik awal\n for x in branchs:\n if(x[0] == i and x[1] == j):\n branchs.remove(x)\n data.extend([int(circles), branchs, corners, chain_codes])\n datas.append(data)\n elif(path_count(i, j, global_image) == 0): # jika hanya satu titik\n corners = []\n corners.append([i,j])\n global_image[i, j] = 2\n circles = 0\n branchs = []\n chain_codes = []\n data = []\n data.extend([int(circles),branchs, corners, chain_codes])\n datas.append(data)\n\n #clean tails and empty chaincodes\n if(data[3] != []):\n max_length = len(max(data[3], key=len))\n removed = [item for item in data[3] if(len(item) < ((max_length - 2) * threshold) +2)]\n data[3] = [item for item in data[3] if(len(item) >= ((max_length - 2) * threshold) +2)]\n #menghapus cabang dan titik ujung palsu\n for x in removed:\n if(len(x) > 2):\n a = x[0]\n b = x[-1]\n for y in data[1]:\n if((abs(a[0] - y[0]) <= 1 and abs(a[1] - y[1] <= 1)) or (abs(b[0] - y[0]) <= 1 and abs(b[1] - y[1] <= 1))):\n data[1].remove(y)\n for z in data[2]:\n if(a == z or b == z):\n data[2].remove(z) \n \n\n\n datas.append([h,w])\n return datas\ndef get_feature_from_array(array_feature):\n n_strokes = len(array_feature) - 1\n n_circle = array_feature[0][0]\n n_branch = len(array_feature[0][1])\n n_corner = len(array_feature[0][2])\n n_chaincode = len(array_feature[0][3])\n h,w = array_feature[-1]\n upleft = 0\n upright = 0\n downleft = 0\n downright = 0\n for x in array_feature[0][2]:\n if(x[0] < h/2 and x[1] < w / 2):\n upleft += 1\n if(x[0] < h/2 and x[1] > w / 2):\n upright += 1\n if(x[0] > h/2 and x[1] < w / 2):\n downleft += 1\n if(x[0] > h/2 and x[1] > w / 2):\n downright += 1\n chaincodes = np.zeros(8, dtype = int)\n\n for m in range (n_strokes):\n for x in array_feature[m][3]:\n for n in range(1, len(x) - 1):\n chaincodes[x[n]] += 1 \n corner_pos = [upleft, upright, downleft, downright]\n return [n_strokes,n_circle,n_branch,n_corner,n_chaincode, corner_pos, chaincodes]\n\ndef check(i,j):\n global global_image\n corners = []\n circles = 0\n branchs = []\n chain_codes = []\n chain_code = []\n chain_code.append([i,j])\n branch_path = 0\n #penelusuran selama masih ada jalan\n while (path_count(i,j, global_image) >= 1):\n if(path_count(i,j, global_image) == 1):\n global_image[i,j] = 2\n i, j, code = next_path(i, j, global_image)\n chain_code.append(code)\n else: #bertemu cabang, panggil fungsi secara rekursif\n global_image[i,j] = 3\n list_of_path = path_list(i,j,global_image)\n branch_path = len(list_of_path)\n for x in list_of_path:\n a,b = x\n circle, branch, corner, rec_chain_code = check(a, b)\n circles = circles + circle\n corners = corners + corner\n branchs = branchs + branch\n chain_codes = chain_codes + rec_chain_code\n #penghitungan properti gambar hasil penelurusan\n if (stop_near_branch(i,j,global_image) and passed_neighbor(i,j,global_image)):\n circles += 1\n global_image[i,j] = 2\n #print(\"circles\", i, j)\n elif(global_image[i,j] == 1):\n corners.append([i,j])\n global_image[i,j] = 2\n #print(\"corners\", i, j)\n elif(global_image[i,j] == 3):\n #print(\"branch\", i, j)\n branchs.append([i,j,branch_path])\n chain_code.append([i,j])\n chain_codes.append(chain_code)\n data = []\n data.extend([circles,branchs, corners, chain_codes])\n return data\n\n#menghitung jumlah jalan yang mungkin\ndef path_count(x, y, image):\n neighbor = neighbours(x, y, image)\n before = neighbor[len(neighbor) - 1]\n a = [[x-1,y],[x-1,y+1],[x,y+1],[x+1,y+1],[x+1,y],[x+1,y-1],[x, y-1],[x-1,y-1]]\n path = 0\n for i in range (len(neighbor)):\n if(neighbor[i] == 1 and before == 0):\n if(not(stop_near_branch(x,y, image)) or not(stop_near_branch(a[i][0], a[i][1], image))):\n path += 1\n before = neighbor[i]\n return path\n\n#True jika berada di dekat cabang\ndef stop_near_branch(x, y, image):\n neighbor = neighbours(x, y, image)\n for i in range (len(neighbor)):\n if(neighbor[i] == 3):\n return True\n return False\n#True jika berada di dekat titik yang telah dilewati\ndef passed_neighbor(x, y, image):\n neighbor = neighbours(x, y, image)\n for i in range (len(neighbor)):\n if(neighbor[i] == 2):\n return True\n return False\n#Mengembalikan daftar titik yang bisa dilalui\ndef path_list(x, y, image):\n neighbor = neighbours(x, y, image)\n a = [[x-1,y],[x-1,y+1],[x,y+1],[x+1,y+1],[x+1,y],[x+1,y-1],[x, y-1],[x-1,y-1]]\n path_straight = []\n path_oblique = []\n before = neighbor[len(neighbor) - 1]\n for i in range (len(neighbor)):\n if(neighbor[i] == 1 and before == 0):\n if(i % 2 == 0):\n path_straight.append(a[i])\n else:\n path_oblique.append(a[i])\n before = neighbor[i]\n return path_straight + path_oblique\n\n#Menentukan titik selanjutnya yang akan diambil\ndef next_path(x, y, image):\n neighbor = neighbours(x, y, image)\n index = 0\n a = [[x-1,y],[x-1,y+1],[x,y+1],[x+1,y+1],[x+1,y],[x+1,y-1],[x, y-1],[x-1,y-1]]\n for i in range (len(neighbor)):\n if(neighbor[i] == 1 and i % 2 == 0):\n b = a[i]\n b.append(i)\n return b\n for i in range (len(neighbor)):\n if(neighbor[i] == 1 and i % 2 == 1):\n b = a[i]\n b.append(i)\n return b\n return [-1,-1, -1]","sub_path":"10/thinning.py","file_name":"thinning.py","file_ext":"py","file_size_in_byte":10785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"98102511","text":"\"\"\"\n 日志模块的详细用法:\n\"\"\"\nimport logging\n\n\n# 1. Logger: 产生日志\n# 创建一个logger\nlogger_1 = logging.getLogger(\"test\")\n\n\n# 2. filter ==》 一般不用\n\n# 3. Handler: 接受logger传过来的日志,进行日志格式化,可以打印到终端,也可以打印到文件\n# 可以有多个: 一个打印到文件, 一个打印到终端\n\n# 打印到终端\nsh = logging.StreamHandler()\n# 打印到文件\nfh1 = logging.FileHandler(\"s1.log\", encoding=\"utf-8\")\nfh2 = logging.FileHandler(\"s2.log\", encoding=\"utf-8\")\n\n# 4. Formatter: 日志格式\n# 可以一个 handler 对应一个 formatter\nformatter1 = logging.Formatter(\n fmt=\"%(asctime)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S %p\",\n)\n\nformatter2 = logging.Formatter(\n fmt=\"%(asctime)s - %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S %p\",\n)\n\n\nformatter3 = logging.Formatter(\n fmt=\"%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S %p\",\n)\n\n# 5. 为handler 绑定日志格式\nsh.setFormatter(formatter1)\nfh1.setFormatter(formatter2)\nfh2.setFormatter(formatter3)\n\n# 6. 为logger 绑定handler\nlogger_1.addHandler(sh)\nlogger_1.addHandler(fh1)\nlogger_1.addHandler(fh2)\n\n# 设置日志级别\nlogger_1.setLevel(10) # 这个最先产生, 所以logger的日志级别必须比下面的级别低,下面的设置才有效\nsh.setLevel(20)\nfh1.setLevel(30)\nfh2.setLevel(40)\n\n# 7. 测试\nlogger_1.debug(\"test\")\nlogger_1.info(\"info\")\nlogger_1.warning(\"warning\")\nlogger_1.error(\"error\")\nlogger_1.critical(\"critical\")\n\n","sub_path":"prac/logging_prac/02_详细用法.py","file_name":"02_详细用法.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470985003","text":"import gradio as gr\n\n# Data function\n\n\ndef arithmetic_operation(num1, num2, operation):\n if operation == 'Add':\n result = num1 + num2\n elif operation == 'Subtract':\n result = num1 - num2\n elif operation == 'Multiply':\n result = num1 * num2\n else:\n result = num1 / num2\n return result\n\n\n# User interface\ninput1 = gr.inputs.Number(label=\"Number 1\")\ninput2 = gr.inputs.Number(label=\"Number 2\")\noperation = gr.inputs.Radio(\n ['Add', 'Subtract', 'Multiply', 'Divide'], label=\"Select operation\")\noutput = gr.outputs.Textbox(label=\"Result\")\n\ntitle = \"Arithmetic Operations\"\ndescription = \"Perform arithmetic operations on two numbers\"\nexamples = [[\"5\", \"3\", \"Add\"], [\"10\", \"5\", \"Multiply\"], [\"15\", \"4\", \"Divide\"]]\n\niface = gr.Interface(fn=arithmetic_operation, inputs=[\n input1, input2, operation], outputs=output, title=title, description=description, examples=examples)\n\n# Launch\niface.launch()\n","sub_path":"python3_playground/gradio_hello.py","file_name":"gradio_hello.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442483698","text":"from pathlib import Path\nimport yaml\n\nfrom format_notes import basic_format\n\n\nDATA_PATH = Path(__file__).parent/'tests'\n\n\ndef prepare_input(fn):\n test_note = yaml.safe_load(fn.open())\n\n input_ = ''\n notes = []\n notes_insert_point = []\n idx = -1\n for syl in test_note['input']:\n if isinstance(syl, str):\n syl = syl.replace('_', ' ')\n input_ += syl\n idx += len(syl)\n else:\n notes_insert_point.append(idx)\n notes.append(syl)\n\n return (input_, notes, notes_insert_point), test_note['expected']\n\n\n\ndef test_basic_format():\n test_fns = [DATA_PATH/'formatting-split-word.yaml', DATA_PATH/'basic-formatting-normal.yaml']\n\n for test_fn in test_fns:\n input_, expected = prepare_input(test_fn)\n result = basic_format(*input_)\n\n assert expected['note'] == result[0]\n\n\nif __name__ == \"__main__\":\n test_basic_format()","sub_path":"1-a-reinsert_notes/test_foot_notes.py","file_name":"test_foot_notes.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"507806700","text":"import os\nimport re\nimport functools\nimport datetime\nimport urllib\n\nfrom flask import Flask, redirect, url_for, session, request, flash, render_template\nfrom peewee import CharField, TextField, BooleanField, DateTimeField\nfrom playhouse.flask_utils import FlaskDB, object_list, get_object_or_404\nfrom playhouse.sqlite_ext import FTS5Model, RowIDField, SearchField, SQL\n\nSECRET_KEY = os.getenv('APP_SECRET_KEY')\nADMIN_PASSWORD = os.getenv('APP_ADMIN_PASSWORD')\nAPP_DIR = os.path.dirname(os.path.realpath(__file__))\nDATABASE = 'sqliteext:///%s' % os.path.join(APP_DIR, 'blog.db')\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\nflask_db = FlaskDB(app)\ndatabase = flask_db.database\n\n\nclass BlogEntry(flask_db.Model):\n title = CharField()\n slug = CharField(unique=True)\n content = TextField()\n published = BooleanField(index=True)\n timestamp = DateTimeField(index=True)\n\n def __build_slug(self):\n self.slug = re.sub(r'[^\\w]+', '-', self.title.lower())\n\n def update_search_index(self):\n try:\n idx_entry = EntryIndex.get(EntryIndex.rowid == self.id)\n except EntryIndex.DoesNotExist:\n EntryIndex.create(rowid=self.id, title=self.title,\n content=self.content)\n else:\n idx_entry.content = self.content\n idx_entry.title = self.title\n idx_entry.save()\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.__build_slug()\n if not self.timestamp:\n self.timestamp = datetime.datetime.utcnow()\n result = super(BlogEntry, self).save(*args, **kwargs)\n self.update_search_index()\n return result\n\n @classmethod\n def public(cls):\n return BlogEntry.select().where(BlogEntry.published == True)\n\n @classmethod\n def search(cls, query):\n words = [word.strip() for word in query.split() if word.strip()]\n if not words:\n return BlogEntry.select().where(BlogEntry.id == 0)\n else:\n search = ' '.join(words)\n return (BlogEntry\n .select(BlogEntry, EntryIndex.rank().alias('score'))\n .join(EntryIndex, on=(BlogEntry.id == EntryIndex.rowid))\n .where((BlogEntry.published == True) & (EntryIndex.match(search)))\n .order_by(SQL('score')))\n\n @classmethod\n def drafts(cls):\n return BlogEntry.select().where(BlogEntry.published == False)\n\n\nclass EntryIndex(FTS5Model):\n\n class Meta:\n database = database\n\n rowid = RowIDField()\n title = SearchField()\n content = SearchField()\n\n\ndef login_required(func):\n @functools.wraps(func)\n def inner(*args, **kwargs):\n if session.get('logged_in'):\n return func(*args, **kwargs)\n return redirect(url_for('login', next=request.path))\n return inner\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n next_url = request.args.get('next') or request.form.get('next')\n if request.method == 'POST' and request.form.get('password'):\n password = request.form.get('password')\n if password == app.config['ADMIN_PASSWORD']:\n session['logged_in'] = True\n session.permament = True\n flash('You are logged in !', 'success')\n return redirect(next_url or url_for('index'))\n else:\n flash('Incorrect password', 'danger')\n return render_template('login.html', next_url=next_url)\n\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef logout():\n if request.method == 'POST':\n session.clear()\n return redirect(url_for('login'))\n return render_template('logout.html')\n\n\n@app.route('/')\ndef index():\n search_query = request.args.get('q')\n if search_query:\n query = BlogEntry.search(search_query)\n else:\n query = BlogEntry.public().order_by(BlogEntry.timestamp.desc())\n return object_list('index.html', query, search=search_query, check_bounds=False)\n\n\n@app.route('/drafts')\n@login_required\ndef drafts():\n query = BlogEntry.drafts().order_by(BlogEntry.timestamp.desc())\n return object_list('index.html', query, check_bounds=False)\n\n\n@app.route('//')\ndef detail(slug):\n if session.get('logged_in'):\n query = BlogEntry.select()\n else:\n query = BlogEntry.public()\n entry = get_object_or_404(query, BlogEntry.slug == slug)\n return render_template('detail.html', entry=entry)\n\n\n@app.route('/create', methods=['GET', 'POST'])\n@login_required\ndef create():\n if request.method == 'POST':\n if request.form.get('title') and request.form.get('content'):\n entry = BlogEntry.create(\n title=request.form['title'],\n content=request.form['content'],\n published=request.form.get('published') or False\n )\n flash('Entry created successfully.', 'success')\n if entry.published:\n return redirect(url_for('detail', slug=entry.slug))\n else:\n return redirect(url_for('edit', slug=entry.slug))\n else:\n flash('Title and content are required', 'danger')\n return render_template('create.html', entry=BlogEntry(title='', content=''))\n\n\n@app.route('//edit', methods=['GET', 'POST'])\n@login_required\ndef edit(slug):\n entry = get_object_or_404(BlogEntry, BlogEntry.slug == slug)\n if request.method == 'POST':\n if request.form.get('title') and request.form.get('content'):\n entry.title = request.form['title']\n entry.content = request.form['content']\n entry.published = request.form.get('published') or False\n entry.save()\n flash('Entry saved successfully', 'success')\n if entry.published:\n return redirect(url_for('detail', slug=entry.slug))\n else:\n return redirect(url_for('edit', slug=entry.slug))\n else:\n flash('Title and content are required', 'danger')\n return render_template('edit.html', entry=entry)\n\n\n@app.template_filter('clean_querystring')\ndef clean_querystring(request_args, *keys_to_remove, **new_values):\n querystring = dict((key, value) for key, value in request_args.items())\n for key in keys_to_remove:\n querystring.pop(key, None)\n querystring.update(new_values)\n return urllib.parse.urlencode(querystring)\n\n\nif __name__ == '__main__':\n database.create_tables([BlogEntry, EntryIndex])\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327617723","text":"import os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom PIL import Image\nimport numpy as np\n\nfrom Component import Generator\nfrom Component import Discriminator\nfrom Component import one_hot\nfrom Component import weights_init_normal\nfrom Component import Tensor2Image\nfrom base_model import BaseModel\n\nclass Single_DRGAN(BaseModel):\n \"\"\"\n The model of Single_DRGAN according to the options.\n \"\"\"\n\n def name(self):\n return 'Single_DRGAN'\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n self.is_Train = opt.is_Train\n\n self.G = Generator(N_p=opt.N_p, N_z=opt.N_z)\n self.D = Discriminator(N_p=opt.N_p, N_d=opt.N_d)\n if self.is_Train:\n self.optimizer_G = optim.Adam(self.G.parameters(), lr=opt.lr_G, betas=(opt.beta1, opt.beta2))\n self.optimizer_D = optim.Adam(self.D.parameters(), lr=opt.lr_D, betas=(opt.beta1, opt.beta2))\n self.criterion = nn.CrossEntropyLoss()\n self.L1_criterion = nn.L1Loss()\n self.w_L1 = opt.w_L1\n\n self.N_z = opt.N_z\n self.N_p = opt.N_p\n self.N_d = opt.N_d\n\n def init_weights(self):\n self.G.apply(weights_init_normal)\n self.D.apply(weights_init_normal)\n\n def set_input(self, input, test_pose=None):\n \"\"\"\n the structure of the input.\n {\n 'image':Bx3x96x96 FloatTensor\n 'pose':Bx1 FloatTensor\n 'identity':Bx1 FloatTensor\n }\n\n test_pose (B): used for the test='initial learning rate\n \"\"\"\n self.image = input['image']\n self.batchsize = len(self.image)\n self.pose = input['pose'].long() #convert to LongTensor\n\n if self.is_Train:\n self.input_pose = one_hot(self.pose, self.N_p)\n else:\n self.input_pose = one_hot(test_pose.long(), self.N_p)\n\n self.identity = input['identity'].long() #convert to LongTensor\n self.name = input['name']\n self.fake_identity = torch.zeros(self.batchsize).long() # 0 indicates fake\n self.noise = torch.FloatTensor(np.random.normal(loc=0.0, scale=0.3, size=(self.batchsize, self.N_z)))\n\n #cuda\n if self.opt.gpu_ids:\n self.image = self.image.cuda()\n self.pose = self.pose.cuda()\n self.input_pose = self.input_pose.cuda()\n self.identity = self.identity.cuda()\n self.fake_identity = self.fake_identity.cuda()\n self.noise = self.noise.cuda()\n\n self.image = Variable(self.image)\n self.pose = Variable(self.pose)\n self.input_pose = Variable(self.input_pose)\n self.identity = Variable(self.identity)\n self.fake_identity = Variable(self.fake_identity)\n self.noise = Variable(self.noise)\n\n def forward(self, input, test_pose=None):\n self.set_input(input, test_pose)\n\n self.syn_image = self.G(self.image, self.input_pose, self.noise)\n self.syn = self.D(self.syn_image)\n self.syn_identity = self.syn[:, :self.N_d+1]\n self.syn_pose = self.syn[:, self.N_d+1:]\n\n self.real = self.D(self.image)\n self.real_identity = self.real[:, :self.N_d+1]\n self.real_pose = self.real[:, self.N_d+1:]\n\n def backward_G(self):\n self.Loss_G_syn_identity = self.criterion(self.syn_identity, self.identity)\n self.Loss_G_syn_pose = self.criterion(self.syn_pose, self.pose)\n self.L1_Loss = self.L1_criterion(self.syn_image, self.image)\n\n self.Loss_G = self.Loss_G_syn_identity + self.Loss_G_syn_pose + self.w_L1 * self.L1_Loss\n self.Loss_G.backward(retain_graph=True)\n\n def backward_D(self):\n self.Loss_D_real_identity = self.criterion(self.real_identity, self.identity)\n self.Loss_D_real_pose = self.criterion(self.real_pose, self.pose)\n\n self.Loss_D_syn = self.criterion(self.syn_identity, self.fake_identity)\n\n self.Loss_D = self.Loss_D_real_identity + self.Loss_D_real_pose + self.Loss_D_syn\n self.Loss_D.backward()\n\n def optimize_G_parameters(self):\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n\n def optimize_D_parameters(self):\n self.optimizer_D.zero_grad()\n self.backward_D()\n self.optimizer_D.step()\n\n def print_current_errors(self):\n print('Loss_G: {0} \\t Loss_D: {1}'.format(self.Loss_G.data[0], self.Loss_D.data[0]))\n\n def save(self, epoch):\n self.save_network(self.G, 'G', epoch, self.gpu_ids)\n self.save_network(self.D, 'D', epoch, self.gpu_ids)\n\n def save_result(self, epoch=None):\n for i, syn_img in enumerate(self.syn_image.data):\n img = self.image.data[i]\n filename = self.name[i]\n\n if epoch:\n filename = 'epoch{0}_{1}'.format(epoch, filename)\n\n path = os.path.join(self.result_dir, filename)\n img = Tensor2Image(img)\n syn_img = Tensor2Image(syn_img)\n\n width, height = img.size\n result_img = Image.new(img.mode, (width*2, height))\n result_img.paste(img)\n result_img.paste(syn_img, box=(width, 0))\n result_img.save(path)\n\nclass Multi_DRGAN(Single_DRGAN):\n \"\"\"\n The model of Multi_DRGAN according to the options.\n \"\"\"\n def name(self):\n return 'Multi_DRGAN'\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n self.is_Train = opt.is_Train\n\n self.G = Generator(N_p=opt.N_p, N_z=opt.N_z, single=False)\n self.D = Discriminator(N_p=opt.N_p, N_d=opt.N_d)\n if self.is_Train:\n self.optimizer_G = optim.Adam(self.G.parameters(), lr=opt.lr_G, betas=(opt.beta1, opt.beta2))\n self.optimizer_D = optim.Adam(self.D.parameters(), lr=opt.lr_D, betas=(opt.beta1, opt.beta2))\n self.criterion = nn.CrossEntropyLoss()\n self.L1_criterion = nn.L1Loss()\n self.w_L1 = opt.w_L1\n\n self.N_z = opt.N_z\n self.N_p = opt.N_p\n self.N_d = opt.N_d\n","sub_path":"Frontal_ReID/model/DRGAN.py","file_name":"DRGAN.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596837549","text":"#Import packages for data analysis\nfrom lib_compute_resilience_and_risk import *\nfrom replace_with_warning import *\nfrom lib_country_dir import *\nfrom lib_gather_data import *\nfrom maps_lib import *\n\nfrom scipy.stats import norm\nimport matplotlib.mlab as mlab\n\nfrom pandas import isnull\nimport pandas as pd\nimport numpy as np\nimport os, time\nimport sys\n\n#Aesthetics\nimport seaborn as sns\nimport brewer2mpl as brew\nfrom matplotlib import colors\nsns.set_style('darkgrid')\nbrew_pal = brew.get_map('Set1', 'qualitative', 8).mpl_colors\nsns_pal = sns.color_palette('Set1', n_colors=8, desat=.4)\ngreys_pal = sns.color_palette('Greys', n_colors=9)\nq_labels = ['Q1 (Poorest)','Q2','Q3','Q4','Q5 (Wealthiest)']\nq_colors = [sns_pal[0],sns_pal[1],sns_pal[2],sns_pal[3],sns_pal[5]]\n\nfont = {'family' : 'sans serif',\n 'size' : 20}\nplt.rc('font', **font)\nmpl.rcParams['xtick.labelsize'] = 16\n\nimport warnings\nwarnings.filterwarnings('always',category=UserWarning)\n\nmyCountry = 'PH'\nif len(sys.argv) >= 2: myCountry = sys.argv[1]\nprint('Running '+myCountry)\n\nmodel = os.getcwd() #get current directory\noutput = model+'/../output_country/'+myCountry+'/'\noutput_plots = model+'/../output_plots/'+myCountry+'/'\n\neconomy = get_economic_unit(myCountry)\nevent_level = [economy, 'hazard', 'rp']\ndem = get_demonym(myCountry)\n\n# Set policy params\nbase_str = 'no'\npds_str = 'unif_poor'\npds2_str = 'no'\nif myCountry == 'FJ':\n pds_str = 'fiji_SPS'\n pds2_str = 'fiji_SPP'\n\ndrm_pov_sign = -1 # toggle subtraction or addition of dK to affected people's incomes\nall_policies = []#['_exp095','_exr095','_ew100','_vul070','_vul070r','_rec067']\n\n# Load base and PDS files\niah_base = pd.read_csv(output+'iah_tax_'+base_str+'_.csv', index_col=[economy,'hazard','rp','hhid'])\niah = pd.read_csv(output+'iah_tax_'+pds_str+'_.csv', index_col=[economy,'hazard','rp','hhid'])\ndf = pd.read_csv(output+'results_tax_'+pds_str+'_.csv', index_col=[economy,'hazard','rp'])\ndf_base = pd.read_csv(output+'results_tax_'+base_str+'_.csv', index_col=[economy,'hazard','rp'])\nmacro = pd.read_csv(output+'macro_tax_'+pds_str+'_.csv', index_col=[economy,'hazard','rp'])\npublic_costs = pd.read_csv(output+'shared_costs_tax_'+base_str+'_.csv', index_col=[economy,'hazard','rp']).reset_index()\n\niah_noPT = pd.read_csv(output+'iah_tax_'+base_str+'__noPT.csv', index_col=[economy,'hazard','rp','hhid'])\n# ^ Scenario: no public transfers to rebuild infrastructure\n\niah_SP2, df_SP2 = None,None\ntry:\n iah_SP2 = pd.read_csv(output+'iah_tax_'+pds2_str+'_.csv', index_col=[economy,'hazard','rp','hhid'])\n df_SP2 = pd.read_csv(output+'results_tax_'+pds2_str+'_.csv', index_col=[economy,'hazard','rp'])\n print('loaded 2 extra files (secondary SP system for '+myCountry+')')\nexcept: pass\n\nfor iPol in all_policies:\n iah_pol = pd.read_csv(output+'iah_tax_'+pds_str+'_'+iPol+'.csv', index_col=[economy,'hazard','rp','hhid'])\n df_pol = pd.read_csv(output+'results_tax_'+pds_str+'_'+iPol+'.csv', index_col=[economy,'hazard','rp'])\n\n iah['dk'+iPol] = iah_pol[['dk','pcwgt']].prod(axis=1)\n iah['dw'+iPol] = iah_pol[['dw','pcwgt']].prod(axis=1)/df_pol.wprime.mean()\n\n print(iPol,'added to iah (these policies are run *with* PDS)')\n\n del iah_pol\n del df_pol\n\n# SAVE OUT SOME RESULTS FILES\ndf_prov = df[['dKtot','dWtot_currency']].copy()\ndf_prov['gdp'] = df[['pop','gdp_pc_pp_prov']].prod(axis=1)\nresults_df = macro.reset_index().set_index([economy,'hazard'])\nresults_df = results_df.loc[results_df.rp==100,'dk_event'].sum(level='hazard')\nresults_df = results_df.rename(columns={'dk_event':'dk_event_100'})\nresults_df = pd.concat([results_df,df_prov.reset_index().set_index([economy,'hazard']).sum(level='hazard')['dKtot']],axis=1,join='inner')\nresults_df.columns = ['dk_event_100','AAL']\nresults_df.to_csv(output+'results_table_new.csv')\nprint('Writing '+output+'results_table_new.csv')\n\n# Manipulate iah\niah['c_initial'] = (iah[['c','hhsize']].prod(axis=1)/iah['hhsize_ae']).fillna(0)# c per AE\niah['delta_c'] = (df['avg_prod_k'].mean()+1/df['T_rebuild_K'].mean())*(iah[['dk','pcwgt']].prod(axis=1)/iah['pcwgt_ae']).fillna(0)\niah['pds_nrh'] = iah['help_fee']-iah['help_received']\niah['c_final'] = (iah['c_initial'] + drm_pov_sign*iah['delta_c'])\niah['c_final_pds'] = (iah['c_initial'] - iah['delta_c'] - iah['pds_nrh'])\n\n# Clone index of iah with just one entry/hhid\niah_res = pd.DataFrame(index=(iah.sum(level=[economy,'hazard','rp','hhid'])).index)\n# Clone index of iah at national level\niah_ntl = pd.DataFrame(index=(iah_res.sum(level=['hazard','rp'])).index)\n\n## Translate from iah by suming over hh categories [(a,na)x(helped,not_helped)]\n# These are special--pcwgt has been distributed among [(a,na)x(helped,not_helped)] categories\niah_res['pcwgt'] = iah['pcwgt'].sum(level=[economy,'hazard','rp','hhid'])\niah_res['pcwgt_ae'] = iah['pcwgt_ae'].sum(level=[economy,'hazard','rp','hhid'])\niah_res['hhwgt'] = iah['hhwgt'].sum(level=[economy,'hazard','rp','hhid'])\n\n#These are the same across [(a,na)x(helped,not_helped)] categories \niah_res['pcinc'] = iah['pcinc'].mean(level=[economy,'hazard','rp','hhid'])\niah_res['pcinc_ae'] = iah['pcinc_ae'].mean(level=[economy,'hazard','rp','hhid'])\niah_res['hhsize_ae'] = iah['hhsize_ae'].mean(level=[economy,'hazard','rp','hhid'])\niah_res['quintile'] = iah['quintile'].mean(level=[economy,'hazard','rp','hhid'])\niah_res['pov_line'] = iah['pov_line'].mean(level=[economy,'hazard','rp','hhid'])\nif get_subsistence_line(myCountry) != None: iah_res['sub_line'] = get_subsistence_line(myCountry)\n\n# These need to be averaged across [(a,na)x(helped,not_helped)] categories (weighted by pcwgt)\n# ^ values still reported per capita\niah_res['pcinc'] = iah[['pcinc','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['k'] = iah[['k','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['dk'] = iah[['dk','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['dc'] = iah[['dc','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['help_received'] = iah[['help_received','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['help_fee'] = iah[['help_fee','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['dc_npv_pre'] = iah[['dc_npv_pre','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\niah_res['dc_npv_post'] = iah[['dc_npv_post','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\n\n# These are the other policies (scorecard)\n# ^ already weighted by pcwgt from their respective files\nfor iPol in all_policies:\n print('dk'+iPol)\n iah_res['dk'+iPol] = iah['dk'+iPol].sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\n iah_res['dw'+iPol] = iah['dw'+iPol].sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\n\n# Note that we're pulling dw in from iah_base here\niah_res['dw'] = (iah_base[['dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt'])/df.wprime.mean()\niah_res['pds_dw'] = ( iah[['dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt'])/df.wprime.mean()\ntry: iah_res['pds_plus_dw'] = ( iah_SP2[['dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt'])/df_SP2.wprime.mean()\nexcept: pass\n\niah_res['c_initial'] = iah[['c_initial' ,'pcwgt_ae']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt_ae'] # c per AE\niah_res['delta_c'] = iah[['delta_c' ,'pcwgt_ae']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt_ae'] # dc per AE\niah_res['pds_nrh'] = iah[['pds_nrh' ,'pcwgt_ae']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt_ae'] # nrh per AE\niah_res['c_final'] = iah[['c_final' ,'pcwgt_ae']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt_ae'] # c per AE\niah_res['c_final_pds'] = iah[['c_final_pds','pcwgt_ae']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt_ae'] # c per AE\n\ntry:\n iah_res['dc_noPT_npv_pre'] = iah_noPT[['dc_npv_pre','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\n iah_res['dw_noPT'] = iah_noPT[['dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp','hhid'])/iah_res['pcwgt']\n \n iah_res['dc_delta'] = iah_res['dc_noPT_npv_pre'] - iah_res['dc_npv_pre']\n iah_res['dw_delta'] = iah_res['dw_noPT'] - iah_res['dw']\n\n iah_res = iah_res.reset_index()\n grab = [['TC'],[1,100,1000]]\n for aHaz in grab[0]:\n for anRP in grab[1]:\n \n ax = iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)].plot.scatter('dc_npv_pre','dc_noPT_npv_pre',c='quintile') \n ax.plot()\n fig = plt.gcf()\n fig.savefig(output_plots+'experiments/infra_dc_npv_pre.pdf',format='pdf')\n print('infra plot 1/2')\n plt.clf()\n\n ax = None\n for iq in range(1,6):\n if iq==1: \n ax = iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq)].plot.scatter('dc_npv_pre','dc_delta',color=q_colors[iq-1],label='Q'+str(iq),alpha=0.4)\n ax.annotate(r'Init.',xy=(0.18,0.95),xycoords='axes fraction',size=6,va='top',ha='left',annotation_clip=False,zorder=100,weight='bold')\n ax.annotate(r'$\\Delta$ ',xy=(0.24,0.95),xycoords='axes fraction',size=6,va='top',ha='left',annotation_clip=False,zorder=100,weight='bold')\n ax.annotate(r'$\\Delta(>)$ ',xy=(0.30,0.95),xycoords='axes fraction',size=6,va='top',ha='left',annotation_clip=False,zorder=100,weight='bold')\n ax.annotate(r'$\\Delta(<)$ ',xy=(0.36,0.95),xycoords='axes fraction',size=6,va='top',ha='left',annotation_clip=False,zorder=100,weight='bold')\n\n else: iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq)].plot.scatter('dc_npv_pre','dc_delta', color=q_colors[iq-1],label='Q'+str(iq),ax=ax,alpha=0.4)\n \n mean_x = str(round(float(iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq),['pcwgt','dc_npv_pre']].prod(axis=1).sum()/\n iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq),['pcwgt']].sum()),1))\n mean_y = str(round(float(iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq),['pcwgt','dc_delta']].prod(axis=1).sum()/\n iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq),['pcwgt']].sum()),1))\n\n mean_y_pos = str(round(float(iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq)&(iah_res.dc_delta>0),['pcwgt','dc_delta']].prod(axis=1).sum()/\n iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq)&(iah_res.dc_delta>0),['pcwgt']].sum()),1))\n mean_y_neg = str(round(float(iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq)&(iah_res.dc_delta<0),['pcwgt','dc_delta']].prod(axis=1).sum()/\n iah_res.loc[(iah_res.Division=='Ba')&(iah_res.hazard==aHaz)&(iah_res.rp==anRP)&(iah_res.quintile==iq)&(iah_res.dc_delta<0),['pcwgt']].sum()),1))\n \n anno_str = 'Q'+str(iq)+' dc = '+mean_x+' - '+mean_y[1:]+' (+'+mean_y_pos+' & '+mean_y_neg+')'\n ax.annotate(anno_str,xy=(0.10,0.95-0.05*iq),xycoords='axes fraction',size=8,va='top',ha='left',annotation_clip=False,zorder=100)\n \n ax.plot()\n plt.xlim(0,6000)\n plt.ylim(-5000,5000)\n fig = plt.gcf()\n fig.savefig(output_plots+'experiments/infra_dc_npv_pre_delta_Ba'+aHaz+str(anRP)+'.pdf',format='pdf')\n print('infra plot 2/2')\n plt.clf()\n plt.close('all')\n\n iah_res = iah_res.reset_index().set_index(event_level+['hhid']).drop(['index'],axis=1)\nexcept: \n print('DID NOT plot effects of public transfers to rebuild infra b/c unexpected error:', sys.exc_info()[0])\n raise\n\n# Huge file\ndel iah_base\n# Calc people who fell into povery on the regional level for each disaster\n#iah_res.loc[(iah_res.pcinc_ae > iah_res.pov_line)&(iah_res.c_final < iah_res.pov_line),'pcwgt'].sum(level=[economy,'hazard','rp'])\n\niah = iah.reset_index()\niah_res = iah_res.reset_index().set_index([economy,'hazard','rp','hhid'])\n\n# Save out iah by economic unit\niah_out = pd.DataFrame(index=iah_res.sum(level=[economy,'hazard','rp']).index)\nfor iPol in ['']+all_policies:\n iah_out['Asset risk'+iPol] = iah_res[['dk'+iPol,'pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n iah_out['Well-being risk'+iPol] = iah_res[['dw'+iPol,'pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n\n# Add public well-being costs to this output\npublic_costs_prov_sum = (public_costs.loc[(public_costs.contributer != public_costs[economy])]).reset_index().set_index(event_level).sum(level=event_level)\niah_out['Well-being risk'] += public_costs_prov_sum['dw']\n\n#iah_out['pds_dw'] = iah_res[['pds_dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n#iah_out['help_fee'] = iah_res[['help_fee','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n#iah_out['pds_plus_dw'] = iah_res[['pds_plus_dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\niah_out['SE capacity'] = iah_out['Asset risk']/iah_out['Well-being risk']\n\niah_out.to_csv(output+'geo_sums.csv')\nprint(iah_out.head(10))\niah_out,_ = average_over_rp(iah_out,'default_rp')\niah_out['SE capacity'] = iah_out['Asset risk']/iah_out['Well-being risk']\niah_out.to_csv(output+'geo_haz_aal_sums.csv')\n\niah_out = iah_out.sum(level=economy)\niah_out['SE capacity'] = iah_out['Asset risk']/iah_out['Well-being risk']\niah_out.to_csv(output+'geo_aal_sums.csv')\niah_out[['Asset risk','Well-being risk']]/=1.E6\niah_out[['SE capacity']]*=100.\niah_out[['Asset risk','SE capacity','Well-being risk']].sort_values(['Well-being risk'],ascending=False).astype(int).to_latex(output+'geo_aal_sums.tex')\nprint('Wrote latex! Sums:\\n',iah_out[['Asset risk','Well-being risk']].sum())\nassert(False)\n\n# Save out iah by economic unit, *only for poorest quintile*\niah_out = pd.DataFrame(index=iah_res.sum(level=[economy,'hazard','rp']).index)\nfor iPol in ['']+all_policies:\n iah_out['Asset risk'+iPol] = iah_res.loc[(iah_res.quintile==1),['dk'+iPol,'pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n iah_out['Well-being risk'+iPol] = iah_res.loc[(iah_res.quintile==1),['dw'+iPol,'pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n#iah_out['pds_dw'] = iah_res.loc[(iah_res.quintile==1),['pds_dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n#iah_out['help_fee'] = iah_res.loc[(iah_res.quintile==1),['help_fee','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\n#iah_out['pds_plus_dw'] = iah_res.loc[(iah_res.quintile==1),['pds_plus_dw','pcwgt']].prod(axis=1).sum(level=[economy,'hazard','rp'])\niah_out['SE capacity'] = iah_out['Asset risk']/iah_out['Well-being risk']\n\niah_out.to_csv(output+'geo_sums_q1.csv')\niah_out,_ = average_over_rp(iah_out,'default_rp')\niah_out['SE capacity'] = iah_out['Asset risk']/iah_out['Well-being risk']\niah_out.to_csv(output+'geo_haz_aal_sums_q1.csv')\n\niah_out = iah_out.sum(level=economy)\niah_out['SE capacity'] = iah_out['Asset risk']/iah_out['Well-being risk']\niah_out.to_csv(output+'geo_aal_sums_q1.csv')\niah_out[['Asset risk','Well-being risk']]/=1.E6\niah_out[['SE capacity']]*=100.\niah_out[['Asset risk','SE capacity','Well-being risk']].sort_values(['Well-being risk'],ascending=False).astype(int).to_latex(output+'geo_aal_sums_q1.tex',bold_rows=True)\nprint('Wrote latex! Q1 sums: ',iah_out.sum())\n\n# Save out iah\niah_out = pd.DataFrame(index=iah_res.sum(level=['hazard','rp']).index)\nfor iPol in ['']+all_policies:\n iah_out['dk'+iPol] = iah_res[['dk'+iPol,'pcwgt']].prod(axis=1).sum(level=['hazard','rp'])\n iah_out['dw'+iPol] = iah_res[['dw'+iPol,'pcwgt']].prod(axis=1).sum(level=['hazard','rp'])\niah_out['pds_dw'] = iah_res[['pds_dw','pcwgt']].prod(axis=1).sum(level=['hazard','rp'])\niah_out['help_fee'] = iah_res[['help_fee','pcwgt']].prod(axis=1).sum(level=['hazard','rp'])\ntry: iah_out['pds_plus_dw'] = iah_res[['pds_plus_dw','pcwgt']].prod(axis=1).sum(level=['hazard','rp'])\nexcept: pass\n\niah_out.to_csv(output+'haz_sums.csv')\nprint(iah_out.head(10))\niah_out,_ = average_over_rp(iah_out,'default_rp')\niah_out.to_csv(output+'sums.csv')\n\niah_ntl['pop'] = iah_res.pcwgt.sum(level=['hazard','rp'])\niah_ntl['pov_pc_i'] = iah_res.loc[(iah_res.pcinc_ae <= iah_res.pov_line),'pcwgt'].sum(level=['hazard','rp'])\niah_ntl['pov_hh_i'] = iah_res.loc[(iah_res.pcinc_ae <= iah_res.pov_line),'hhwgt'].sum(level=['hazard','rp'])\niah_ntl['pov_pc_f'] = iah_res.loc[(iah_res.c_final < iah_res.pov_line),'pcwgt'].sum(level=['hazard','rp'])\niah_ntl['pov_hh_f'] = iah_res.loc[(iah_res.c_final < iah_res.pov_line),'hhwgt'].sum(level=['hazard','rp'])\niah_ntl['pov_pc_D'] = iah_ntl['pov_pc_f'] - iah_ntl['pov_pc_i']\niah_ntl['pov_hh_D'] = iah_ntl['pov_hh_f'] - iah_ntl['pov_hh_i']\niah_ntl['pov_pc_pds_f'] = iah_res.loc[(iah_res.c_final_pds < iah_res.pov_line),'pcwgt'].sum(level=['hazard','rp'])\niah_ntl['pov_hh_pds_f'] = iah_res.loc[(iah_res.c_final_pds < iah_res.pov_line),'hhwgt'].sum(level=['hazard','rp'])\niah_ntl['pov_pc_pds_D'] = iah_ntl['pov_pc_pds_f'] - iah_ntl['pov_pc_i']\niah_ntl['pov_hh_pds_D'] = iah_ntl['pov_hh_pds_f'] - iah_ntl['pov_hh_i']\nprint('Initial poverty incidence:',iah_ntl[['pov_pc_i','pov_hh_i']].mean())\n\niah_ntl['eff_pds'] = iah_ntl['pov_pc_pds_D'] - iah_ntl['pov_pc_D']\n\n# Print out plots for iah_res\niah_res = iah_res.reset_index()\niah_ntl = iah_ntl.reset_index()\n\nmyHaz = None\nif myCountry == 'FJ': myHaz = [['Ba','Lau','Tailevu'],get_all_hazards(myCountry,iah_res),[1,10,100,500,1000]]\nelif myCountry == 'PH': myHaz = [['NCR'],get_all_hazards(myCountry,iah_res),get_all_rps(myCountry,iah_res)]\n\n##################################################################\n# This code generates the histograms showing income before & after disaster\n# ^ this is nationally, so we'll use iah_res \nupper_clip = 2E5\nscale_fac = 1.0\nif myCountry == 'FJ': \n scale_fac = 2.321208\n upper_clip = 2E4\n\nfor aReg in myHaz[0]:\n for aDis in get_all_hazards(myCountry,iah_res):\n \n myC_ylim = None\n c_bins = [None,50]\n for anRP in myHaz[2][::-1]: \n\n ax=plt.gca()\n\n cf_heights, cf_bins = np.histogram((iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),'c_final']/scale_fac).clip(upper=upper_clip), bins=c_bins[1], \n weights=iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),'pcwgt']/get_pop_scale_fac(myCountry)[0])\n if c_bins[0] == None: c_bins = [cf_bins,cf_bins]\n ci_heights, ci_bins = np.histogram((iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),'c_initial']/scale_fac).clip(upper=upper_clip), bins=c_bins[1], \n weights=iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),'pcwgt']/get_pop_scale_fac(myCountry)[0])\n \n ax.bar(c_bins[1][:-1], ci_heights, width=(c_bins[1][1]-c_bins[1][0]), label=aReg+' - Initial', facecolor=q_colors[1],alpha=0.4)\n ax.bar(c_bins[1][:-1], cf_heights, width=(c_bins[1][1]-c_bins[1][0]), label=aReg+' - Post-disaster', facecolor=q_colors[0],alpha=0.4)\n \n if myC_ylim == None: myC_ylim = ax.get_ylim()\n plt.ylim(myC_ylim[0],1.4*myC_ylim[1])\n\n mny = get_currency(myCountry)\n\n plt.xlim(0,upper_clip)\n plt.xlabel(r'Income ('+mny[0]+' yr$^{-1}$)')\n plt.ylabel('Population'+get_pop_scale_fac(myCountry)[1])\n plt.title(str(anRP)+'-year '+aDis+' event in '+aReg)\n leg = ax.legend(loc='best',labelspacing=0.75,ncol=1,fontsize=9,borderpad=0.75,fancybox=True,frameon=True,framealpha=0.9)\n leg.get_frame().set_color('white')\n leg.get_frame().set_edgecolor(greys_pal[7])\n leg.get_frame().set_linewidth(0.2)\n\n ax.annotate('Total asset losses: '+str(round(iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),['pcwgt','dk']].prod(axis=1).sum()/mny[1],1))+mny[0],\n xy=(0.03,-0.18), xycoords=leg.get_frame(),size=7,va='top',ha='left',annotation_clip=False,zorder=100)\n ax.annotate('Int. well-being losses: '+str(round(iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),['pcwgt','dw']].prod(axis=1).sum()/mny[1],1))+mny[0],\n xy=(0.03,-0.50), xycoords=leg.get_frame(),size=7,va='top',ha='left',annotation_clip=False,zorder=100)\n ax.annotate('Natl. liability: '+str(round(float(public_costs.loc[(public_costs.contributer!=aReg)&(public_costs[economy]==aReg)&(public_costs.hazard==aDis)&(public_costs.rp==anRP),['transfer_k']].sum()/mny[1]),1))+mny[0],\n xy=(0.03,-0.92), xycoords=leg.get_frame(),size=7,va='top',ha='left',annotation_clip=False,zorder=100)\n ax.annotate('Natl. well-being losses: '+str(round(float(public_costs.loc[(public_costs.contributer!=aReg)&(public_costs[economy]==aReg)&(public_costs.hazard==aDis)&(public_costs.rp==anRP),['dw']].sum()/mny[1]),1))+mny[0],\n xy=(0.03,-1.24), xycoords=leg.get_frame(),size=7,va='top',ha='left',annotation_clip=False,zorder=100)\n\n new_pov = int(iah_res.loc[((iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)\n &(iah_res.pcinc_ae > iah_res.pov_line)&(iah_res.c_final < iah_res.pov_line)),'pcwgt'].sum())\n new_pov_pct = round(100.*float(new_pov)/float(iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),'pcwgt'].sum()),1)\n plt.plot([iah_res.pov_line.mean()/scale_fac,iah_res.pov_line.mean()/scale_fac],[0,1.21*cf_heights[:-2].max()],'k-',lw=2.5,color=greys_pal[7],zorder=100,alpha=0.85)\n ax.annotate('Poverty line',xy=(1.1*iah_res.pov_line.mean()/scale_fac,1.21*cf_heights[:-2].max()),xycoords='data',ha='left',va='top',fontsize=8,annotation_clip=False,weight='bold')\n ax.annotate(r'$\\Delta$N$_p$ = +'+int_w_commas(new_pov)+' ('+str(new_pov_pct)+'% of population)',\n xy=(1.1*iah_res.pov_line.mean()/scale_fac,1.14*cf_heights[:-2].max()),xycoords='data',ha='left',va='top',fontsize=8,annotation_clip=False)\n\n sub_line, new_sub = get_subsistence_line(myCountry), None\n if sub_line is not None:\n new_sub = int(iah_res.loc[((iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)\n &(iah_res.pcinc_ae > sub_line)&(iah_res.c_final < sub_line)),'pcwgt'].sum())\n new_sub_pct = round(100.*float(new_sub)/float(iah_res.loc[(iah_res[economy]==aReg)&(iah_res.hazard==aDis)&(iah_res.rp==anRP),'pcwgt'].sum()),1)\n plt.plot([sub_line,sub_line],[0,1.41*cf_heights[:-2].max()],'k-',lw=2.5,color=greys_pal[7],zorder=100,alpha=0.85)\n ax.annotate('Subsistence line',xy=(1.1*sub_line,1.41*cf_heights[:-2].max()),xycoords='data',ha='left',va='top',fontsize=9,annotation_clip=False,weight='bold')\n ax.annotate(r'$\\Delta$N$_s$ = +'+int_w_commas(new_sub)+' ('+str(new_sub_pct)+'% of population)',\n xy=(1.1*sub_line,1.34*cf_heights[:-2].max()),xycoords='data',ha='left',va='top',fontsize=8,annotation_clip=False)\n\n print(aReg,aDis,anRP,new_pov,'people into poverty &',new_sub,'into subsistence') \n\n fig = ax.get_figure()\n fig.savefig(output_plots+'npr_poverty_k_'+aReg+'_'+aDis+'_'+str(anRP)+'.pdf',format='pdf')\n fig.savefig(output_plots+'png/npr_poverty_k_'+aReg+'_'+aDis+'_'+str(anRP)+'.png',format='png')\n plt.clf()\n plt.close('all')\n print(aReg+'_poverty_k_'+aDis+'_'+str(anRP)+'.pdf')\n\n##################################################################\n# This code generates the histograms including [k,dk,dc,dw,&pds]\n# ^ this is by province, so it will use iah_res\nfor aProv in myHaz[0]:\n for aDis in myHaz[1]:\n for anRP in myHaz[2]:\n\n plt.figure(1)\n ax = plt.subplot(111)\n\n plt.figure(2)\n ax2 = plt.subplot(111)\n\n for myQ in range(1,6): #nQuintiles\n \n print(aProv,aDis,anRP,'shape:',iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].shape[0])\n \n k = (0.01*iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['k','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n \n dk = (iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['dk','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n \n dc = (iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['dc_npv_pre','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n \n dw = (iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['dw','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n \n pds_nrh = (iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['pds_nrh','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n\n pds_dw = (iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['pds_dw','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n\n try:\n pds_plus_dw = (iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),['pds_plus_dw','pcwgt']].prod(axis=1).sum()/\n iah_res.loc[(iah_res[economy]==aProv)&(iah_res.hazard==aDis)&(iah_res.rp==anRP)&(iah_res.quintile==myQ),'pcwgt'].sum())\n except: pds_plus_dw = 0\n\n ax.bar([6*ii+myQ for ii in range(1,6)],[dk,dc,dw,pds_nrh,pds_dw],\n color=q_colors[myQ-1],alpha=0.7,label=q_labels[myQ-1])\n\n np.savetxt('/Users/brian/Desktop/to_send/dk_dc_dw_pds_'+aProv+'_'+aDis+'_'+str(anRP)+'_Q'+str(myQ)+'.csv',[dk,dc,dw,pds_nrh,pds_dw],delimiter=',')\n\n lbl= None\n if myQ==1: \n ax2.bar([0],[0],color=[q_colors[0]],alpha=0.7,label='No post-disaster support')\n ax2.bar([0],[0],color=[q_colors[1]],alpha=0.7,label='Winston-like response')\n ax2.bar([0],[0],color=[q_colors[2]],alpha=0.7,label='Wider & stronger response')\n ax2.bar([4*myQ+ii for ii in range(1,4)],[dw,pds_dw,pds_plus_dw],color=[q_colors[0],q_colors[1],q_colors[2]],alpha=0.7)\n \n np.savetxt('/Users/brian/Desktop/to_send/pds_comparison_'+aProv+'_'+aDis+'_'+str(anRP)+'_Q'+str(myQ)+'.csv',[dw,pds_dw,pds_plus_dw], delimiter=',')\n \n out_str = None\n if myCountry == 'FJ': out_str = ['Asset loss','Consumption\\nloss','Well-being\\nloss','Net cost of\\nWinston-like\\nsupport','Well-being loss\\npost support']\n elif myCountry == 'PH': out_str = ['Asset loss','Consumption\\nloss','Well-being\\nloss','Net cost of\\nsupport','Well-being loss\\npost support']\n\n for ni, ii in enumerate(range(1,6)):\n ax.annotate(out_str[ni],xy=(6*ii+1,ax.get_ylim()[0]/4.),xycoords='data',ha='left',va='top',weight='bold',fontsize=8,annotation_clip=False)\n\n fig = ax.get_figure() \n leg = ax.legend(loc='best',labelspacing=0.75,ncol=1,fontsize=9,borderpad=0.75,fancybox=True,frameon=True,framealpha=0.9)\n leg.get_frame().set_color('white')\n leg.get_frame().set_edgecolor(greys_pal[7])\n leg.get_frame().set_linewidth(0.2)\n \n plt.figure(1)\n plt.plot([xlim for xlim in ax.get_xlim()],[0,0],'k-',lw=0.50,color=greys_pal[7],zorder=100,alpha=0.85)\n ax.xaxis.set_ticks([])\n plt.ylabel('Disaster losses ('+get_currency(myCountry)[0][3:]+' per capita)')\n\n print('losses_k_'+aDis+'_'+str(anRP)+'.pdf')\n fig.savefig(output_plots+'npr_'+aProv+'_'+aDis+'_'+str(anRP)+'.pdf',format='pdf')#+'.pdf',format='pdf')\n fig.savefig(output_plots+'png/npr_'+aProv+'_'+aDis+'_'+str(anRP)+'.png',format='png')\n\n plt.figure(2)\n fig2 = ax2.get_figure()\n leg = ax2.legend(loc='best',labelspacing=0.75,ncol=1,fontsize=9,borderpad=0.75,fancybox=True,frameon=True,framealpha=0.9)\n leg.get_frame().set_color('white')\n leg.get_frame().set_edgecolor(greys_pal[7])\n leg.get_frame().set_linewidth(0.2)\n\n ann_y = -ax2.get_ylim()[1]/50\n\n out_str = ['Q1','Q2','Q3','Q4','Q5']\n for ni, ii in enumerate(range(1,6)):\n ax2.annotate(out_str[ni],xy=(4*ii+1.05,ann_y),zorder=100,xycoords='data',\n ha='left',va='center',weight='bold',fontsize=8,annotation_clip=False)\n plt.plot([4*ii+1.80,4*ii+3.78],[ann_y,ann_y],'k-',lw=0.50,color=greys_pal[7],zorder=100,alpha=0.85)\n plt.plot([4*ii+3.78,4*ii+3.78],[ann_y*0.9,ann_y*1.1],'k-',lw=0.50,color=greys_pal[7],zorder=100,alpha=0.85)\n\n ax2.xaxis.set_ticks([])\n plt.xlim(3,26)\n plt.plot([i for i in ax2.get_xlim()],[0,0],'k-',lw=1.5,color=greys_pal[7],zorder=100,alpha=0.85)\n plt.ylabel('Well-being losses ('+get_currency(myCountry)[0][3:]+' per capita)')\n fig2.savefig(output_plots+'npr_pds_schemes_'+aProv+'_'+aDis+'_'+str(anRP)+'.pdf',format='pdf')\n fig2.savefig(output_plots+'png/npr_pds_schemes_'+aProv+'_'+aDis+'_'+str(anRP)+'.png',format='png')\n \n plt.clf()\n plt.close('all')\n \n\niah_ntl.to_csv(output+'poverty_ntl_by_haz.csv')\niah_ntl = iah_ntl.reset_index().set_index(['hazard','rp'])\niah_ntl_haz,_ = average_over_rp(iah_ntl,'default_rp')\niah_ntl_haz.sum(level='hazard').to_csv(output+'poverty_haz_sum.csv')\n\niah_ntl = iah_ntl.reset_index().set_index('rp').sum(level='rp')\niah_ntl.to_csv(output+'poverty_ntl.csv')\niah_sum,_ = average_over_rp(iah_ntl,'default_rp')\niah_sum.sum().to_csv(output+'poverty_sum.csv')\n","sub_path":"new_process_data.py","file_name":"new_process_data.py","file_ext":"py","file_size_in_byte":31918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270658647","text":"# -*- coding: utf-8 -*-\n#转载:https://www.v2ex.com/amp/t/599858/2\nimport os\nimport os.path\nimport shutil\nimport random\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\n\n\ndef get_exif_and_arrange_img(imgfile,imgfilename,outdir):\n if (not os.path.isdir(outdir)):\n os.mkdir(outdir)\n \n try:\n img = Image.open(imgfile,\"r\")\n except:\n print(\"not an image file:\" + imgfilename)\n videodir = outdir + '\\\\'+ 'VIDEOS'\n if (not os.path.isdir(videodir)):\n os.mkdir(videodir)\n newvideofilename = imgfilename[:imgfilename.rfind('.')] + '_' + str(random.randint(1,999)) + imgfilename[imgfilename.rfind('.'):]\n newvideofilename = imgfilename\n shutil.copyfile(imgfile,videodir + '\\\\' + newvideofilename)\n else:\n try:\n exif_data = img._getexif()\n except:\n print(\"cannot read exif:\" + imgfilename)\n otherdir = outdir + '\\\\'+ 'OTHERS'\n if (not os.path.isdir(otherdir)):\n os.mkdir(otherdir)\n newphotofilename = imgfilename[:imgfilename.rfind('.')] + '_' + str(random.randint(1,999)) + imgfilename[imgfilename.rfind('.'):]\n newphotofilename = imgfilename\n shutil.copyfile(imgfile,otherdir + '\\\\' + newphotofilename)\n else:\n if (exif_data):\n device = ''\n photodate = ''\n fulldate = ''\n for tag, value in exif_data.items():\n #begin\n decoded = TAGS.get(tag,tag)\n #print('%s (%s) = %s' % (decoded, tag, value) )\n if (decoded == 'Make'):\n device += value + '_'\n if (decoded == 'Model'):\n device += value\n if (decoded == 'DateTime'):\n photodate = value.replace(':','')[0:6]\n fulldate = value.replace(':','')\n print(fulldate)\n #if (decoded == 'DateTimeDigitized'):\n # createdate = value.replace(':','').replace(' ','-')\n # print(''+'************'+createdate)\n #end\n #begin\n \n device = device.replace(\"\\0\",'')\n #device = device.replace(\"\\32\",'')\n newfulldate = fulldate.replace(' ','_') \n print(imgfile + '---' + device + '---' + photodate + '---' + newfulldate)\n #设备名目录\n #devicedir = outdir + '\\\\' + device\n #if (not os.path.isdir(devicedir)):\n # os.mkdir(devicedir)\n #拍照时间\n device_datedir = outdir + '\\\\' + photodate\n if (not os.path.isdir(device_datedir)):\n os.mkdir(device_datedir)\n #文件名\n newphotofilename = newfulldate + '_' + str(random.randint(1,9999999)) + imgfilename[imgfilename.rfind('.'):]\n newphotofilename = imgfilename\n shutil.copyfile(imgfile,device_datedir + '\\\\' + newphotofilename)\n img.close()\n #end\n\nrootdir = \"xxxx\"\noutdir = \"xxx\"\n\nfor parent,dirnames,filenames in os.walk(rootdir):\n for filename in filenames:\n imgfile = os.path.join(parent,filename)\n imgfilename = filename\n get_exif_and_arrange_img(imgfile,imgfilename,outdir)","sub_path":".history/photo_20200701110323.py","file_name":"photo_20200701110323.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293956378","text":"import os\n\nimport pandas as pd\nimport numpy as np\nimport pingouin as pg\n\nmainDirectory = os.getcwd()\n\n\ndef calculateICCMDC(measurement):\n files = [measurement + '_Zitten',\n measurement + '_Staan', \n measurement + '_Staan ogen dicht', \n measurement + '_Staan op foam', \n measurement + '_Staan voeten samen'\n ] \n \n\n for filename in files:\n if measurement == 'FM':\n directory = mainDirectory + '/Results/Single measurement'\n os.chdir(directory)\n nFilesPP = 2\n elif measurement == 'AM':\n directory = mainDirectory + '/Results/Averaged measurements'\n os.chdir(directory) \n nFilesPP = 4\n \n if filename == 'AM_Zitten':\n continue\n loadfile = filename + '.xlsx'\n xls = pd.read_excel(loadfile, index_col = 0)\n \n countValues = xls['Subject number'].value_counts()\n inComplete = countValues.loc[countValues != nFilesPP].index\n xls.drop(xls.loc[xls['Subject number'].isin(inComplete)].index, inplace = True)\n \n if measurement == 'FM':\n if filename == 'FM_Staan voeten samen':\n # 4,5 = clonus : S006p\n xls.drop(xls.loc[xls['Subject number']== 'S006P'].index, inplace = True)\n # 13,14 = Stapjes: S014P \n xls.drop(xls.loc[xls['Subject number'] == 'S014P'].index, inplace = True)\n \n elif filename == 'FM_Staan ogen dicht':\n # 5,6 = clonus: S006P\n xls.drop(xls.loc[xls['Subject number']== 'S006P'].index, inplace = True)\n # 13,14 = Stapjes: S014P \n xls.drop(xls.loc[xls['Subject number'] == 'S014P'].index, inplace = True)\n \n elif filename == 'FM_Staan op foam':\n # 5,6 = clonus: S006P\n xls.drop(xls.loc[xls['Subject number']== 'S006P'].index, inplace = True)\n # 13,14 = Stapjes: S020P \n xls.drop(xls.loc[xls['Subject number'] == 'S020P'].index, inplace = True)\n \n elif measurement == 'AM':\n if filename == 'AM_staan voeten samen':\n # 5,6 = clonus: S006P\n xls.drop(xls.loc[xls['Subject number']== 'S006P'].index, inplace = True)\n # 13,14 = Stapjes: S014P \n xls.drop(xls.loc[xls['Subject number'] == 'S014P'].index, inplace = True)\n \n elif filename == 'AM_staan ogen dicht':\n # 5,6 = clonus: S006P\n xls.drop(xls.loc[xls['Subject number']== 'S006P'].index, inplace = True)\n # 13,14 = Stapjes: S014P \n xls.drop(xls.loc[xls['Subject number'] == 'S014P'].index, inplace = True)\n \n elif filename == 'AM_staan op foam':\n # 5,6 = clonus: S006P\n xls.drop(xls.loc[xls['Subject number']== 'S006P'].index, inplace = True)\n # 13,14 = Clonus: S020P \n xls.drop(xls.loc[xls['Subject number'] == 'S020P'].index, inplace = True)\n \n \n results = pd.DataFrame(columns = xls.columns[3:]).astype(float)\n results = results.append(pd.Series(name='ICC', dtype = 'float64'))\n results = results.append(pd.Series(name='MDC', dtype = 'float64'))\n \n if measurement == 'AM':\n firstMeasurement = xls.loc[xls['Trial']== 0].reset_index(drop = True) \n secondMeasurement = xls.loc[xls['Trial']== 1].reset_index(drop = True) \n if len(firstMeasurement) == len(secondMeasurement):\n doubleDF = (firstMeasurement.iloc[:,3:] + secondMeasurement.iloc[:,3:])\n newDF = doubleDF.div(2)\n xls = firstMeasurement\n xls.iloc[:,3:] = newDF\n else:\n print(f'Something is wrong with calculation of: {filename}')\n break\n \n for variable in xls.columns[3:]:\n variableDF = xls[['Subject number', 'testType', variable]]\n icc = pg.intraclass_corr(data=variableDF, targets='Subject number', raters = 'testType',\n ratings=variable).round(10)\n ICC = icc['ICC'].loc[1]\n CI = icc['CI95%'].loc[1]\n SEM = (np.std(variableDF.loc[:,variable]) * np.sqrt(1 - ICC))\n MDC = (1.96 * SEM * np.sqrt(2))\n SEM = SEM.round(3)\n ICC_CI = str(ICC.round(3))+ ' ['+ str(CI[0]) + ',' + str(CI[1]) + ']' \n MDC_SEM = str(MDC.round(3))+ ' (' + str(SEM) + ')'\n results.loc['ICC',variable] = ICC\n results.loc['ICC_CI',variable] = ICC_CI\n results.loc['MDC',variable] = MDC\n results.loc['MDC_SEM',variable] = MDC_SEM\n \n test = xls.loc[0::2 , variable]\n meantest = np.mean(test)\n stdtest = np.std(test)\n \n hertest = xls.loc[1::2, variable]\n meanhertest = np.mean(hertest)\n stdhertest = np.std(hertest)\n \n first = str(round(meantest,3)) + ' (' + str(round(stdtest,3)) + ')'\n second = str(round(meanhertest,3)) + ' (' + str(round(stdhertest,3)) + ')'\n \n results.loc['test_mean_std',variable] = first\n results.loc['test_mean',variable] = meantest \n results.loc['test_std',variable] = stdtest \n \n results.loc['hertestmean_std',variable] = second\n results.loc['hertestmean',variable] = meanhertest\n results.loc['hertest_std',variable] = stdhertest \n \n \n if measurement == 'FM':\n saveDirectory = mainDirectory + '/Results/ICC single measurement'\n os.chdir(saveDirectory)\n elif measurement == 'AM':\n saveDirectory = mainDirectory + '/Results/ICC averaged measurement'\n os.chdir(saveDirectory) \n \n results = results.transpose()\n save_xls = filename + '_ICC.xlsx'\n results.to_excel(save_xls)\n \n os.chdir(mainDirectory)\n \n\nif __name__ == '__main__':\n calculateICCMDC(measurement = 'FM')\n calculateICCMDC(measurement = 'AM')\n \n \n \n","sub_path":"calcICC.py","file_name":"calcICC.py","file_ext":"py","file_size_in_byte":6379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"426629532","text":"from typing import Optional, List\n\nfrom server.lib.database import request_session\nfrom server.lib.model.models import EnemyModel, MapModel, BattlemapModel\n\n\ndef get_map(map_id: int) -> Optional[MapModel]:\n db = request_session()\n\n return db.query(MapModel) \\\n .filter(MapModel.id == map_id) \\\n .one_or_none()\n\n\ndef create_map(mapmodel: MapModel):\n db = request_session()\n\n db.add(mapmodel)\n db.commit()\n\n\ndef commit():\n db = request_session()\n db.commit()\n\n\ndef get_children(map_id: int) -> Optional[List[MapModel]]:\n db = request_session()\n\n return db.query(MapModel) \\\n .filter(MapModel.parent_map_id == map_id) \\\n .all()\n\n\ndef get_all_maps(playthrough_id: str) -> List[MapModel]:\n db = request_session()\n\n return db.query(MapModel) \\\n .filter(MapModel.playthrough_id == playthrough_id) \\\n .all()\n\n\ndef get_all_battlemaps(playthrough_id: int):\n db = request_session()\n\n return db.query(BattlemapModel) \\\n .filter(BattlemapModel.playthrough_id == playthrough_id) \\\n .all()\n","sub_path":"server/lib/repository/map_repository.py","file_name":"map_repository.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"475894879","text":"# -*- encoding:utf-8 -*-\r\nimport os\r\nfrom zipfile import ZipFile\r\n\r\ndef dirCreate(path):\r\n if not os.path.exists(path):\r\n os.mkdir(path)\r\n\r\ndef unzip(path):\r\n os.rename(path, path + '.zip')\r\n dirCreate(path)\r\n zipfile = ZipFile(path + '.zip')\r\n for name in zipfile.namelist():\r\n tmp_path = os.path.join(path, name)\r\n if tmp_path.endswith('/'):\r\n dirCreate(tmp_path)\r\n else:\r\n file(tmp_path, 'wb').write(zipfile.read(name)) \r\n zipfile.close()\r\n\r\n# ear文件加压,���支持其中的war文件解压 \r\npath = 'E:\\\\zyxpython\\\\'\r\nfor file_name in os.listdir(path):\r\n if file_name.endswith('.ear'):\r\n unzip(path + file_name)\r\n \r\n","sub_path":"xmicros/unzipear/earunzip.py","file_name":"earunzip.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"478056151","text":"from gtts import gTTS\nimport os\n\n\n# It's just a text to speech function..\ndef saySomething(somethingToSay):\n myobj = gTTS(text=somethingToSay, lang=\"es\", slow=False)\n myobj.save(\"somethingToSay.mp3\")\n os.system(\"mpg321 somethingToSay.mp3\")\n\n\nwhile True:\n something = input(\"Something to say? \")\n print(\"Saying something with speakers..\")\n saySomething(something)","sub_path":"0510-2021/hablando.py","file_name":"hablando.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486362679","text":"from tkinter import *\n\nALL = N+S+W+E\n\n\nclass Application(Frame):\n \n def clicker1(self, event):\n print(\"Frame 1 was clicked at\", event.x, event.y)\n \n def clicker2(self, event):\n print(\"Frame 2 was clicked at\", event.x, event.y)\n \n def red(self):\n self.text.configure(fg=\"red\")\n def blue(self):\n self.text.configure(fg=\"blue\")\n def green(self):\n self.text.configure(fg=\"green\")\n def black(self):\n self.text.configure(fg=\"black\")\n def openz(self):\n self.path = self.entry.get() \n try:\n with open(self.path, \"r\") as f:\n lines = f.readlines()\n result = ''.join(lines)\n self.text.insert('1.0', result)\n except:\n self.text.insert('1.0', \"No such file or content\")\n \n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master.rowconfigure(0, weight=1)\n self.master.columnconfigure(0, weight=1)\n self.grid(sticky=ALL)\n for r in range(2):\n self.rowconfigure(r, weight=1)\n for c in range(5):\n self.columnconfigure(c, weight=1)\n\n f1 = Frame(self, bg=\"green\") \n f1.grid(row=0, column=0, rowspan=1, columnspan=2, sticky=ALL) \n l1 = Label(f1, text=\"Frame1\", bg=\"green\", fg=\"white\")\n l1.bind(\"\", self.clicker1) \n l1.pack(side=TOP, fill=BOTH, expand=True)\n \n f2 = Frame(self, bg=\"blue\")\n f2.grid(row=1, column=0, rowspan=1, columnspan=2, sticky=ALL)\n f2.bind(\"\", self.clicker2)\n l2 = Label(f2, text=\"Frame2\", bg=\"blue\", fg=\"white\")\n l2.bind(\"\", self.clicker2) \n l2.pack(side=TOP, fill=BOTH, expand=True)\n \n f3 = Frame(self, bg=\"white\") \n f3.grid(row=0, column=2, rowspan=3, columnspan=3, sticky=ALL)\n l3 = Label(f3, text=\"Frame3\", bg=\"white\", fg=\"black\")\n l3.pack(side=TOP, fill=BOTH, expand=True) \n \n self.entry = Entry(f3)\n self.entry.pack(side=TOP, fill=X, expand=True)\n\n self.text = Text(self, height=7, width=10)\n self.text = Text(f3)\n self.text.pack(side=LEFT, fill=BOTH, expand=True)\n \n Button(self, command=self.red, height=5, width=28, text=\"Red\").grid(row=2, column=0, sticky=E+W)\n Button(self, command=self.blue, height=5, width=28, text=\"Blue\").grid(row=2, column=1, sticky=E+W)\n Button(self, command=self.green, height=5, width=28, text=\"Green\").grid(row=2, column=2, sticky=E+W)\n Button(self, command=self.black, height=5, width=28, text=\"Black\").grid(row=2, column=3, sticky=E+W)\n Button(self, command=self.openz, height=5, width=28, text=\"Open\").grid(row=2, column=4, sticky=E+W)\n \n\nroot = Tk()\napp = Application(master=root)\napp.mainloop()\n","sub_path":"python2/MoreGUI_Homework/src/moreGUIv2.py","file_name":"moreGUIv2.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385903709","text":"import os\nimport requests\nfrom yaml import load, Loader\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\nfrom flaskr.synergyCalc import CalculatedSynergy\n\ndef create_app(test_config=None):\n app = Flask(__name__, instance_relative_config=True)\n CORS(app)\n app.config.from_mapping(\n SECRET_KEY='dev',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n \n if test_config is None:\n # Load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py', silent=True)\n else:\n # Load the test config if passed in\n app.config.from_mapping(test_config)\n\n # enusre instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n def retrieve_all_types():\n print(\"Downloading MTG types data...\")\n types_req = requests.get('https://api.magicthegathering.io/v1/types')\n if types_req.status_code is 200:\n with open('./data/types.yaml', 'w') as f:\n f.write(str(types_req.json()))\n else:\n print(\"types_req status code: \", types_req.status_code)\n\n def retrieve_all_sets():\n print(\"Downloading MTG sets data...\")\n sets_req = requests.get('https://api.magicthegathering.io/v1/sets')\n if sets_req.status_code is 200:\n with open('./data/sets.yaml', 'w') as f:\n f.write(str(sets_req.json()))\n else:\n print(\"sets_req status code: \", sets_req.status_code)\n\n def retrieve_all_keywords():\n print(\"Downloading MTG keywords data...\")\n keywords_req = requests.get('https://mtgjson.com/api/v5/Keywords.json')\n if keywords_req.status_code is 200:\n with open('./data/keywords.yaml', 'w') as f:\n f.write(str(keywords_req.json()))\n else:\n print(\"keywords_req status code: \", keywords_req.status_code)\n\n def retrieve_all_data():\n retrieve_all_types()\n retrieve_all_sets()\n retrieve_all_keywords()\n\n def get_all_sets():\n with open('./data/sets.yaml', 'r') as f:\n sets = load(f, Loader=Loader)\n return sets\n\n def get_all_types():\n with open('./data/types.yaml', 'r') as f:\n types = load(f, Loader=Loader)\n return types\n\n def get_all_keywords():\n with open('./data/keywords.yaml', 'r') as f:\n keywords = load(f, Loader=Loader)\n return keywords\n\n def merge_keywords_data():\n raw = get_all_keywords()\n merged = []\n for category in raw[\"data\"]:\n for keyword in raw[\"data\"][category]:\n if keyword not in merged:\n merged.append(keyword)\n merged.sort()\n with open('./data/merged_keywords.yaml', 'w') as f:\n f.write(str(merged)) \n\n @app.route('/api', methods=['GET'])\n def api():\n return {\"data\": 1234}\n\n @app.route('/api/synergize', methods=['POST'])\n def synergize():\n selected_card = request.args.get('card')\n data = request.get_json()\n synergy = CalculatedSynergy(selected_card, data['otherCards'])\n\n syn_calc = synergy.get_synergy_scores()\n\n return jsonify(syn_calc)\n\n return app\n","sub_path":"server/flaskr/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101605705","text":"# Flask web app server imports\nfrom flask import Flask, jsonify, abort, request\napp = Flask(__name__)\n\n# Database imports\nimport sqlite3\nfrom flask import g\n\n# Global debug flag\nimport sys\ndbDebug = True\n\n# Database connection establishment helper\ndef connect_db(database):\n\treturn sqlite3.connect(database)\n\n# Helper function for the database\ndef query_db(query, args=(), one=False):\n\tglobal dbDebug\n\tif (dbDebug):\n\t\tprint >> sys.stderr, \"Executing query: \" + str(query)\n\tcur = g.db.execute(query, args)\n\trv = [dict((cur.description[idx][0], value)\n\t\tfor idx, value in enumerate(row)) for row in cur.fetchall()]\n\tg.db.commit() # save whatever...\n\treturn (rv[0] if rv else None) if one else rv\n","sub_path":"src/FlaskBackend.py","file_name":"FlaskBackend.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143366278","text":"# A script to fetch a string from a remote\n# server, reverse it, and send the result back\n\n\nimport requests\nfrom registration import token, doubleCheck\n\n# instance variables\nget_url = 'http://challenge.code2040.org/api/reverse'\npost_url = 'http://challenge.code2040.org/api/reverse/validate'\n\n# fetch the data\nobjectToReverse = requests.post(get_url, data={'token' : token})\n\n# Reverse the string\ndef reverse(string):\n return string[::-1]\n\n# send the result back\nreversedString = reverse(objectToReverse.text)\npost = requests.post(post_url, data = {'token': token, 'string' : reversedString})\n\n# check\ndoubleCheck(post)\n","sub_path":"reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"73903266","text":"import config\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import Flask, render_template, Blueprint\n\napp = Flask(__name__)\napp.config.from_object(config)\n\ndb = SQLAlchemy(app)\ndb.create_all()\n\n\n@app.route('/')\ndef hello():\n return 'hello'\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"418189512","text":"# settings.py - settings for chickenrobot, a controller for a coop door and cam controller\n# author: Wes Modes \n# date: Oct 2020\n# license: MIT\n\nimport os, sys\nfrom dotenv import load_dotenv\nload_dotenv()\nif sys.platform == \"darwin\":\n # OS X\n import fake_rpi\n sys.modules['RPi'] = fake_rpi.RPi # Fake RPi\n sys.modules['RPi.GPIO'] = fake_rpi.RPi.GPIO # Fake GPIO\n # sys.modules['smbus'] = fake_rpi.smbus # Fake smbus (I2C)\nimport RPi.GPIO as GPIO\nimport logging\n\n# Chickenrobot class\nLOG_FILENAME = \"logs/cr.log\"\nLOG_LEVEL = logging.INFO\n\n# Light class\n#\n# Felton, CA 37.0513° N, 122.0733° W\nCITY_NAME = \"Felton, CA\"\nLATITUDE = 37.0513\nLONGITUDE = -122.0733\nSUNRISE_DELAY = 0 # minutes\nSUNSET_DELAY = 60 # minutes\nTIME_FORMAT = '%-I:%M%p'\n\n# Camera class\n#\nSFTP_LOG_LEVEL = logging.WARNING\nif sys.platform == \"darwin\":\n MAX_HORZ = 1920\n MAX_VERT = 1080\nelse:\n MAX_HORZ = 1280\n MAX_VERT = 1024\nMAX_CAMS = 8\nACTIVE_CAMS = 0\n\n# Local file deets\n#\nIMAGE_DIR = \"images\"\nIMAGE_FILE_BASE = IMAGE_DIR + \"/image\"\nIMAGE_FILE_POSTFIX = '.jpg'\nIMAGE_URL_BASE = 'https://modes.io/interactive/chickenrobot/'\nDOOR_STATE_FILE = \"door.state\"\nSTATUS_FILE = \"status.html\"\n\n# SFTP deets\n#\nSFTP_SERVER = 'sftp.sd5.gpaas.net'\nSFTP_USER = '41496'\nSFTP_IMAGE_DIR = '/lamp0/web/vhosts/modes.io/htdocs/interactive/chickenrobot/images'\nSFTP_MAIN_DIR = '/lamp0/web/vhosts/modes.io/htdocs/interactive/chickenrobot'\nSFTP_LOG = 'logs/sftp.log'\nSFTP_PASSWORD = os.environ['SFTP_PASSWORD']\n\n# GPIO Configs\n#\nDIR_PIN = 20 # Direction GPIO pin\nSTEP_PIN = 21 # Step GPIO pin\nCAMLIGHT_PIN = 19 # Activate camlight GPIO pin\nINDICATOR_PIN = 26 # Activate indicator GPIO pin\nPINOUT_SCHEME = GPIO.BCM # Boradcom pin numbering (NOT Wiring Pin numbering)\n\n# Door class\n#\nSPR = 200 # Steps per revolution (360/1.8) from stepper datasheet\nREVS = 10 # number of revolutions to bring door up or lower it down\n\n# Comms class\n#\nTWILIO_ACCOUNT_SID = os.environ['TWILIO_ACCOUNT_SID']\nTWILIO_AUTH_TOKEN = os.environ['TWILIO_AUTH_TOKEN']\nTWILIO_LOG_LEVEL = logging.WARNING\nMSG_PREFIX = \"Message from Chicken Robot:\\n\"\nMSG_POSTFIX = \"\\nBawwwk! 🐓🤖\"\nORIGIN_NUM = '+18313370604'\n# TARGET_NUMS = ['+18314190044', '+18312269992', '+17025929231']\nTARGET_NUMS = ['+18314190044', '+18312269992']\n# TARGET_NUMS = ['+18314190044']\n","sub_path":"experiments/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282833952","text":"import uuid\nfrom datetime import date, timedelta\n\nfrom flask import abort, request\nfrom flask_peewee.auth import Auth\n\nfrom app import app, db\nfrom models import ServiceToken, Token, User\n\ndef create_auth(app, db):\n return Auth(app, db)\n\n# API Utils\ndef create_token(user):\n token_string = uuid.uuid4()\n expires_on = date.today() + timedelta(days=365) # 1 year\n token = Token.create(\n user = user,\n token = token_string,\n created_on = date.today(),\n expires_on = expires_on\n )\n return token.token\n\ndef authorize_user():\n token = request.headers.get('Authorization')\n try:\n token = Token.get(Token.token == token)\n return token.user\n except Token.DoesNotExist:\n return None\n\n# Slack Utils\ndef has_slack_token():\n # Token support for slack, because it doesn't support customizing headers out of the box\n auth_key = (request.args.get('token') or\n request.form.get('token'))\n try:\n return ServiceToken.get(ServiceToken.key == auth_key)\n except ServiceToken.DoesNotExist:\n return None\n\n\ndef has_username():\n username = (request.args.get('user_name') or\n request.form.get('user_name') or\n request.get_json(force=True).get('username'))\n try:\n return User.get(User.slackname == username)\n except User.DoesNotExist:\n return None\n\n# Get user from slack of API\ndef get_user():\n user = has_username() # slack user\n if not user:\n user = authorize_user() # API user\n\n return user\n\n# Method before request to check if allowed to make request\ndef before_slack_request():\n if not has_slack_token() or not has_username():\n abort(401)\n\ndef before_slotmachien_request():\n if not authorize_user():\n abort(401)\n\n# Do the Auth\nauth = create_auth(app, db)\n","sub_path":"Web/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"223415306","text":"import numpy as np\nimport argparse\nimport configparser\nimport json\nfrom data_loader import load_audio, preprocess\nfrom decoder import GreedyDecoder\nfrom vad import VAD\nfrom pydub import AudioSegment\nfrom io import BytesIO\nfrom multiprocessing.pool import ThreadPool\nfrom requests import request\n\n\nclass SpeechRecognizer(object):\n def __init__(self, config_path='config.ini'):\n if config_path is None:\n raise Exception('Path to config file is None')\n self.config = configparser.ConfigParser()\n self.config.read(config_path, encoding='UTF-8')\n self.labels = self.config['Wav2Letter']['labels'][1:-1]\n self.sample_rate = int(self.config['Wav2Letter']['sample_rate'])\n self.window_size = float(self.config['Wav2Letter']['window_size'])\n self.window_stride = float(self.config['Wav2Letter']['window_stride'])\n self.greedy = int(self.config['Wav2Letter']['greedy'])\n self.cpu = int(self.config['Wav2Letter']['cpu'])\n self.vad = VAD(\n mode=int(self.config['Wav2Letter']['vad_aggressiveness_mode']),\n frame_duration_ms=int(self.config['Wav2Letter']['vad_frame_duration_ms']),\n max_pause_ms=int(self.config['Wav2Letter']['vad_max_pause_ms'])\n )\n\n if self.cpu:\n from PuzzleLib import Config\n Config.backend = Config.Backend.cpu\n\n from PuzzleLib.Models.Nets.WaveToLetter import loadW2L\n from PuzzleLib.Modules import MoveAxis\n\n nfft = int(self.sample_rate * self.window_size)\n self.w2l = loadW2L(modelpath=self.config['Wav2Letter']['model_path'], inmaps=(1 + nfft // 2),\n nlabels=len(self.labels))\n self.w2l.append(MoveAxis(src=2, dst=0))\n\n if not self.cpu:\n self.w2l.calcMode(np.float16)\n\n self.w2l.evalMode()\n\n if not self.greedy:\n # from decoder import TrieDecoder\n # lexicon = self.config['Wav2Letter']['lexicon']\n # tokens = self.config['Wav2Letter']['tokens']\n # lm_path = self.config['Wav2Letter']['lm_path']\n # beam_threshold = float(self.config['Wav2Letter']['beam_threshold'])\n # self.decoder = TrieDecoder(lexicon, tokens, lm_path, beam_threshold)\n self.decoder_url = \"http://localhost:8889/decode\"\n else:\n self.decoder = GreedyDecoder(self.labels)\n\n def decode_request(self, args):\n outputs, start_timestamp = args\n data = {\n \"outputs\": outputs.tolist(),\n \"start_timestamp\": start_timestamp\n }\n\n response = request(\"POST\", self.decoder_url, json=data)\n\n result = json.loads(response.text)\n\n return result\n\n\n def recognize(self, audio_path, max_chunk_len=30000):\n results = []\n inputs = []\n outputs = []\n\n audio = load_audio(audio_path, self.sample_rate).raw_data\n segments = self.vad.collect(audio, self.sample_rate)\n start_timestamps = []\n current_timestamp = 0.0\n\n for segment in segments:\n start, end = segment.get()\n start_timestamps.append(current_timestamp)\n\n sound = AudioSegment.from_raw(\n BytesIO(audio[start:end]), sample_width=2, frame_rate=self.sample_rate, channels=1\n )\n current_timestamp += sound.duration_seconds\n\n audio_segment = np.array(sound.get_array_of_samples()).astype(float)\n\n preprocessed_audio = preprocess(audio_segment, self.sample_rate, self.window_size, self.window_stride)\n\n chunk_outputs = []\n for i in range(1 + preprocessed_audio.shape[1] // max_chunk_len):\n audio_chunk = preprocessed_audio[::, i * max_chunk_len:(i + 1) * max_chunk_len]\n\n if self.cpu:\n from PuzzleLib.CPU.CPUArray import CPUArray\n inputs = CPUArray.toDevice(np.array([audio_chunk]).astype(np.float32))\n else:\n from PuzzleLib.Backend import gpuarray\n inputs = gpuarray.to_gpu(np.array([audio_chunk]).astype(np.float16))\n\n chunk_outputs.append(self.w2l(inputs).get())\n\n outputs.append(np.vstack(chunk_outputs))\n\n if not self.cpu:\n from PuzzleLib.Backend.gpuarray import memoryPool\n memoryPool.freeHeld()\n\n if self.greedy:\n pool = ThreadPool(processes=4)\n results = pool.map(\n self.decoder.decode,\n zip([np.vstack(output).astype(np.float32) for output in outputs], start_timestamps)\n )\n results = [\n {\n \"text\": result.text,\n \"score\": result.score,\n \"words\": result.words\n } for result in results\n ]\n else:\n pool = ThreadPool(processes=4)\n results = pool.map(\n self.decode_request,\n zip([np.vstack(output).astype(np.float32) for output in outputs], start_timestamps)\n )\n\n if inputs:\n del inputs\n if outputs:\n del outputs\n\n return results\n\n\ndef test():\n parser = argparse.ArgumentParser(description='Pipeline')\n parser.add_argument('--audio', default='data/test.wav', metavar='DIR', help='Path to wav file')\n parser.add_argument('--config', default='config.ini', help='Path to config')\n args = parser.parse_args()\n\n recognizer = SpeechRecognizer(args.config)\n\n print(recognizer.recognize(args.audio))\n\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"speech_recognizer.py","file_name":"speech_recognizer.py","file_ext":"py","file_size_in_byte":5608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"31464181","text":"\"\"\"\nAdapted from https://github.com/NVIDIA/tacotron2\n\"\"\"\nimport torch\nfrom torch import nn\nfrom typing import List, Tuple\n\n\nclass Tacotron2Loss(nn.Module):\n def __init__(self, gate_loss_pos_weight=1.0):\n \"\"\"\n :param float gate_loss_pos_weight: The weight of the positive class in gate loss. Used to adjust the stop token loss to to account for the imbalance between positive and negative classes.\n \"\"\"\n super(Tacotron2Loss, self).__init__()\n self.gate_loss_pos_weight = gate_loss_pos_weight\n\n def forward(self, model_output: List, targets: Tuple) -> torch.Tensor:\n mel_target, gate_target = targets[0], targets[1]\n mel_target.requires_grad = False\n gate_target.requires_grad = False\n gate_target = gate_target.view(-1, 1)\n\n mel_out, mel_out_postnet, gate_out, _ = model_output\n gate_out = gate_out.view(-1, 1)\n mel_loss = nn.MSELoss()(mel_out, mel_target) + \\\n nn.MSELoss()(mel_out_postnet, mel_target)\n gate_loss = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(self.gate_loss_pos_weight))(gate_out, gate_target)\n return mel_loss + gate_loss\n","sub_path":"tacotron2_gst/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"307098367","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 10 21:55:27 2017\n\n@author: Thanh\n\"\"\"\n\n#==============================================================================\n# maximize sum(song.song_len) \n# s.t. sum(song.size) < max_size\n#==============================================================================\ndef song_playlist(songs, max_size):\n \"\"\"\n songs: list of tuples, ('song_name', song_len, song_size)\n max_size: float, maximum size of total songs that you can fit\n\n Start with the song first in the 'songs' list, then pick the next \n song to be the one with the lowest file size not already picked, repeat\n\n Returns: a list of a subset of songs fitting in 'max_size' in the order \n in which they were chosen.\n \"\"\"\n selection = [] \n if songs[0][2] < max_size:\n selection.append(songs[0][0]) \n sum_size = songs[0][2] \n copy = sorted(songs[1:], key=lambda x : x[2])\n for s in copy:\n if sum_size + s[2] < max_size:\n selection.append(s[0])\n sum_size += s[2]\n else:\n break\n return selection \n\n#songs = [('Roar',4.4, 4.0),('Sail',3.5, 7.7),('Timber', 5.1, 6.9),('Wannabe',2.7, 1.2)]\n#print(song_playlist(songs, 12.2))\n#print(song_playlist(songs, 11))\n","sub_path":"quiz/song_selection.py","file_name":"song_selection.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226175288","text":"import pandas as pd\nimport numpy as np\nimport math\n\n\n\ndef main():\n # The application should prompt for a ticker, not a file name.\n # The fact that there is a file is an implementation detail.\n filename = input('Enter the ticker: ')\n data = get_data_from_file(filename)\n\n # Having a main function is a good idea. If you do this, you should have\n # all of the top-level (not inside a function) code inside main.\n data3 = 0\n\n # list is a type, which means you should not use for a variable name.\n temp_list = []\n\n adj_closes = data['Adj Close']\n\n for i in range(1, len(adj_closes)):\n data1 = adj_closes[i - 1]\n data2 = adj_closes[i]\n data3 = (data2 - data1) / data1\n temp_list.append(data3)\n\n num = len(temp_list)\n value = 0\n\n for i in range(0, num):\n value = value + temp_list[i]\n\n muVal = value / len(temp_list)\n print(\"Mu = \", muVal)\n\n\ndef get_data_from_file(ticker):\n # Also, you need to append the \".csv\" to the filename\n # The code I gave you did that.\n f_name = ticker + \".csv\"\n data = pd.read_csv(f_name)\n # You needed to return what you read.\n # data is scoped inside the function.\n return data\n\n\nmain()\n\n","sub_path":"homeworks/hw2/ma.py","file_name":"ma.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"299901781","text":"import pymysql\r\n\r\nclass BDvenda(object):\r\n\r\n def __init__(self):\r\n self.db = pymysql.connect(\"localhost\", \"root\", \"\", \"comercio\")\r\n self.cursor = self.db.cursor()\r\n\r\n def gravaBDvenda(self, dhVenda, itensVendidos):\r\n dados = (dhVenda, itensVendidos)\r\n self.cursor.execute(\"INSERT INTO venda(dhVenda, itensVendidos) VALUES (%s, %s)\", dados)\r\n self.db.commit()\r\n self.db.close()\r\n\r\n def recuperaBDvenda(self, numero):\r\n self.cursor.execute(\"SELECT * FROM venda WHERE numero = %s\", numero)\r\n dado = self.cursor.fetchall()\r\n self.db.close()\r\n return dado\r\n\r\n def atualizaDHvenda(self, numero, dhVenda):\r\n dados = (dhVenda, numero)\r\n self.cursor.execute(\"UPDATE item SET dhVenda = %s WHERE numero = %s\", dados)\r\n self.db.commit()\r\n self.db.close()\r\n\r\n def atualizaItensVendidos(self, numero, itensVendidos):\r\n dados = (itensVendidos, numero)\r\n self.cursor.execute(\"UPDATE item SET itensVendidos = %s WHERE numero = %s\", dados)\r\n self.db.commit()\r\n self.db.close()\r\n\r\n def validaBDvenda(self, numero):\r\n self.cursor.execute(\"SELECT id FROM venda WHERE numero = %s\", numero)\r\n dado = self.cursor.fetchone()\r\n self.db.close()\r\n if not dado:\r\n return False\r\n else:\r\n return True\r\n","sub_path":"algoritmos/Ex1/Codigo Sistema Comercio/BDVenda.py","file_name":"BDVenda.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"370415703","text":"GO_BACK = -3\nNO_MOVE = -1\nGO = 0\nOLD_KENT_ROAD = 1\nJUST_VISITING = 10\nPALL_MALL = 11\nMARYLEBONE_STATION = 15\nTRAFALGAR_SQUARE = 24\nGO_TO_JAIL = 30\nMAYFAIR = 39\nIN_JAIL = 40\nPOSITION_NAMES_UK = [\"Go\", \"Old Kent Road\", \"Community Chest\", \"Whitechapel Road\", \"Income Tax\", \"Kings Cross Station\",\n \"The Angel, Islington\", \"Chance\", \"Euston Road\", \"Pentonville Road\", \"Just Visiting\", \"Pall Mall\",\n \"Electric Company\", \"Whitehall\", \"Northumberland Avenue\", \"Marylebone Station\", \"Bow Street\",\n \"Community Chest\", \"Marlborough Street\", \"Vine Street\", \"Free Parking\", \"Strand\", \"Chance\",\n \"Fleet Street\", \"Trafalgar Square\", \"Fenchurch Street Station\", \"Leicester Square\",\n \"Coventry Street\", \"Water Works\", \"Piccadilly\", \"Go To Jail\", \"Regent Street\", \"Oxford Street\",\n \"Community Chest\", \"Bond Street\", \"Liverpool Street Station\", \"Chance\", \"Park Lane\", \"Super Tax\",\n \"Mayfair\", \"Jail\"]\n\nMAX_DOUBLES = 3","sub_path":"Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309834063","text":"import maya.cmds as cmds\nimport mrt_functions as mfunc\nimport mrt_objects as objects\nimport maya.mel as mel\nimport math, os\nfrom functools import partial\n\nclass MRT_Module(object):\n def __init__(self, moduleInfo):\n \"\"\" Initial class variables.\"\"\"\n # Module type.\n self.moduleName = moduleInfo['node_type']\n # Number of nodes in the module.\n self.numNodes = moduleInfo['num_nodes']\n # Length of the module.\n self.moduleLen = moduleInfo['module_length']\n # Creation plane.\n self.onPlane = moduleInfo['creation_plane'][-2:]\n # Offset from origin.\n self.moduleOffset = moduleInfo['module_offset']\n # Node Axes.\n self.nodeAxes = moduleInfo['node_axes']\n # Proxy geometry creation on/off.\n self.proxyGeoStatus = moduleInfo['node_compnts'][2]\n # Proxy bones.\n self.proxyGeoBones = moduleInfo['proxy_geo_options'][0]\n # Proxy elbow.\n self.proxyGeoElbow = moduleInfo['proxy_geo_options'][1]\n\n self.proxyElbowType = moduleInfo['proxy_geo_options'][2]\n # Mirror instance for proxy geometry.\n self.proxyGeoMirrorInstance = moduleInfo['proxy_geo_options'][3]\n # Create mirror module on/off.\n self.mirrorModule = moduleInfo['mirrorModule']\n self.mirrorModuleStatus = moduleInfo['mirror_options'][0]\n # Translation function for mirroring.\n self.mirrorTranslationFunc = moduleInfo['mirror_options'][1]\n # Rotation function for mirroring.\n self.mirrorRotationFunc = moduleInfo['mirror_options'][2]\n # Variables to set visibility attributes for hierarchy, orientation representations.\n self.showHierarchy = moduleInfo['node_compnts'][0]\n self.showOrientation = moduleInfo['node_compnts'][1]\n # Module handle colour.\n self.modHandleColour = moduleInfo['handle_colour'] - 1\n # Module namespace.\n self.moduleNamespace = moduleInfo['module_Namespace']\n # Generated mirror module namespace\n self.mirror_moduleNamespace = moduleInfo['mirror_module_Namespace']\n # Module container name.\n self.moduleContainer = self.moduleNamespace + ':module_container'\n\n def returnNodeInfoTransformation(self, numNodes):\n \"\"\"\n This method calculates the position(s) for module node(s) based on their quantity and provided length\n from the UI. It also takes into account the offset position of the module from the origin, based on the\n creation plane for the module.\n \"\"\"\n # List to record the positions.\n self.initNodePos = []\n if self.mirrorModule:\n self.moduleOffset = self.moduleOffset * -1\n # Axis for offset.\n axisForOffset = {'XY':'Z', 'YZ':'X', 'XZ':'Y'}[self.onPlane]\n # Record the position of the root node for the module.\n if axisForOffset == 'X':\n self.initNodePos.append([self.moduleOffset, 0, 0])\n if axisForOffset == 'Y':\n self.initNodePos.append([0, self.moduleOffset, 0])\n if axisForOffset == 'Z':\n self.initNodePos.append([0, 0, self.moduleOffset])\n # If the module has single node, return.\n if self.moduleLen == 0 or self.numNodes == 1:\n return\n # Increment for subsequent nodes in the module after root.\n increment = self.moduleLen / (numNodes - 1)\n # Calculate and append the node positions.\n incrementAxis = {'XY':'Y', 'YZ':'Y', 'XZ':'X'}[self.onPlane]\n if incrementAxis == 'Y':\n posIncrement = [0, 1, 0]\n if incrementAxis == 'X':\n posIncrement = [1, 0, 0]\n for i in range(numNodes - 1):\n self.initNodePos.append(map(lambda x,y:x+y, [c*increment for c in posIncrement], self.initNodePos[-1]))\n\n def createJointNodeModule(self):\n \"\"\"Create a joint node module.\"\"\"\n mfunc.updateAllTransforms()\n #mfunc.forceSceneUpdate()\n # Set the current namespace to root.\n cmds.namespace(setNamespace=':')\n # Create a new namespace for the module.\n cmds.namespace(add=self.moduleNamespace)\n # Create the module container.\n moduleContainer = cmds.container(name=self.moduleContainer)\n # Create an empty group for containing module handle segments.\n self.moduleHandleSegmentGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleHandleSegmentCurveGrp')\n self.moduleParentRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleParentRepresentationGrp')\n # Create an empty group for containing module hierarchy/orientation representations.\n self.moduleOrientationHierarchyRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleOrientationHierarchyRepresentationGrp')\n # Create module representation group containing the above two groups.\n self.moduleRepresentationGrp = cmds.group([self.moduleHandleSegmentGrp, self.moduleOrientationHierarchyRepresentationGrp, self.moduleParentRepresentationGrp], name=self.moduleNamespace+':moduleRepresentationObjGrp')\n # Create module extras group.\n self.moduleExtrasGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleExtrasGrp')\n # Create group under module extras to keep clusters for scaling node handle shapes.\n self.moduleNodeHandleShapeScaleClusterGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleNodeHandleShapeScaleClusterGrp', parent=self.moduleExtrasGrp)\n # Create main module group.\n self.moduleGrp = cmds.group([self.moduleRepresentationGrp, self.moduleExtrasGrp], name=self.moduleNamespace+':moduleGrp')\n # Add a custom attribute to the module group to store the number of nodes.\n cmds.addAttr(self.moduleGrp, attributeType='short', longName='numberOfNodes', defaultValue=self.numNodes, keyable=False)\n cmds.addAttr(self.moduleGrp, dataType='string', longName='nodeOrient', keyable=False)\n cmds.setAttr(self.moduleGrp+'.nodeOrient', self.nodeAxes, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='moduleParent', keyable=False)\n cmds.setAttr(self.moduleGrp+'.moduleParent', 'None', type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='onPlane', keyable=False)\n cmds.setAttr(self.moduleGrp+'.onPlane', '+'+self.onPlane, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorTranslation', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorTranslation', self.mirrorTranslationFunc, type='string')\n if self.mirrorModule:\n cmds.setAttr(self.moduleGrp+'.onPlane', '-'+self.onPlane, type='string')\n if self.mirrorModuleStatus == 'On':\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorModuleNamespace', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorModuleNamespace', self.mirror_moduleNamespace, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorRotation', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorRotation', self.mirrorRotationFunc, type='string')\n # Create a group for proxy geometry.\n if self.proxyGeoStatus:\n if self.proxyGeoElbow or self.proxyGeoBones:\n self.proxyGeoGrp = cmds.group(empty=True, name=self.moduleNamespace+':proxyGeometryGrp')\n cmds.setAttr(self.proxyGeoGrp+'.overrideEnabled', 1)\n cmds.setAttr(self.proxyGeoGrp+'.overrideDisplayType', 2)\n if self.proxyGeoElbow:\n cmds.addAttr(self.proxyGeoGrp, dataType='string', longName='elbowType', keyable=False)\n cmds.setAttr(self.proxyGeoGrp+'.elbowType', self.proxyElbowType, type='string', lock=True)\n if self.mirrorModuleStatus == 'On':\n cmds.addAttr(self.proxyGeoGrp, dataType='string', longName='mirrorInstance', keyable=False)\n cmds.setAttr(self.proxyGeoGrp+'.mirrorInstance', self.proxyGeoMirrorInstance, type='string', lock=True)\n # Create module joints group, under the module group.\n self.moduleJointsGrp = cmds.group(empty=True, parent=self.moduleGrp, name=self.moduleNamespace+':moduleJointsGrp')\n # Initialize a list to contain created module node joints.\n self.joints = []\n # Get the positions of the module nodes, where the called method updates the self.initNodePos.\n self.returnNodeInfoTransformation(self.numNodes)\n # Move the joints group to the start position for the first joint node.\n cmds.xform(self.moduleJointsGrp, worldSpace=True, translation=self.initNodePos[0])\n # Create the module nodes (joints) by their position and name them accordingly.\n index = 0\n for nodePos in self.initNodePos:\n if index == 0:\n jointName = cmds.joint(name=self.moduleNamespace+':root_node_transform', position=nodePos, radius=0.0, scaleCompensate=False)\n elif nodePos == self.initNodePos[-1]:\n jointName = cmds.joint(name=self.moduleNamespace+':end_node_transform', position=nodePos, radius=0.0, scaleCompensate=False)\n else:\n jointName = cmds.joint(name=self.moduleNamespace+':node_%s_transform'%(index), position=nodePos, radius=0.0, scaleCompensate=False)\n cmds.setAttr(jointName+'.drawStyle', 2)\n cmds.setAttr(jointName+'.rotateX', keyable=False)\n cmds.setAttr(jointName+'.rotateY', keyable=False)\n cmds.setAttr(jointName+'.rotateZ', keyable=False)\n cmds.setAttr(jointName+'.scaleX', keyable=False)\n cmds.setAttr(jointName+'.scaleY', keyable=False)\n cmds.setAttr(jointName+'.scaleZ', keyable=False)\n cmds.setAttr(jointName+'.visibility', keyable=False, channelBox=False)\n cmds.setAttr(jointName+'.radius', keyable=False, channelBox=False)\n self.joints.append(jointName)\n index += 1\n # Orient the joints.\n cmds.select(self.joints[0], replace=True)\n # For orientation we'll use the axis perpendicular to the creation plane as the up axis for secondary axis orient.\n secondAxisOrientation = {'XY':'z', 'YZ':'x', 'XZ':'y'}[self.onPlane] + 'up'\n cmds.joint(edit=True, orientJoint=self.nodeAxes.lower(), secondaryAxisOrient=secondAxisOrientation, zeroScaleOrient=True, children=True)\n\n if self.mirrorModule and self.mirrorRotationFunc == 'Behaviour':\n mirrorPlane = {'XY':False, 'YZ':False, 'XZ':False}\n mirrorPlane[self.onPlane] = True\n mirroredJoints = cmds.mirrorJoint(self.joints[0], mirrorXY=mirrorPlane['XY'], mirrorYZ=mirrorPlane['YZ'], mirrorXZ=mirrorPlane['XZ'], mirrorBehavior=True)\n cmds.delete(self.joints[0])\n self.joints = []\n for joint in mirroredJoints:\n newJoint = cmds.rename(joint, self.moduleNamespace+':'+joint)\n self.joints.append(newJoint)\n # Orient the end joint node, if the module contains more than one joint node.\n if self.numNodes > 1:\n cmds.setAttr(self.joints[-1]+'.jointOrientX', 0)\n cmds.setAttr(self.joints[-1]+'.jointOrientY', 0)\n cmds.setAttr(self.joints[-1]+'.jointOrientZ', 0)\n # Clear selection after joint orientation.\n cmds.select(clear=True)\n # Add the module transform to the module, at the position of the root node.\n moduleTransform = objects.load_xhandleShape(self.moduleNamespace+'_handle', 24, True)\n cmds.setAttr(moduleTransform[0]+'.localScaleX', 0.26)\n cmds.setAttr(moduleTransform[0]+'.localScaleY', 0.26)\n cmds.setAttr(moduleTransform[0]+'.localScaleZ', 0.26)\n cmds.setAttr(moduleTransform[0]+'.drawStyle', 8)\n cmds.setAttr(moduleTransform[0]+'.drawOrtho', 0)\n cmds.setAttr(moduleTransform[0]+'.wireframeThickness', 2)\n cmds.setAttr(moduleTransform[1]+'.scaleX', keyable=False)\n cmds.setAttr(moduleTransform[1]+'.scaleY', keyable=False)\n cmds.setAttr(moduleTransform[1]+'.scaleZ', keyable=False)\n cmds.setAttr(moduleTransform[1]+'.visibility', keyable=False)\n cmds.addAttr(moduleTransform[1], attributeType='float', longName='globalScale', hasMinValue=True, minValue=0, defaultValue=1, keyable=True)\n self.moduleTransform = cmds.rename(moduleTransform[1], self.moduleNamespace+':module_transform')\n tempConstraint = cmds.pointConstraint(self.joints[0], self.moduleTransform, maintainOffset=False)\n cmds.delete(tempConstraint)\n # Add the module transform to the module group.\n cmds.parent(self.moduleTransform, self.moduleGrp, absolute=True)\n # Set up constraints for the module transform.\n module_node_parentConstraint = cmds.parentConstraint(self.moduleTransform, self.moduleJointsGrp, maintainOffset=True, name=self.moduleNamespace+':moduleTransform_rootNode_parentConstraint')\n module_node_scaleConstraint = cmds.scaleConstraint(self.moduleTransform, self.moduleJointsGrp, maintainOffset=False, name=self.moduleNamespace+':moduleTransform_rootNode_scaleConstraint')\n cmds.connectAttr(self.moduleTransform+'.globalScale', self.moduleTransform+'.scaleX')\n cmds.connectAttr(self.moduleTransform+'.globalScale', self.moduleTransform+'.scaleY')\n cmds.connectAttr(self.moduleTransform+'.globalScale', self.moduleTransform+'.scaleZ')\n # Connect the scale attributes to an aliased 'globalScale' attribute (This could've been done on the raw def itself, but it was issuing a cycle; not sure why. But the DG eval was not cyclic).\n # Create hierarchy/orientation representation on joint node(s), depending on number of nodes in the module.\n containedNodes = self.createHandleControlRepresentation()\n if len(self.joints) == 1:\n self.moduleSingleOrientationRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleSingleOrientationRepresentationGrp', parent=self.moduleRepresentationGrp)\n singleOrientationTransform = objects.createRawSingleOrientationRepresentation()\n cmds.setAttr(singleOrientationTransform+'.scale', 0.65, 0.65, 0.65, type='double3')\n cmds.makeIdentity(singleOrientationTransform, scale=True, apply=True)\n #if self.mirrorModule and self.mirrorRotationFunc == 'Behaviour':\n #for axis in self.onPlane:\n #cmds.setAttr(singleOrientationTransform+'.scale'+axis, -1)\n #cmds.makeIdentity(singleOrientationTransform, scale=True, apply=True)\n cmds.parent(singleOrientationTransform, self.moduleSingleOrientationRepresentationGrp, absolute=True)\n cmds.rename(singleOrientationTransform, self.moduleNamespace+':'+singleOrientationTransform)\n cmds.xform(self.moduleSingleOrientationRepresentationGrp, worldSpace=True, absolute=True, translation=cmds.xform(self.joints[0], query=True, worldSpace=True, translation=True))\n cmds.parentConstraint(self.joints[0], self.moduleSingleOrientationRepresentationGrp, maintainOffset=False, name=self.moduleSingleOrientationRepresentationGrp+'_parentConstraint')\n cmds.scaleConstraint(self.moduleTransform, self.moduleSingleOrientationRepresentationGrp, maintainOffset=False, name=self.moduleSingleOrientationRepresentationGrp+'_scaleConstraint')\n for joint in self.joints:\n xhandle = objects.load_xhandleShape(joint, self.modHandleColour)\n cmds.setAttr(xhandle[0]+'.localScaleX', 0.089)\n cmds.setAttr(xhandle[0]+'.localScaleY', 0.089)\n cmds.setAttr(xhandle[0]+'.localScaleZ', 0.089)\n #cmds.parent(xhandle[0], joint, relative=True, shape=True)\n #cmds.delete(xhandle[1])\n cmds.setAttr(xhandle[0]+'.ds', 5)\n # If there's more than one node, create orientation/hierarchy representations for all joints, except for the end joint.\n # Also unparent the individual joints in the oriented joint chain to the joint group. This is needed only if there are more than one\n # joint in the module; then the unparenting will begin from the second joint, since the first (start) is already under joints group.\n if len(self.joints) > 1:\n for joint in self.joints[1:]:\n cmds.parent(joint, self.moduleJointsGrp, absolute=True)\n containedNodes += self.createOrientationHierarchyRepresentationOnNodes()\n # Clear selection.\n cmds.select(clear=True)\n # If the module contains only one node then delete the handle segment and orientation/hierarchy representation groups, since they're not needed.\n if self.numNodes == 1:\n cmds.delete([self.moduleHandleSegmentGrp, self.moduleOrientationHierarchyRepresentationGrp])\n\n containedNodes += self.createHierarchySegmentForModuleParentingRepresentation()\n\n if self.proxyGeoStatus:\n if self.proxyGeoElbow:\n self.createProxyGeo_elbows(self.proxyElbowType)\n if self.proxyGeoBones:\n self.createProxyGeo_bones()\n\n # Add the module group to the contained nodes list.\n containedNodes += [self.moduleGrp]\n # Add the contained nodes to the module container.\n mfunc.addNodesToContainer(self.moduleContainer, containedNodes, includeHierarchyBelow=True, includeShapes=True)\n # Publish contents to the container.\n # Publish the orientation representation control for module joints.\n for joint in self.joints:\n jointName = mfunc.stripMRTNamespace(joint)[1] # Nice name for the joint, used as published name.\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[joint+'.translate', jointName+'_translate'])\n if joint != self.joints[-1]:\n jointOrientationRepresentation = joint + '_orientation_representation_transform'\n jointOrientationRotateAxis = self.nodeAxes[0]\n jointOrientationRepresentationName = mfunc.stripMRTNamespace(jointOrientationRepresentation)[1]\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[jointOrientationRepresentation+'.rotate'+jointOrientationRotateAxis, jointOrientationRepresentationName+'_rotate'+jointOrientationRotateAxis])\n\n # Publish the attributes for the module transform.\n moduleTransformName = mfunc.stripMRTNamespace(self.moduleTransform)[1]\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[self.moduleTransform+'.translate', moduleTransformName+'_translate'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[self.moduleTransform+'.rotate', moduleTransformName+'_rotate'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[self.moduleTransform+'.globalScale', moduleTransformName+'_globalScale'])\n # If the module contains only single node, publish its orientation control.\n if len(self.joints) == 1:\n singleOrientationTransform = self.moduleNamespace+':single_orientation_representation_transform'\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[singleOrientationTransform+'.rotate', 'single_orientation_representation_transform_rotate'])\n # Add and publish custom attributes on the module transform.\n self.addCustomAttributesOnModuleTransform()\n if self.numNodes > 1:\n self.connectCustomOrientationReprToBoneProxies()\n #cmds.setAttr(self.moduleTransform+'.globalScale', 4)\n\n def createHierarchySegmentForModuleParentingRepresentation(self, *args):\n containedNodes = []\n #handleSegmentParts = objects.createRawHandleSegment(3)\n handleSegmentParts = objects.createRawSegmentCurve(3)\n hierarchyRepresentation = objects.createRawHierarchyRepresentation('X')\n cmds.setAttr(hierarchyRepresentation+'.scale', 1.0, 1.0, 1.0, type='double3')\n cmds.makeIdentity(hierarchyRepresentation, scale=True, apply=True)\n hierarchyRepresentationShape = cmds.listRelatives(hierarchyRepresentation, children=True, shapes=True)[0]\n cmds.setAttr(hierarchyRepresentationShape+'.overrideColor', 2)\n for node in handleSegmentParts[4]:\n if cmds.objExists(node):\n containedNodes.append(cmds.rename(node, self.moduleNamespace+':moduleParentRepresentationSegment_clusterParts_'+node))\n cmds.pointConstraint(self.joints[0], handleSegmentParts[5], maintainOffset=False, name=self.moduleNamespace+':moduleParentRepresentationSegment_startLocator_pointConstraint')\n cmds.parent([handleSegmentParts[1], handleSegmentParts[2][1], handleSegmentParts[3][1], handleSegmentParts[5], handleSegmentParts[6]], self.moduleParentRepresentationGrp, absolute=True)\n cmds.pointConstraint(handleSegmentParts[5], handleSegmentParts[6], hierarchyRepresentation, maintainOffset=False, name=self.moduleNamespace+':moduleParentRepresentationSegment_hierarchyRepresentation_pointConstraint')\n # Scale constrain the hierarchy representation to the joint in iteration.\n cmds.scaleConstraint(self.joints[0], hierarchyRepresentation, maintainOffset=False, name=self.moduleNamespace+':moduleParentRepresentationSegment_hierarchyRepresentation_scaleConstraint')\n cmds.aimConstraint(handleSegmentParts[5], hierarchyRepresentation, maintainOffset=False, aimVector=[1.0, 0.0, 0.0], upVector=[0.0, 1.0, 0.0], worldUpVector=[0.0, 1.0, 0.0], worldUpType='objectRotation', worldUpObject=handleSegmentParts[5], name=self.moduleNamespace+':moduleParentRepresentationSegment_hierarchyRepresentation_aimConstraint')\n # Parent the orientation representation pre-transform and the hierarchy representation to their appropriate group.\n cmds.parent(hierarchyRepresentation, self.moduleParentRepresentationGrp, absolute=True)\n cmds.rename(hierarchyRepresentation, self.moduleNamespace+':moduleParentRepresentationSegment_'+hierarchyRepresentation)\n tempConstraint = cmds.pointConstraint(self.joints[0], handleSegmentParts[6], maintainOffset=False)\n cmds.delete(tempConstraint)\n cmds.rename(handleSegmentParts[1], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[1])\n # Rename the 'start' and 'end' locators which constrain the cluster handles.\n cmds.rename(handleSegmentParts[5], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[5])\n cmds.rename(handleSegmentParts[6], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[6])\n # Rename the cluster handles.\n newStartClusterHandle = cmds.rename(handleSegmentParts[2][1], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[2][1])\n newEndClusterHandle = cmds.rename(handleSegmentParts[3][1], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[3][1])\n # Rename the constraints on the cluster handles. Here, it is necessary to specify the constraints by their DAG path.\n cmds.rename(newStartClusterHandle+'|'+handleSegmentParts[7].rpartition('|')[2], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[7].rpartition('|')[2])\n cmds.rename(newEndClusterHandle + '|'+handleSegmentParts[8].rpartition('|')[2], self.moduleNamespace+':moduleParentRepresentationSegment_'+handleSegmentParts[8].rpartition('|')[2])\n ##startClusterGrpParts = cmds.rename('handleControlSegmentCurve_StartClusterGroupParts', newStartClusterHandle+'_ClusterGroupParts')\n ##endClusterGrpParts = cmds.rename('handleControlSegmentCurve_EndClusterGroupParts', newEndClusterHandle+'_ClusterGroupParts')\n startClusterGrpParts = cmds.rename('segmentCurve_startClusterGroupParts', newStartClusterHandle+'_clusterGroupParts')\n endClusterGrpParts = cmds.rename('segmentCurve_endClusterGroupParts', newEndClusterHandle+'_clusterGroupParts')\n # Clear the selection, and force an update on DG.\n cmds.select(clear=True)\n cmds.setAttr(self.moduleParentRepresentationGrp+'.visibility', 0)\n # Collect the nodes.\n containedNodes.extend([newStartClusterHandle+'Cluster', newEndClusterHandle+'Cluster', startClusterGrpParts, endClusterGrpParts])\n return containedNodes\n\n def createHandleControlRepresentation(self):\n \"\"\"\n Creates handle control representation objects on module nodes when called. It also creates segments between node(s) to\n represent how the module nodes are connected.\n \"\"\"\n mfunc.updateAllTransforms()\n #mfunc.forceSceneUpdate()\n # List to collect non DAG nodes as they're generated, so that they can be added to the module container.\n containedNodes = []\n # Create handle(s) on every module node(s)(joint) in iteration.\n i = 0\n for joint in self.joints:\n # Create a raw handle object.\n ##handleNodes = objects.createRawHandle(self.modHandleColour)\n handleNodes = objects.createRawControlSurface(joint, self.modHandleColour)\n # Parent and then rename their shapes with the joint node.\n ##cmds.parent(handleNodes[1], joint, relative=True, shape=True)\n ##newHandleShape = cmds.rename(handleNodes[1], joint+'_'+handleNodes[1])\n newHandleShape = handleNodes[1]\n # Delete the empty transform for the raw handle objects.\n ##cmds.delete(handleNodes[0])\n # Select and add a cluster to the joint node, which will affect its shape node. The selection command is important here since it'll\n # update the DG in context to the joint with its new shape node. Otherwise the cluster will report 'no deformable objects' when\n # directly processing the joint or its shape node when passed in as the first argument.\n ##handleShapeScaleCluster = cmds.cluster(newHandleShape, relative=True, name=newHandleShape+'_handleShapeScaleCluster')\n handleShapeScaleCluster = cmds.cluster(newHandleShape, relative=True, name=newHandleShape+'_scaleCluster')\n # Parent the cluster handle appropriately and turn off its visibility.\n cmds.parent(handleShapeScaleCluster[1], self.moduleNodeHandleShapeScaleClusterGrp, absolute=True)\n cmds.setAttr(handleShapeScaleCluster[1]+'.visibility', 0)\n #cmds.xform(handleShapeScaleCluster[1], scalePivot=self.initNodePos[i])\n #cmds.sets(newHandleShape, add=handleShapeScaleCluster[0]+'Set')\n # Collect the cluster nodes.\n clusterNodes = cmds.listConnections(newHandleShape, source=True, destination=True)\n # Remove the tweak node.\n for node in clusterNodes:\n if cmds.nodeType(node) == 'tweak':\n cmds.delete(node)\n break\n # Update the cluster node list and collect it.\n clusterNodes = cmds.listConnections(newHandleShape, source=True, destination=True)\n containedNodes.extend(clusterNodes)\n # Create a locator and point constrain it to the joint node in iteration for indicating its world position. This will be needed later for utility purposes.\n worldPosLocator = cmds.spaceLocator(name=joint+'_worldPosLocator')[0]\n cmds.pointConstraint(joint, worldPosLocator, maintainOffset=False, name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_worldPosLocator_pointConstraint')\n # Turn off its visibility and parent it accordingly.\n cmds.setAttr(worldPosLocator + '.visibility', 0)\n cmds.setAttr(newHandleShape+'.visibility', 0)\n cmds.parent(worldPosLocator, self.moduleHandleSegmentGrp, absolute=True)\n i += 1\n # If the module contains more the one node (joint), create segment representations between the joints in hierarchy.\n if len(self.joints) > 1:\n j = 0\n # Iterate through every joint except the last joint.\n for joint in self.joints[:-1]:\n # Create a raw segment object.\n ##handleSegmentParts = objects.createRawHandleSegment(self.modHandleColour)\n handleSegmentParts = objects.createRawSegmentCurve(self.modHandleColour)\n # Rename its associated non DAG nodes and collect them.\n for node in handleSegmentParts[4]:\n if cmds.objExists(node):\n containedNodes.append(cmds.rename(node, self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_clusterParts_'+node))\n # Now set up DG connections with appropriate nodes to help limit the segment curve between the handle surfaces. This is done so that the length\n # of this segment curve can be used to adjust the length of the orientation representation control object, so that it always fits between\n # two node handle surfaces, even if they change in sizes.\n startClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=joint+'_'+handleSegmentParts[5]+'_closestPointOnSurface')\n ##cmds.connectAttr(joint+'_handleControlShape.worldSpace[0]', startClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(joint+'_controlShape.worldSpace[0]', startClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[j+1]+'_worldPosLocator.translate', startClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(startClosestPointOnSurface+'.position', handleSegmentParts[5]+'.translate')\n endClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=self.joints[j+1]+'_'+handleSegmentParts[6]+'_closestPointOnSurface')\n ##cmds.connectAttr(self.joints[j+1]+'_handleControlShape.worldSpace[0]', endClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[j+1]+'_controlShape.worldSpace[0]', endClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(joint+'_worldPosLocator.translate', endClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(endClosestPointOnSurface+'.position', handleSegmentParts[6]+'.translate')\n # Parent the segment and its related nodes to their associated group.\n cmds.parent([handleSegmentParts[1], handleSegmentParts[2][1], handleSegmentParts[3][1], handleSegmentParts[5], handleSegmentParts[6]], self.moduleHandleSegmentGrp, absolute=True)\n # Rename the nodes.\n # Rename the curve transform.\n cmds.rename(handleSegmentParts[1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+handleSegmentParts[1])\n # Rename the 'start' and 'end' locators which constrain the cluster handles.\n cmds.rename(handleSegmentParts[5], joint+'_'+handleSegmentParts[5])\n cmds.rename(handleSegmentParts[6], self.joints[j+1]+'_'+handleSegmentParts[6])\n # Rename the cluster handles.\n newStartClusterHandle = cmds.rename(handleSegmentParts[2][1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+handleSegmentParts[2][1])\n newEndClusterHandle = cmds.rename(handleSegmentParts[3][1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(self.joints[j+1])[1]+'_'+handleSegmentParts[3][1])\n # Rename the constraints on the cluster handles. Here, it is necessary to specify the constraints by their DAG path.\n cmds.rename(newStartClusterHandle+'|'+handleSegmentParts[7].rpartition('|')[2], joint+'_'+handleSegmentParts[7].rpartition('|')[2])\n cmds.rename(newEndClusterHandle + '|'+handleSegmentParts[8].rpartition('|')[2], self.joints[j+1]+'_'+handleSegmentParts[8].rpartition('|')[2])\n ##startClusterGrpParts = cmds.rename('handleControlSegmentCurve_StartClusterGroupParts', newStartClusterHandle+'_ClusterGroupParts')\n startClusterGrpParts = cmds.rename('segmentCurve_startClusterGroupParts', newStartClusterHandle+'_clusterGroupParts')\n ##endClusterGrpParts = cmds.rename('handleControlSegmentCurve_EndClusterGroupParts', newEndClusterHandle+'_ClusterGroupParts')\n endClusterGrpParts = cmds.rename('segmentCurve_endClusterGroupParts', newEndClusterHandle+'_clusterGroupParts')\n # Clear the selection, and force an update on DG.\n cmds.select(clear=True)\n # Collect the nodes.\n containedNodes.extend([newStartClusterHandle+'Cluster', newEndClusterHandle+'Cluster', startClosestPointOnSurface, endClosestPointOnSurface, startClusterGrpParts, endClusterGrpParts])\n j += 1\n return containedNodes\n\n def createOrientationHierarchyRepresentationOnNodes(self):\n \"\"\"This method creates orientation and hierarchy representation object(s) for every node except the last.\"\"\"\n # List to collect non DAG nodes as they're generated, so that they can be added to the module container.\n containedNodes = []\n # Create representation objects for every module node(s)(joint) except the last in iteration.\n index = 0\n for joint in self.joints[:-1]:\n # Create raw representation objects.\n hierarchyRepresentation = objects.createRawHierarchyRepresentation(self.nodeAxes[0])\n orientationRepresentationNodes = objects.createRawOrientationRepresentation(self.nodeAxes[0])\n if self.mirrorModule and self.mirrorRotationFunc == 'Behaviour':\n cmds.setAttr(orientationRepresentationNodes[0]+'.scale'+self.nodeAxes[2], -1)\n cmds.makeIdentity(orientationRepresentationNodes[0], scale=True, apply=True)\n # Point constrain the orientation representation pre-transform to the joint in iteration.\n cmds.pointConstraint(joint, orientationRepresentationNodes[1], maintainOffset=False, name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_orientation_representation_transformGroup_pointConstraint')\n # Get the name(reference) for the 'start' and 'end' locators(while creating the node segment representations). These locators are on the node handle shape surfaces via CPS.\n ##startLocator = joint + '_handleControlSegmentCurve_startLocator'\n ##endLocator = self.joints[index+1] + '_handleControlSegmentCurve_endLocator'\n startLocator = joint + '_segmentCurve_startLocator'\n endLocator = self.joints[index+1] + '_segmentCurve_endLocator'\n # Point constrain the hierarchy representation to the start and end locators.\n cmds.pointConstraint(startLocator, endLocator, hierarchyRepresentation, maintainOffset=False, name=joint+'_hierarchy_representation_pointConstraint')\n # Scale constrain the hierarchy representation to the joint in iteration.\n cmds.scaleConstraint(joint, hierarchyRepresentation, maintainOffset=False, name=joint+'_hierarchy_representation_scaleConstraint')\n # Aim constrain the orientation representation pre-transform and the hierarchy representation with the next joint in iteration.\n aimVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[0]]\n upVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[1]]\n cmds.aimConstraint(self.joints[index+1], orientationRepresentationNodes[1], maintainOffset=False, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(self.joints[index+1])[1]+'_orientation_representation_transformGroup_aimConstraint')\n cmds.aimConstraint(self.joints[index+1], hierarchyRepresentation, maintainOffset=False, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(self.joints[index+1])[1]+'_hierarchy_representation_aimConstraint')\n # Parent the orientation representation pre-transform and the hierarchy representation to their appropriate group.\n cmds.parent(hierarchyRepresentation, self.moduleOrientationHierarchyRepresentationGrp, absolute=True)\n cmds.parent(orientationRepresentationNodes[1], self.moduleOrientationHierarchyRepresentationGrp, absolute=True)\n # Point constrain the orientation representation to the start locator, on the surface of the shape node of the joint in iteration.\n ##cmds.pointConstraint(joint+'_handleControlSegmentCurve_startLocator', orientationRepresentationNodes[0], maintainOffset=True, name=self.moduleNamespace+':'+orientationRepresentationNodes[0]+'_basePointConstraint')\n cmds.pointConstraint(joint+'_segmentCurve_startLocator', orientationRepresentationNodes[0], maintainOffset=True, name=self.moduleNamespace+':'+orientationRepresentationNodes[0]+'_basePointConstraint')\n # Depending on the node aim axis, connect the scale attributes for the orientation representation. The scaling along the aim axis will\n # be the size of the orientation representation, proportional to the arc length of the segment curve between two nodes.\n if self.nodeAxes[0] == 'X':\n ##arclen = cmds.arclen(joint+'_handleControlSegmentCurve', constructionHistory=True)\n arclen = cmds.arclen(joint+'_segmentCurve', constructionHistory=True)\n cmds.connectAttr(arclen+'.arcLength', orientationRepresentationNodes[0]+'.scaleX')\n cmds.connectAttr(self.moduleTransform+'.globalScale', orientationRepresentationNodes[0]+'.scaleY')\n cmds.connectAttr(self.moduleTransform+'.globalScale', orientationRepresentationNodes[0]+'.scaleZ')\n ##cmds.rename(arclen, joint+'_handleControlSegmentCurve_curveInfo')\n ##containedNodes.append(joint+'_handleControlSegmentCurve_curveInfo')\n cmds.rename(arclen, joint+'_segmentCurve_curveInfo')\n containedNodes.append(joint+'_segmentCurve_curveInfo')\n if self.nodeAxes[0] == 'Y':\n ##arclen = cmds.arclen(joint+'_handleControlSegmentCurve', constructionHistory=True)\n arclen = cmds.arclen(joint+'_segmentCurve', constructionHistory=True)\n cmds.connectAttr(arclen+'.arcLength', orientationRepresentationNodes[0]+'.scaleY')\n cmds.connectAttr(self.moduleTransform+'.globalScale', orientationRepresentationNodes[0]+'.scaleX')\n cmds.connectAttr(self.moduleTransform+'.globalScale', orientationRepresentationNodes[0]+'.scaleZ')\n ##cmds.rename(arclen, joint+'_handleControlSegmentCurve_curveInfo')\n ##containedNodes.append(joint+'_handleControlSegmentCurve_curveInfo')\n cmds.rename(arclen, joint+'_segmentCurve_curveInfo')\n containedNodes.append(joint+'_segmentCurve_curveInfo')\n if self.nodeAxes[0] == 'Z':\n ##arclen = cmds.arclen(joint+'_handleControlSegmentCurve', constructionHistory=True)\n arclen = cmds.arclen(joint+'_segmentCurve', constructionHistory=True)\n cmds.connectAttr(arclen+'.arcLength', orientationRepresentationNodes[0]+'.scaleZ')\n cmds.connectAttr(self.moduleTransform+'.globalScale', orientationRepresentationNodes[0]+'.scaleX')\n cmds.connectAttr(self.moduleTransform+'.globalScale', orientationRepresentationNodes[0]+'.scaleY')\n ##cmds.rename(arclen, joint+'_handleControlSegmentCurve_curveInfo')\n ##containedNodes.append(joint+'_handleControlSegmentCurve_curveInfo')\n cmds.rename(arclen, joint+'_segmentCurve_curveInfo')\n containedNodes.append(joint+'_segmentCurve_curveInfo')\n\n # Rename the hierarchy representation, orientation representation and its pre-transform.\n cmds.rename(hierarchyRepresentation, joint+'_'+hierarchyRepresentation)\n cmds.rename(orientationRepresentationNodes[0], self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+orientationRepresentationNodes[0])\n cmds.rename(orientationRepresentationNodes[1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+orientationRepresentationNodes[1])\n index += 1\n return containedNodes\n\n def createSplineNodeModule(self, *args):\n \"\"\"Create a spline node module.\"\"\"\n #mfunc.forceSceneUpdate()\n mfunc.updateAllTransforms()\n # Set the current namespace to root.\n cmds.namespace(setNamespace=':')\n # Create a new namespace for the module.\n cmds.namespace(add=self.moduleNamespace)\n # Create the module container.\n moduleContainer = cmds.container(name=self.moduleContainer)\n # Create an empty group for containing module handle segments.\n self.moduleSplineCurveGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleSplineCurveGrp')\n # Create an empty group for containing module hierarchy/orientation representations.\n self.moduleHandleGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleHandleGrp')\n self.moduleParentRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleParentRepresentationGrp')\n # Create an empty group for containing splineAdjustCurveTransform.\n self.moduleSplineAdjustCurveGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleSplineAdjustCurveGrp')\n # Create an empty group for containing orientation representation transforms and nodes.\n self.moduleOrientationRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleOrientationRepresentationGrp')\n # Create a module representation group containing the above four groups.\n self.moduleRepresentationGrp = cmds.group([self.moduleSplineAdjustCurveGrp, self.moduleSplineCurveGrp, self.moduleHandleGrp, self.moduleOrientationRepresentationGrp, self.moduleParentRepresentationGrp], name=self.moduleNamespace+':moduleRepresentationObjGrp')\n # Create a main module group, with the representation group as the child.\n self.moduleGrp = cmds.group([self.moduleRepresentationGrp], name=self.moduleNamespace+':moduleGrp')\n # Add a custom attribute to the module group to store the number of nodes.\n cmds.addAttr(self.moduleGrp, attributeType='short', longName='numberOfNodes', defaultValue=self.numNodes, keyable=False)\n cmds.addAttr(self.moduleGrp, dataType='string', longName='nodeOrient', keyable=False)\n cmds.setAttr(self.moduleGrp+'.nodeOrient', self.nodeAxes, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='moduleParent', keyable=False)\n cmds.setAttr(self.moduleGrp+'.moduleParent', 'None', type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='onPlane', keyable=False)\n cmds.setAttr(self.moduleGrp+'.onPlane', '+'+self.onPlane, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorTranslation', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorTranslation', self.mirrorTranslationFunc, type='string')\n if self.mirrorModule:\n cmds.setAttr(self.moduleGrp+'.onPlane', '-'+self.onPlane, type='string')\n if self.mirrorModuleStatus == 'On':\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorModuleNamespace', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorModuleNamespace', self.mirror_moduleNamespace, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorRotation', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorRotation', self.mirrorRotationFunc, type='string')\n # Create a group for proxy geometry.\n if self.proxyGeoStatus and self.proxyGeoElbow:\n self.proxyGeoGrp = cmds.group(empty=True, name=self.moduleNamespace+':proxyGeometryGrp')\n cmds.setAttr(self.proxyGeoGrp+'.overrideEnabled', 1)\n cmds.setAttr(self.proxyGeoGrp+'.overrideDisplayType', 2)\n cmds.addAttr(self.proxyGeoGrp, dataType='string', longName='elbowType', keyable=False)\n cmds.setAttr(self.proxyGeoGrp+'.elbowType', self.proxyElbowType, type='string', lock=True)\n if self.mirrorModuleStatus == 'On':\n cmds.addAttr(self.proxyGeoGrp, dataType='string', longName='mirrorInstance', keyable=False)\n cmds.setAttr(self.proxyGeoGrp+'.mirrorInstance', self.proxyGeoMirrorInstance, type='string', lock=True)\n # Create a module joints group, under the module group.\n self.moduleJointsGrp = cmds.group(empty=True, parent=self.moduleGrp, name=self.moduleNamespace+':moduleJointsGrp')\n # Initialize a list to contain created module node joints.\n self.joints = []\n # Get the positions of the module nodes, where the called method updates the self.initNodePos.\n self.returnNodeInfoTransformation(numNodes=4)\n # Initialize a list to collect non DAG nodes, for adding to the module container.\n collectedNodes = []\n\n splineNodeCurve = cmds.curve(degree=3, point=self.initNodePos, worldSpace=True)\n cmds.xform(splineNodeCurve, centerPivots=True)\n cmds.rebuildCurve(splineNodeCurve, constructionHistory=False, replaceOriginal=True, rebuildType=0, degree=3, endKnots=True, keepEndPoints=True, keepRange=0, keepControlPoints=False, keepTangents=False, spans=cmds.getAttr(splineNodeCurve+'.spans'), tolerance=0.01)\n newSplineNodeCurve = cmds.rename(splineNodeCurve, self.moduleNamespace+':splineNode_curve')\n cmds.displaySmoothness(newSplineNodeCurve, pointsWire=32)\n cmds.toggle(newSplineNodeCurve, template=True, state=True)\n cmds.parent(newSplineNodeCurve, self.moduleSplineCurveGrp, absolute=True)\n\n cmds.select(clear=True)\n self.returnNodeInfoTransformation(self.numNodes)\n self.joints = []\n for index in range(len(self.initNodePos)):\n if index == 0:\n jointName = cmds.joint(name=self.moduleNamespace+':root_node_transform', position=self.initNodePos[index], radius=0.0)\n elif index == len(self.initNodePos)-1:\n jointName = cmds.joint(name=self.moduleNamespace+':end_node_transform', position=self.initNodePos[index], radius=0.0)\n else:\n jointName = cmds.joint(name=self.moduleNamespace+':node_%s_transform'%(index), position=self.initNodePos[index], radius=0.0)\n self.joints.append(jointName)\n # Orient the joints.\n cmds.select(self.joints[0], replace=True)\n # For orientation we'll use the axis perpendicular to the creation plane as the up axis for secondary axis orient.\n secondAxisOrientation = {'XY':'z', 'YZ':'x', 'XZ':'y'}[self.onPlane] + 'up'\n cmds.joint(edit=True, orientJoint=self.nodeAxes.lower(), secondaryAxisOrient=secondAxisOrientation, zeroScaleOrient=True, children=True)\n cmds.parent(self.joints[0], self.moduleJointsGrp, absolute=True)\n if self.mirrorModule and self.mirrorRotationFunc == 'Behaviour':\n mirrorPlane = {'XY':False, 'YZ':False, 'XZ':False}\n mirrorPlane[self.onPlane] = True\n mirroredJoints = cmds.mirrorJoint(self.joints[0], mirrorXY=mirrorPlane['XY'], mirrorYZ=mirrorPlane['YZ'], mirrorXZ=mirrorPlane['XZ'], mirrorBehavior=True)\n cmds.delete(self.joints[0])\n self.joints = []\n for joint in mirroredJoints:\n newJoint = cmds.rename(joint, self.moduleNamespace+':'+joint)\n self.joints.append(newJoint)\n # Orient the end joint node.\n cmds.setAttr(self.joints[-1]+'.jointOrientX', 0)\n cmds.setAttr(self.joints[-1]+'.jointOrientY', 0)\n cmds.setAttr(self.joints[-1]+'.jointOrientZ', 0)\n # Clear selection after joint orientation.\n cmds.select(clear=True)\n # Unparent the spline node joints.\n for joint in self.joints[1:]:\n cmds.parent(joint, self.moduleJointsGrp, absolute=True)\n\n u_parametersOnCurve = [1.0/(len(self.joints)-1)*c for c in xrange(len(self.joints))]\n for index in range(len(self.joints)):\n pointOnCurveInfo = cmds.createNode('pointOnCurveInfo', name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(self.joints[index])[1]+'_pointOnCurveInfo')\n cmds.connectAttr(self.moduleNamespace+':splineNode_curveShape.worldSpace', pointOnCurveInfo+'.inputCurve')\n cmds.connectAttr(pointOnCurveInfo+'.position', self.joints[index]+'.translate')\n cmds.setAttr(pointOnCurveInfo+'.parameter', u_parametersOnCurve[index])\n collectedNodes.append(pointOnCurveInfo)\n\n clusterWeights = sorted([1.0/3*c for c in xrange(4)], reverse=True)[:-1]\n startCluster = cmds.cluster([newSplineNodeCurve+'.cv[%s]'%(cv) for cv in xrange(0, 3)], relative=True, name=newSplineNodeCurve+'_startCluster')\n cmds.setAttr(startCluster[1]+'.visibility', 0)\n cmds.parent(startCluster[1], self.moduleSplineCurveGrp, absolute=True)\n for (cv, weight) in zip(xrange(0, 3), clusterWeights):\n cmds.percent(startCluster[0], '%s.cv[%s]'%(newSplineNodeCurve, cv), value=weight)\n endCluster = cmds.cluster([newSplineNodeCurve+'.cv[%s]'%(cv) for cv in xrange(3, 0, -1)], relative=True, name=newSplineNodeCurve+'_endCluster')\n cmds.setAttr(endCluster[1]+'.visibility', 0)\n cmds.parent(endCluster[1], self.moduleSplineCurveGrp, absolute=True)\n for (cv, weight) in zip(xrange(3, 0, -1), clusterWeights):\n cmds.percent(endCluster[0], '%s.cv[%s]'%(newSplineNodeCurve, cv), value=weight)\n collectedNodes.extend([startCluster[0], endCluster[0]])\n\n # Add the module transform to the module, at the position of the root node.\n\n startHandle = objects.load_xhandleShape(self.moduleNamespace+'_startHandle', 11, True)\n cmds.setAttr(startHandle[0]+'.localScaleX', 0.4)\n cmds.setAttr(startHandle[0]+'.localScaleY', 0.4)\n cmds.setAttr(startHandle[0]+'.localScaleZ', 0.4)\n cmds.setAttr(startHandle[0]+'.drawStyle', 3)\n cmds.setAttr(startHandle[0]+'.wireframeThickness', 2)\n cmds.setAttr(startHandle[1]+'.rotateX', keyable=False)\n cmds.setAttr(startHandle[1]+'.rotateY', keyable=False)\n cmds.setAttr(startHandle[1]+'.rotateZ', keyable=False)\n cmds.setAttr(startHandle[1]+'.scaleX', keyable=False)\n cmds.setAttr(startHandle[1]+'.scaleY', keyable=False)\n cmds.setAttr(startHandle[1]+'.scaleZ', keyable=False)\n cmds.setAttr(startHandle[1]+'.visibility', keyable=False)\n newStartHandle = cmds.rename(startHandle[1], self.moduleNamespace+':splineStartHandleTransform')\n\n tempConstraint = cmds.pointConstraint(self.joints[0], newStartHandle, maintainOffset=False)\n cmds.delete(tempConstraint)\n cmds.pointConstraint(newStartHandle, startCluster[1], maintainOffset=True, name=startCluster[1]+'_parentConstraint')\n cmds.parent(newStartHandle, self.moduleHandleGrp, absolute=True)\n\n endHandle = objects.load_xhandleShape(self.moduleNamespace+'_endHandle', 10, True)\n cmds.setAttr(endHandle[0]+'.localScaleX', 0.35)\n cmds.setAttr(endHandle[0]+'.localScaleY', 0.35)\n cmds.setAttr(endHandle[0]+'.localScaleZ', 0.35)\n cmds.setAttr(endHandle[0]+'.drawStyle', 3)\n cmds.setAttr(endHandle[0]+'.wireframeThickness', 2)\n cmds.setAttr(endHandle[1]+'.rotateX', keyable=False)\n cmds.setAttr(endHandle[1]+'.rotateY', keyable=False)\n cmds.setAttr(endHandle[1]+'.rotateZ', keyable=False)\n cmds.setAttr(endHandle[1]+'.scaleX', keyable=False)\n cmds.setAttr(endHandle[1]+'.scaleY', keyable=False)\n cmds.setAttr(endHandle[1]+'.scaleZ', keyable=False)\n cmds.setAttr(endHandle[1]+'.visibility', keyable=False)\n newEndHandle = cmds.rename(endHandle[1], self.moduleNamespace+':splineEndHandleTransform')\n\n tempConstraint = cmds.pointConstraint(self.joints[-1], newEndHandle, maintainOffset=False)\n cmds.delete(tempConstraint)\n cmds.pointConstraint(newEndHandle, endCluster[1], maintainOffset=True, name=endCluster[1]+'_parentConstraint')\n cmds.parent(newEndHandle, self.moduleHandleGrp, absolute=True)\n\n splineAdjustCurveTransformList = []\n for (index, startWeight, endWeight) in [(0, 1, 0), (1, 0.66, 0.33), (2, 0.33, 0.66), (3, 0, 1)]:\n splineAdjustCurveTransforms = objects.createRawSplineAdjustCurveTransform(self.modHandleColour)\n cmds.setAttr(splineAdjustCurveTransforms[0]+'.scale', 0.8, 0.8, 0.8, type='double3')\n cmds.makeIdentity(splineAdjustCurveTransforms[0], scale=True, apply=True)\n newSplineAdjustCurvePreTransform = cmds.rename(splineAdjustCurveTransforms[0], self.moduleNamespace+':'+splineAdjustCurveTransforms[0].partition('_')[0]+'_'+str(index+1)+'_'+splineAdjustCurveTransforms[0].partition('_')[2])\n newSplineAdjustCurveTransform = cmds.rename(splineAdjustCurveTransforms[1], self.moduleNamespace+':'+splineAdjustCurveTransforms[1].partition('_')[0]+'_'+str(index+1)+'_'+splineAdjustCurveTransforms[1].partition('_')[2])\n splineAdjustCurveTransformList.append(newSplineAdjustCurveTransform)\n\n splineAdjustCurveCluster = cmds.cluster('%s.cv[%s]'%(newSplineNodeCurve, index), relative=True, name=newSplineAdjustCurveTransform+'_Cluster')\n cmds.setAttr(splineAdjustCurveCluster[1]+'.visibility', 0)\n collectedNodes.append(splineAdjustCurveCluster[0])\n\n tempConstraint = cmds.pointConstraint(splineAdjustCurveCluster[1], newSplineAdjustCurvePreTransform, maintainOffset=False)\n cmds.delete(tempConstraint)\n\n startPointConstraint = cmds.pointConstraint(newStartHandle, newSplineAdjustCurvePreTransform, maintainOffset=False, weight=startWeight, name=newSplineAdjustCurvePreTransform+'_startHandle_pointConstraint')\n endPointConstraint = cmds.pointConstraint(newEndHandle, newSplineAdjustCurvePreTransform, maintainOffset=False, weight=endWeight, name=newSplineAdjustCurvePreTransform+'_endHandle_pointConstraint')\n\n clusterGroup = cmds.group(splineAdjustCurveCluster[1], name=splineAdjustCurveCluster[1]+'_preTransform')\n cmds.parent(clusterGroup, newSplineAdjustCurvePreTransform, absolute=True)\n cmds.pointConstraint(newSplineAdjustCurveTransform, splineAdjustCurveCluster[1], maintainOffset=True, name=splineAdjustCurveCluster[1]+'_pointConstraint')\n\n cmds.parent(newSplineAdjustCurvePreTransform, self.moduleSplineAdjustCurveGrp, absolute=True)\n\n if index == 3:\n tangentConstraintTargetObject = newSplineAdjustCurveTransform\n\n worldReferenceTransform = cmds.createNode('transform', name=self.moduleNamespace+':orientationWorldReferenceTransform', parent=self.moduleOrientationRepresentationGrp)\n aimVector={'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[0]]\n upVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[1]]\n worldUpVector = {'XY':[0.0, 0.0, 1.0], 'YZ':[1.0, 0.0, 0.0], 'XZ':[0.0, 1.0, 0.0]}[self.onPlane]\n if self.mirrorModule and self.mirrorRotationFunc == 'Behaviour':\n aimVector = [i*-1 for i in aimVector]\n pairBlend_inputDriven = []\n for index in range(len(self.joints)):\n pairBlend = cmds.createNode('pairBlend', name=self.joints[index]+'_pairBlend', skipSelect=True)\n pairBlend_inputDriven.append(pairBlend)\n orientConstraint = cmds.orientConstraint(worldReferenceTransform, self.joints[index], maintainOffset=False, name=self.joints[index]+'_orientConstraint')[0]\n cmds.disconnectAttr(orientConstraint+'.constraintRotateX', self.joints[index]+'.rotateX')\n cmds.disconnectAttr(orientConstraint+'.constraintRotateY', self.joints[index]+'.rotateY')\n cmds.disconnectAttr(orientConstraint+'.constraintRotateZ', self.joints[index]+'.rotateZ')\n tangentConstraint = cmds.tangentConstraint(self.moduleNamespace+':splineNode_curve', self.joints[index], aimVector=aimVector, upVector=upVector, worldUpType='objectrotation', worldUpVector=worldUpVector, worldUpObject=tangentConstraintTargetObject, name=self.joints[index]+'_tangentConstraint')[0]\n cmds.disconnectAttr(tangentConstraint+'.constraintRotateX', self.joints[index]+'.rotateX')\n cmds.disconnectAttr(tangentConstraint+'.constraintRotateY', self.joints[index]+'.rotateY')\n cmds.disconnectAttr(tangentConstraint+'.constraintRotateZ', self.joints[index]+'.rotateZ')\n cmds.connectAttr(orientConstraint+'.constraintRotateX', pairBlend+'.inRotateX1')\n cmds.connectAttr(orientConstraint+'.constraintRotateY', pairBlend+'.inRotateY1')\n cmds.connectAttr(orientConstraint+'.constraintRotateZ', pairBlend+'.inRotateZ1')\n cmds.connectAttr(tangentConstraint+'.constraintRotateX', pairBlend+'.inRotateX2')\n cmds.connectAttr(tangentConstraint+'.constraintRotateY', pairBlend+'.inRotateY2')\n cmds.connectAttr(tangentConstraint+'.constraintRotateZ', pairBlend+'.inRotateZ2')\n cmds.connectAttr(pairBlend+'.outRotateX', self.joints[index]+'.rotateX')\n cmds.connectAttr(pairBlend+'.outRotateY', self.joints[index]+'.rotateY')\n cmds.connectAttr(pairBlend+'.outRotateZ', self.joints[index]+'.rotateZ')\n cmds.setAttr(pairBlend+'.rotateMode', 2)\n collectedNodes.extend(pairBlend_inputDriven)\n\n clusterNodes = cmds.listConnections(newSplineNodeCurve+'Shape', source=True, destination=True)\n for node in clusterNodes:\n if cmds.nodeType(node) == 'tweak':\n cmds.delete(node)\n break\n collectedNodes.append(self.moduleGrp)\n newRawLocaAxesInfoRepresentationTransforms = []\n for joint in self.joints:\n rawLocalAxesInfoRepresentationTransforms = objects.createRawLocalAxesInfoRepresentation()\n cmds.setAttr(rawLocalAxesInfoRepresentationTransforms[0]+'.scale', 0.8, 0.8, 0.8, type='double3')\n cmds.makeIdentity(rawLocalAxesInfoRepresentationTransforms[0], scale=True, apply=True)\n cmds.parent(rawLocalAxesInfoRepresentationTransforms[0], self.moduleOrientationRepresentationGrp)\n\n newRawLocaAxesInfoRepresentationPreTransform = cmds.rename(rawLocalAxesInfoRepresentationTransforms[0], joint+'_'+rawLocalAxesInfoRepresentationTransforms[0])\n newRawLocaAxesInfoRepresentationTransform = cmds.rename(rawLocalAxesInfoRepresentationTransforms[1], joint+'_'+rawLocalAxesInfoRepresentationTransforms[1])\n\n cmds.addAttr(newRawLocaAxesInfoRepresentationTransform, attributeType='enum', longName='tangent_Up_vector', enumName='Original:Reversed:', defaultValue=0, keyable=True)\n\n for (driver, driven) in ((1, -1), (0, 1)):\n cmds.setAttr(newRawLocaAxesInfoRepresentationTransform+'.tangent_Up_vector', driver)\n cmds.setAttr(joint+'_tangentConstraint.upVector'+self.nodeAxes[1].upper(), driven)\n cmds.setDrivenKeyframe(joint+'_tangentConstraint.upVector'+self.nodeAxes[1].upper(), currentDriver=newRawLocaAxesInfoRepresentationTransform+'.tangent_Up_vector')\n\n xhandle = objects.load_xhandleShape(joint, 2)\n cmds.setAttr(xhandle[0]+'.localScaleX', 0.09)\n cmds.setAttr(xhandle[0]+'.localScaleY', 0.09)\n cmds.setAttr(xhandle[0]+'.localScaleZ', 0.09)\n cmds.setAttr(xhandle[0]+'.ds', 5)\n\n cmds.pointConstraint(joint, newRawLocaAxesInfoRepresentationPreTransform, maintainOffset=False, name=newRawLocaAxesInfoRepresentationPreTransform+'_pointConstraint')\n cmds.orientConstraint(joint, newRawLocaAxesInfoRepresentationPreTransform, maintainOffset=False, name=newRawLocaAxesInfoRepresentationPreTransform+'_orientConstraint')\n\n newRawLocaAxesInfoRepresentationTransforms.append(newRawLocaAxesInfoRepresentationTransform)\n\n cmds.select(clear=True)\n\n collectedNodes += self.createHierarchySegmentForModuleParentingRepresentation()\n\n if self.proxyGeoStatus and self.proxyGeoElbow:\n self.createProxyGeo_elbows(self.proxyElbowType)\n\n mfunc.addNodesToContainer(self.moduleContainer, collectedNodes, includeHierarchyBelow=True, includeShapes=True)\n\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[newStartHandle+'.translate', mfunc.stripMRTNamespace(newStartHandle)[1]+'_translate'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[newEndHandle+'.translate', mfunc.stripMRTNamespace(newEndHandle)[1]+'_translate'])\n for transform in splineAdjustCurveTransformList:\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[transform+'.translate', mfunc.stripMRTNamespace(transform)[1]+'_translate'])\n\n self.addCustomAttributesOnModuleTransform()\n cmds.connectAttr(newStartHandle+'.Global_size', newStartHandle+'.scaleX')\n cmds.connectAttr(newStartHandle+'.Global_size', newStartHandle+'.scaleY')\n cmds.connectAttr(newStartHandle+'.Global_size', newStartHandle+'.scaleZ')\n cmds.connectAttr(newStartHandle+'.Global_size', newEndHandle+'.scaleX')\n cmds.connectAttr(newStartHandle+'.Global_size', newEndHandle+'.scaleY')\n cmds.connectAttr(newStartHandle+'.Global_size', newEndHandle+'.scaleZ')\n\n for i in range(1, 5):\n for j in ['X', 'Y', 'Z']:\n cmds.connectAttr(newStartHandle+'.Global_size', self.moduleNamespace+':spline_'+str(i)+'_adjustCurve_transform.scale'+str(j))\n for joint in self.joints:\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'Shape.addScaleX')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'Shape.addScaleY')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'Shape.addScaleZ')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'_localAxesInfoRepresentation_preTransform.scaleX')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'_localAxesInfoRepresentation_preTransform.scaleY')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'_localAxesInfoRepresentation_preTransform.scaleZ')\n if self.proxyGeoStatus and self.proxyGeoElbow:\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'_proxy_elbow_geo_scaleTransform.scaleX')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'_proxy_elbow_geo_scaleTransform.scaleY')\n cmds.connectAttr(newStartHandle+'.Global_size', joint+'_proxy_elbow_geo_scaleTransform.scaleZ')\n\n cmds.connectAttr(newStartHandle+'.Node_Orientation_Info', self.moduleOrientationRepresentationGrp+'.visibility')\n for transform in newRawLocaAxesInfoRepresentationTransforms:\n rotateAxis = self.nodeAxes[0]\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[transform+'.tangent_Up_vector', mfunc.stripMRTNamespace(transform)[1]+'_tangent_Up_Vector'])\n cmds.connectAttr(newStartHandle+'.Axis_Rotate', transform+'.rotate'+rotateAxis)\n cmds.connectAttr(newStartHandle+'.Node_Local_Orientation_Representation_Size', transform+'.scaleX')\n cmds.connectAttr(newStartHandle+'.Node_Local_Orientation_Representation_Size', transform+'.scaleY')\n cmds.connectAttr(newStartHandle+'.Node_Local_Orientation_Representation_Size', transform+'.scaleZ')\n\n cmds.setAttr(newStartHandle+'.Node_Local_Orientation_Representation_Size', 0.7)\n\n cmds.namespace(setNamespace=self.moduleNamespace)\n namespaceNodes = cmds.namespaceInfo(listOnlyDependencyNodes=True)\n animCurveNodes = cmds.ls(namespaceNodes, type='animCurve')\n mfunc.addNodesToContainer(self.moduleContainer, animCurveNodes)\n cmds.namespace(setNamespace=':')\n\n if not self.showOrientation:\n cmds.setAttr(newStartHandle+'.Node_Orientation_Info', 0)\n self.connectCustomOrientationReprToBoneProxies()\n #cmds.setAttr(newStartHandle+'.Global_size', 4)\n\n def checkPlaneAxisDirectionForIKhingeForOrientationRepresentation(self):\n offsetAxisVectorTransforms = {'XY':[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], 'YZ':[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], 'XZ':[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]}[self.onPlane]\n planeAxisOffset = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}\n IKhingePlaneAxisVectorTransforms = []\n tempLocatorForWorldTransformInfo_IKhingeOrientationVector = cmds.spaceLocator()[0]\n tempConstraint = cmds.parentConstraint(self.joints[1], tempLocatorForWorldTransformInfo_IKhingeOrientationVector, maintainOffset=False)\n cmds.delete(tempConstraint)\n cmds.parent(tempLocatorForWorldTransformInfo_IKhingeOrientationVector, self.joints[1])\n IKhingePlaneAxisVectorTransforms.append(cmds.xform(tempLocatorForWorldTransformInfo_IKhingeOrientationVector, query=True, worldSpace=True, translation=True))\n cmds.xform(tempLocatorForWorldTransformInfo_IKhingeOrientationVector, objectSpace=True, relative=True, translation=planeAxisOffset[self.nodeAxes[2]])\n IKhingePlaneAxisVectorTransforms.append(cmds.xform(tempLocatorForWorldTransformInfo_IKhingeOrientationVector, query=True, worldSpace=True, translation=True))\n cmds.delete(tempLocatorForWorldTransformInfo_IKhingeOrientationVector)\n\n direction_cosine = mfunc.returnDotProductDirection(offsetAxisVectorTransforms[0], offsetAxisVectorTransforms[1], IKhingePlaneAxisVectorTransforms[0], IKhingePlaneAxisVectorTransforms[1])[0]\n\n hingePreferredOrientationRepresentationAffectDueToIKRotation_directionCheck = {'XY':1.0, 'YZ':-1.0, 'XZ':1.0}[self.onPlane]\n\n if hingePreferredOrientationRepresentationAffectDueToIKRotation_directionCheck == direction_cosine:\n return True\n else:\n return False\n\n def createHingeNodeModule(self):\n #mfunc.forceSceneUpdate()\n mfunc.updateAllTransforms()\n # Set the current namespace to root.\n cmds.namespace(setNamespace=':')\n # Create a new namespace for the module.\n cmds.namespace(add=self.moduleNamespace)\n # Clear selection.\n cmds.select(clear=True)\n # Create the module container.\n moduleContainer = cmds.container(name=self.moduleContainer)\n # Create an empty group for containing module handle segments.\n self.moduleHandleSegmentGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleHandleSegmentCurveGrp')\n self.moduleParentRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleParentRepresentationGrp')\n # Create an empty group for containing module hand hierarchy representations.\n self.moduleHierarchyRepresentationGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleHierarchyRepresentationGrp')\n # Create a module representation group containing the above two groups.\n self.moduleRepresentationGrp = cmds.group([self.moduleHandleSegmentGrp, self.moduleHierarchyRepresentationGrp, self.moduleParentRepresentationGrp], name=self.moduleNamespace+':moduleRepresentationObjGrp')\n # Create a module extras group.\n self.moduleExtrasGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleExtrasGrp')\n # Create a group under module extras to keep clusters for scaling node handle shapes.\n self.moduleNodeHandleShapeScaleClusterGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleNodeHandleShapeScaleClusterGrp', parent=self.moduleExtrasGrp)\n # Create a group under module extras to keep the IK segment aim nodes.\n self.moduleIKsegmentMidAimGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleIKsegmentMidAimGrp', parent=self.moduleExtrasGrp)\n # Create a group to contain the IK nodes and handles.\n self.moduleIKnodesGrp = cmds.group(empty=True, name=self.moduleNamespace+':moduleIKnodesGrp')\n # Create a main module group.\n self.moduleGrp = cmds.group([self.moduleRepresentationGrp, self.moduleExtrasGrp, self.moduleIKnodesGrp], name=self.moduleNamespace+':moduleGrp')\n\n # Add a custom attribute to the module group to store the number of nodes.\n cmds.addAttr(self.moduleGrp, attributeType='short', longName='numberOfNodes', defaultValue=self.numNodes, keyable=False)\n cmds.addAttr(self.moduleGrp, dataType='string', longName='nodeOrient', keyable=False)\n cmds.setAttr(self.moduleGrp+'.nodeOrient', self.nodeAxes, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='moduleParent', keyable=False)\n cmds.setAttr(self.moduleGrp+'.moduleParent', 'None', type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='onPlane', keyable=False)\n cmds.setAttr(self.moduleGrp+'.onPlane', '+'+self.onPlane, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorTranslation', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorTranslation', self.mirrorTranslationFunc, type='string')\n if self.mirrorModule:\n cmds.setAttr(self.moduleGrp+'.onPlane', '-'+self.onPlane, type='string')\n if self.mirrorModuleStatus == 'On':\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorModuleNamespace', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorModuleNamespace', self.mirror_moduleNamespace, type='string')\n cmds.addAttr(self.moduleGrp, dataType='string', longName='mirrorRotation', keyable=False)\n cmds.setAttr(self.moduleGrp+'.mirrorRotation', self.mirrorRotationFunc, type='string')\n # Create a group for proxy geometry.\n if self.proxyGeoStatus:\n if self.proxyGeoElbow or self.proxyGeoBones:\n self.proxyGeoGrp = cmds.group(empty=True, name=self.moduleNamespace+':proxyGeometryGrp')\n cmds.setAttr(self.proxyGeoGrp+'.overrideEnabled', 1)\n cmds.setAttr(self.proxyGeoGrp+'.overrideDisplayType', 2)\n if self.proxyGeoElbow:\n cmds.addAttr(self.proxyGeoGrp, dataType='string', longName='elbowType', keyable=False)\n cmds.setAttr(self.proxyGeoGrp+'.elbowType', self.proxyElbowType, type='string', lock=True)\n if self.mirrorModuleStatus == 'On':\n cmds.addAttr(self.proxyGeoGrp, dataType='string', longName='mirrorInstance', keyable=False)\n cmds.setAttr(self.proxyGeoGrp+'.mirrorInstance', self.proxyGeoMirrorInstance, type='string', lock=True)\n # Create a main module joints group, under the module group.\n self.moduleJointsGrp = cmds.group(empty=True, parent=self.moduleGrp, name=self.moduleNamespace+':moduleJointsGrp')\n # Initialize a list to contain created module node joints.\n self.joints = []\n # Get the positions of the module nodes, where the called method updates the self.initNodePos.\n self.returnNodeInfoTransformation(self.numNodes)\n # Move the joints group and the nodule IK nodes to the start position for the first joint node.\n cmds.xform(self.moduleJointsGrp, worldSpace=True, translation=self.initNodePos[0])\n cmds.xform(self.moduleIKnodesGrp, worldSpace=True, translation=self.initNodePos[0])\n\n containedNodes = []\n offset = self.moduleLen / 10.0\n hingeOffset = {'YZ':[offset, 0.0, 0.0], 'XZ':[0.0, offset, 0.0], 'XY':[0.0, 0.0, offset]}[self.onPlane]\n self.initNodePos[1] = map(lambda x,y: x+y, self.initNodePos[1], hingeOffset)\n\n # Create the module nodes (joints) by their position and name them accordingly.\n index = 0\n for nodePos in self.initNodePos:\n if index == 0:\n jointName = cmds.joint(name=self.moduleNamespace+':root_node_transform', position=nodePos, radius=0.0, scaleCompensate=False)\n elif nodePos == self.initNodePos[-1]:\n jointName = cmds.joint(name=self.moduleNamespace+':end_node_transform', position=nodePos, radius=0.0, scaleCompensate=False)\n else:\n jointName = cmds.joint(name=self.moduleNamespace+':node_%s_transform'%(index), position=nodePos, radius=0.0, scaleCompensate=False)\n cmds.setAttr(jointName+'.drawStyle', 2)\n self.joints.append(jointName)\n index += 1\n # Orient the joints.\n cmds.select(self.joints[0], replace=True)\n # For orientation we'll use the axis perpendicular to the creation plane as the up axis for secondary axis orient.\n secondAxisOrientation = {'XY':'z', 'YZ':'x', 'XZ':'y'}[self.onPlane] + 'up'\n cmds.joint(edit=True, orientJoint=self.nodeAxes.lower(), secondaryAxisOrient=secondAxisOrientation, zeroScaleOrient=True, children=True)\n\n if self.mirrorModule and self.mirrorRotationFunc == 'Behaviour':\n mirrorPlane = {'XY':False, 'YZ':False, 'XZ':False}\n mirrorPlane[self.onPlane] = True\n mirroredJoints = cmds.mirrorJoint(self.joints[0], mirrorXY=mirrorPlane['XY'], mirrorYZ=mirrorPlane['YZ'], mirrorXZ=mirrorPlane['XZ'], mirrorBehavior=True)\n cmds.delete(self.joints[0])\n self.joints = []\n for joint in mirroredJoints:\n newJoint = cmds.rename(joint, self.moduleNamespace+':'+joint)\n self.joints.append(newJoint)\n # Orient the end joint node.\n cmds.setAttr(self.joints[-1]+'.jointOrientX', 0)\n cmds.setAttr(self.joints[-1]+'.jointOrientY', 0)\n cmds.setAttr(self.joints[-1]+'.jointOrientZ', 0)\n # Clear selection after joint orientation.\n cmds.select(clear=True)\n\n ikNodes = cmds.ikHandle(startJoint=self.joints[0], endEffector=self.joints[-1], name=self.moduleNamespace+':rootToEndNode_ikHandle', solver='ikRPsolver')\n ikEffector = cmds.rename(ikNodes[1], self.moduleNamespace+':rootToEndNode_ikEffector')\n ikHandle = ikNodes[0]\n cmds.parent(ikHandle, self.moduleIKnodesGrp, absolute=True)\n cmds.setAttr(ikHandle + '.visibility', 0)\n\n cmds.xform(ikHandle, worldSpace=True, absolute=True, rotation=cmds.xform(self.joints[-1], query=True, worldSpace=True, absolute=True, rotation=True))\n\n ##rootHandle = objects.createRawHandle(self.modHandleColour)\n rootHandle = objects.createRawControlSurface(self.joints[0], self.modHandleColour, True)\n ##newRootHandle = cmds.rename(rootHandle[0], self.joints[0]+'_'+rootHandle[0])\n cmds.setAttr(rootHandle[0]+'.rotateX', keyable=False)\n cmds.setAttr(rootHandle[0]+'.rotateY', keyable=False)\n cmds.setAttr(rootHandle[0]+'.rotateZ', keyable=False)\n cmds.setAttr(rootHandle[0]+'.scaleX', keyable=False)\n cmds.setAttr(rootHandle[0]+'.scaleY', keyable=False)\n cmds.setAttr(rootHandle[0]+'.scaleZ', keyable=False)\n cmds.setAttr(rootHandle[0]+'.visibility', keyable=False)\n cmds.xform(rootHandle[0], worldSpace=True, absolute=True, translation=self.initNodePos[0])\n rootHandleConstraint = cmds.pointConstraint(rootHandle[0], self.joints[0], maintainOffset=False, name=self.joints[0]+'_pointConstraint')\n cmds.parent(rootHandle[0], self.moduleIKnodesGrp, absolute=True)\n\n ##elbowHandle = objects.createRawHandle(self.modHandleColour)\n elbowHandle = objects.createRawControlSurface(self.joints[1], self.modHandleColour, True)\n ##newElbowHandle = cmds.rename(elbowHandle[0], self.joints[1]+'_'+elbowHandle[0])\n cmds.setAttr(elbowHandle[0]+'.rotateX', keyable=False)\n cmds.setAttr(elbowHandle[0]+'.rotateY', keyable=False)\n cmds.setAttr(elbowHandle[0]+'.rotateZ', keyable=False)\n cmds.setAttr(elbowHandle[0]+'.scaleX', keyable=False)\n cmds.setAttr(elbowHandle[0]+'.scaleY', keyable=False)\n cmds.setAttr(elbowHandle[0]+'.scaleZ', keyable=False)\n cmds.setAttr(elbowHandle[0]+'.visibility', keyable=False)\n cmds.xform(elbowHandle[0], worldSpace=True, absolute=True, translation=self.initNodePos[1])\n elbowHandleConstraint = cmds.poleVectorConstraint(elbowHandle[0], ikHandle, name=ikHandle+'_poleVectorConstraint')\n cmds.parent(elbowHandle[0], self.moduleIKnodesGrp, absolute=True)\n\n ##endHandle = objects.createRawHandle(self.modHandleColour)\n endHandle = objects.createRawControlSurface(self.joints[-1], self.modHandleColour, True)\n ##newEndHandle = cmds.rename(endHandle[0], self.joints[-1]+'_'+endHandle[0])\n cmds.setAttr(endHandle[0]+'.rotateX', keyable=False)\n cmds.setAttr(endHandle[0]+'.rotateY', keyable=False)\n cmds.setAttr(endHandle[0]+'.rotateZ', keyable=False)\n cmds.setAttr(endHandle[0]+'.scaleX', keyable=False)\n cmds.setAttr(endHandle[0]+'.scaleY', keyable=False)\n cmds.setAttr(endHandle[0]+'.scaleZ', keyable=False)\n cmds.setAttr(endHandle[0]+'.visibility', keyable=False)\n cmds.xform(endHandle[0], worldSpace=True, absolute=True, translation=self.initNodePos[2])\n endHandleConstraint = cmds.pointConstraint(endHandle[0], ikHandle, maintainOffset=False, name=ikHandle+'_pointConstraint')\n cmds.parent(endHandle[0], self.moduleIKnodesGrp, absolute=True)\n\n for startPos, endPos, drivenJoint in [(rootHandle[0], elbowHandle[0], self.joints[1]), (elbowHandle[0], endHandle[0], self.joints[2])]:\n # Create a distance node to measure the distance between two joint handles, and connect the worldSpace translate values.\n segmentDistance = cmds.createNode('distanceBetween', name=drivenJoint+'_distanceNode')\n cmds.connectAttr(startPos+'.translate', segmentDistance+'.point1')\n cmds.connectAttr(endPos+'.translate', segmentDistance+'.point2')\n #\n distanceDivideFactor = cmds.createNode('multiplyDivide', name=drivenJoint+'_distanceDivideFactor')\n cmds.setAttr(distanceDivideFactor + '.operation', 2)\n aimAxis = self.nodeAxes[0]\n originalLength = cmds.getAttr(drivenJoint+'.translate'+aimAxis)\n cmds.connectAttr(segmentDistance+'.distance', distanceDivideFactor+'.input1'+aimAxis)\n cmds.setAttr(distanceDivideFactor+'.input2'+aimAxis, originalLength)\n\n drivenJointAimTranslateMultiply = cmds.createNode('multiplyDivide', name=drivenJoint+'_drivenJointAimTranslateMultiply')\n cmds.connectAttr(distanceDivideFactor+'.output'+aimAxis, drivenJointAimTranslateMultiply+'.input1'+aimAxis)\n cmds.setAttr(drivenJointAimTranslateMultiply+'.input2'+aimAxis, math.fabs(originalLength))\n cmds.connectAttr(drivenJointAimTranslateMultiply+'.output'+aimAxis, drivenJoint+'.translate'+aimAxis)\n containedNodes.extend([segmentDistance, distanceDivideFactor, drivenJointAimTranslateMultiply])\n mfunc.updateAllTransforms()\n #mfunc.forceSceneUpdate()\n i = 0\n for joint in self.joints:\n\n ##handleShape = joint+'_handleControlShape'\n handleShape = joint+'_controlShape'\n ##handleShapeScaleCluster = cmds.cluster(handleShape, relative=True, name=handleShape+'_handleShapeScaleCluster')\n handleShapeScaleCluster = cmds.cluster(handleShape, relative=True, name=handleShape+'_scaleCluster')\n cmds.parent(handleShapeScaleCluster[1], self.moduleNodeHandleShapeScaleClusterGrp, absolute=True)\n cmds.setAttr(handleShapeScaleCluster[1]+'.visibility', 0)\n # Collect the cluster nodes.\n clusterNodes = cmds.listConnections(handleShape, source=True, destination=True)\n # Remove the tweak node.\n for node in clusterNodes:\n if cmds.nodeType(node) == 'tweak':\n cmds.delete(node)\n break\n # Update the cluster node list.\n clusterNodes = cmds.listConnections(handleShape, source=True, destination=True)\n containedNodes.extend(clusterNodes)\n\n worldPosLocator = cmds.spaceLocator(name=joint+'_worldPosLocator')[0]\n cmds.setAttr(worldPosLocator + '.visibility', 0)\n worldPosLocator_constraint = cmds.pointConstraint(joint, worldPosLocator, maintainOffset=False, name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_worldPosLocator_pointConstraint')\n cmds.parent(worldPosLocator, self.moduleHandleSegmentGrp, absolute=True)\n i += 1\n\n j = 0\n for joint in self.joints:\n if joint == self.joints[-1]:\n break\n #handleSegmentParts = objects.createRawHandleSegment(self.modHandleColour)\n handleSegmentParts = objects.createRawSegmentCurve(self.modHandleColour)\n extra_nodes = []\n for node in handleSegmentParts[4]:\n if cmds.objExists(node):\n extra_nodes.append(cmds.rename(node, self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_clusterParts_'+node))\n containedNodes.extend(extra_nodes)\n\n startClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=joint+'_'+handleSegmentParts[5]+'_closestPointOnSurface')\n ##cmds.connectAttr(joint+'_handleControlShape.worldSpace[0]', startClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(joint+'_controlShape.worldSpace[0]', startClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[j+1]+'_worldPosLocator.translate', startClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(startClosestPointOnSurface+'.position', handleSegmentParts[5]+'.translate')\n endClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=self.joints[j+1]+'_'+handleSegmentParts[6]+'_closestPointOnSurface')\n ##cmds.connectAttr(self.joints[j+1]+'_handleControlShape.worldSpace[0]', endClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[j+1]+'_controlShape.worldSpace[0]', endClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(joint+'_worldPosLocator.translate', endClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(endClosestPointOnSurface+'.position', handleSegmentParts[6]+'.translate')\n\n cmds.parent([handleSegmentParts[1], handleSegmentParts[2][1], handleSegmentParts[3][1], handleSegmentParts[5], handleSegmentParts[6]], self.moduleHandleSegmentGrp, absolute=True)\n\n cmds.rename(handleSegmentParts[1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+handleSegmentParts[1])\n\n newStartLocator = cmds.rename(handleSegmentParts[5], joint+'_'+handleSegmentParts[5])\n newEndLocator = cmds.rename(handleSegmentParts[6], self.joints[j+1]+'_'+handleSegmentParts[6])\n\n newStartClusterHandle = cmds.rename(handleSegmentParts[2][1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+handleSegmentParts[2][1])\n newEndClusterHandle = cmds.rename(handleSegmentParts[3][1], self.moduleNamespace+':'+mfunc.stripMRTNamespace(self.joints[j+1])[1]+'_'+handleSegmentParts[3][1])\n cmds.rename(newStartClusterHandle+'|'+handleSegmentParts[7].rpartition('|')[2], joint+'_'+handleSegmentParts[7].rpartition('|')[2])\n cmds.rename(newEndClusterHandle+'|'+handleSegmentParts[8].rpartition('|')[2], self.joints[j+1]+'_'+handleSegmentParts[8].rpartition('|')[2])\n ##startClusterGrpParts = cmds.rename('handleControlSegmentCurve_StartClusterGroupParts', newStartClusterHandle+'_ClusterGroupParts')\n ##endClusterGrpParts = cmds.rename('handleControlSegmentCurve_EndClusterGroupParts', newEndClusterHandle+'_ClusterGroupParts')\n startClusterGrpParts = cmds.rename('segmentCurve_startClusterGroupParts', newStartClusterHandle+'_clusterGroupParts')\n endClusterGrpParts = cmds.rename('segmentCurve_endClusterGroupParts', newEndClusterHandle+'_clusterGroupParts')\n\n\n\n ##arclen = cmds.arclen(joint+'_handleControlSegmentCurve', constructionHistory=True)\n ##namedArclen = cmds.rename(arclen, joint+'_handleControlSegmentCurve_curveInfo')\n arclen = cmds.arclen(joint+'_segmentCurve', constructionHistory=True)\n namedArclen = cmds.rename(arclen, joint+'_segmentCurve_curveInfo')\n\n cmds.select(clear=True)\n containedNodes.extend([newStartClusterHandle, newEndClusterHandle, newStartClusterHandle+'Cluster', newEndClusterHandle+'Cluster', startClosestPointOnSurface, endClosestPointOnSurface, namedArclen, startClusterGrpParts, endClusterGrpParts])\n j += 1\n\n #rootEndHandleSegmentParts = objects.createRawHandleSegment(3)\n rootEndHandleSegmentParts = objects.createRawSegmentCurve(3)\n #cmds.setAttr(rootEndHandleSegmentParts[0]+'.overrideEnabled', 1)\n #cmds.setAttr(rootEndHandleSegmentParts[0]+'.overrideColor', 3)\n extra_nodes = []\n for node in rootEndHandleSegmentParts[4]:\n if cmds.objExists(node):\n extra_nodes.append(cmds.rename(node, self.moduleNamespace+':'+'rootEndHandleIKsegment_clusterParts_'+node))\n containedNodes.extend(extra_nodes)\n\n startClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=self.moduleNamespace+':startHandleIKsegment_'+rootEndHandleSegmentParts[5]+'_closestPointOnSurface')\n ##cmds.connectAttr(self.joints[0]+'_handleControlShape.worldSpace[0]', startClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[0]+'_controlShape.worldSpace[0]', startClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[-1]+'_worldPosLocator.translate', startClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(startClosestPointOnSurface+'.position', rootEndHandleSegmentParts[5]+'.translate')\n endClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=self.moduleNamespace+':endHandleIKsegment_'+rootEndHandleSegmentParts[6]+'_closestPointOnSurface')\n ##cmds.connectAttr(self.joints[-1]+'_handleControlShape.worldSpace[0]', endClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[-1]+'_controlShape.worldSpace[0]', endClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[0]+'_worldPosLocator.translate', endClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(endClosestPointOnSurface+'.position', rootEndHandleSegmentParts[6]+'.translate')\n\n cmds.parent([rootEndHandleSegmentParts[1], rootEndHandleSegmentParts[2][1], rootEndHandleSegmentParts[3][1], rootEndHandleSegmentParts[5], rootEndHandleSegmentParts[6]], self.moduleHandleSegmentGrp, absolute=True)\n\n rootEndHandleIKsegmentCurve = cmds.rename(rootEndHandleSegmentParts[1], self.moduleNamespace+':rootEndHandleIKsegment_'+rootEndHandleSegmentParts[1])\n\n newStartLocator = cmds.rename(rootEndHandleSegmentParts[5], self.moduleNamespace+':startHandleIKsegment_'+rootEndHandleSegmentParts[5])\n newEndLocator = cmds.rename(rootEndHandleSegmentParts[6], self.moduleNamespace+':endHandleIKsegment_'+rootEndHandleSegmentParts[6])\n\n newStartClusterHandle = cmds.rename(rootEndHandleSegmentParts[2][1], self.moduleNamespace+':startHandleIKsegment_'+rootEndHandleSegmentParts[2][1])\n newEndClusterHandle = cmds.rename(rootEndHandleSegmentParts[3][1], self.moduleNamespace+':endHandleIKsegment_'+rootEndHandleSegmentParts[3][1])\n cmds.rename(newStartClusterHandle+'|'+rootEndHandleSegmentParts[7].rpartition('|')[2], self.moduleNamespace+':startHandleIKsegment_'+rootEndHandleSegmentParts[7].rpartition('|')[2])\n cmds.rename(newEndClusterHandle + '|'+rootEndHandleSegmentParts[8].rpartition('|')[2], self.moduleNamespace+':endHandleIKsegment_'+rootEndHandleSegmentParts[8].rpartition('|')[2])\n #startClusterGrpParts = cmds.rename('handleControlSegmentCurve_StartClusterGroupParts', newStartClusterHandle+'_ClusterGroupParts')\n #endClusterGrpParts = cmds.rename('handleControlSegmentCurve_EndClusterGroupParts', newEndClusterHandle+'_ClusterGroupParts')\n startClusterGrpParts = cmds.rename('segmentCurve_startClusterGroupParts', newStartClusterHandle+'_clusterGroupParts')\n endClusterGrpParts = cmds.rename('segmentCurve_endClusterGroupParts', newEndClusterHandle+'_clusterGroupParts')\n\n cmds.select(clear=True)\n\n containedNodes.extend([newStartClusterHandle, newEndClusterHandle, newStartClusterHandle+'Cluster', newEndClusterHandle+'Cluster', startClosestPointOnSurface, endClosestPointOnSurface, startClusterGrpParts, endClusterGrpParts])\n\n rootEndHandleIKsegmentMidLocator = cmds.spaceLocator(name=self.moduleNamespace+':rootEndHandleIKsegmentMidLocator')[0]\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.translateX', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.translateY', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.translateZ', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.rotateX', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.rotateY', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.rotateZ', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.scaleX', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.scaleY', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.scaleZ', keyable=False)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'.visibility', keyable=False)\n\n cmds.parent(rootEndHandleIKsegmentMidLocator, self.moduleIKsegmentMidAimGrp, absolute=True)\n rootEndHandleIKsegmentMidLocator_pointOnCurveInfo = cmds.createNode('pointOnCurveInfo', name=self.moduleNamespace+':rootEndHandleIKsegmentCurveMidLocator_pointOnCurveInfo')\n cmds.connectAttr(rootEndHandleIKsegmentCurve+'Shape.worldSpace[0]', rootEndHandleIKsegmentMidLocator_pointOnCurveInfo+'.inputCurve')\n cmds.setAttr(rootEndHandleIKsegmentMidLocator_pointOnCurveInfo+'.turnOnPercentage', True)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator_pointOnCurveInfo+'.parameter', 0.5)\n cmds.connectAttr(rootEndHandleIKsegmentMidLocator_pointOnCurveInfo+'.position', rootEndHandleIKsegmentMidLocator+'.translate')\n containedNodes.append(rootEndHandleIKsegmentMidLocator_pointOnCurveInfo)\n\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'Shape.localScaleX', 0.1)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'Shape.localScaleY', 0)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'Shape.localScaleZ', 0.1)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'Shape.overrideEnabled', 1)\n cmds.setAttr(rootEndHandleIKsegmentMidLocator+'Shape.overrideColor', 2)\n\n ikSegmentAimStartLocator = cmds.spaceLocator(name=self.moduleNamespace+':ikSegmentAimStartLocator')[0]\n cmds.setAttr(ikSegmentAimStartLocator+'.visibility', 0)\n cmds.parent(ikSegmentAimStartLocator, self.moduleIKsegmentMidAimGrp, absolute=True)\n\n ikSegmentAimEndLocator = cmds.spaceLocator(name=self.moduleNamespace+':ikSegmentAimEndLocator')[0]\n cmds.setAttr(ikSegmentAimEndLocator+'.visibility', 0)\n cmds.parent(ikSegmentAimEndLocator, self.moduleIKsegmentMidAimGrp, absolute=True)\n\n cmds.geometryConstraint(rootEndHandleIKsegmentCurve, ikSegmentAimStartLocator, name=ikSegmentAimStartLocator+'_geoConstraint')\n #cmds.pointConstraint(self.joints[1]+'_handleControl', ikSegmentAimStartLocator, maintainOffset=False, name=ikSegmentAimStartLocator+'_pointConstraint')\n cmds.pointConstraint(self.joints[1]+'_control', ikSegmentAimStartLocator, maintainOffset=False, name=ikSegmentAimStartLocator+'_pointConstraint')\n ikSegmentAimStartClosestPointOnSurface = cmds.createNode('closestPointOnSurface', name=self.moduleNamespace+':ikSegmentAimClosestPointOnSurface')\n ##cmds.connectAttr(self.joints[1]+'_handleControlShape.worldSpace[0]', ikSegmentAimStartClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(self.joints[1]+'_controlShape.worldSpace[0]', ikSegmentAimStartClosestPointOnSurface+'.inputSurface')\n cmds.connectAttr(ikSegmentAimStartLocator+'Shape.worldPosition[0]', ikSegmentAimStartClosestPointOnSurface+'.inPosition')\n cmds.connectAttr(ikSegmentAimStartClosestPointOnSurface+'.position', ikSegmentAimEndLocator+'.translate')\n containedNodes.append(ikSegmentAimStartClosestPointOnSurface)\n\n ikSegmentAimCurve = cmds.createNode('transform', name=self.moduleNamespace+':ikSegmentAimCurve')\n cmds.setAttr(ikSegmentAimCurve+'.translateX', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.translateY', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.translateZ', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.rotateX', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.rotateY', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.rotateZ', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.scaleX', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.scaleY', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.scaleZ', keyable=False)\n cmds.setAttr(ikSegmentAimCurve+'.visibility', keyable=False)\n cmds.createNode('nurbsCurve', name=self.moduleNamespace+':ikSegmentAimCurveShape', parent=ikSegmentAimCurve)\n cmds.setAttr('.overrideEnabled', 1)\n cmds.setAttr('.overrideColor', 2)\n mel.eval('''setAttr \".cached\" -type \"nurbsCurve\"\n 1 1 0 no 3\n 2 0 1\n 2\n 0 0 0\n 1 0 0;''')\n cmds.parent(ikSegmentAimCurve, self.moduleIKsegmentMidAimGrp, absolute=True)\n\n cmds.pointConstraint(ikSegmentAimStartLocator, ikSegmentAimCurve, maintainOffset=False, name=ikSegmentAimCurve+'_pointConstraint')\n cmds.aimConstraint(ikSegmentAimEndLocator, ikSegmentAimCurve, maintainOffset=False, aimVector=[1.0, 0.0, 0.0], upVector=[0.0, 1.0, 0.0], worldUpType='scene', name=ikSegmentAimCurve+'_aimConstraint')\n\n rootEndHandleIKsegmentMidLocatorAimConstraint = cmds.aimConstraint(self.joints[-1], rootEndHandleIKsegmentMidLocator, maintainOffset=False, aimVector=[0.0, 1.0, 0.0], upVector=[0.0, 0.0, 1.0], worldUpType='object', worldUpObject=ikSegmentAimEndLocator, name=rootEndHandleIKsegmentMidLocator+'_aimConstraint')[0]\n cmds.setAttr(rootEndHandleIKsegmentMidLocatorAimConstraint+'.offsetY', 45)\n\n ikSegmentAimCurveLength_distance = cmds.createNode('distanceBetween', name=self.moduleNamespace+':ikSegmentAimCurveLength_distanceNode')\n cmds.connectAttr(ikSegmentAimStartLocator+'Shape.worldPosition[0]', ikSegmentAimCurveLength_distance+'.point1')\n cmds.connectAttr(ikSegmentAimEndLocator+'Shape.worldPosition[0]', ikSegmentAimCurveLength_distance+'.point2')\n cmds.connectAttr(ikSegmentAimCurveLength_distance+'.distance', ikSegmentAimCurve+'.scaleX')\n containedNodes.append(ikSegmentAimCurveLength_distance)\n\n # Add the module transform to the module, at the position of the root node.\n moduleTransform = objects.load_xhandleShape(self.moduleNamespace+'_handle', 24, True)\n cmds.setAttr(moduleTransform[0]+'.localScaleX', 0.26)\n cmds.setAttr(moduleTransform[0]+'.localScaleY', 0.26)\n cmds.setAttr(moduleTransform[0]+'.localScaleZ', 0.26)\n cmds.setAttr(moduleTransform[0]+'.drawStyle', 8)\n cmds.setAttr(moduleTransform[0]+'.drawOrtho', 0)\n cmds.setAttr(moduleTransform[0]+'.wireframeThickness', 2)\n cmds.setAttr(moduleTransform[1]+'.scaleX', keyable=False)\n cmds.setAttr(moduleTransform[1]+'.scaleY', keyable=False)\n cmds.setAttr(moduleTransform[1]+'.scaleZ', keyable=False)\n cmds.setAttr(moduleTransform[1]+'.visibility', keyable=False)\n cmds.addAttr(moduleTransform[1], attributeType='float', longName='globalScale', hasMinValue=True, minValue=0, defaultValue=1, keyable=True)\n self.moduleTransform = cmds.rename(moduleTransform[1], self.moduleNamespace+':module_transform')\n tempConstraint = cmds.pointConstraint(self.joints[0], self.moduleTransform, maintainOffset=False)\n cmds.delete(tempConstraint)\n\n cmds.parent(self.moduleTransform, self.moduleGrp, absolute=True)\n cmds.parentConstraint(self.moduleTransform, self.moduleIKnodesGrp, maintainOffset=True, name=self.moduleTransform+'_parentConstraint')\n cmds.scaleConstraint(self.moduleTransform, self.moduleIKnodesGrp, maintainOffset=False, name=self.moduleTransform+'_scaleConstraint')\n cmds.scaleConstraint(self.moduleTransform, self.moduleJointsGrp, maintainOffset=False, name=self.moduleTransform+'_scaleConstraint')\n cmds.scaleConstraint(self.moduleTransform, rootEndHandleIKsegmentMidLocator, maintainOffset=False, name=self.moduleTransform+'_scaleConstraint')\n\n # Connect the scale attributes to an aliased 'globalScale' attribute (This could've been done on the raw def itself, but it was issuing a cycle; not sure why. But the DG eval was not cyclic).\n cmds.connectAttr(self.moduleTransform+'.globalScale', self.moduleTransform+'.scaleX')\n cmds.connectAttr(self.moduleTransform+'.globalScale', self.moduleTransform+'.scaleY')\n cmds.connectAttr(self.moduleTransform+'.globalScale', self.moduleTransform+'.scaleZ')\n\n # Connect the globalScale attribute of the module transform to the xhandleShape(s).\n #for handle in [rootHandle[0], elbowHandle[0], endHandle[0]]:\n #xhandle = objects.load_xhandleShape(handle, self.modHandleColour)\n #cmds.setAttr(xhandle[0]+'.localScaleX', 0.145)\n #cmds.setAttr(xhandle[0]+'.localScaleY', 0.145)\n #cmds.setAttr(xhandle[0]+'.localScaleZ', 0.145)\n ##cmds.parent(xhandle[0], handle, shape=True, relative=True)\n ##cmds.delete(xhandle[1])\n #cmds.setAttr(xhandle[0]+'.ds', 5)\n #cmds.setAttr(handle+'Shape.visibility', 0)\n\n for handle in [rootHandle[0], elbowHandle[0], endHandle[0]]:\n xhandle = objects.load_xhandleShape(handle+'X', self.modHandleColour, True)\n cmds.setAttr(xhandle[0]+'.localScaleX', 0.089)\n cmds.setAttr(xhandle[0]+'.localScaleY', 0.089)\n cmds.setAttr(xhandle[0]+'.localScaleZ', 0.089)\n cmds.parent(xhandle[0], handle, shape=True, relative=True)\n cmds.delete(xhandle[1])\n cmds.setAttr(xhandle[0]+'.ds', 5)\n cmds.setAttr(handle+'Shape.visibility', 0)\n\n hingeAxisRepresentation = objects.createRawIKhingeAxisRepresenation(self.nodeAxes[1:])\n cmds.setAttr(hingeAxisRepresentation+'.scale', 2.3, 2.3, 2.3, type='double3')\n cmds.makeIdentity(hingeAxisRepresentation, scale=True, apply=True)\n hingeAxisRepresentation = cmds.rename(hingeAxisRepresentation, self.joints[1]+'_'+hingeAxisRepresentation)\n cmds.parent(hingeAxisRepresentation, self.moduleRepresentationGrp, absolute=True)\n cmds.parentConstraint(self.joints[1], hingeAxisRepresentation, maintainOffset=False, name=hingeAxisRepresentation+'_parentConstraint')\n cmds.scaleConstraint(self.moduleTransform, hingeAxisRepresentation, maintainOffset=False, name=self.moduleTransform+'_scaleConstraint')\n\n ikPreferredRotationRepresentaton = objects.createRawIKPreferredRotationRepresentation(self.nodeAxes[2])\n cmds.setAttr(ikPreferredRotationRepresentaton+'.scale', 0.6, 0.6, 0.6, type='double3')\n cmds.makeIdentity(ikPreferredRotationRepresentaton, scale=True, apply=True)\n ikPreferredRotationRepresentaton = cmds.rename(ikPreferredRotationRepresentaton, self.moduleNamespace+':'+ikPreferredRotationRepresentaton)\n cmds.parent(ikPreferredRotationRepresentaton, self.moduleRepresentationGrp, absolute=True)\n cmds.pointConstraint(self.moduleNamespace+':rootEndHandleIKsegmentMidLocator', ikPreferredRotationRepresentaton, maintainOffset=False, name=ikPreferredRotationRepresentaton+'_pointConstraint')\n cmds.scaleConstraint(self.moduleTransform, ikPreferredRotationRepresentaton, maintainOffset=False, name=self.moduleTransform+'_ikPreferredRotRepr_scaleConstraint')\n orientConstraint = cmds.orientConstraint(self.moduleNamespace+':rootEndHandleIKsegmentMidLocator', ikPreferredRotationRepresentaton, maintainOffset=False, name=ikPreferredRotationRepresentaton+'_orientConstraint')[0]\n cmds.setAttr(orientConstraint+'.offsetY', -45)\n #modifyIKhingePreferredOrientationRepresentation = self.checkPlaneAxisDirectionForIKhingeForOrientationRepresentation()\n #if modifyIKhingePreferredOrientationRepresentation and self.mirrorRotationFunc == 'Behaviour':\n #scaleAxisApply = {'X':[-1.0, 1.0, 1.0], 'Y':[1.0, -1.0, 1.0], 'Z':[1.0, 1.0, -1.0]}[self.nodeAxes[1]]\n #cmds.select(['{0}_hingeRotate_Shape.cv[{1}]'.format(hingeOrientationRepresentation, cv) for cv in range(41)])\n #cmds.xform(scale=scaleAxisApply, absolute=True)\n #cmds.select(clear=True)\n\n index = 0\n for joint in self.joints[:-1]:\n\n hierarchyRepresentation = objects.createRawHierarchyRepresentation(self.nodeAxes[0])\n\n ##startLocator = joint + '_handleControlSegmentCurve_startLocator'\n ##endLocator = self.joints[index+1] + '_handleControlSegmentCurve_endLocator'\n startLocator = joint + '_segmentCurve_startLocator'\n endLocator = self.joints[index+1] + '_segmentCurve_endLocator'\n cmds.pointConstraint(startLocator, endLocator, hierarchyRepresentation, maintainOffset=False, name=joint+'_hierarchy_representation_pointConstraint')\n cmds.scaleConstraint(joint, hierarchyRepresentation, maintainOffset=False, name=joint+'_hierarchy_representation_scaleConstraint')\n\n aimVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[0]]\n upVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[1]]\n cmds.aimConstraint(self.joints[index+1], hierarchyRepresentation, maintainOffset=False, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=self.moduleNamespace+':'+mfunc.stripMRTNamespace(self.joints[index+1])[1]+'_hierarchy_representation_aimConstraint')\n\n cmds.parent(hierarchyRepresentation, self.moduleHierarchyRepresentationGrp, absolute=True)\n\n cmds.rename(hierarchyRepresentation, joint+'_'+hierarchyRepresentation)\n index += 1\n\n cmds.select(clear=True)\n\n containedNodes += self.createHierarchySegmentForModuleParentingRepresentation()\n\n if self.proxyGeoStatus:\n if self.proxyGeoElbow:\n self.createProxyGeo_elbows(self.proxyElbowType)\n if self.proxyGeoBones:\n self.createProxyGeo_bones()\n\n # Add the module group to the contained nodes list.\n containedNodes += [self.moduleGrp]\n # Add the contained nodes to the module container.\n mfunc.addNodesToContainer(self.moduleContainer, containedNodes, includeHierarchyBelow=True, includeShapes=True)\n\n moduleTransformName = mfunc.stripMRTNamespace(self.moduleTransform)[1]\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[self.moduleTransform+'.translate', moduleTransformName+'_translate'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[self.moduleTransform+'.rotate', moduleTransformName+'_rotate'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[self.moduleTransform+'.globalScale', moduleTransformName+'_globalScale'])\n\n for handle in (rootHandle[0], elbowHandle[0], endHandle[0]):\n handleName = mfunc.stripMRTNamespace(handle)[1]\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[handle+'.translate', handleName+'_translate'])\n\n for joint in self.joints:\n jointName = mfunc.stripMRTNamespace(joint)[1]\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[joint+'.rotate', jointName+'_rotate'])\n\n self.addCustomAttributesOnModuleTransform()\n if self.onPlane == 'XZ':\n offset = cmds.getAttr(self.moduleNamespace+':node_1_transform_control.translateY')\n cmds.setAttr(self.moduleNamespace+':node_1_transform_control.translateY', 0)\n cmds.setAttr(self.moduleNamespace+':node_1_transform_control.translateZ', offset)\n if self.onPlane == 'XY' and self.mirrorModule:\n ##offset = cmds.getAttr(self.moduleNamespace+':node_1_transform_handleControl.translateZ')\n ##cmds.setAttr(self.moduleNamespace+':node_1_transform_handleControl.translateZ', offset*-1)\n offset = cmds.getAttr(self.moduleNamespace+':node_1_transform_control.translateZ')\n cmds.setAttr(self.moduleNamespace+':node_1_transform_control.translateZ', offset*-1)\n if self.onPlane == 'YZ' and self.mirrorModule:\n ##offset = cmds.getAttr(self.moduleNamespace+':node_1_transform_handleControl.translateX')\n ##cmds.setAttr(self.moduleNamespace+':node_1_transform_handleControl.translateX', offset*-1)\n offset = cmds.getAttr(self.moduleNamespace+':node_1_transform_control.translateX')\n cmds.setAttr(self.moduleNamespace+':node_1_transform_control.translateX', offset*-1)\n\n ##mfunc.forceSceneUpdate()\n #cmds.setAttr(self.moduleTransform+'.globalScale', 4)\n\n def addCustomAttributesOnModuleTransform(self):\n if self.moduleName == 'JointNode':\n\n moduleNode = '|' + self.moduleGrp + '|' + self.moduleTransform\n\n if len(self.joints) > 1:\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Orientation_Representation_Toggle', enumName='----------------------------:', keyable=True)\n for joint in self.joints[:-1]:\n longName = mfunc.stripMRTNamespace(joint)[1]+'_orientation_representation_transform'\n cmds.addAttr(moduleNode, attributeType='enum', longName=longName, enumName='Off:On:', defaultValue=1, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_orientation_representation_transform.visibility')\n if not self.showOrientation:\n cmds.setAttr(moduleNode+'.'+longName, 0)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName+'_toggle'])\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Hierarchy_Representation_Toggle', enumName='----------------------------:', keyable=True)\n for joint in self.joints[:-1]:\n longName = mfunc.stripMRTNamespace(joint)[1]+'_hierarchy_representation'\n cmds.addAttr(moduleNode, attributeType='enum', longName=longName, enumName='Off:On:', defaultValue=1, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_hierarchy_representation.visibility')\n ##cmds.connectAttr(moduleNode+'.'+longName, joint+'_handleControlSegmentCurve.visibility')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_segmentCurve.visibility')\n if not self.showHierarchy:\n cmds.setAttr(moduleNode+'.'+longName, 0)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName+'_toggle'])\n\n if len(self.joints) == 1:\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Orientation_Representation_Toggle', enumName='----------------------------:', keyable=True)\n longName = mfunc.stripMRTNamespace(self.joints[0])[1]+'_single_orientation_representation_transform'\n cmds.addAttr(moduleNode, attributeType='enum', longName=longName, enumName='Off:On:', defaultValue=1, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, mfunc.stripMRTNamespace(self.joints[0])[0]+':single_orientation_representation_transform.visibility')\n if not self.showOrientation:\n cmds.setAttr(moduleNode+'.'+longName, 0)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName+'_toggle'])\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Handle_Size', enumName='---------------------------:', keyable=True)\n for joint in self.joints:\n longName = mfunc.stripMRTNamespace(joint)[1]+'_handle_size'\n cmds.addAttr(moduleNode, attributeType='float', longName=longName, hasMinValue=True, minValue=0, defaultValue=1, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlShape_scaleClusterHandle.scaleX')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlShape_scaleClusterHandle.scaleY')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlShape_scaleClusterHandle.scaleZ')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'Shape.addScaleX')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'Shape.addScaleY')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'Shape.addScaleZ')\n #cmds.setAttr(moduleNode+'.'+longName, 0.2)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName])\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Rotation_Order', enumName='---------------------------:', keyable=True)\n for joint in self.joints:\n longName = mfunc.stripMRTNamespace(joint)[1]+'_rotate_order'\n cmds.addAttr(moduleNode, attributeType='enum', longName=longName, enumName='xyz:yzx:zxy:xzy:yxz:zyx:', defaultValue=0, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, joint+'.rotateOrder')\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName+'_switch'])\n\n if self.proxyGeoStatus:\n cmds.addAttr(moduleNode, attributeType='enum', longName='Proxy_Geometry', enumName='---------------------------:', keyable=True)\n cmds.addAttr(moduleNode, attributeType='enum', longName='proxy_geometry_draw', enumName='Opaque:Transparent:', defaultValue=1, keyable=True)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.proxy_geometry_draw', 'module_transform_proxy_geometry_draw_toggle'])\n\n if self.moduleName == 'SplineNode':\n\n moduleNode = self.moduleNamespace + ':splineStartHandleTransform'\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Representation', enumName='----------------------:', keyable=True)\n cmds.addAttr(moduleNode, attributeType='float', longName='Global_size', hasMinValue=True, minValue=0, defaultValue=1, keyable=True)\n cmds.addAttr(moduleNode, attributeType='float', longName='Axis_Rotate', defaultValue=0, keyable=True)\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Orientation_Info', enumName='Off:On:', defaultValue=1, keyable=True)\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Orientation_Type', enumName='World:Object:', defaultValue=1, keyable=True)\n cmds.addAttr(moduleNode, attributeType='float', longName='Node_Local_Orientation_Representation_Size', hasMinValue=True, minValue=0.01, defaultValue=1, keyable=True)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Global_size', 'module_globalRepr_Size'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Axis_Rotate', 'module_Axis_Rotate'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Node_Orientation_Info', 'root_transform_Node_Orientation'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Node_Orientation_Type', 'root_transform_Node_Orientation_Type'])\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Node_Local_Orientation_Representation_Size', 'root_transform_Node_Orientation_Representation_Size'])\n\n if self.proxyGeoStatus:\n cmds.addAttr(moduleNode, attributeType='enum', longName='Proxy_Geometry', enumName='---------------------------:', keyable=True)\n cmds.addAttr(moduleNode, attributeType='enum', longName='proxy_geometry_draw', enumName='Opaque:Transparent:', defaultValue=1, keyable=True)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.proxy_geometry_draw', 'module_transform_proxy_geometry_draw_toggle'])\n\n if self.moduleName == 'HingeNode':\n\n moduleNode = '|' + self.moduleGrp + '|' + self.moduleTransform\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Hinge_Orientation_Representation_Toggle', enumName='Off:On:', defaultValue=1, keyable=True)\n cmds.connectAttr(moduleNode+'.Hinge_Orientation_Representation_Toggle', self.joints[1]+'_IKhingeAxisRepresenation.visibility')\n cmds.connectAttr(moduleNode+'.Hinge_Orientation_Representation_Toggle', self.moduleNamespace+':IKPreferredRotationRepresentation.visibility')\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Hinge_Orientation_Representation_Toggle', mfunc.stripMRTNamespace(self.joints[1])[1]+'_Hinge_Orientation_Representation_Toggle'])\n if not self.showOrientation:\n cmds.setAttr(moduleNode+'.Hinge_Orientation_Representation_Toggle', 0)\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Module_Hierarchy_Representation_Toggle', enumName='Off:On:', defaultValue=1, keyable=True)\n for joint in self.joints[:-1]:\n cmds.connectAttr(moduleNode+'.Module_Hierarchy_Representation_Toggle', joint+'_hierarchy_representation.visibility')\n cmds.connectAttr(moduleNode+'.Module_Hierarchy_Representation_Toggle', joint+'_segmentCurve.visibility')\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.Module_Hierarchy_Representation_Toggle', 'Module_Hierarchy_Representation_Toggle'])\n if not self.showHierarchy:\n cmds.setAttr(moduleNode+'.Module_Hierarchy_Representation_Toggle', 0)\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Handle_Size', enumName='---------------------------:', keyable=True)\n for joint in self.joints:\n longName = mfunc.stripMRTNamespace(joint)[1]+'_handle_size'\n cmds.addAttr(moduleNode, attributeType='float', longName=longName, hasMinValue=True, minValue=0, defaultValue=1, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlShape_scaleClusterHandle.scaleX')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlShape_scaleClusterHandle.scaleY')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlShape_scaleClusterHandle.scaleZ')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlXShape.addScaleX')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlXShape.addScaleY')\n cmds.connectAttr(moduleNode+'.'+longName, joint+'_controlXShape.addScaleZ')\n #cmds.setAttr(moduleNode+'.'+longName, 0.2)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName])\n\n cmds.addAttr(moduleNode, attributeType='enum', longName='Node_Rotation_Order', enumName='---------------------------:', keyable=True)\n for joint in self.joints:\n longName = mfunc.stripMRTNamespace(joint)[1]+'_rotate_order'\n cmds.addAttr(moduleNode, attributeType='enum', longName=longName, enumName='xyz:yzx:zxy:xzy:yxz:zyx:', defaultValue=0, keyable=True)\n cmds.connectAttr(moduleNode+'.'+longName, joint+'.rotateOrder')\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.'+longName, 'module_transform_'+longName+'_switch'])\n\n if self.proxyGeoStatus:\n cmds.addAttr(moduleNode, attributeType='enum', longName='Proxy_Geometry', enumName='---------------------------:', keyable=True)\n cmds.addAttr(moduleNode, attributeType='enum', longName='proxy_geometry_draw', enumName='Opaque:Transparent:', defaultValue=1, keyable=True)\n cmds.container(self.moduleContainer, edit=True, publishAndBind=[moduleNode+'.proxy_geometry_draw', 'module_transform_proxy_geometry_draw_toggle'])\n\n def createProxyGeo_elbows(self, geoType='sphere'):\n if geoType == 'sphere':\n filePathSuffix = 'MRT/elbow_proxySphereGeo.ma'\n if geoType == 'cube':\n filePathSuffix = 'MRT/elbow_proxyCubeGeo.ma'\n filePath = cmds.internalVar(userScriptDir=True) + filePathSuffix\n if self.mirrorModule:\n originalNamespace = cmds.getAttr(self.moduleGrp+'.mirrorModuleNamespace')\n index = 0\n hingeAimConstraints = []\n for joint in self.joints:\n cmds.file(filePath, i=True, prompt=False, ignoreVersion=True)\n proxyElbowGeoPreTransform = '_proxy_elbow_geo_preTransform'\n proxyElbowGeoScaleTransform = '_proxy_elbow_geo_scaleTransform'\n proxyElbowTransform = '_proxy_elbow_geo'\n if self.mirrorModule and self.proxyGeoMirrorInstance == 'On':\n originalNamespace = cmds.getAttr(self.moduleGrp+'.mirrorModuleNamespace')\n originalProxyElbowTransform = originalNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+proxyElbowTransform\n cmds.delete(proxyElbowTransform)\n transformInstance = cmds.duplicate(originalProxyElbowTransform, instanceLeaf=True, name='_proxy_elbow_geo')[0]\n cmds.parent(transformInstance, proxyElbowGeoScaleTransform, relative=True)\n if self.moduleName != 'HingeNode':\n scaleFactorAxes = {'XY':[1, 1, -1], 'YZ':[-1, 1, 1], 'XZ':[1, -1, 1]}[self.onPlane]\n else:\n scaleFactorAxes = {'XY':[-1, 1, 1], 'YZ':[1, 1, -1], 'XZ':[1, 1, -1]}[self.onPlane]\n cmds.setAttr(proxyElbowGeoScaleTransform+'.scale', *scaleFactorAxes)\n cmds.select(proxyElbowTransform+'.vtx[*]', replace=True)\n cmds.polyColorPerVertex(alpha=0.3, rgb=[0.663, 0.561, 0.319], notUndoable=True, colorDisplayOption=True)\n cmds.pointConstraint(joint, proxyElbowGeoPreTransform, maintainOffset=False, name=joint+'_pointConstraint')\n cmds.scaleConstraint(joint, proxyElbowGeoPreTransform, maintainOffset=False, name=joint+'_scaleConstraint')\n if self.moduleName == 'JointNode':\n aimVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[0]]\n upVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[1]]\n if self.numNodes > 1:\n if index == 0:\n cmds.aimConstraint(self.joints[index+1], proxyElbowGeoPreTransform, maintainOffset=True, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=joint+'_'+proxyElbowGeoPreTransform+'_aimConstraint')\n else:\n cmds.aimConstraint(self.joints[index-1], proxyElbowGeoPreTransform, maintainOffset=True, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=joint+'_'+proxyElbowGeoPreTransform+'_aimConstraint')\n if self.numNodes == 1:\n cmds.orientConstraint(self.moduleNamespace+':single_orientation_representation_transform', proxyElbowGeoPreTransform, maintainOffset=True, name=proxyElbowGeoPreTransform+'_orientConstraint')\n if self.moduleName == 'HingeNode':\n aimVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[0]]\n upVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[1]]\n if index == 0:\n aimConstraint = cmds.aimConstraint(self.joints[index+1], proxyElbowGeoPreTransform, maintainOffset=True, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=joint+'_'+proxyElbowGeoPreTransform+'_aimConstraint')[0]\n else:\n aimConstraint = cmds.aimConstraint(self.joints[index-1], proxyElbowGeoPreTransform, maintainOffset=True, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=joint+'_'+proxyElbowGeoPreTransform+'_aimConstraint')[0]\n hingeAimConstraints.append(aimConstraint)\n\n if self.moduleName == 'SplineNode':\n cmds.orientConstraint(joint, proxyElbowGeoPreTransform, maintainOffset=True, name=joint+'_'+proxyElbowGeoPreTransform+'_orientConstraint')\n cmds.parent(proxyElbowGeoPreTransform, self.proxyGeoGrp, absolute=True)\n cmds.rename(proxyElbowGeoPreTransform, joint+proxyElbowGeoPreTransform)\n cmds.rename(proxyElbowGeoScaleTransform, joint+proxyElbowGeoScaleTransform)\n cmds.rename(proxyElbowTransform, joint+proxyElbowTransform)\n extra_nodes = [u'elbow_proxyGeo_uiConfigurationScriptNode', u'elbow_proxyGeo_sceneConfigurationScriptNode']\n for node in extra_nodes:\n if cmds.objExists(node):\n cmds.delete(node)\n index += 1\n\n # Find and change the aim constraint offset values on hinge node in order to properly orient the elbow proxy geo.\n if hingeAimConstraints:\n l_val = [0.0, 90.0, 180.0, 270.0, 360.0]\n for constraint in hingeAimConstraints:\n for attr in ['X', 'Y', 'Z']:\n val = cmds.getAttr(constraint+'.offset'+attr)\n if not round(abs(val),0) in l_val:\n l_cmp = {}\n for item in l_val:\n l_cmp[abs(item - abs(val))] = item\n off_value = l_cmp[min(l_cmp)]\n off_value = math.copysign(off_value, val)\n cmds.setAttr(constraint+'.offset'+attr, off_value)\n\n cmds.select(clear=True)\n\n def createProxyGeo_bones(self):\n filePath = cmds.internalVar(userScriptDir=True) + 'MRT/bone_proxyGeo.ma'\n index = 0\n for joint in self.joints[:-1]:\n cmds.namespace(setNamespace=':')\n cmds.file(filePath, i=True, prompt=False, ignoreVersion=True)\n proxyBoneGeoPreTransform = 'proxy_bone_geo_preTransform'\n proxyBoneGeoScaleTransform = 'proxy_bone_geo_scaleTransform'\n proxyBoneTransform = 'proxy_bone_geo'\n\n if self.nodeAxes[0] == 'X':\n cmds.move(0,[proxyBoneGeoPreTransform+'.scalePivot', proxyBoneGeoPreTransform+'.rotatePivot'], moveX=True)\n cmds.move(0,[proxyBoneGeoScaleTransform+'.scalePivot', proxyBoneGeoScaleTransform+'.rotatePivot'], moveX=True)\n cmds.move(0,[proxyBoneTransform+'.scalePivot', proxyBoneTransform+'.rotatePivot'], moveX=True)\n if self.nodeAxes[0] == 'Y':\n cmds.move(0,[proxyBoneGeoPreTransform+'.scalePivot', proxyBoneGeoPreTransform+'.rotatePivot'], moveY=True)\n cmds.move(0,[proxyBoneGeoScaleTransform+'.scalePivot', proxyBoneGeoScaleTransform+'.rotatePivot'], moveY=True)\n cmds.move(0,[proxyBoneTransform+'.scalePivot', proxyBoneTransform+'.rotatePivot'], moveY=True)\n if self.nodeAxes[0] == 'Z':\n cmds.move(0,[proxyBoneGeoPreTransform+'.scalePivot', proxyBoneGeoPreTransform+'.rotatePivot'], moveZ=True)\n cmds.move(0,[proxyBoneGeoScaleTransform+'.scalePivot', proxyBoneGeoScaleTransform+'.rotatePivot'], moveZ=True)\n cmds.move(0,[proxyBoneTransform+'.scalePivot', proxyBoneTransform+'.rotatePivot'], moveZ=True)\n\n if self.mirrorModule and self.proxyGeoMirrorInstance == 'On':\n originalNamespace = cmds.getAttr(self.moduleGrp+'.mirrorModuleNamespace')\n originalProxyBoneTransform = originalNamespace+':'+mfunc.stripMRTNamespace(joint)[1]+'_'+proxyBoneTransform\n cmds.delete(proxyBoneTransform)\n transformInstance = cmds.duplicate(originalProxyBoneTransform, instanceLeaf=True, name='proxy_bone_geo')[0]\n cmds.parent(transformInstance, proxyBoneGeoScaleTransform, relative=True)\n if self.moduleName == 'HingeNode' and self.mirrorRotationFunc == 'Orientation':\n scaleFactorAxes = {'X':[-1, 1, 1], 'Y':[1, -1, 1], 'Z':[1, 1, -1]}[self.nodeAxes[2]]\n else:\n scaleFactorAxes = {'X':[-1, 1, 1], 'Y':[1, -1, 1], 'Z':[1, 1, -1]}[self.nodeAxes[1]]\n cmds.setAttr(proxyBoneGeoScaleTransform+'.scale', *scaleFactorAxes)\n\n cmds.select(proxyBoneTransform+'.vtx[*]', replace=True)\n cmds.polyColorPerVertex(alpha=0.3, rgb=[0.663, 0.561, 0.319], notUndoable=True, colorDisplayOption=True)\n if not self.mirrorModule:\n for axis in self.nodeAxes[1:]:\n cmds.setAttr(proxyBoneGeoPreTransform+'.scale'+axis, 0.17)\n cmds.makeIdentity(proxyBoneGeoPreTransform, scale=True, apply=True)\n if self.mirrorModule and self.proxyGeoMirrorInstance == 'Off':\n for axis in self.nodeAxes[1:]:\n cmds.setAttr(proxyBoneGeoPreTransform+'.scale'+axis, 0.17)\n cmds.makeIdentity(proxyBoneGeoPreTransform, scale=True, apply=True)\n\n cmds.parent(proxyBoneGeoPreTransform, self.proxyGeoGrp, absolute=True)\n\n tempConstraint = cmds.orientConstraint(joint, proxyBoneGeoPreTransform, maintainOffset=False)\n cmds.delete(tempConstraint)\n\n for axis in self.nodeAxes[1:]:\n cmds.connectAttr(self.moduleTransform+'.globalScale', proxyBoneGeoPreTransform+'.scale'+axis)\n ##curveInfo = joint + '_handleControlSegmentCurve_curveInfo'\n curveInfo = joint + '_segmentCurve_curveInfo'\n cmds.connectAttr(curveInfo+'.arcLength', proxyBoneGeoPreTransform+'.scale'+self.nodeAxes[0])\n ##cmds.pointConstraint(joint+'_handleControlSegmentCurve_startLocator', proxyBoneGeoPreTransform, maintainOffset=False, name=self.moduleNamespace+':'+proxyBoneGeoPreTransform+'_basePointConstraint')\n cmds.pointConstraint(joint+'_segmentCurve_startLocator', proxyBoneGeoPreTransform, maintainOffset=False, name=self.moduleNamespace+':'+proxyBoneGeoPreTransform+'_basePointConstraint')\n aimVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[0]]\n upVector = {'X':[1.0, 0.0, 0.0], 'Y':[0.0, 1.0, 0.0], 'Z':[0.0, 0.0, 1.0]}[self.nodeAxes[1]]\n\n cmds.aimConstraint(self.joints[index+1], proxyBoneGeoPreTransform, maintainOffset=False, aimVector=aimVector, upVector=upVector, worldUpVector=upVector, worldUpType='objectRotation', worldUpObject=joint, name=self.joints[index+1]+'_'+proxyBoneGeoPreTransform+'_aimConstraint')\n cmds.rename(proxyBoneGeoPreTransform, joint+'_'+proxyBoneGeoPreTransform)\n cmds.rename(proxyBoneGeoScaleTransform, joint+'_'+proxyBoneGeoScaleTransform)\n cmds.rename(proxyBoneTransform, joint+'_'+proxyBoneTransform)\n extra_nodes = [u'bone_proxyGeo_uiConfigurationScriptNode', u'bone_proxyGeo_sceneConfigurationScriptNode']\n for node in extra_nodes:\n if cmds.objExists(node):\n cmds.delete(node)\n index += 1\n cmds.select(clear=True)\n\n def connectCustomOrientationReprToBoneProxies(self):\n if self.moduleName == 'JointNode':\n rotAxis = cmds.getAttr(self.moduleGrp+'.nodeOrient')\n rotAxis = rotAxis[0]\n for joint in self.joints[:-1]:\n ori_repr_control = joint+'_orientation_representation_transform'\n boneProxy_s_transform = joint+'_proxy_bone_geo_scaleTransform'\n if cmds.objExists(boneProxy_s_transform):\n cmds.connectAttr(ori_repr_control+'.rotate'+rotAxis, boneProxy_s_transform+'.rotate'+rotAxis)\n if self.moduleName == 'SplineNode':\n startHandle = self.joints[0].rpartition(':')[0] + ':splineStartHandleTransform'\n for joint in self.joints:\n elbowProxy_s_transform = joint+'_proxy_elbow_geo_scaleTransform'\n if cmds.objExists(elbowProxy_s_transform):\n cmds.connectAttr(startHandle+'.Axis_Rotate', elbowProxy_s_transform+'.rotateY')\n","sub_path":"mrt_module.py","file_name":"mrt_module.py","file_ext":"py","file_size_in_byte":129870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97267289","text":"#!/usr/bin/env python3\n\n# Copyright 2015 The Meson development team\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This script reads config.h.meson, looks for header\nchecks and writes the corresponding meson declaration.\n\nCopy config.h.in to config.h.meson, replace #undef\nwith #mesondefine and run this. We can't do this automatically\nbecause some configure scripts have #undef statements\nthat are unrelated to configure checks.\n\"\"\"\n\nimport sys\n\n\n# Add stuff here as it is encountered.\nfunction_data = \\\n {'HAVE_FEENABLEEXCEPT' : ('feenableexcept', 'fenv.h'),\n 'HAVE_FECLEAREXCEPT' : ('feclearexcept', 'fenv.h'),\n 'HAVE_FEDISABLEEXCEPT' : ('fedisableexcept', 'fenv.h'),\n 'HAVE_MMAP' : ('mmap', 'sys/mman.h'),\n 'HAVE_GETPAGESIZE' : ('getpagesize', 'unistd.h'),\n 'HAVE_GETISAX' : ('getisax', 'sys/auxv.h'),\n 'HAVE_GETTIMEOFDAY' : ('gettimeofday', 'sys/time.h'),\n 'HAVE_MPROTECT' : ('mprotect', 'sys/mman.h'),\n 'HAVE_POSIX_MEMALIGN' : ('posix_memalign', 'stdlib.h'),\n 'HAVE_SIGACTION' : ('sigaction', 'signal.h'),\n 'HAVE_ALARM' : ('alarm', 'unistd.h'),\n 'HAVE_CLOCK_GETTIME' : ('clock_gettime', 'time.h'),\n 'HAVE_CTIME_R' : ('ctime_r', 'time.h'),\n 'HAVE_DRAND48' : ('drand48', 'stdlib.h'),\n 'HAVE_FLOCKFILE' : ('flockfile', 'stdio.h'),\n 'HAVE_FORK' : ('fork', 'unistd.h'),\n 'HAVE_FUNLOCKFILE' : ('funlockfile', 'stdio.h'),\n 'HAVE_GETLINE' : ('getline', 'stdio.h'),\n 'HAVE_LINK' : ('link', 'unistd.h'),\n 'HAVE_RAISE' : ('raise', 'signal.h'),\n 'HAVE_STRNDUP' : ('strndup', 'string.h'),\n 'HAVE_SCHED_GETAFFINITY' : ('sched_getaffinity', 'sched.h'),\n 'HAVE_WAITPID' : ('waitpid', 'sys/wait.h'),\n 'HAVE_XRENDERCREATECONICALGRADIENT' : ('XRenderCreateConicalGradient', 'xcb/render.h'),\n 'HAVE_XRENDERCREATELINEARGRADIENT' : ('XRenderCreateLinearGradient', 'xcb/render.h'),\n 'HAVE_XRENDERCREATERADIALGRADIENT' : ('XRenderCreateRadialGradient', 'xcb/render.h'),\n 'HAVE_XRENDERCREATESOLIDFILL' : ('XRenderCreateSolidFill', 'xcb/render.h'),\n 'HAVE_DCGETTEXT': ('dcgettext', 'libintl.h'),\n 'HAVE_ENDMNTENT': ('endmntent', 'mntent.h'),\n 'HAVE_ENDSERVENT' : ('endservent', 'netdb.h'),\n 'HAVE_EVENTFD': ('eventfd', 'sys/eventfd.h'),\n 'HAVE_FALLOCATE': ('fallocate', 'fcntl.h'),\n 'HAVE_FCHMOD': ('fchmod', 'sys/stat.h'),\n 'HAVE_FCHOWN': ('fchown', 'unistd.h'),\n 'HAVE_FDWALK': ('fdwalk', 'stdlib.h'),\n 'HAVE_FSYNC': ('fsync', 'unistd.h'),\n 'HAVE_GETC_UNLOCKED': ('getc_unlocked', 'stdio.h'),\n 'HAVE_GETFSSTAT': ('getfsstat', 'sys/mount.h'),\n 'HAVE_GETMNTENT_R': ('getmntent_r', 'mntent.h'),\n 'HAVE_GETPROTOBYNAME_R': ('getprotobyname_r', 'netdb.h'),\n 'HAVE_GETRESUID' : ('getresuid', 'unistd.h'),\n 'HAVE_GETVFSSTAT' : ('getvfsstat', 'sys/statvfs.h'),\n 'HAVE_GMTIME_R' : ('gmtime_r', 'time.h'),\n 'HAVE_HASMNTOPT': ('hasmntopt', 'mntent.h'),\n 'HAVE_IF_INDEXTONAME': ('if_indextoname', 'net/if.h'),\n 'HAVE_IF_NAMETOINDEX': ('if_nametoindex', 'net/if.h'),\n 'HAVE_INOTIFY_INIT1': ('inotify_init1', 'sys/inotify.h'),\n 'HAVE_ISSETUGID': ('issetugid', 'unistd.h'),\n 'HAVE_KEVENT': ('kevent', 'sys/event.h'),\n 'HAVE_KQUEUE': ('kqueue', 'sys/event.h'),\n 'HAVE_LCHMOD': ('lchmod', 'sys/stat.h'),\n 'HAVE_LCHOWN': ('lchown', 'unistd.h'),\n 'HAVE_LSTAT': ('lstat', 'sys/stat.h'),\n 'HAVE_MEMCPY': ('memcpy', 'string.h'),\n 'HAVE_MEMALIGN': ('memalign', 'stdlib.h'),\n 'HAVE_MEMMEM': ('memmem', 'string.h'),\n 'HAVE_NEWLOCALE': ('newlocale', 'locale.h'),\n 'HAVE_PIPE2': ('pipe2', 'fcntl.h'),\n 'HAVE_POLL': ('poll', 'poll.h'),\n 'HAVE_PRLIMIT': ('prlimit', 'sys/resource.h'),\n 'HAVE_PTHREAD_ATTR_SETSTACKSIZE': ('pthread_attr_setstacksize', 'pthread.h'),\n 'HAVE_PTHREAD_CONDATTR_SETCLOCK': ('pthread_condattr_setclock', 'pthread.h'),\n 'HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP': ('pthread_cond_timedwait_relative_np', 'pthread.h'),\n 'HAVE_READLINK': ('readlink', 'unistd.h'),\n 'HAVE_RES_INIT': ('res_init', 'resolv.h'),\n 'HAVE_SENDMMSG': ('sendmmsg', 'sys/socket.h'),\n 'HAVE_SOCKET' : ('socket', 'sys/socket.h'),\n 'HAVE_GETENV': ('getenv', 'stdlib.h'),\n 'HAVE_SETENV': ('setenv', 'stdlib.h'),\n 'HAVE_PUTENV': ('putenv', 'stdlib.h'),\n 'HAVE_UNSETENV': ('unsetenv', 'stdlib.h'),\n 'HAVE_SETMNTENT': ('setmntent', 'mntent.h'),\n 'HAVE_SNPRINTF': ('snprintf', 'stdio.h'),\n 'HAVE_SPLICE': ('splice', 'fcntl.h'),\n 'HAVE_STATFS': ('statfs', 'mount.h'),\n 'HAVE_STATVFS': ('statvfs', 'sys/statvfs.h'),\n 'HAVE_STPCOPY': ('stpcopy', 'string.h'),\n 'HAVE_STRCASECMP': ('strcasecmp', 'strings.h'),\n 'HAVE_STRLCPY': ('strlcpy', 'string.h'),\n 'HAVE_STRNCASECMP': ('strncasecmp', 'strings.h'),\n 'HAVE_STRSIGNAL': ('strsignal', 'signal.h'),\n 'HAVE_STRTOD_L': ('strtod_l', 'stdlib.h'),\n 'HAVE_STRTOLL_L': ('strtoll_l', 'stdlib.h'),\n 'HAVE_STRTOULL_L': ('strtoull_l', 'stdlib.h'),\n 'HAVE_SYMLINK': ('symlink', 'unistd.h'),\n 'HAVE_SYSCTLBYNAME': ('sysctlbyname', 'sys/sysctl.h'),\n 'HAVE_TIMEGM': ('timegm', 'time.h'),\n 'HAVE_USELOCALE': ('uselocale', 'xlocale.h'),\n 'HAVE_UTIMES': ('utimes', 'sys/time.h'),\n 'HAVE_VALLOC': ('valloc', 'stdlib.h'),\n 'HAVE_VASPRINTF': ('vasprintf', 'stdio.h'),\n 'HAVE_VSNPRINTF': ('vsnprintf', 'stdio.h'),\n 'HAVE_BCOPY': ('bcopy', 'strings.h'),\n 'HAVE_STRERROR': ('strerror', 'string.h'),\n 'HAVE_MEMMOVE': ('memmove', 'string.h'),\n 'HAVE_STRTOIMAX': ('strtoimax', 'inttypes.h'),\n 'HAVE_STRTOLL': ('strtoll', 'stdlib.h'),\n 'HAVE_STRTOQ': ('strtoq', 'stdlib.h'),\n 'HAVE_ACCEPT4': ('accept4', 'sys/socket.h'),\n 'HAVE_CHMOD': ('chmod', 'sys/stat.h'),\n 'HAVE_CHOWN': ('chown', 'unistd.h'),\n 'HAVE_FSTAT': ('fstat', 'sys/stat.h'),\n 'HAVE_GETADDRINFO': ('getaddrinfo', 'netdb.h'),\n 'HAVE_GETGRGID_R': ('getgrgid_r', 'grp.h'),\n 'HAVE_GETGRNAM_R': ('getgrnam_r', 'grp.h'),\n 'HAVE_GETGROUPS': ('getgroups', 'grp.h'),\n 'HAVE_GETOPT_LONG': ('getopt_long', 'getopt.h'),\n 'HAVE_GETPWNAM_R': ('getpwnam', 'pwd.h'),\n 'HAVE_GETPWUID_R': ('getpwuid_r', 'pwd.h'),\n 'HAVE_GETUID': ('getuid', 'unistd.h'),\n 'HAVE_LRINTF': ('lrintf', 'math.h'),\n 'HAVE_DECL_ISNAN': ('isnan', 'math.h'),\n 'HAVE_DECL_ISINF': ('isinf', 'math.h'),\n 'HAVE_ROUND': ('round', 'math.h'),\n 'HAVE_NEARBYINT': ('nearbyint', 'math.h'),\n 'HAVE_RINT': ('rint', 'math.h'),\n 'HAVE_MKFIFO': ('mkfifo', 'sys/stat.h'),\n 'HAVE_MLOCK': ('mlock', 'sys/mman.h'),\n 'HAVE_NANOSLEEP': ('nanosleep', 'time.h'),\n 'HAVE_PIPE': ('pipe', 'unistd.h'),\n 'HAVE_PPOLL': ('ppoll', 'poll.h'),\n 'HAVE_REGEXEC': ('regexec', 'regex.h'),\n 'HAVE_SETEGID': ('setegid', 'unistd.h'),\n 'HAVE_SETEUID': ('seteuid', 'unistd.h'),\n 'HAVE_SETPGID': ('setpgid', 'unistd.h'),\n 'HAVE_SETREGID': ('setregid', 'unistd.h'),\n 'HAVE_SETRESGID': ('setresgid', 'unistd.h'),\n 'HAVE_SETRESUID': ('setresuid', 'unistd.h'),\n 'HAVE_SHM_OPEN': ('shm_open', 'fcntl.h'),\n 'HAVE_SLEEP': ('sleep', 'unistd.h'),\n 'HAVE_STRERROR_R': ('strerror_r', 'string.h'),\n 'HAVE_STRTOF': ('strtof', 'stdlib.h'),\n 'HAVE_SYSCONF': ('sysconf', 'unistd.h'),\n 'HAVE_USLEEP': ('usleep', 'unistd.h'),\n 'HAVE_VFORK': ('vfork', 'unistd.h'),\n 'HAVE_MALLOC': ('malloc', 'stdlib.h'),\n 'HAVE_CALLOC': ('calloc', 'stdlib.h'),\n 'HAVE_REALLOC': ('realloc', 'stdlib.h'),\n 'HAVE_FREE': ('free', 'stdlib.h'),\n 'HAVE_ALLOCA': ('alloca', 'alloca.h'),\n 'HAVE_QSORT': ('qsort', 'stdlib.h'),\n 'HAVE_ABS': ('abs', 'stdlib.h'),\n 'HAVE_MEMSET': ('memset', 'string.h'),\n 'HAVE_MEMCMP': ('memcmp', 'string.h'),\n 'HAVE_STRLEN': ('strlen', 'string.h'),\n 'HAVE_STRLCAT': ('strlcat', 'string.h'),\n 'HAVE_STRDUP': ('strdup', 'string.h'),\n 'HAVE__STRREV': ('_strrev', 'string.h'),\n 'HAVE__STRUPR': ('_strupr', 'string.h'),\n 'HAVE__STRLWR': ('_strlwr', 'string.h'),\n 'HAVE_INDEX': ('index', 'strings.h'),\n 'HAVE_RINDEX': ('rindex', 'strings.h'),\n 'HAVE_STRCHR': ('strchr', 'string.h'),\n 'HAVE_STRRCHR': ('strrchr', 'string.h'),\n 'HAVE_STRSTR': ('strstr', 'string.h'),\n 'HAVE_STRTOL': ('strtol', 'stdlib.h'),\n 'HAVE_STRTOUL': ('strtoul', 'stdlib.h'),\n 'HAVE_STRTOULL': ('strtoull', 'stdlib.h'),\n 'HAVE_STRTOD': ('strtod', 'stdlib.h'),\n 'HAVE_ATOI': ('atoi', 'stdlib.h'),\n 'HAVE_ATOF': ('atof', 'stdlib.h'),\n 'HAVE_STRCMP': ('strcmp', 'string.h'),\n 'HAVE_STRNCMP': ('strncmp', 'string.h'),\n 'HAVE_VSSCANF': ('vsscanf', 'stdio.h'),\n 'HAVE_ATAN': ('atan', 'math.h'),\n 'HAVE_ATAN2': ('atan2', 'math.h'),\n 'HAVE_ACOS': ('acos', 'math.h'),\n 'HAVE_ASIN': ('asin', 'math.h'),\n 'HAVE_ASINH': ('asinh', 'math.h'),\n 'HAVE_CEIL': ('ceil', 'math.h'),\n 'HAVE_COPYSIGN': ('copysign', 'math.h'),\n 'HAVE_COS': ('cos', 'math.h'),\n 'HAVE_COSH': ('cosh', 'math.h'),\n 'HAVE_COSF': ('cosf', 'math.h'),\n 'HAVE_FABS': ('fabs', 'math.h'),\n 'HAVE_FLOOR': ('floor', 'math.h'),\n 'HAVE_ISINF': ('isinf', 'math.h'),\n 'HAVE_LOG': ('log', 'math.h'),\n 'HAVE_POW': ('pow', 'math.h'),\n 'HAVE_SCALBN': ('scalbn', 'math.h'),\n 'HAVE_SIN': ('sin', 'math.h'),\n 'HAVE_SINF': ('sinf', 'math.h'),\n 'HAVE_SINH': ('sinh', 'math.h'),\n 'HAVE_SQRT': ('sqrt', 'math.h'),\n 'HAVE_FSEEKO': ('fseeko', 'stdio.h'),\n 'HAVE_FSEEKO64': ('fseeko64', 'stdio.h'),\n 'HAVE_SETJMP': ('setjmp', 'setjmp.h'),\n 'HAVE_PTHREAD_SETNAME_NP': ('pthread_setname_np', 'pthread.h'),\n 'HAVE_PTHREAD_SET_NAME_NP': ('pthread_set_name_np', 'pthread.h'),\n }\n\nheaders = []\nfunctions = []\nsizes = []\nwith open(sys.argv[1]) as f:\n for line in f:\n line = line.strip()\n arr = line.split()\n\n # Check for headers.\n if line.startswith('#mesondefine') and line.endswith('_H'):\n token = line.split()[1]\n tarr = token.split('_')[1:-1]\n tarr = [x.lower() for x in tarr]\n hname = '/'.join(tarr) + '.h'\n headers.append((token, hname))\n\n # Check for functions.\n try:\n token = arr[1]\n if token in function_data:\n fdata = function_data[token]\n functions.append((token, fdata[0], fdata[1]))\n elif token.startswith('HAVE_') and not token.endswith('_H'):\n functions.append((token, ))\n except Exception:\n pass\n\n # Check for sizeof tests.\n if len(arr) != 2:\n continue\n elem = arr[1]\n if elem.startswith('SIZEOF_'):\n typename = elem.split('_', 1)[1] \\\n .replace('_P', '*') \\\n .replace('_', ' ') \\\n .lower() \\\n .replace('size t', 'size_t')\n sizes.append((elem, typename))\n\nprint('''cc = meson.get_compiler('c')\ncdata = configuration_data()''')\n\n# Convert header checks.\n\nprint('check_headers = [')\nfor token, hname in headers:\n print(\" ['%s', '%s'],\" % (token, hname))\nprint(']\\n')\n\nprint('''foreach h : check_headers\n if cc.has_header(h.get(1))\n cdata.set(h.get(0), 1)\n endif\nendforeach\n''')\n\n# Convert function checks.\n\nprint('check_functions = [')\nfor token in functions:\n if len(token) == 3:\n token, fdata0, fdata1 = token\n print(\" ['%s', '%s', '#include<%s>'],\" % (token, fdata0, fdata1))\n else:\n print('# check token', token)\nprint(']\\n')\n\nprint('''foreach f : check_functions\n if cc.has_function(f.get(1), prefix : f.get(2))\n cdata.set(f.get(0), 1)\n endif\nendforeach\n''')\n\n# Convert sizeof checks.\n\nfor elem, typename in sizes:\n print(\"cdata.set('%s', cc.sizeof('%s'))\" % (elem, typename))\n\nprint('''\nconfigure_file(input : 'config.h.meson',\n output : 'config.h',\n configuration : cdata)''')\n","sub_path":"tools/ac_converter.py","file_name":"ac_converter.py","file_ext":"py","file_size_in_byte":12326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412367039","text":"import pickle\n\nclass Persona:\n def __init__(self,nombre):\n self.nombre = nombre\n def __str__(self):\n return self.nombre\n\n\nnombres = ['Hector','Mario','Marta']\npersonas = []\n\nfor n in nombres:\n p = Persona(n)\n personas.append(p)\n\nfichero = open(r'personas.pckl','wb')\npickle.dump(personas,fichero)\nfichero.close()\ndel(fichero)\n\nfichero = open(r'personas.pckl','rb')\npersonas_nuevas = pickle.load(fichero)\n\nfor persona in personas_nuevas:\n print(persona)","sub_path":"manejo_ficheros/ficheros_pickle_clases.py","file_name":"ficheros_pickle_clases.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"454886800","text":"from django.conf.urls import url\nfrom . import views\napp_name = 'app'\nurlpatterns = [\n url(r'^register/',views.register,name='register'),\n url(r'^users/',views.use,name=\"users\")\n]\n\n\n# \n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105445889","text":"from setuptools import setup, find_packages\n\ns = setup(\n name=\"MachineIt\",\n version=\"1.0.1\",\n license=\"MIT\",\n description=\"MachineIt is a package which compares data...\",\n url='https://github.com/gitnark/MachineIt.git',\n packages=find_packages(),\n install_requires=[],\n python_requires = \">= 3.4\",\n author=\"Conor Venus\",\n author_email=\"narktrading@gmail.com\",\n )","sub_path":"pypi_install_script/machineit-1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"56117476","text":"import random\nimport tempfile\n\nimport aiohttp\nimport langdetect\nfrom gtts import gTTS\nfrom langdetect import DetectorFactory\nfrom langdetect.lang_detect_exception import LangDetectException\n\nfrom plugin_system import Plugin\nfrom utils import load_settings, SenderUser\n\nADDITIONAL_LANGUAGES = {\n 'uk': 'Ukrainian',\n}\n\ngTTS.LANGUAGES.update(ADDITIONAL_LANGUAGES)\n\nDetectorFactory.seed = 0\n\nplugin = Plugin('Голос', usage=[\"скажи [выражение] - бот сформирует \"\n \"голосовое сообщение на основе текста голосом Google\",\n \"озвуч [выражение] - бот сформирует \"\n \"голосовое сообщение на основе текста голосом Yandex\"])\n\nFAIL_MSG = 'Я не смог это произнести :('\n\n\n@plugin.on_init()\nasync def on_init(vk):\n plugin.temp_data['s'] = load_settings(plugin)\n\n\n@plugin.on_command('скажи')\nasync def say_text_google(msg, args):\n # Используется озвучка гугла gTTS\n try:\n text, lang = await args_validation(msg, args, 'google')\n tts = gTTS(text=text, lang=lang)\n # Сохраняем файл с голосом\n # TODO: Убрать сохранение (хранить файл в памяти)\n tts.save('audio.mp3')\n audio_file = open('audio.mp3', 'rb')\n await upload_voice(msg, audio_file)\n except ValueError:\n pass\n\n\n@plugin.on_command('озвуч')\nasync def say_text_yandex(msg, args):\n # Используется озвучка яндекса. Класс yTTS\n try:\n text, lang = await args_validation(msg, args, 'yandex')\n\n kwargs = {}\n if plugin.temp_data['s'].get('key', ''):\n kwargs['key'] = plugin.temp_data['s']['key']\n\n tts = yTTS(text=text, lang=lang, **kwargs)\n tmp_file = await tts.save()\n audio_file = tmp_file.read()\n await upload_voice(msg, audio_file)\n except ValueError:\n pass\n\n\nasync def args_validation(msg, args=None, tts='google'):\n # Функция проверяет текст на соответствие правилам\n # Возвращает текст и язык сообщения или возбуждает исключение\n google_limit = 450\n yandex_limit = 2000\n\n if not args:\n await msg.answer('Вы не ввели сообщение!\\nПример: скажи <текст>')\n raise ValueError\n\n text = ' '.join(args)\n text_length = google_limit if tts == 'google' else yandex_limit\n if len(text) > text_length:\n await msg.answer('Слишком длинное сообщение!')\n raise ValueError\n\n lang = get_lang(text)\n return text, lang\n\n\nasync def get_data(url, params=None):\n async with aiohttp.ClientSession() as sess:\n async with sess.get(url, data=params) as resp:\n if resp.status != 200:\n raise ValueError\n return await resp.read()\n\n\nasync def upload_voice(msg, audio_file):\n sender = SenderUser(msg.vk.current_user)\n\n # Получаем URL для загрузки аудио сообщения\n upload_method = 'docs.getUploadServer'\n upload_server = await msg.vk.method(upload_method, {'type': 'audio_message'}, send_from=sender)\n url = upload_server.get('upload_url')\n if not url:\n return await msg.answer(FAIL_MSG)\n\n # Загружаем аудио через aiohttp\n form_data = aiohttp.FormData()\n form_data.add_field('file', audio_file)\n async with aiohttp.ClientSession() as session:\n async with session.post(url, data=form_data) as resp:\n file_url = await resp.json()\n\n file = file_url.get('file')\n\n if not file:\n return await msg.answer(FAIL_MSG + 'NOT_FILE')\n\n # Сохраняем файл в документы (чтобы можно было прикрепить к сообщению)\n saved_data = await msg.vk.method('docs.save', {'file': file}, send_from=sender)\n if not saved_data:\n return await msg.answer(FAIL_MSG)\n # Получаем первый элемент, так как мы сохранили 1 файл\n media = saved_data[0]\n media_id, owner_id = media['id'], media['owner_id']\n # Прикрепляем аудио к сообщению :)\n await msg.answer('', attachment=f'doc{owner_id}_{media_id}')\n\n\ndef get_lang(text):\n try:\n lang = langdetect.detect(text)\n if lang in ('mk', 'bg'):\n lang = 'ru'\n except LangDetectException:\n lang = 'ru'\n return lang\n\n\nclass yTTS(object):\n base_url = \"https://tts.voicetech.yandex.net/tts\"\n\n speakers = [\"jane\", \"oksana\", \"alyss\", \"omazh\", \"zahar\", \"ermil\"]\n emotion = [\"good\", \"neutral\", \"evil\"]\n\n def __init__(self, text, lang='ru_RU', **kwargs):\n # Инициализируем данные для запроса\n self.params = {\n \"text\": text,\n \"lang\": self.get_lang_name(lang),\n \"emotion\": random.choice(self.emotion),\n \"speaker\": random.choice(self.speakers),\n \"speed\": random.uniform(0.3, 1.5),\n \"format\": 'mp3',\n }\n if not kwargs.get('key'):\n pass\n # hues.info('Получите ключ в кабинете разработчика yandex cloud.')\n self.params.update(kwargs)\n\n async def save(self):\n # Возвращает объект временного файла. Асинхронно.\n tmp = tempfile.NamedTemporaryFile(suffix='.mp3')\n data = await get_data(self.base_url, self.params)\n with open(tmp.name, 'wb') as f:\n f.write(data)\n return tmp\n\n def save_file(self, name='test.mp3'):\n # Сохраняет в файл. Синхронно.\n import requests\n resp = requests.get(self.base_url, params=self.params, stream=True)\n resp.raise_for_status()\n with open(name, 'wb') as f:\n f.write(resp.content)\n for chunk in resp.iter_content(chunk_size=1024):\n f.write(chunk)\n\n @staticmethod\n def get_lang_name(lang):\n # Преобразует коды стран в понятный формат для yandex speech cloud\n # Яндекс поддерживает только 4 языка: RU, UK, EN, TR\n languages = {\n 'en': 'en_US',\n 'ru': 'ru_RU',\n 'uk': 'uk_UK',\n 'tr': 'tr_TR',\n }\n if lang in languages:\n return languages[lang]\n else:\n return languages['ru']\n\n\n","sub_path":"plugins/tts/tts.py","file_name":"tts.py","file_ext":"py","file_size_in_byte":6763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442233944","text":"from django.views.generic import TemplateView, CreateView, UpdateView, FormView\nfrom braces.views import LoginRequiredMixin, MultiplePermissionsRequiredMixin\nfrom django.conf import settings\nfrom usuarios import forms, models\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.models import Permission, Group\nfrom django.shortcuts import redirect\nfrom usuarios.models import PaqueteActivacion, CodigoActivacion\nfrom usuarios.tasks import build_file_paquete_activacion\n# Create your views here.\n\n#------------------------------- SELECCIÓN ----------------------------------------\n\nclass UsuariosoptionsView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/lista.html'\n permissions = {\n \"all\": [\"usuarios.usuarios.ver\"]\n }\n\n def dispatch(self, request, *args, **kwargs):\n items = self.get_items()\n if len(items) == 0:\n return redirect(self.login_url)\n return super(UsuariosoptionsView, self).dispatch(request, *args, **kwargs)\n\n def get_items(self):\n items = []\n\n if self.request.user.has_perm('usuarios.usuarios.cuentas.ver'):\n items.append({\n 'sican_categoria': 'Cuentas',\n 'sican_color': 'orange darken-4',\n 'sican_order': 1,\n 'sican_url': 'cuentas/',\n 'sican_name': 'Cuentas',\n 'sican_icon': 'group',\n 'sican_description': 'Gestión y creación'\n })\n\n if self.request.user.has_perm('usuarios.usuarios.roles.ver'):\n items.append({\n 'sican_categoria': 'Roles',\n 'sican_color': 'green darken-4',\n 'sican_order': 2,\n 'sican_url': 'roles/',\n 'sican_name': 'Roles',\n 'sican_icon': 'class',\n 'sican_description': 'Perfiles de usuario'\n })\n\n if self.request.user.has_perm('usuarios.usuarios.permisos.ver'):\n items.append({\n 'sican_categoria': 'Permisos',\n 'sican_color': 'brown darken-4',\n 'sican_order': 3,\n 'sican_url': 'permisos/',\n 'sican_name': 'Permisos',\n 'sican_icon': 'add_box',\n 'sican_description': 'Directivas de acceso'\n })\n\n if self.request.user.has_perm('usuarios.usuarios.codigos.ver'):\n items.append({\n 'sican_categoria': 'Codigos',\n 'sican_color': 'blue-grey darken-4',\n 'sican_order': 4,\n 'sican_url': 'codigos/',\n 'sican_name': 'Codigos',\n 'sican_icon': 'vpn_key',\n 'sican_description': 'Claves para la activación de usuarios'\n })\n\n return items\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"usuarios\"\n kwargs['items'] = self.get_items()\n return super(UsuariosoptionsView,self).get_context_data(**kwargs)\n\n#----------------------------------------------------------------------------------\n\n#----------------------------------- HV -------------------------------------------\n\nclass GestionHvView(LoginRequiredMixin,\n FormView):\n \"\"\"\n \"\"\"\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/hv.html'\n form_class = forms.HojaDeVidaForm\n success_url = \"../\"\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"MI HOJA DE VIDA\"\n return super(GestionHvView,self).get_context_data(**kwargs)\n\n def get_initial(self):\n return {'user':self.request.user.id}\n\n#----------------------------------------------------------------------------------\n#-------------------------------- CUENTAS -----------------------------------------\n\nclass CuentasListView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\"usuarios.usuarios.cuentas.ver\"]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/cuentas/lista.html'\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"cuentas de usuario\"\n kwargs['url_datatable'] = '/rest/v1.0/usuarios/cuentas/'\n kwargs['permiso_crear'] = self.request.user.has_perm('usuarios.usuarios.cuentas.crear')\n return super(CuentasListView,self).get_context_data(**kwargs)\n\n\nclass CuentasCreateView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n CreateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.cuentas.ver\",\n \"usuarios.usuarios.cuentas.crear\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/cuentas/crear.html'\n form_class = forms.UserForm\n success_url = \"../\"\n model = models.User\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"CREAR USUARIO\"\n return super(CuentasCreateView,self).get_context_data(**kwargs)\n\n\nclass CuentasUpdateView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n UpdateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.cuentas.ver\",\n \"usuarios.usuarios.cuentas.editar\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/cuentas/editar.html'\n form_class = forms.UserForm\n success_url = \"../../\"\n model = models.User\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"ACTUALIZAR USUARIO\"\n kwargs['breadcrum_active'] = models.User.objects.get(id=self.kwargs['pk']).email\n return super(CuentasUpdateView,self).get_context_data(**kwargs)\n\n#----------------------------------------------------------------------------------\n\n#--------------------------------- ROLES ------------------------------------------\n\nclass RolesListView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/roles/lista.html'\n permissions = {\n \"all\": [\"usuarios.usuarios.roles.ver\"]\n }\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"roles\"\n kwargs['url_datatable'] = '/rest/v1.0/usuarios/roles/'\n kwargs['permiso_crear'] = self.request.user.has_perm('usuarios.usuarios.roles.crear')\n return super(RolesListView,self).get_context_data(**kwargs)\n\n\nclass RolesCreateView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n CreateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.roles.ver\",\n \"usuarios.usuarios.roles.crear\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/roles/crear.html'\n form_class = forms.GroupForm\n success_url = \"../\"\n model = Group\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"crear rol\"\n return super(RolesCreateView,self).get_context_data(**kwargs)\n\nclass RolesUpdateView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n UpdateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.roles.ver\",\n \"usuarios.usuarios.roles.editar\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/roles/editar.html'\n form_class = forms.GroupForm\n success_url = \"../../\"\n model = Group\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"actualizar rol\"\n kwargs['breadcrum_active'] = Group.objects.get(id=self.kwargs['pk']).name\n return super(RolesUpdateView,self).get_context_data(**kwargs)\n\n#----------------------------------------------------------------------------------\n\n#------------------------------- PERMISOS -----------------------------------------\n\nclass PermisosListView(LoginRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/permisos/lista.html'\n permissions = {\n \"all\": [\"usuarios.usuarios.permisos.ver\"]\n }\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"permisos\"\n kwargs['url_datatable'] = '/rest/v1.0/usuarios/permisos/'\n kwargs['permiso_crear'] = self.request.user.has_perm('usuarios.usuarios.permisos.crear')\n return super(PermisosListView,self).get_context_data(**kwargs)\n\nclass PermisosCreateView(LoginRequiredMixin,\n CreateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.permisos.ver\",\n \"usuarios.usuarios.permisos.crear\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/permisos/crear.html'\n form_class = forms.PermisoForm\n success_url = \"../\"\n model = Permission\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"crear permiso\"\n return super(PermisosCreateView,self).get_context_data(**kwargs)\n\nclass PermisosUpdateView(LoginRequiredMixin,\n UpdateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.permisos.ver\",\n \"usuarios.usuarios.permisos.editar\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/permisos/editar.html'\n form_class = forms.PermisoForm\n success_url = \"../../\"\n model = Permission\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"editar permiso\"\n kwargs['breadcrum_active'] = Permission.objects.get(id = self.kwargs['pk']).codename\n return super(PermisosUpdateView,self).get_context_data(**kwargs)\n\n#----------------------------------------------------------------------------------\n\n#------------------------------- CODIGOS -----------------------------------------\n\nclass CodigosListView(LoginRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/codigos/lista.html'\n permissions = {\n \"all\": [\"usuarios.usuarios.codigos.ver\"]\n }\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"paquetes de códigos\"\n kwargs['url_datatable'] = '/rest/v1.0/usuarios/paquetes/'\n kwargs['permiso_crear'] = self.request.user.has_perm('usuarios.usuarios.codigos.crear')\n return super(CodigosListView,self).get_context_data(**kwargs)\n\nclass CodigosCreateView(LoginRequiredMixin,\n CreateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.codigos.ver\",\n \"usuarios.usuarios.codigos.crear\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/codigos/crear.html'\n form_class = forms.PaqueteCodigoForm\n success_url = \"../\"\n model = PaqueteActivacion\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"crear paquete de códigos\"\n return super(CodigosCreateView,self).get_context_data(**kwargs)\n\n def form_valid(self, form):\n\n description = form.cleaned_data['description']\n generados = form.cleaned_data['generados']\n permisos = form.cleaned_data['permissions']\n\n self.object = PaqueteActivacion.objects.create(\n description = description,\n generados = generados,\n usados = 0,\n )\n self.object.permissions.set(permisos)\n self.object.save()\n\n\n build_file_paquete_activacion.delay(str(self.object.id),self.request.user.email)\n\n return HttpResponseRedirect(self.get_success_url())\n\nclass CodigosUpdateView(LoginRequiredMixin,\n UpdateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\n \"usuarios.usuarios.codigos.ver\",\n \"usuarios.usuarios.codigos.crear\"\n ]\n }\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/codigos/editar.html'\n form_class = forms.PaqueteCodigoUpdateForm\n success_url = \"../../\"\n model = PaqueteActivacion\n\n def form_valid(self, form):\n self.object = form.save()\n return super(CodigosUpdateView, self).form_valid(form)\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"crear paquete de códigos\"\n return super(CodigosUpdateView,self).get_context_data(**kwargs)\n\n\nclass CodigosShowView(LoginRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n login_url = settings.LOGIN_URL\n template_name = 'usuarios/codigos/lista_codigos.html'\n permissions = {\n \"all\": [\"usuarios.usuarios.codigos.ver\"]\n }\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"paquetes de códigos\"\n kwargs['url_datatable'] = '/rest/v1.0/usuarios/paquetes/' + str(kwargs['pk'])\n kwargs['descripcion'] = PaqueteActivacion.objects.get(id=kwargs['pk']).description\n return super(CodigosShowView,self).get_context_data(**kwargs)\n\n#----------------------------------------------------------------------------------","sub_path":"sican_2018/usuarios/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593199637","text":"from chainer import cuda\nfrom chainer import gradient_check\nimport numpy\nimport pytest\n\nfrom chainer_chemistry.links.connection.graph_mlp import GraphMLP # NOQA\n\nin_size = 3\natom_size = 5\nout_size = 4\nchannels = [16, out_size]\nbatch_size = 2\n\n\n@pytest.fixture\ndef model():\n l = GraphMLP(channels, in_channels=in_size)\n l.cleargrads()\n return l\n\n\n@pytest.fixture\ndef data():\n x_data = numpy.random.uniform(\n -1, 1, (batch_size, atom_size, in_size)).astype(numpy.float32)\n y_grad = numpy.random.uniform(\n -1, 1, (batch_size, atom_size, out_size)).astype(numpy.float32)\n return x_data, y_grad\n\n\ndef test_forward_cpu(model, data):\n # only testing shape for now...\n x_data = data[0]\n y_actual = model(x_data)\n assert y_actual.shape == (batch_size, atom_size, out_size)\n assert len(model.layers) == len(channels)\n\n\n@pytest.mark.gpu\ndef test_forward_gpu(model, data):\n x_data = cuda.to_gpu(data[0])\n model.to_gpu()\n y_actual = model(x_data)\n assert y_actual.shape == (batch_size, atom_size, out_size)\n assert len(model.layers) == len(channels)\n\n\ndef test_backward_cpu(model, data):\n x_data, y_grad = data\n gradient_check.check_backward(model, x_data, y_grad, list(model.params()),\n atol=1e-3, rtol=1e-3)\n\n\n@pytest.mark.gpu\ndef test_backward_gpu(model, data):\n x_data, y_grad = [cuda.to_gpu(d) for d in data]\n model.to_gpu()\n gradient_check.check_backward(model, x_data, y_grad, list(model.params()),\n atol=1e-3, rtol=1e-3)\n\n\nif __name__ == '__main__':\n pytest.main([__file__, '-v', '-s'])\n","sub_path":"tests/links_tests/connection_tests/test_graph_mlp.py","file_name":"test_graph_mlp.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82741933","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 13 22:38:06 2019\r\n\r\n@author: dipie\r\n\"\"\"\r\n\r\nimport time\r\nfrom operator import itemgetter\r\nfrom itertools import groupby, takewhile\r\n\r\n#Ready, set, go!\r\nstart = time.time()\r\n\r\n#This file has the raw data\r\ndef cleanData(filepath):\r\n with open(filepath, \"r\", encoding=\"unicode_escape\") as file:\r\n #Create an array with partially clean data\r\n parsedresults = []\r\n for line in file:\r\n if \"=\" in line: parsedresults.append(line)\r\n data = [x.replace(\"DNF\",\"99\").replace(\"DNS\",\"98\") for x in parsedresults]\r\n return data\r\n\r\ndef getNumbers(data):\r\n numbers = [[a for a in line if a.isdigit()] for line in data]\r\n numbers = [(x[0]+x[1],x[2]+x[3],x[4]+x[5]) for x in numbers]\r\n numbers = [[int(x) for x in l] for l in numbers]\r\n numbers = [(x+[round((sum(x)/3),2)]) for x in numbers]\r\n numbers = [[str(n) for n in x] for x in numbers]\r\n numbers = [[s.replace(\"99\",\"DNF\").replace(\"98\",\"DNS\") for s in x] for x in numbers]\r\n for each in numbers:\r\n if \"DNF\" in each or \"DNS\" in each:\r\n each[3] = \"DNF\"\r\n return numbers\r\n\r\ndef getNames(data):\r\n data = [[''.join(list(takewhile((lambda x: not x.isdigit()),l))[0:-1])] for l in data]\r\n return data\r\n\r\ndef genDataArray(rawdata):\r\n names = getNames(rawdata)\r\n numbers = getNumbers(rawdata)\r\n arr = [names[i]+numbers[i] for i in range(len(names))]\r\n arr = list(sorted(arr, key=itemgetter(3,4)))\r\n arr = [[str(i+1)] + l for i,(k,g) in enumerate(groupby(arr,key=itemgetter(3,4))) for l in g]\r\n return arr\r\n\r\ntest = genDataArray(cleanData(\"FMCranks.txt\"))\r\n\r\n#Finished!\r\nprint(str(time.time() - start) + \" seconds elapsed.\\nEnjoy ;D\")","sub_path":"FMCranksParserV3.py","file_name":"FMCranksParserV3.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588801275","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n'''This script demonstrates how to read in a csv file using the pandas library, clean up table of data so that it is organized properly, how to display some of\nthat information, and how to plot that information '''\n\n\n\nimport pandas as pd\n\n\n\n# Below we read in a csv file and fix the order of information -- sep tells panda what is separating the data, encoding is the language (french), parse_dates=['Date']\n# and in this case the day does come first, our first column, index col, is the Date column. Now panda can read in the data properly\nbikes = pd.read_csv('/home/tyler/Desktop/Dolezal_Python_Practice/p_cookbook/data/bikes.csv', sep = ';' , encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')\n\n\n#print(bikes[:3]) #displaying, in table form, the data from the csv file\n\n\n#bikes.plot(figsize = (20,10)) #plots each column of the csv file\n\n\n'''----------- Adding in weekdays to our data; focusing just on the Berri 1 path --------------------''' \n\n\n\nberri_bikes = bikes[['Berri 1']].copy()\n\n# berri_bikes.index.weekday #this command displays which day of the week each date is; where 0 is Monday and 6 is Sunday\n\n# Now we are are going to add in a column to our berri_bikes data\n\nberri_bikes.loc[:, 'Weekday'] = berri_bikes.index.weekday # adds a column titled Weekday to our berri_bikes data\n\n\n\n'''---------------------------- Now we can sum up the amount of bikers present on a given weekday by using the groupby command ------------------'''\n\n\n\nwkday_counts = berri_bikes.groupby('Weekday').aggregate(sum)\n\n#lets replace 0, 1, etc with the name of the day\n\nwkday_counts.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\nwkday_counts.plot(figsize = (15,7.5), kind ='bar')\n\n\n'''--------------------------------- Another Example using trail named Rachel1 ---------------------------------------------------------'''\n\nrachel_bikes = bikes[['Rachel1']].copy()\n\nrachel_bikes.loc[:, 'Weekdays'] = rachel_bikes.index.weekday\n\nwkdayR_counts = rachel_bikes.groupby('Weekdays').aggregate(sum)\n\nwkdayR_counts.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\nwkdayR_counts.plot(figsize = (15,7.5), kind = 'bar')\n\n'''----------------------------------------- Comparing two trails against one another --------------------------------------------------------'''\n\ncomp_bikes = bikes[['Berri 1', 'Rachel1']].copy()\n\ncomp_bikes.loc[:,'Weekday'] = comp_bikes.index.weekday\n\nwkdayC_counts = comp_bikes.groupby('Weekday').aggregate(sum)\n\nwkdayC_counts.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\nwkdayC_counts.plot(figsize=(15,7.5),kind ='bar')","sub_path":"read_csv_plot_correct.py","file_name":"read_csv_plot_correct.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"495366356","text":"import torch\nimport argparse\n\nfrom torch.jit import trace\n\nfrom config import Params\nfrom network import MobileNetv2_DeepLabv3\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Transfer PyTorch Model to Torch Script Model')\n parser.add_argument('--ckp_file', default=None, help='Path to a pytorch checkpoint')\n parser.add_argument('--save_path', default='deeplab-traced-eval.pth', help='Path to save torch script model')\n args = parser.parse_args()\n\n params = Params()\n net = MobileNetv2_DeepLabv3(params)\n\n pretrain = torch.load(args.ckp_file)\n net.network.load_state_dict(pretrain[\"state_dict\"])\n\n net.network.eval()\n\n image_cuda = torch.rand(1, 3, 512, 1689).cuda()\n\n with torch.no_grad():\n traced_model = trace(net.network, image_cuda)\n\n traced_model.save(args.save_path)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"to_torch_script.py","file_name":"to_torch_script.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"444507558","text":"#!/usr/bin/env python\n\"\"\"\nThis is a convenience script for running BIRRP. \n\narguments:\nbirrp executable, stationname (uppercase), directory containing time series files, coherence threshold\n\nA subfolder 'birrp_processed' for the output is generated within the time series directory \n\n\"\"\"\n\n\nimport numpy as np\nimport re\nimport sys, os\nimport glob\nimport os.path as op\nimport glob\nimport calendar\nimport time\n\n\nimport mtpy.utils.exceptions as MTex\n\nimport mtpy.processing.birrp as MTbp\nreload(MTbp)\n\n\ndef main():\n\n if len(sys.argv) < 4:\n print('\\nNeed at least 3 arguments: '\\\n ' \\n\\n'\\\n 'Optional arguments: \\n [coherence threshold]\\n'\\\n ' [start time] \\n [end time]\\n\\n')\n return\n\n try:\n coherence_th = float(sys.argv[4])\n if not 0 <= coherence_th <= 1: \n raise\n except: \n print('coherence value invalid (float from interval [0,1]) - set to 0 instead')\n coherence_th = 0\n\n try:\n starttime = float(sys.argv[5])\n except:\n starttime = None\n\n try:\n endtime = float(sys.argv[6])\n except:\n endtime = None\n \n\n birrp_exe_raw = sys.argv[1] \n birrp_exe = op.abspath(op.realpath(birrp_exe_raw))\n\n if not op.isfile(birrp_exe):\n raise MTex.MTpyError_inputarguments('Birrp executable not existing: %s' % (birrp_exe))\n\n stationname = sys.argv[2].upper()\n\n ts_dir_raw = sys.argv[3]\n ts_dir = op.abspath(op.realpath(ts_dir_raw))\n\n\n if not op.isdir(ts_dir):\n raise MTex.MTpyError_inputarguments('Time series directory not existing: %s' % (ts_dir))\n\n if 1:\n MTbp.runbirrp_Nin2out_simple(birrp_exe, stationname, ts_dir, coherence_th,\n None, 2,None, starttime, endtime)\n # except:\n # print 'ERROR - Could not process input data using BIRRP'\n\n\n\nif __name__=='__main__':\n main()\n","sub_path":"mtpy/uofa/birrp_2in2out_simple.py","file_name":"birrp_2in2out_simple.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539623403","text":"import logging\nfrom pyVmomi import vim\n\nfrom .operator import Operator, OperatorError\n\nlogger = logging.getLogger()\n\n\nclass Uninstall(Operator):\n def run(self, vm, env=None):\n logger.info(\"Operation: Uninstall\")\n choco_bin = \"C:\\\\ProgramData\\\\chocolatey\\\\bin\\\\choco.exe\"\n uninstall_success = True\n for app in self.params:\n if app in self.conf[\"choco_apps\"]:\n arguments = \"uninstall -y {}\".format(app)\n logger.debug(\"Removing {}\".format(app))\n success = vm.execute_cmd(choco_bin, arguments, run_async=False)\n if not success:\n logger.warning(\"Some errors with {} removing\".format(app))\n uninstall_success = False\n else:\n (cmd, arguments) = app.split(\" \", 1)\n logger.debug(\"{} is not in chocolatey repo, run it as binary {} | Args: {}\".format(app, cmd, arguments))\n try:\n success = vm.execute_cmd(cmd, arguments, run_async=False, timeout=self.conf[\"max_installation_time\"])\n except vim.fault.FileNotFound:\n logger.error(\"File {} not found\".format(cmd))\n return False\n if not success:\n logger.warning(\"Some errors with {} installation\".format(app))\n uninstall_success = False\n return uninstall_success\n","sub_path":"src/operators/uninstall.py","file_name":"uninstall.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218563275","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QToolBar\nfrom PyQt5.QtWidgets import QAction, QStatusBar, QCheckBox\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import Qt\n\n\n# Subclass QMainWindow to customise your application's main window\nclass MainWindow(QMainWindow):\n\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.setWindowTitle(\"My Awesome App\")\n\n label = QLabel(\"This is a PyQt5 window!\")\n\n # The `Qt` namespace has a lot of attributes to customise\n # widgets. See: http://doc.qt.io/qt-5/qt.html\n label.setAlignment(Qt.AlignCenter)\n\n # Set the central widget of the Window. Widget will expand\n # to take up all the space in the window by default.\n self.setCentralWidget(label)\n\n toolbar = QToolBar(\"My main toolbar\")\n # disable right clicking on the toolbar to prevent user from hiding it\n toolbar.setContextMenuPolicy(Qt.PreventContextMenu)\n self.addToolBar(toolbar)\n\n button_action = QAction(QIcon(\"/home/ychoon/python-gui/gui-demo/fugue-icons-3.5.6/icons/calendar.png\"), \"My button\", self)\n button_action.setStatusTip(\"This is my button.\")\n button_action.triggered.connect(self.onMyToolBarButtonClick)\n button_action.setCheckable(True)\n toolbar.addAction(button_action)\n\n toolbar.addSeparator()\n\n button_action2 = QAction(QIcon(\"/home/ychoon/python-gui/gui-demo/fugue-icons-3.5.6/icons/bug.png\"), \"Your button2\", self)\n button_action2.setStatusTip(\"This is your button2\")\n button_action2.triggered.connect(self.onMyToolBarButtonClick)\n button_action2.setCheckable(True)\n toolbar.addAction(button_action2)\n\n toolbar.addWidget(QLabel(\"Hello\"))\n toolbar.addWidget(QCheckBox())\n\n toolbar.addSeparator()\n\n button_action3 = QAction(QIcon(\"/home/ychoon/python-gui/gui-demo/fugue-icons-3.5.6/bonus/icons-32/cross.png\"),\"Quit\", self)\n button_action3.triggered.connect(app.quit)\n toolbar.addAction(button_action3)\n\n self.setStatusBar(QStatusBar(self))\n\n def onMyToolBarButtonClick(self, s):\n print(\"clicked\", s)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n\n window = MainWindow()\n window.show()\n\n app.exec_()\n","sub_path":"gui-demo/myapp_window_toolbars.py","file_name":"myapp_window_toolbars.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82529504","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom transformers import AlbertPreTrainedModel, AlbertModel\n\n\nclass AlbertForAnswerSelectionWithConcat(AlbertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.albert = AlbertModel(config)\n self.dropout = nn.Dropout(config.classifier_dropout_prob)\n self.classifier = nn.Linear(\n config.hidden_size, 1)\n\n self.init_weights()\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n additional_feature=None,\n labels=None,\n answer_index=None,\n ):\n outputs = self.albert(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n )\n\n sequence_output = outputs[0] # B x L x d\n \n #print(sequence_output.shape)\n \n answer_index = answer_index.unsqueeze(-1).repeat(1,1,sequence_output.shape[-1])\n\n answer_output = torch.gather(sequence_output,dim = 1, index = answer_index) # B x Nans x d\n\n #print(answer_output.shape)\n logits = self.classifier(answer_output).squeeze() # B x Nans\n #print(logits.shape)\n\n #pooled_output = outputs[1]\n\n #pooled_output = self.dropout(pooled_output)\n\n #pooled_output = torch.cat((pooled_output, additional_feature), 1)\n\n #logits = self.classifier(pooled_output)\n\n # add hidden states and attention if they are here\n outputs = (logits,) + outputs[2:]\n\n\n if labels is not None:\n if self.num_labels == 1:\n # We are doing regression\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(\n logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs\n","sub_path":"MyNewModel.py","file_name":"MyNewModel.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"537875676","text":"import ffmpeg\nimport glob\nimport os\nfrom datetime import datetime\nimport time\nimport argparse\nfrom env_sidesmile_calc import text2lists\n\n\"\"\"\n1.連番画像のタイトルを取得\n2.与えられたフレームレートと1を使って、その画像が動画の何秒地点なのかを計算\n3.1のはじめから次の画像が0.3秒以内に存在するのかを確認\n4.あれば同一の笑いとみなす、なければ、次の笑い区間として2に戻る\n5.次の区間に移る際に、1秒以上笑い区間であれば、その区間の始まりと終わりの時間から真ん中を算��\n6.その真ん中から8秒手前2秒後の時に何秒地点なのかを変数(s=8,f=18)に保持\n7.配列の末尾の値内にsがなければ、変数を配列[[8,18],[25,35],[40,50]]に格納、あれば末尾の値の2番目にfを代入する\n8.配列内の値を使ってffmpegで前側カメラで撮影した動画を切り取った動画を出力する。\n\"\"\"\n\n\ndef cut_video(startT, input, output, path, f, pathtype):\n\n stream = ffmpeg.input(input)\n # path = \"./20190124201103_result/P_20190124201103/\"\n starttime = int(startT * 60) # 1は39分から,2は34分から\n framerate = f\n beforeTime = 0\n sumTime = 0\n time_List = []\n flg = False\n nextTime = -1\n\n if pathtype:\n filelist = text2lists(path)\n else:\n\n filelist = sorted(glob.glob(path + \"*.jpg\"))\n\n for file in filelist:\n if pathtype:\n file = file.split()\n file = file[0].replace(\"img/\", \"\").replace(\"image_\", \"\").replace(\".jpg\", \"\")\n else:\n file = os.path.splitext(os.path.basename(file))[0]\n fileTime = round(int(file.replace(\"image_\", \"\")) / int(framerate), 2)\n\n if fileTime < nextTime:\n # print(\"un\")\n continue\n # print(fileTime)\n # print(sumTime)\n elapsed = round(fileTime - beforeTime, 2)\n\n # 0.5秒ぶんより大きければ、次の区間へ\n if beforeTime == 0 or elapsed > 0.5:\n # 1笑い0.4~0.8が一番多かったため。\n if sumTime >= 0.4:\n mid = beforeTime - (sumTime / 2)\n s = mid - 8\n # s = (beforeTime - sumTime) + ((beforeTime - (beforeTime - sumTime)) / 2) - 8\n if s < 0:\n s = 0\n f = mid + 8\n # f = (beforeTime - sumTime) + ((beforeTime - (beforeTime - sumTime)) / 2) + 8\n time_List.append([s, f])\n nextTime = mid + 10\n # if time_List != [] and time_List[-1][1] > s:\n # time_List[-1][1] = f\n # else:\n # time_List.append([s, f])\n print(time_List)\n sumTime = 0\n else:\n print(\"sum:{0}\".format(sumTime))\n sumTime += elapsed\n beforeTime = fileTime\n # time_List = time_List + starttime\n\n for time_l in time_List:\n f = time_l[1] - time_l[0]\n s = time_l[0] + starttime\n print(time_l)\n dstream = ffmpeg.output(stream, output + str(s) + \"-\" + str(f) + \".avi\", t=f, ss=s)\n ffmpeg.run(dstream)\n # time.sleep(10)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"cutting video\")\n parser.add_argument(\"--starttime\", \"-s\", type=int, default=24, help=\"Start time\")\n parser.add_argument(\"--input\", \"-i\", type=str, help=\"Input movie\")\n parser.add_argument(\"--output\", \"-o\", type=str, help=\"Output dir\")\n parser.add_argument(\"--path\", \"-p\", type=str, help=\"imageFile dir or textfile\")\n parser.add_argument(\"--framerate\", \"-f\", type=int, default=25, help=\"framerate in the movie\")\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n\n args = parse_args()\n\n if os.path.isdir(args.path):\n pathtype = 0\n else:\n assert os.path.splitext(args.path) not in [\".txt\", \".dat\"], \"ファイルの拡張子は.txtか.datにしてね。\"\n pathtype = 1\n\n cut_video(args.starttime, args.input, args.output, args.path, args.framerate, pathtype)\n","sub_path":"detection/cut_video.py","file_name":"cut_video.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599352143","text":"# -*- coding:utf-8 -*-\n# @Author : 'longguangbin'\n# @Contact : lgb453476610@163.com\n# @Date : 2019/1/27\n\"\"\" \nUsage Of '121_max_profit.py' : \n\"\"\"\n\n\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # 32 ms\t- 80.10% | 28 ms - 99.84%\n if not prices:\n return 0\n min_v = 1e10\n res = 0\n for i in prices:\n if min_v > i:\n min_v = i\n res = max(res, i - min_v)\n return res\n\n def maxProfit2(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # 动态规划\n iCurrentMax = 0\n iFinalMax = 0\n for i in range(len(prices) - 1):\n iCurrentMax += prices[i + 1] - prices[i]\n if iCurrentMax < 0:\n iCurrentMax = 0\n if iCurrentMax > iFinalMax:\n iFinalMax = iCurrentMax\n return iFinalMax\n\n\ndef get_test_instance(example=1):\n prices = [7, 1, 5, 3, 6, 4]\n if example == 1:\n pass\n if example == 2:\n prices = [7, 6, 4, 3, 1]\n return prices\n\n\ndef main():\n prices = get_test_instance(example=1)\n # prices = get_test_instance(example=2)\n res = Solution().maxProfit(prices)\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"leetcode/dynamic_programming/121_max_profit.py","file_name":"121_max_profit.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"615965732","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom setuptools import setup, find_packages\n\nwith open(\"frank/__init__.py\", \"r\") as f:\n for line in f:\n if line.startswith('__version__'):\n version = line.split('=')[1].strip().strip('\"\\'')\n\nsetup(\n name=\"frank\",\n version=version,\n packages=find_packages(),\n include_package_data=True,\n author=\"Richard Booth, Jeff Jennings, Marco Tazzari\",\n author_email=\"jmj51@ast.cam.ac.uk\",\n description=\"Frankenstein, the flux reconstructor\",\n long_description_content_type=\"text/markdown\",\n long_description=open('README.md').read(),\n python_requires='>=3',\n install_requires=[line.rstrip() for line in open(\"requirements.txt\", \"r\").readlines()],\n extras_require={\n 'test' : ['pytest'],\n 'docs-build' : ['sphinx', 'sphinxcontrib-fulltoc', 'sphinx_rtd_theme', 'nbsphinx'],\n },\n license=\"GPLv3\",\n url=\"https://github.com/discsim/frank\",\n classifiers=[\n \"Development Status :: 1 - Planning\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)\",\n \"Programming Language :: Python :: 3\",\n ]\n)\n","sub_path":"pypi_install_script/frank-0.1.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155679904","text":"__all__ = [\"Magic\"]\n\nfrom Collider import Collider\nimport util\n\nfrom Vector2 import Vector2\nimport config\nimport pygame.transform\nimport math\n\n# Local settings\nMAGIC_SPEED = 5\nMAGIC_ATTACK_IMAGE = \"fireballRight.png\"\nMAGIC_DAMAGE = 2\n\nclass Magic(Collider):\n\t\t'''\n\t\t\t\tMagic class for the magic attack\n\t\t'''\n\t\tloadedImage = False\n\n\t\tdef __init__(self, x, y, direction, parent):\n\t\t\tsuper(Magic,self).__init__()\n\t\t\tself.dieoncollide = True\n\t\t\tself.parent = parent\n\n\t\t\tif not Magic.loadedImage:\n\t\t\t\tMagic.loadedImage,tmp = util.loadImage(MAGIC_ATTACK_IMAGE)\n\n\t\t\tself.setImage(Magic.loadedImage)\n\t\t\tself.setPos(x, y)\n\t\t\tself.setVel(direction.normalized() * MAGIC_SPEED)\n\t\t\tself.image = pygame.transform.rotate(self.image,270+360*(math.atan2(self.vel.x,self.vel.y)/6.28))\n\n\t\t#Use to find coordinates of mouse relative to current pos. Set Vector\n\t\tdef magicPath(self):\n\t\t\t\tpass\n\n\t\tdef damage(self, target):\n\t\t\ttarget.damaged(MAGIC_DAMAGE)\n\n\t\tdef hitplayer(self, clock, player):\n\t\t\tif self.collidex or self.collidey:\n\t\t\t\tself.damage(player)\n\t\t\tsuper(Magic, self).hitplayer(clock, player)\n\n\t\tdef hitenemy(self, clock, enemy):\n\t\t\tif self.collidex or self.collidey:\n\t\t\t\tself.damage(enemy)\n\t\t\tsuper(Magic, self).hitenemy(clock, enemy)\n\n\t\tdef update(self, clock, player, enemies, surfaces):\n\t\t\tsuper(Magic,self).update(clock, player, enemies, surfaces)\n\n\t\t\t#Kill magic object if it reaches the windows bounds.\n\t\t\tif self.rect.top > config.HEIGHT or self.rect.top < 0 or self.rect.right < 64 or self.rect.right > config.WIDTH - 64:\n\t\t\t\tself.kill()\n\n","sub_path":"src/Magic.py","file_name":"Magic.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160918109","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 15 20:26:13 2016\r\n\r\n@author: anayp2\r\n\"\"\"\r\n\r\n# For running\r\nimport random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom agent import agent\r\nimport func\r\nimport settings\r\n \r\nplotting=True\r\nreward=0\r\n#QM=np.zeros((9999,5))\r\nQM = np.loadtxt('test1.txt')\r\n#%% Learning loop starts\r\nfor i in range(settings.episodes):\r\n active=True # State of the Game\r\n detected=0\r\n crash=0\r\n#%% Initialize positions for each episode\r\n conInit= np.array([random.randrange(0,settings.gridSize[0]),0])\r\n patInit=np.array([random.randrange(0,settings.gridSize[0]),random.randrange(settings.gridSize[1]-1)])\r\n enemy=agent(patInit,'enemy',detected)\r\n convoy=agent( conInit,'convoy',detected)\r\n# print \"initiat\"+ str(convoy.location)+str(enemy.location)\r\n crash=func.crasher(crash, enemy, convoy ) #crash from beginning\r\n func.detector(enemy,convoy) #Detected from beginning\r\n#%% Start the episode\r\n timer=0\r\n while active and timer<=settings.maxSteps:\r\n if plotting:\r\n func.plotter(convoy,enemy) \r\n \r\n prevState=func.hashFunction(convoy,enemy) # Store in form of look up table\r\n action=func.convoyMovement(QM,prevState,convoy) #convoy movement\r\n crash=func.crasher(crash, enemy, convoy ) #crash ?\r\n func.detector(enemy,convoy) #Detected ?\r\n func.patrolMovement(enemy,convoy,prevState) #patrol movement\r\n crash=func.crasher(crash, enemy, convoy ) #crash ?\r\n func.detector(enemy,convoy) #Detected ?\r\n newState=func.hashFunction(convoy,enemy) # Store the new state in look up table\r\n if crash or timer==settings.maxSteps:\r\n active=False #Game ends\r\n reward=settings.losePenalty\r\n if plotting:\r\n func.plotter(convoy,enemy)\r\n plt.close()\r\n elif convoy.location[1]==settings.gridSize[1]-1:\r\n active=False\r\n reward=settings.winReward\r\n if plotting:\r\n func.plotter(convoy,enemy)\r\n plt.close()\r\n else:\r\n reward=settings.livReward \r\n# print convoy.location,enemy.location \r\n func.Qlearn(QM,prevState,action,newState,reward) #Update Q matrix\r\n timer=timer+1","sub_path":"run_learnt.py","file_name":"run_learnt.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"104640324","text":"# 给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。 \n# \n# \n# 如果剩余字符少于 k 个,则将剩余字符全部反转。 \n# 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。 \n# \n# \n# \n# \n# 示例: \n# \n# 输入: s = \"abcdefg\", k = 2\n# 输出: \"bacdfeg\"\n# \n# \n# \n# \n# 提示: \n# \n# \n# 该字符串只包含小写英文字母。 \n# 给定字符串的长度和 k 在 [1, 10000] 范围内。 \n# \n# Related Topics 字符串 \n# 👍 87 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n n = len(s)\n ans = \"\"\n for i in range(0,n,2*k):\n tmp = s[i:i +k]\n tmp = tmp[::-1] + s[i+k : i + 2*k]\n ans +=tmp\n return ans\n \n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_06/[541]反转字符串 II.py","file_name":"[541]反转字符串 II.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264917439","text":"#!/usr/bin/env python\n\n\"\"\"\nQuick and simple sequence cluster generator.\n\ndrift() will randomly change (insert/delete/subsitute) individual bases in a\nsequence with a given probability. By copying and then drift()ing sets of\nsequences we can make clusters of more or less similar sequences.\n\"\"\"\n\nimport sys\nfrom random import choice, random\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.Alphabet import generic_dna\n\nBASES = [\"A\", \"C\", \"T\", \"G\"]\n\ndef random_seq(length=100):\n s = [choice(BASES) for i in range(length)]\n s = ''.join(s)\n return(s)\n\ndef drift(seq, prob=0.1):\n seq = list(seq)\n for i in range(len(seq)):\n if random() < prob:\n new = choice(BASES + ['', '-'])\n if new == \"-\":\n new = choice(BASES)\n seq[i] = new\n seq = ''.join(seq)\n return(seq)\n\ndef create_clusters():\n # First, one random seq as three copies.\n seq = random_seq()\n seqs = [seq]*3\n # Change a bit.\n seqs = [drift(s, 0.3) for s in seqs]\n # These will be copies, to start.\n children = seqs + seqs\n children = [drift(s) for s in children]\n # Write the whole set. Give sequence IDs that show the grouping.\n combo = seqs + children\n combo = [Seq(''.join(s), generic_dna) for s in combo]\n prefix = [\"A\", \"B\", \"C\"]\n suffix = [\"a\", \"b\", \"c\"]\n labels = [\"%s_%s\" % (prefix[i//3], suffix[i%3]) for i in range(9)]\n recs = [SeqRecord(combo[i], id=labels[i], description='') for i in range(len(combo))]\n SeqIO.write(recs, sys.stdout, \"fasta\")\n\nif __name__ == '__main__':\n create_clusters()\n","sub_path":"simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599822643","text":"import sys\n\ndef frequency_calculation(word_counts,frequency,sentences):\n\tlength = len(sentences)\t\n\t# For loop will calculate the frequency values and round it to 3 d.p.\n\tfor keys, values in sorted(word_counts.items()):\n\t\ta = values/length\n\t\t# The frequency values are appended to a list\n\t\tfrequency.append(round(a,3))\n\ndef print_table(word_counts,frequency):\n\ti = 0\n\t# The name of the output file is the same as the input however .out is concatenated to it\n\tfile_output = open(sys.argv[1]+'.out','w')\n\t# The 'sorted' sorts the dictionary in lexographic order\n\t# This for loop will iterate over every item in both the list and dictionary and print them \n\tfor keys, items in sorted(word_counts.items()): \n\t\tcurrent_Freq = frequency[i]\n\t\tprinting = ('{} {} {}\\n'.format(keys,items,current_Freq))\n\t\tfile_output.write(printing)\n\t\ti+=1\n\tfile_output.close()\n\ndef frequency():\n\t# Opening the user-inputted file (second arguement)\n\tfile_input = open(sys.argv[1],'r')\n\tfrequency = []\n\tsentences = file_input.read().split()\n\t# Dictionary is generated\n\tword_counts = dict()\n\tfor word in sentences: \n\t\tif word in word_counts:\n\t\t\t# Increments if the word already exists in the dictionary and is repeated \n\t\t\tword_counts[word] += 1\n\t\telse: \n\t\t\t# If the word isnt in the dictionary it will be added\n\t\t\tword_counts[word] = 1\n\t\n\tfrequency_calculation(word_counts,frequency,sentences)\n\tprint_table(word_counts,frequency)\n\tfile_input.close()\n\n\nif __name__ == \"__main__\":\n\t# If and elif statement for error handling \t\t\n\tif len(sys.argv) > 2:\n\t\tprint('Too many arguements, enter only 2')\n\t\texit()\n\telif len(sys.argv) < 2:\n\t\tprint('Too little arguements, enter 2')\n\t\texit()\n\telse:\n\t\tpass\n\t\n\tfrequency()\n","sub_path":"freq.py","file_name":"freq.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200047289","text":"import os\nimport random \nimport argparse\n\ndef main():\n p = argparse.ArgumentParser()\n p.add_argument(\"--input_file\", type=str, \n help=\"input file id\")\n p.add_argument(\"--output_file\", type=str,\n help=\"output file id\")\n p.add_argument(\"--utts\", type=int, default=100,\n help=\"uttarance numbers\")\n p.add_argument(\"--tag\", type=str, default=\"\",\n help=\"evaluation tag\")\n args = p.parse_args()\n\n input_file = args.input_file\n output_file = args.output_file\n utts = args.utts\n if args.tag != \"\":\n tag = args.tag\n output_file = output_file + \"_\" + tag + \"_\" + str(utts)\n else:\n output_file = output_file + \"_\" + str(utts)\n with open(input_file, \"r\") as input_f:\n container = [a for a in input_f]\n try:\n utts <= len(container)\n except ValueError:\n print(\"uttarance is larger than samples\")\n \n random.seed(0)\n random.shuffle(container)\n evaluation_container = container[0: utts]\n\n with open(output_file, \"w\") as output_f:\n output_f.write(''.join(evaluation_container))\n \nif __name__ == \"__main__\":\n main()","sub_path":"generate_eval.py","file_name":"generate_eval.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"502126696","text":"from django.conf.urls import url\nfrom . import views\nfrom django.urls import include\n\napp_name = \"blogapp\"\n\nurlpatterns = [\n url(r'^$', views.index, name=\"index\"),\n url(r'^detail/(\\d+)/$', views.detail, name=\"detail\"),\n url(r'^tags/$', views.tags, name=\"tags\"),\n url(r'^langure/$', views.langure, name=\"langure\"),\n]","sub_path":"end/project4/myapp/apps/blogapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45100143","text":"import os\nos.chdir(os.path.dirname(os.path.abspath(__file__))) \nfrom getVocabList import getVocabList\nimport re # 정규식을 처리하기 위해 import\nfrom nltk.stem.porter import PorterStemmer # porterStemmer import\nimport numpy as np\n\ndef processEmail(email_contents):\n #PROCESSEMAIL preprocesses a the body of an email and\n #returns a list of word_indices \n # word_indices = PROCESSEMAIL(email_contents) preprocesses \n # the body of an email and returns a list of indices of the \n # words contained in the email. \n #\n \n # Load Vocabulary\n vocabList = getVocabList()\n \n # Init return value\n word_indices = []\n \n # ========================== Preprocess Email ===========================\n \n # Find the Headers ( \\n\\n and remove )\n # Uncomment the following lines if you are working with raw emails with the\n # full headers\n \n # hdrstart = strfind(email_contents, ([char(10) char(10)]));\n # email_contents = email_contents(hdrstart(1):end);\n \n # Lower case\n email_contents = str.lower(email_contents)\n\n # regexprep 를 re.sub 로 대체.\n # renew = re.sub(정규식 표현, 대체할 문자열, source)\n # reference : https://docs.python.org/3/library/re.html#module-re\n \n # Strip all HTML\n # Looks for any expression that starts with < and ends with > and replace\n # and does not have any < or > in the tag it with a space\n email_contents = re.sub('<[^<>]+>', '', email_contents)\n \n # Handle Numbers\n # Look for one or more characters between 0-9\n email_contents = re.sub('[0-9]+', 'number', email_contents)\n \n # Handle URLS\n # Look for strings starting with http:// or https://\n email_contents = re.sub('(http|https)://[^\\s]*', 'httpaddr', email_contents)\n \n # Handle Email Addresses\n # Look for strings with @ in the middle\n email_contents = re.sub('[^\\s]+@[^\\s]+', 'emailaddr', email_contents)\n \n # Handle $ sign\n email_contents = re.sub('[$]+', 'dollar', email_contents)\n \n # ========================== Tokenize Email ===========================\n \n # Output the email to screen as well\n print('==== Processed Email ====')\n \n # Process file\n l = 0\n \n # Remove any non alphanumeric characters (also get rid of any punctuation)\n email_contents = re.sub('[^a-zA-Z0-9]', ' ', email_contents)\n \n for word in email_contents.split(' '): \n word = word.strip()\n \n # Stem the word \n # (the porterStemmer sometimes has issues, so we use a try catch block\n # 어간 추출 library\n # reference : https://www.nltk.org/api/nltk.stem.html?highlight=porterstemmer#nltk.stem.porter.PorterStemmer\n try:\n stemmer = PorterStemmer()\n word = stemmer.stem(word)\n except:\n word = ''\n continue \n \n # Skip the word if it is too shor\n if len(word) < 1:\n continue\n \n # Look up the word in the dictionary and add to word_indices if\n # found\n # ====================== YOUR CODE HERE ======================\n # Instructions: Fill in this function to add the index of str to\n # word_indices if it is in the vocabulary. At this point\n # of the code, you have a stemmed word from the email in\n # the variable str. You should look up str in the\n # vocabulary list (vocabList). If a match exists, you\n # should add the index of the word to the word_indices\n # vector. Concretely, if str = 'action', then you should\n # look up the vocabulary list to find where in vocabList\n # 'action' appears. For example, if vocabList{18} =\n # 'action', then, you should add 18 to the word_indices \n # vector (e.g., word_indices = [word_indices ; 18]; ).\n # \n # Note: vocabList{idx} returns a the word with index idx in the\n # vocabulary list.\n # \n # Note: You can use strcmp(str1, str2) to compare two strings (str1 and\n # str2). It will return 1 only if the two strings are equivalent.\n #\n \n \n for k,v in vocabList.items():\n if v == word: \n word_indices = np.append(word_indices, k)\n break\n \n # Print to screen, ensuring that the output lines are not too long\n if (l + len(word) + 1) > 78:\n print()\n l = 0\n\n print(word, end=' ')\n l = l + len(word) + 1\n \n print('\\n\\n=========================')\n \n return word_indices","sub_path":"ex6/processEmail.py","file_name":"processEmail.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509472165","text":"#!/usr/bin/python3.4\n#author: Alex Fence\nimport sys\nimport waifuviewer.gui as gui\nfrom PyQt4 import QtGui\nimport os\n\ndef run():\n\tapp = QtGui.QApplication(sys.argv)\n\ttry:\n\t\tconfig = open(os.getcwd() + \"/config.txt\", \"r\")\n\t\turl = config.readline()\n\t\tconfig.close()\n\n\t\tif url.find(\"safebooru\") == -1:\n\t\t\turl = \"http://safebooru.org/index.php?page=dapi&s=post&q=index&tags=hatsune_miku\"\n\n\texcept:\n\t\tconfig = open(os.getcwd() + \"/config.txt\", \"w\")\n\t\tconfig.write(\"hatsune_miku\")\n\t\tconfig.close()\n \t\n\tGUI = gui.Window(url)\n\tGUI.show()\n\tsys.exit(app.exec_())\n\nrun()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"49213278","text":"import Tkinter as tk\n\nfrom Control import *\nfrom Drone import *\nfrom InfoPanel import *\n\nclass Simulator(tk.Tk):\n def __init__(self, dt):\n self.WIDTH = 1000.0\n self.HEIGHT = 500.0\n self.time = 0.0\n self.dt = dt\n \n tk.Tk.__init__( self )\n \n self.drone = Drone(self.dt)\n #self.drone2 = Drone(self.dt)\n self.control = Control(self.drone)\n #self.control2 = Control(self.drone2)\n self.drone.setControl(self.control)\n #self.drone2.setControl(self.control2) \n\n screen = tk.Frame(self)\n screen.pack()\n \n self.canvas = tk.Canvas(screen, width=self.WIDTH, height=self.HEIGHT,borderwidth=10)\n self.canvas.grid(column=1, row=1)\n \n self.infos = InfoPanel(screen, self.drone)\n self.infos.panel.grid(column=2, row=1)\n #self.infos2 = InfoPanel(screen, self.drone2)\n #self.infos2.panel.grid(column=3, row=1)\n \n # to receive commands\n screen.focus_set() \n \n self.drone_ui = self.canvas.create_oval(40, self.HEIGHT, 50, self.HEIGHT-10, fill = \"red\")\n #self.drone2_ui = self.canvas.create_oval(100, self.HEIGHT, 110, self.HEIGHT-10, fill = \"blue\") \n\n def onBtnUpHand(e):\n self.control.onBtnUp()\n\n def onBtnDownHand(e):\n self.control.onBtnDown()\n \n def onBtnLeftHand(e):\n self.control.onBtnLeft()\n \n def onBtnRightHand(e):\n self.control.onBtnRight()\n\n def onBtnAHand(e): \n if self.control.switch == 0:\n self.control.setSwitch(1)\n self.control.load(self.control.stay, self.drone.pos)\n \n def onBtnRHand(e):\n self.control.reset()\n \n def onBtnGHand(e): \n if self.control.switch == 0:\n self.control.setSwitch(1)\n self.control.load(self.control.goto, [Vector(0,50), Vector(30,100)])\n \n def onBtnOHand(e):\n self.control.resetControl()\n\n screen.bind(\"\", onBtnUpHand)\n screen.bind(\"\", onBtnDownHand)\n screen.bind(\"\", onBtnLeftHand)\n screen.bind(\"\", onBtnRightHand)\n screen.bind(\"\", onBtnAHand)\n screen.bind(\"\", onBtnRHand)\n screen.bind(\"\", onBtnGHand)\n screen.bind(\"\", onBtnOHand)\n\n def simLoop(self): \n self.drone.refreshPos()\n #self.drone2.refreshHeight()\n if self.control.switch == 1:\n self.control.run()\n \n #self.control2.load(self.control2.goto, [self.drone.height])\n #self.control2.run()\n \n self.canvas.coords(self.drone_ui, self.drone.pos.coords[0]+40, self.HEIGHT-self.drone.pos.coords[1], self.drone.pos.coords[0]+50, self.HEIGHT-10-self.drone.pos.coords[1])\n #self.canvas.coords(self.drone2_ui, 100, self.HEIGHT-self.drone2.height, 110, self.HEIGHT-10-self.drone2.height)\n\n self.infos.texts.setUiTexts()\n #self.infos2.texts.setUiTexts()\n \n self.after(int(1000*self.dt), self.simLoop)","sub_path":"Simulator.py","file_name":"Simulator.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461406429","text":"import os\n\nfrom flask import session, jsonify, Blueprint, send_file\nfrom flask import request\nfrom werkzeug.utils import secure_filename\n\nfrom app.database import db_session\nfrom app.store import service as store_service\nimport config\n\n__author__ = 'swsong'\n\nmod = Blueprint('store', __name__)\n\n@mod.route('/apps',methods=['POST'])\ndef fileupload():\n docker_hub=\"\"\n vm_repo =\"\"\n vm_size =\"\"\n ssh_id = \"\"\n text = \"\"\n name = request.json['name']\n url = request.json['url']\n source_repo = request.json['source_repo']\n category = request.json['category']\n if 'text' in request.json:\n text = request.json['text']\n if 'docker_hub' in request.json:\n docker_hub = request.json['docker_hub']\n if 'vm_repo' in request.json:\n vm_repo = request.json['vm_repo']\n if 'vm_size' in request.json:\n vm_size = request.json['vm_size']\n operating_sys = request.json['os']\n os_ver = request.json['os_ver']\n os_bit = request.json['os_bit']\n if 'ssh_id' in request.json:\n ssh_id = request.json['ssh_id']\n return jsonify(files=store_service.add_app(name,url,source_repo,category,text,docker_hub,vm_repo,vm_size,operating_sys,os_ver,os_bit,ssh_id,db_session))\n\n@mod.route('/apps/',methods=['POST'])\ndef changefileupload(id):\n file = request.files['file']\n if file and allowed_file(file.filename):\n icon = secure_filename(file.filename)\n file.save(os.path.join(config.IMAGE_PATH, icon))\n return jsonify(files=store_service.change_thumbnail(id,icon,db_session))\n\n@mod.route('/apps',methods=['GET'])\ndef Storelist():\n category=\"\"\n pre = session.get('pre','No')\n if 'category' in request.args:\n category = request.args.get('category')\n return jsonify(apps=store_service.storelist(pre,category,db_session))\n\n@mod.route('/apps//', methods=['GET'])\ndef Storeinfo(id,type):\n return jsonify(apps=store_service.storedetail(id,type,db_session))\n\n@mod.route('/apps/',methods=['PUT'])\ndef appChange(id):\n icon=\"\"\n name=\"\"\n url=\"\"\n source_repo=\"\"\n text=\"\"\n docker_hub=\"\"\n vm_repo = \"\"\n category=\"\"\n vm_size=\"\"\n operating_sys=\"\"\n os_ver =\"\"\n os_bit =\"\"\n ssh_id=\"\"\n if 'name' in request.json:\n name =request.json['name']\n if 'url' in request.json:\n url =request.json['url']\n if 'source_repo' in request.json:\n source_repo =request.json['source_repo']\n if 'category' in request.json:\n category =request.json['category']\n if 'text' in request.json:\n text =request.json['text']\n if 'docker_hub' in request.json:\n docker_hub =request.json['docker_hub']\n if 'vm_repo' in request.json:\n vm_repo = request.json['vm_repo']\n if 'vm_size' in request.json:\n vm_size = request.json['vm_size']\n if 'os' in request.json:\n operating_sys = request.json['os']\n if 'os_ver' in request.json:\n os_ver = request.json['os_ver']\n if 'os_bit' in request.json:\n os_bit=request.json['os_bit']\n if 'ssh_id' in request.json:\n ssh_id=request.json['ssh_id']\n return jsonify(files=store_service.change_app(id,icon,name,url,source_repo,category,text,docker_hub,vm_repo,vm_size,operating_sys,os_ver,os_bit,ssh_id,db_session))\n\n@mod.route('/apps/',methods=['DELETE'])\ndef app_Delete(id):\n return jsonify(apps=store_service.del_app(id, db_session))\n\n@mod.route('/apps/shows/',methods=['PUT'])\ndef showChange(id):\n action=request.json['type']\n return jsonify(shows=store_service.showchange(id,action,db_session))\n\n\n@mod.route('/categorys',methods=['GET'])\ndef CategoryList():\n pre = session.get('pre','No')\n return jsonify(categorys=store_service.categorylist(pre,db_session))\n\n@mod.route('/replys', methods=['POST'])\ndef StoreReply():\n if 'text' in request.json:\n if request.json['text'] != None:\n text =request.json['text']\n parent_id = request.json['id']\n id =session['userId']\n name=session['userName']\n return jsonify(replys=store_service.stoercommunity(text, id, name, parent_id, db_session))\n else:\n return jsonify(replys='text')\n else:\n return jsonify(replys='text')\n\n@mod.route('/replys/',methods=['DELETE'])\ndef StoreReplydel(id):\n return jsonify(replys=store_service.storecommunitydel(id, db_session))\n\n\n\n@mod.route('/thumbnail/',methods=['GET'])\ndef send_files(id):\n return send_file(config.IMAGE_PATH+id, mimetype='image/*')\n\n@mod.route('/screenshot/',methods=['GET'])\ndef Send_files(id):\n return send_file(config.SCREENSHOT_PATH+id, mimetype='image/*')\n\n\n@mod.route('/screenshots//',methods=['POST'])\ndef Fileuploads(id,name):\n file = request.files['file']\n if file and allowed_file(file.filename):\n icon = secure_filename(file.filename)\n file.save(os.path.join(config.SCREENSHOT_PATH, name+'-'+icon))\n icon = name+'-'+icon\n return jsonify(screenshots=store_service.add_screenshot(id,icon,db_session))\n\n@mod.route('/screenshots/',methods=['DELETE'])\ndef Screeshotdel(id):\n return jsonify(screenshots=store_service.screenshotdel(id,db_session))\n\n@mod.route('/categorys/actions/select',methods=['GET'])\ndef selectcate():\n return jsonify(select=store_service.allcate(db_session))\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in config.ALLOWED_EXTENSIONS\n\n\n\n\n","sub_path":"app/store/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412891966","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport urllib\nimport os\n\nHISTORICAL_DISTRICT_SCHOOL_SUMMARY_URL = \"https://www.mischooldata.org/Other/DataFiles/DistrictSchoolInformation/HistoricalDistrictSchoolSummary.aspx\"\n\ndef make_soup(url):\n html = urlopen(url).read()\n return BeautifulSoup(html, \"lxml\")\n\ndef DOWNLOAD_DISTRICT_SCHOOL_SUMMARY(section_url):\n soup = make_soup(section_url)\n\n #DOWNLOAD SCHOOL DATA\n if not os.path.exists(\"School Data\"):\n os.makedirs(\"School Data\")\n\n all_tables = soup.find_all(\"table\", class_ = \"what_it_means_editor_data_files\")\n school_data_table = all_tables[0]\n school_data_table_rows = school_data_table.find_all(\"tr\")\n school_data_table_headers_row = school_data_table_rows[1]\n headers_tag = school_data_table_headers_row.find_all(\"font\")\n headers = []\n for header in headers_tag:\n headerValue = \" \".join(header.text.split())\n headers.append(headerValue)\n for i in range(2,len(school_data_table_rows)):\n all_columns = school_data_table_rows[i].find_all(\"td\")\n school_year_folder =\"School Data/\"+ headers[0]+ \" \" + all_columns[0].text.strip()\n if not os.path.exists(school_year_folder):\n os.makedirs(school_year_folder)\n for i in range(1,len(all_columns)):\n column_folder = school_year_folder + \"/\" +headers[i]\n if not os.path.exists(column_folder):\n os.makedirs(column_folder)\n a_tag = all_columns[i].find(\"a\")\n if a_tag:\n href = a_tag[\"href\"]\n fileName = column_folder + \"/\" + os.path.basename(href)\n urllib.request.urlretrieve(href, fileName)\n\n #DOWNLOAD EEM AND SCM DATA\n if not os.path.exists(\"Educational Entity Master (EEM) School Code Master (SCM) Data\"):\n os.makedirs(\"Educational Entity Master (EEM) School Code Master (SCM) Data\")\n\n eem_scm_table = all_tables[1]\n eem_scm_table_rows = eem_scm_table.find_all(\"tr\")\n for i in range(1,len(eem_scm_table_rows)-1):\n row_folder = \"Educational Entity Master (EEM) School Code Master (SCM) Data/\"+ eem_scm_table_rows[i].find_all(\"td\")[0].text.strip()\n row_folder = \" \".join(row_folder.split())\n if not os.path.exists(row_folder):\n os.makedirs(row_folder)\n a_tag = eem_scm_table_rows[i].find_all(\"td\")[1].find(\"a\")\n if a_tag:\n href = a_tag[\"href\"]\n fileName = row_folder + \"/\" + os.path.basename(href)\n urllib.request.urlretrieve(href, fileName)\n\nif __name__ == '__main__':\n DOWNLOAD_DISTRICT_SCHOOL_SUMMARY(HISTORICAL_DISTRICT_SCHOOL_SUMMARY_URL)\n","sub_path":"District - School Summary.py","file_name":"District - School Summary.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"186703088","text":"import numpy as np\nimport h5py\n\nfrom scipy.stats import linregress\nimport os\ntry:\n from noisi.util.plot import plot_grid\nexcept ImportError:\n print('Plotting unavailable, is basemap installed?')\n\nfrom noisi.util.geo import get_spherical_surface_elements\n\nclass NoiseSource(object):\n \"\"\"\n 'model' of the noise source that comes in terms of a couple of basis \n functions and associated weights. The NoiseSource object should contain a \n function to determine weights from a (kernel? source model?), and to expand from weights and basis \n functions.\n \n \"\"\"\n \n \n def __init__(self,model,w='r'):\n \n # Model is an hdf5 file which contains the basis and weights of the source model!\n \n \n try:\n self.model = h5py.File(model,w)\n self.src_loc = self.model['coordinates']\n self.freq = self.model['frequencies']\n \n # Presumably, these arrays are small and will be used very often --> good to have in memory.\n self.distr_basis = self.model['distr_basis'][:]\n self.spect_basis = self.model['spect_basis'][:]\n self.distr_weights = self.model['distr_weights'][:]\n\n # The surface area of each grid element...new since June 18\n try:\n self.surf_area = self.model['surf_areas'][:]\n except KeyError:\n # approximate as spherical surface elements...\n self.surf_area = get_spherical_surface_elements(\n self.src_loc[0],self.src_loc[1])\n np.save('surface_areas_grid.npy',self.surf_area)\n \n self.spatial_source_model = self.expand_distr()\n \n except IOError:\n msg = 'Unable to open model file '+model\n raise IOError(msg)\n\n\n \n def __enter__(self):\n return self\n \n def __exit__(self,type,value,traceback):\n \n if self.model is not None:\n self.model.close()\n #ToDo: Check what parameters/data should be written before file closed\n\n def project_gridded(self):\n pass\n\n def expand_distr(self):\n expand = np.dot(self.distr_weights,self.distr_basis)\n \n return np.array(expand,ndmin=2)\n\n\n def get_spect(self,iloc):\n # return one spectrum in location with index iloc\n # The reason this function is for one spectrum only is that the entire gridded matrix of spectra by location is most probably pretty big.\n \n\n weights = self.spatial_source_model[:,iloc]#np.array(self.expand_distr()[:,iloc])\n \n \n return np.dot(weights, self.spect_basis)\n \n \n def plot(self,**options):\n \n # plot the distribution\n \n for m in self.spatial_source_model: \n plot_grid(self.src_loc[0],self.src_loc[1],m,**options)\n\n\n \n # Note: Inefficient way of doing things! Whichever script needs the noise source field should rather look up things directly in the hdf5 file.\n # But: ToDo: This could be used internally to write to a file, rather than reading from.\n # Although: A problem to think about: noise source should behave the same, whether it is defined by model or by file. So maybe, since model will be the default option anyway, work with this!\n #def get_spectrum(self,iloc):\n # # Return the source spectrum at location nr. iloc\n # \n # #if self.file is not None:\n # # return self.sourcedistr[iloc] * self.spectra[iloc,:]\n # if self.model is not None:\n # return self.spectr.\n # # (Expand from basis fct. in model)\n #def get_sourcedistr(self,i):\n # # Return the spatial distribution of max. PSD\n # if self.file is not None:\n # return np.multiply(self.sourcedistr[:],self.spectra[:,i])\n # else:\n # raise NotImplementedError\n \n","sub_path":"noisi/my_classes/noisesource.py","file_name":"noisesource.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492930152","text":"import os\r\nimport random\r\nfrom tensorflow.keras.utils import plot_model\r\nfrom siamese_net import SiameseNet\r\nfrom utils.data_loader import split_train_val, load_dataset\r\nimport pathlib\r\n\r\n\r\ndef run_siamnet_train(dataset_zip_path: str, train_file_path , test_file_path, batch_size=2):\r\n random.seed(42)\r\n print('images zip path: {}'.format(dataset_zip_path))\r\n\r\n print('train file: {} , test file: {}'.format(train_file_path, test_file_path))\r\n\r\n train_dataset, y_array_train, first_image_title_train_list, second_image_title_train_list, \\\r\n test_dataset, y_array_test, first_image_title_test_list, second_image_title_test_list = load_dataset(\r\n dataset_zip_path,\r\n train_file_path,\r\n test_file_path)\r\n print('train dataset has {} samples'.format(len(train_dataset[0])))\r\n print('test dataset has {} samples'.format(len(test_dataset[0])))\r\n\r\n train_dataset, y_array_train, val_dataset, y_array_val = split_train_val(train_dataset, y_array_train)\r\n print('train (after val split) dataset has {} samples'.format(len(train_dataset[0])))\r\n print('val dataset has {} samples'.format(len(val_dataset[0])))\r\n\r\n input_image_shape = (250, 250, 1)\r\n num_train_samples = len(train_dataset[0])\r\n\r\n siamnet = SiameseNet(input_image_shape, num_train_samples, batch_size)\r\n model_img_file = 'siam_model_architecture.png'\r\n plot_model(siamnet.siam_model, to_file=model_img_file, show_shapes=True)\r\n\r\n curr_script_dir = pathlib.Path(__file__).parent.absolute()\r\n saved_model_dir = os.path.join(curr_script_dir, 'saved_models')\r\n\r\n if not os.path.isdir(saved_model_dir):\r\n os.mkdir(saved_model_dir)\r\n siamnet.train(train_dataset, y_array_train, val_dataset, y_array_val, save_model_path=saved_model_dir,\r\n batch_size=batch_size)\r\n\r\nif __name__ == '__main__':\r\n run_siamnet_train(r'C:\\Users\\USER\\Google Drive\\Master_deg\\למידה עמוקה\\ex2\\data_\\lfwa.zip',\r\n r'C:\\Users\\USER\\Google Drive\\Master_deg\\למידה עמוקה\\ex2\\pairsDevTrain.txt',\r\n r'C:\\Users\\USER\\Google Drive\\Master_deg\\למידה עמוקה\\ex2\\pairsDevTest.txt',\r\n batch_size=1)\r\n","sub_path":"ex2/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"162811768","text":"import datetime\n\nclass CNP:\n def __init__(self, cnp_string: str, date_created: datetime.datetime=datetime.datetime.now()):\n \"\"\"the CNP class will hold the cnp string and the date created\"\"\"\n self.cnp_string=cnp_string\n self.date_created=date_created\n\n @property\n def cnp_string(self):\n return self._cnp_string\n\n @property\n def date_created(self):\n return self._date_created\n\n @cnp_string.setter\n def cnp_string(self, value):\n self._cnp_string=value\n\n @date_created.setter\n def date_created(self, value):\n self._date_created=value\n\n def __str__(self):\n return f'CNP({self.cnp_string}) created at {self.date_created}'\n\n\n\"\"\"a few helper functions\"\"\"\n\ndef __generate_digits_range(min_value: int=0, max_value: int=99):\n \"\"\" this is a helper function that will generate string representing numbers \n within a range with leading zeros (eg. 001, 045, 00443)\n \"\"\"\n digits=[str(i) for i in range(min_value, max_value)]\n digits=[(len(str(max_value))-len(digit))*'0'+str(digit) for digit in digits]\n return digits\n\ndef __check_day_digits(cnp: CNP):\n \"\"\"the function will check if the 6th and 7th characters form a valid day number (01 to 31)\"\"\"\n digits=__generate_digits_range(1, 32)\n day_digits=cnp.cnp_string[5:7]\n if day_digits not in digits:\n raise ValueError('the day digits must be in the range 01 to 31')\n\ndef __check_month_digits(cnp: CNP):\n \"\"\"the function will check if the 4th and 5th characters form a valid month number (01 to 12)\"\"\"\n digits=__generate_digits_range(1, 13)\n month_digits=cnp.cnp_string[3:5]\n if month_digits not in digits:\n raise ValueError('the month digits must be in the range 01 to 12')\n\ndef __check_year_digits(cnp: CNP):\n \"\"\"the function will check if the 2nd and 3rd characters form a valid combination \n of the last two digits of an year (00 to 99)\n \"\"\"\n digits=__generate_digits_range(0, 99)\n digits.append('99')\n year_digits=cnp.cnp_string[1:3]\n if year_digits not in digits:\n raise ValueError('the year digits must be in the range 00 to 99')\n\ndef __check_birthdate(cnp: CNP) -> datetime.datetime:\n \"\"\"the function will check if the characters from 2nd to the 7th form a valid\n date, taking into account the first gender digit.\n \"\"\"\n __check_year_digits(cnp)\n __check_month_digits(cnp)\n __check_day_digits(cnp)\n year=int(cnp.cnp_string[1:3])\n valid_year=0\n if cnp.cnp_string[0] in '12789':\n valid_year=1900+year\n elif cnp.cnp_string[0] in '34':\n valid_year=1800+year\n elif cnp.cnp_string[0] in '56':\n valid_year=2000+year\n else:\n raise ValueError('invalid gender value')\n try:\n return datetime.datetime(valid_year, int(cnp.cnp_string[3:5]), int(cnp.cnp_string[5:7]))\n except ValueError as e:\n print(e)\n return\n\ndef __check_nnn_format(cnp: CNP):\n \"\"\"the function will check if the nnn number is within the range 001 to 999\"\"\"\n min_value=0\n max_value=999\n digits=[str(i) for i in range(max_value)]\n digits=[(len(str(max_value))-len(digit))*'0'+str(digit) for digit in digits]\n digits.append('999')\n nnn=cnp.cnp_string[10:13]\n if nnn not in digits:\n raise ValueError('nnn number is not the range 000 - 999.') \n\n\n\"\"\"the main validation function\"\"\"\ndef cnp_validator(cnp: CNP, other_cnp: CNP=None)->bool:\n \"\"\"the actual function that will validate the given CNP instance and will return true\n if the cnp is valid and false if cnp is invalid.\n \"\"\"\n __check_type(cnp)\n __check_length(cnp)\n __check_is_digit(cnp)\n __check_first_digit(cnp)\n __check_location_digits(cnp)\n __check_valid_birtdate(cnp)\n __check_valid_nnn_digits(cnp)\n return __check_c_digit(cnp)\n\n\n\"\"\"The validation functions\"\"\"\ndef __check_type(cnp: CNP):\n \"\"\"the function will check if the value entered is of type string\"\"\"\n if type(cnp.cnp_string)!=str:\n raise TypeError('cnp must only be a string')\n\ndef __check_is_digit(cnp: CNP):\n \"\"\"the function will check the characters within the string represent integers\"\"\"\n if not str(cnp.cnp_string).isdigit():\n raise ValueError('cnp must contain only digits from 0 to 9')\n\ndef __check_length(cnp: CNP):\n \"\"\"a valid cnp will have no more and no less than 13 numeric characters\"\"\"\n if len(cnp.cnp_string)!=13 or len(cnp.cnp_string)==0:\n raise ValueError('cnp must contain exactly 14 digits')\n\ndef __check_first_digit(cnp: CNP):\n \"\"\"the first digit, correponding to the gender, must not be 0\"\"\"\n if cnp.cnp_string[0]=='0':\n raise ValueError('first digit can only be a digit from 1 to 9')\n\ndef __check_location_digits(cnp: CNP):\n \"\"\"The location code must be verified and it must be between 01 and 46, 51 or 52\"\"\"\n digits=__generate_digits_range(1, 47)\n digits.extend(['51', '52'])\n location_digits=cnp.cnp_string[7:9]\n if location_digits not in digits:\n raise ValueError('the location digits of the cnp must be in range 01 to 46 or 51 or 52')\n\ndef __check_valid_birtdate(cnp: CNP):\n try:\n birthdate=__check_birthdate(cnp)\n if not birthdate:\n raise ValueError('invalid birthdate')\n except Exception as e:\n print(e)\n\ndef __check_valid_nnn_digits(cnp: CNP, other_cnp: CNP=None):\n \"\"\"the function will compare the substrings of two cnp's to see if the same nnn number\n has been assigned to two individuals in the same day in a district/county.\n \"\"\"\n if other_cnp:\n if cnp.cnp_string[7:-1]==other_cnp.cnp_string[7:-1] and \\\n cnp.date_created.year==other_cnp.date_created.year and \\\n cnp.date_created.month==other_cnp.date_created.month and \\\n cnp.date_created.day==other_cnp.date_created.day:\n print(cnp.cnp_string[7:-1])\n print(other_cnp.cnp_string[7:-1])\n raise ValueError('cannot assign the same nnn value to two CNP\\'s created\\\n in the same day in the same county/district')\n\ndef __check_c_digit(cnp: CNP):\n sum_of_digits=0\n control_digit=''\n remainder=0\n check_number='279146358279'\n for i, j in zip(check_number, cnp._cnp_string[:-1]):\n sum_of_digits+=int(i)*int(j)\n remainder=sum_of_digits%11\n if remainder==10:\n control_digit='1'\n else:\n control_digit=str(remainder)\n if control_digit!=cnp._cnp_string[-1]:\n raise ValueError('control digit is incorrect')\n return False\n else:\n return True\n","sub_path":"cnp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291751449","text":"from .core import *\nfrom .utils import *\nfrom .vparsers import *\n\n\nclass Zeromskiego53Parser(SingleRequestLoaderMixin, BaseParser):\n middlewares = [ JSONMiddleware() ]\n parsers = { \n \"status\": StatusParser(), \"int\": IntParser(), \"area\": AreaParser() \n }\n\n url = \"http://zeromskiego53.pl/search.php\"\n method = \"POST\"\n data = \"pow_od=&pow_do=&pietro=&pokoje=\"\n headers = {\n \"Host\": \"zeromskiego53.pl\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0\",\n \"Accept\": \"*/*\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Referer\": \"http://zeromskiego53.pl/kondygnacje\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Connection\": \"keep-alive\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\"\n }\n\n def get_records(self):\n return self.load()\n\n def parse_record(self, data):\n return {\n \"area\": self.parsers[\"area\"](data.get(\"powierzchnia\", None)),\n \"number\": data.get(\"title\", None),\n \"fid\": data.get(\"title\", None),\n \"rooms\": self.parsers[\"int\"](data.get(\"liczba_pokoi\", None)),\n \"floor\": self.parsers[\"int\"](data.get(\"pietro\", None)),\n \"status\": self.parsers[\"status\"](data.get(\"status\", None))\n }","sub_path":"parsers/zeromskiego53.py","file_name":"zeromskiego53.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245829916","text":"# Dyma Volodymyr. KNIT16-A\n# Дана последовательность целых чисел а_1...а_n (могут быть повторяющиеся).\n# Вывести на экран все числа, которые входят в последовательность по одному\n# разу.\n\nwhile True:\n try:\n a = input('Input integers separated by space: ')\n b = sorted(set(a.split()))\n c = set()\n if len(b) == 0:\n print('Enter something!')\n break\n set(map(int, b))\n for i in b:\n if a.count(i) == 1:\n c.add(i)\n if len(c) == 0:\n print('Result is an empty set.')\n else:\n print(sorted(c))\n except ValueError:\n print('Input integers, separated by spaces!')\n if input('Press Enter to continue...') != '':\n break\n","sub_path":"Lab7/i_1a.py","file_name":"i_1a.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588992619","text":"#!/usr/bin/env python\n# encoding: utf-8\n# @software: PyCharm\n# @time: 2019/8/5 9:57\n# @author: Paulson●Wier\n# @file: use_tesserocr.py\n# @desc:\nimport time\nimport tesserocr\nfrom PIL import Image\n\nimage = Image.open('code.png')\n\nimage = image.convert('L')\nthreshold = 127\ntable = []\nfor i in range(256):\n if i < threshold:\n table.append(0)\n else:\n table.append(1)\n\nimage = image.point(table, '1')\nresult = tesserocr.image_to_text(image)\nprint(result)","sub_path":"captcha_image/use_tesserocr.py","file_name":"use_tesserocr.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"459962547","text":"import collections\nimport string\n\ndef create_vocab(PATH):\n # load train corpus\n with open(PATH, 'r') as f:\n lines = f.readlines()\n\n # get the word from each line in the dataset\n words = [line.split('\\t')[0] for line in lines]\n\n # define defaultdict of type 'int'\n freq = collections.defaultdict(int)\n\n # count frequency of ocurrence for each word in the dataset\n for word in words:\n freq[word] += 1\n\n # create the vocabulary by filtering the 'freq' dictionary\n # filter out words that appeared only once and newline character\n vocab = [k for k, v in freq.items() if (v > 1 and k != '\\n')]\n\n # sort the vocabulary, changes the list directly\n vocab.sort()\n\n return vocab\n\n\ndef assign_unk(word):\n \"\"\" assign tokens to unknouwn word\"\"\"\n # punctuation characters\n punct = set(string.punctuation)\n\n # morphology rules used to assign unknown word token\n noun_suffix = [\n \"action\", \"age\", \"ance\", \"cy\", \"dom\",\n \"ee\", \"ence\", \"er\", \"hood\", \"ion\",\n \"ism\", \"ist\", \"ity\", \"ling\", \"ment\",\n \"ness\", \"or\", \"ry\", \"scape\", \"ship\",\n \"ty\"\n ]\n\n verb_suffix = [\n \"ate\", \"ify\", \"ise\", \"ize\"\n ]\n\n adj_suffix = [\n \"able\", \"ese\", \"ful\", \"i\", \"ian\",\n \"ible\", \"ic\", \"ish\", \"ive\", \"less\",\n \"ly\", \"ous\"\n ]\n\n adv_suffix = [\n \"ward\", \"wards\", \"wise\"\n ]\n\n # loop the characters in the word, check if any is digit\n if any(char.isdigit() for char in word):\n return \"--unk_digit--\"\n\n # loop the characters in the word, check if any is a punctuation character\n elif any(char in punct for char in word):\n return \"--unk_punct--\"\n\n # loop the characters in the word, check if any is an upper case character\n elif any(char.isupper() for char in word):\n return \"--unk_upper--\"\n\n # check if word ends with any noun suffix\n elif any(word.endswith(suffix) for suffix in noun_suffix):\n return \"--unk_noun--\"\n\n # check if word ends with any verb suffix\n elif any(word.endswith(suffix) for suffix in verb_suffix):\n return \"--unk_verb--\"\n\n # check if word ends with any adjective suffix\n elif any(word.endswith(suffix) for suffix in adj_suffix):\n return \"--unk_adj--\"\n\n # check if word ends with any adverb suffix\n elif any(word.endswith(suffix) for suffix in adv_suffix):\n return \"--unk_adv--\"\n\n # if none of the previous criteria is met, return plain unknown\n return word\n\n\ndef get_word_tag(line, vocab):\n # if line is empty return placeholders for word and tag\n if not line.split():\n word = \"--n--\"\n tag = \"--\"\n else:\n # split line to separate word and tag\n word, tag = line.split()\n\n # check if word is not in vocabulary\n if word not in vocab:\n word = assign_unk(word)\n\n return word, tag\n\n\ndef preprocess(vocab, data_fp):\n \"\"\"\n Preprocess data\n \"\"\"\n orig = []\n prep = []\n\n # Read data\n with open(data_fp, \"r\") as data_file:\n\n for cnt, word in enumerate(data_file):\n\n # End of sentence\n if not word.split():\n orig.append(word.strip())\n word = \"--n--\"\n prep.append(word)\n continue\n\n # Handle unknown words\n elif word.strip() not in vocab:\n orig.append(word.strip())\n word = assign_unk(word)\n prep.append(word)\n continue\n\n else:\n orig.append(word.strip())\n prep.append(word.strip())\n\n assert(len(orig) == len(open(data_fp, \"r\").readlines()))\n assert(len(prep) == len(open(data_fp, \"r\").readlines()))\n\n return orig, prep\n\n\n\n","sub_path":"src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"628233641","text":"# Author: Christian Brodbeck \nimport warnings\n\nfrom nose.tools import assert_almost_equal, eq_, assert_raises\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_equal\nimport scipy.stats\n\nfrom eelbrain import datasets\nfrom eelbrain._stats import stats\nfrom eelbrain._stats.permutation import permute_order\n\n\ndef test_confidence_interval():\n \"Test confidence_interval()\"\n from rpy2.robjects import r\n\n ds = datasets.get_loftus_masson_1994()\n y = ds['n_recalled'].x[:, None].astype(np.float64)\n x = ds['exposure'].as_factor()\n subject = ds['subject']\n ds.to_r('ds')\n\n # simple confidence interval of the mean\n ci = stats.confidence_interval(y)[0]\n r(\"s <- sd(ds$n_recalled)\")\n r(\"n <- length(ds$n_recalled)\")\n ci_r = r(\"qt(0.975, df=n-1) * s / sqrt(n)\")[0]\n eq_(ci, ci_r)\n\n # pooled variance\n ci = stats.confidence_interval(y, x)[0]\n assert_almost_equal(ci, 3.85, delta=0.01)\n assert_raises(NotImplementedError, stats.confidence_interval, y[1:], x[1:])\n\n # within subject confidence interval\n ci = stats.confidence_interval(y, x, subject)[0]\n assert_almost_equal(ci, 0.52, 2)\n\n\ndef test_corr():\n \"Test stats.corr\"\n ds = datasets.get_uts()\n y = ds.eval(\"uts.x[:,:3]\")\n x = ds.eval('Y.x')\n n_cases = len(y)\n df = n_cases - 2\n\n corr = stats.corr(y, x)\n p = stats.rtest_p(corr, df)\n for i in xrange(len(corr)):\n r_sp, p_sp = scipy.stats.pearsonr(y[:, i], x)\n assert_almost_equal(corr[i], r_sp)\n assert_almost_equal(p[i], p_sp)\n\n # NaN\n with warnings.catch_warnings(): # divide by 0\n warnings.simplefilter(\"ignore\")\n eq_(stats.corr(np.arange(10), np.zeros(10)), 0)\n\n # perm\n y_perm = np.empty_like(y)\n for perm in permute_order(n_cases, 2):\n y_perm[perm] = y\n stats.corr(y, x, corr, perm)\n for i in xrange(len(corr)):\n r_sp, _ = scipy.stats.pearsonr(y_perm[:, i], x)\n assert_almost_equal(corr[i], r_sp)\n\n\ndef test_lm():\n \"Test linear model function against scipy lstsq\"\n ds = datasets.get_uts(True)\n uts = ds['uts']\n utsnd = ds['utsnd']\n x = ds.eval(\"A*B\")\n p = x._parametrize()\n n = ds.n_cases\n\n # 1d betas\n betas = stats.betas(uts.x, x)\n sp_betas = scipy.linalg.lstsq(p.x, uts.x.reshape((n, -1)))[0]\n # sp_betas = sp_betas.reshape((x.df,) + uts.shape[1:])\n assert_allclose(betas, sp_betas)\n\n # 2d betas\n betas = stats.betas(utsnd.x, x)\n sp_betas = scipy.linalg.lstsq(p.x, utsnd.x.reshape((n, -1)))[0]\n sp_betas = sp_betas.reshape((x.df,) + utsnd.shape[1:])\n assert_allclose(betas, sp_betas)\n\n\ndef test_sem_and_variability():\n \"Test variability() and standard_error_of_the_mean() functions\"\n ds = datasets.get_loftus_masson_1994()\n y = ds['n_recalled'].x.astype(np.float64)\n x = ds['exposure'].as_factor()\n match = ds['subject']\n\n # invalid spec\n assert_raises(ValueError, stats.variability, y, 0, 0, '1mile', 0)\n assert_raises(ValueError, stats.variability, y, 0, 0, 'ci7ci', 0)\n\n # standard error\n target = scipy.stats.sem(y, 0, 1)\n e = stats.variability(y, None, None, 'sem', False)\n assert_almost_equal(e, target)\n e = stats.variability(y, None, None, '2sem', False)\n assert_almost_equal(e, 2 * target)\n # within subject standard-error\n target = scipy.stats.sem(stats.residuals(y[:, None], match), 0, len(match.cells))\n assert_almost_equal(stats.variability(y, None, match, 'sem', True), target)\n assert_almost_equal(stats.variability(y, None, match, 'sem', False), target)\n # one data point per match cell\n n = match.df + 1\n assert_raises(ValueError, stats.variability, y[:n], None, match[:n], 'sem', True)\n\n target = np.array([scipy.stats.sem(y[x == cell], 0, 1) for cell in x.cells])\n es = stats.variability(y, x, None, 'sem', False)\n assert_allclose(es, target)\n\n stats.variability(y, x, None, 'sem', True)\n\n # confidence intervals\n stats.variability(y, None, None, '95%ci', False)\n stats.variability(y, x, None, '95%ci', True)\n stats.variability(y, x, match, '95%ci', True)\n\n assert_equal(stats.variability(y, x, None, '95%ci', False)[::-1],\n stats.variability(y, x, None, '95%ci', False, x.cells[::-1]))\n\n\ndef test_t_1samp():\n \"Test 1-sample t-test\"\n ds = datasets.get_uts(True)\n\n y = ds['uts'].x\n t = scipy.stats.ttest_1samp(y, 0, 0)[0]\n assert_allclose(stats.t_1samp(y), t, 10)\n\n y = ds['utsnd'].x\n t = scipy.stats.ttest_1samp(y, 0, 0)[0]\n assert_allclose(stats.t_1samp(y), t, 10)\n\n\ndef test_t_ind():\n \"Test independent samples t-test\"\n ds = datasets.get_uts(True)\n y = ds.eval(\"utsnd.x\")\n n_cases = len(y)\n n = n_cases / 2\n groups = (np.arange(n_cases) < n)\n groups.dtype = np.int8\n\n t = stats.t_ind(y, groups)\n p = stats.ttest_p(t, n_cases - 2)\n t_sp, p_sp = scipy.stats.ttest_ind(y[:n], y[n:])\n assert_allclose(t, t_sp)\n assert_allclose(p, p_sp)\n assert_allclose(stats.ttest_t(p, n_cases - 2), np.abs(t))\n\n # permutation\n y_perm = np.empty_like(y)\n for perm in permute_order(n_cases, 2):\n stats.t_ind(y, groups, out=t, perm=perm)\n y_perm[perm] = y\n t_sp, _ = scipy.stats.ttest_ind(y_perm[:n], y_perm[n:])\n assert_allclose(t, t_sp)\n","sub_path":"eelbrain/_stats/tests/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534122014","text":"import hyperion\nimport pytest\nfrom time import sleep\n\ninstrument_ip = '217.74.248.42'\n\ndef test_hyperion_tcp_comm():\n\n response = hyperion.HCommTCPClient.hyperion_command(instrument_ip, \"#GetSerialNumber\")\n\n assert response.content[:3].decode() == 'HIA'\n assert len(response.content) == 6\n\ndef test_hyperion_properties():\n\n hyp_inst = hyperion.Hyperion(instrument_ip)\n\n serial_number = hyp_inst.serial_number\n\n assert len(serial_number) == 6\n\n library_version = hyp_inst.library_version\n\n firmware_version = hyp_inst.firmware_version\n\n fpga_version = hyp_inst.fpga_version\n\n original_name = hyp_inst.instrument_name\n\n test_name = 'testname'\n\n hyp_inst.instrument_name = test_name\n\n assert hyp_inst.instrument_name == test_name\n\n hyp_inst.instrument_name = original_name.replace(' ', '_');\n\n assert hyp_inst.instrument_name == original_name\n\n assert hyp_inst.is_ready\n\n assert hyp_inst.channel_count in [1,4,8,16]\n\n max_peak_counts = hyp_inst.max_peak_count_per_channel\n\n peak_detection_settings = hyp_inst.available_detection_settings\n\n assert peak_detection_settings[128].name == '0.25 nm Peak'\n\n channel_detection_settings = hyp_inst.channel_detection_setting_ids\n\n active_channels = hyp_inst.active_full_spectrum_channel_numbers\n\n test_active_channels = range(1, hyp_inst.channel_count + 1)\n\n hyp_inst.active_full_spectrum_channel_numbers = test_active_channels\n\n assert (hyp_inst.active_full_spectrum_channel_numbers == test_active_channels).all()\n\n hyp_inst.active_full_spectrum_channel_numbers = [1]\n\n assert (hyp_inst.active_full_spectrum_channel_numbers == [1]).all()\n\n hyp_inst.active_full_spectrum_channel_numbers = active_channels\n\n available_laser_scan_speeds = hyp_inst.available_laser_scan_speeds\n\n current_speed = hyp_inst.laser_scan_speed\n\n hyp_inst.laser_scan_speed = available_laser_scan_speeds[0]\n\n assert hyp_inst.laser_scan_speed == available_laser_scan_speeds[0]\n\n hyp_inst.laser_scan_speed = available_laser_scan_speeds[-1]\n\n assert hyp_inst.laser_scan_speed == available_laser_scan_speeds[-1]\n\n hyp_inst.laser_scan_speed = current_speed\n\n active_net_settings = hyp_inst.active_network_settings\n\n static_net_settings = hyp_inst.static_network_settings\n\n ip_mode = hyp_inst.network_ip_mode\n\n if ip_mode == 'STATIC':\n assert active_net_settings == static_net_settings\n\n test_static_net_settings = hyperion.NetworkSettings('10.0.53.53','255.255.0.0','10.0.0.1')\n\n hyp_inst.static_network_settings = test_static_net_settings\n\n\n sleep(2)\n\n hyp_inst.network_ip_mode = 'static'\n\n sleep(2)\n\n\n assert hyp_inst.static_network_settings == test_static_net_settings\n\n hyp_inst.static_network_settings = static_net_settings\n\n sleep(2)\n\n hyp_inst.instrument_utc_date_time = hyp_inst.instrument_utc_date_time\n\n hyp_inst.ntp_enabled = not hyp_inst.ntp_enabled\n\n hyp_inst.ntp_enabled = not hyp_inst.ntp_enabled\n\n hyp_inst.ntp_server = hyp_inst.ntp_server\n\n peaks = hyp_inst.peaks\n\n channel_peaks = hyp_inst.peaks[1]\n\n spectra = hyp_inst.spectra\n\n channel_spectra = hyp_inst.spectra[active_channels[0]]\n\n assert channel_spectra.size == spectra.spectra_header['num_points']\n\n\n\n\ndef test_sensors_api():\n\n test_sensors = [\n ['sensor_1', 'os7510', 1, 1510.0, 66.0],\n ['sensor_2', 'os7510', 1, 1530.0, 66.0],\n ['sensor_3', 'os7510', 2, 1550.0, 66.0],\n ['sensor_4', 'os7510', 2, 1570.0, 66.0]\n ]\n\n hyp_inst = hyperion.Hyperion(instrument_ip)\n\n hyp_inst.remove_sensors()\n\n\n for sensor in test_sensors:\n hyp_inst.add_sensor(*sensor)\n\n\n sensor_names = hyp_inst.get_sensor_names()\n\n test_sensor_names = [sensor_config[0] for sensor_config in test_sensors]\n\n assert sensor_names == test_sensor_names\n\n hyp_inst.save_sensors()\n\n hyp_inst.remove_sensors()\n #checking for problem with re-adding sensors\n for sensor in test_sensors:\n hyp_inst.add_sensor(*sensor)\n\n sensors = hyp_inst.export_sensors()\n\n for sensor, test_sensor in zip(sensors, test_sensors):\n\n assert [sensor['name'],\n sensor['model'],\n sensor['channel'],\n sensor['wavelength'],\n sensor['calibration_factor']] == test_sensor\n\n\n hyp_inst.remove_sensors()\n\n\ndef test_detection_settings_api():\n\n hyp_inst = hyperion.Hyperion(instrument_ip)\n\n detection_setting = hyp_inst.get_detection_setting(128)\n\n detection_setting.setting_id = 1\n\n hyp_inst.add_or_update_detection_setting(detection_setting)\n\n detection_setting.name = 'Test update detection setting'\n\n hyp_inst.add_or_update_detection_setting(detection_setting)\n\n new_setting = hyp_inst.get_detection_setting(detection_setting.setting_id)\n\n assert new_setting.name == detection_setting.name\n\n hyp_inst.remove_detection_setting(detection_setting.setting_id)\n\n with pytest.raises(hyperion.HyperionError):\n hyp_inst.get_detection_setting(detection_setting.setting_id)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"test_hyperion.py","file_name":"test_hyperion.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245183208","text":"import scrapy\n\n\nclass QuotesSpider(scrapy.Spider):\n name = 'quotes'\n\n def __init__(self, tag='', **kwargs):\n if tag:\n tag = f'tag/{tag}'\n self.start_urls = [f'https://quotes.toscrape.com/{tag}']\n super().__init__(**kwargs)\n\n\n def parse(self, response):\n for quote in response.css('div.quote'):\n yield {\n 'title': quote.css('span.text::text').get(),\n 'author': {\n 'name': quote.xpath('span/small/text()').get(),\n 'url': 'https://quotes.toscrape.com{}'.format(\n quote.xpath('span/a/@href').get())\n },\n 'tags': quote.css('div.tags a.tag::text').getall(),\n }\n\n next_page = response.css('li.next a::attr(\"href\")').get()\n if next_page is not None:\n yield response.follow(next_page, self.parse)\n","sub_path":"scrawlinkinpark/scrawlinkinpark/spiders/quotes_spyder.py","file_name":"quotes_spyder.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"261899225","text":"import numpy as np\r\nimport os\r\nfrom pathlib import Path\r\nimport time\r\nimport warnings\r\nfrom sklearn.metrics import accuracy_score\r\nimport sys\r\nimport torch\r\nimport torchvision\r\nimport torch.nn as nn\r\nfrom PIL import Image\r\nimport tensorflow as tf\r\nimport torch.backends.cudnn as cudnn\r\nfrom torch import tensor\r\nfrom keras.models import load_model\r\nfrom torch.optim import SGD\r\nfrom torch.nn import BCELoss, MSELoss\r\nfrom torchvision import transforms\r\n\r\n\r\nwidth = 64\r\nheight = 56\r\nfinal_width, final_height, final_channels = int(width/1), int(height/1), 3\r\nbatch = 1000\r\ndevice=torch.device('cuda')\r\nimport os\r\ncudnn.benchmark = True\r\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"]='0,1'\r\n\r\nprint(torch.cuda.is_available())\r\nprint(torch.cuda.current_device())\r\nprint(torch.cuda.device(0))\r\nprint(torch.cuda.device_count())\r\nprint(torch.cuda.get_device_name(0))\r\n\r\n\r\ndef convert_pred(vid, shape):\r\n edit_vid = np.zeros((6,128,128,1), dtype=np.uint8)\r\n for i in range(vid.shape[0]):\r\n img = Image.fromarray(vid[i], 'RGB').convert('L')\r\n img = img.resize((128,128))\r\n edit_vid[i,:,:,0] = img\r\n\r\n edit_vid = torch.from_numpy(np.reshape(edit_vid, shape))\r\n return edit_vid.to(device)\r\n\r\n\r\ndef convert_actual(vid):\r\n edit_vid = np.zeros((1,6,64,64,3), dtype=np.uint8)\r\n for i in range(vid.shape[0]):\r\n img = Image.fromarray(vid[i])\r\n img = img.resize((64,64))\r\n edit_vid[0,i] = img\r\n\r\n edit_vid = torch.from_numpy(edit_vid)\r\n return edit_vid.to(device)\r\n\r\ndef load_img(img):\r\n img = Image.fromarray((img).astype(np.uint8)).resize((128,128))\r\n img = transforms.ToTensor()(img)\r\n return img[None].to(device)\r\n\r\ndef load_image(img):\r\n img = torch.from_numpy(img).permute(3,1,2,0).float()\r\n return img[None].to(device)\r\n\r\ndef get_flow_ini(vid):\r\n flow_val = np.zeros((6,64,64,3), dtype=np.uint8)\r\n for j in range(5):\r\n image1 = load_img(vid[j])\r\n image2 = load_img(vid[j+1])\r\n padder = InputPadder(image1.shape)\r\n image1, image2 = padder.pad(image1, image2)\r\n flow_low, flow_up = model_flow(image1, image2, iters=4, test_mode=True)\r\n\r\n img = image1[0].permute(1,2,0).cpu().detach().numpy()\r\n flo = flow_up[0].permute(1,2,0).cpu().detach().numpy()\r\n flo = flow_viz.flow_to_image(flo)\r\n flo = Image.fromarray(flo).resize((64,64))\r\n flow_val[j] = transforms.ToTensor()(flo).permute(1,2,0).float()\r\n return flow_val\r\n\r\ndef get_flow(vid):\r\n flow_val = np.zeros((1,6,64,64,3), dtype=np.uint8)\r\n for j in range(6):\r\n image1 = load_img(vid[0,j])\r\n image2 = load_img(vid[0,j+1])\r\n padder = InputPadder(image1.shape)\r\n image1, image2 = padder.pad(image1, image2)\r\n flow_low, flow_up = model_flow(image1, image2, iters=4, test_mode=True)\r\n\r\n img = image1[0].permute(1,2,0).cpu().detach().numpy()\r\n flo = flow_up[0].permute(1,2,0).cpu().detach().numpy()\r\n flo = flow_viz.flow_to_image(flo)\r\n flo = Image.fromarray(flo).resize((64,64))\r\n flow_val[0,j] = transforms.ToTensor()(flo).permute(1,2,0).float()\r\n return flow_val\r\n\r\nback = load_model('../../models/back_ref.hdf5')\r\nobs = load_model('../../models/obs_ref.hdf5')\r\nprint(\"models loaded\")\r\n\r\ninp = np.load('../../data/reflection-inp.npy')\r\nvid1 = np.load('../../data/reflection-vid1.npy')\r\nvid2 = np.load('../../data/reflection-vid2.npy')\r\nmixed = np.load('../../data/reflection-mixed.npy')\r\nprint(inp.shape)\r\nprint(\"loading inputs\")\r\n\r\n\r\n#Loading the encoder model\r\nTORCH_R2PLUS1D = \"moabitcoin/ig65m-pytorch\" # From https://github.com/moabitcoin/ig65m-pytorch\r\nMODELS = {\r\n # Model name followed by the number of output classes.\r\n \"r2plus1d_34_32_ig65m\": 359,\r\n \"r2plus1d_34_32_kinetics\": 400,\r\n \"r2plus1d_34_8_ig65m\": 487,\r\n \"r2plus1d_34_8_kinetics\": 400,\r\n}\r\nmodel_name = 'r2plus1d_34_8_kinetics'\r\n\r\n#Loading the optical flow model\r\nsys.path.append('../../RAFT/core/')\r\nfrom raft import RAFT\r\nfrom argparse import Namespace\r\nfrom utils import flow_viz\r\nfrom utils.utils import InputPadder\r\nargs = Namespace(alternate_corr=False, mixed_precision=False, model='../../RAFT/raft-things.pth', small=False)\r\nmodel = torch.nn.DataParallel(RAFT(args))\r\nmodel.load_state_dict(torch.load(args.model))\r\nprint(\"model-optical flow created\")\r\nmodel_flow = model.module\r\nmodel_flow.to(device)\r\nmodel_flow.eval()\r\n\r\nclass conv3d_bn(nn.Module):\r\n def __init__(self, in_ch, out_ch, k=(1, 1, 1), s=(1, 1, 1), p=(0, 0, 0)):\r\n super().__init__()\r\n self.in_ch = in_ch\r\n self.out_ch = out_ch\r\n self.k = k\r\n self.s = s\r\n self.p = p\r\n self.conv3d = nn.Sequential(\r\n nn.Conv3d(self.in_ch,\r\n self.out_ch,\r\n kernel_size=self.k,\r\n stride=self.s,\r\n padding=self.p), nn.BatchNorm3d(self.out_ch),\r\n nn.ReLU(inplace=True))\r\n\r\n def forward(self, x):\r\n return self.conv3d(x)\r\n\r\n\r\nclass trans3d_bn(nn.Module):\r\n def __init__(self, in_ch, out_ch=(64, 64), k=(1, 1, 1), s=(1, 1, 1), p=(0, 0, 0)):\r\n super().__init__()\r\n self.in_ch = in_ch\r\n self.out_ch = out_ch\r\n self.k = k\r\n self.s = s\r\n self.p = p\r\n self.trans3d = nn.Sequential(\r\n nn.ConvTranspose3d(self.in_ch,\r\n self.out_ch[0],\r\n kernel_size=self.k,\r\n stride=self.s,\r\n padding=self.p),\r\n nn.BatchNorm3d(self.out_ch[0]),\r\n nn.ReLU(inplace=True),\r\n conv3d_bn(self.out_ch[0],\r\n self.out_ch[1],\r\n k=(3, 5, 3),\r\n s=(1, 1, 1),\r\n p=(1, 2, 1)) # default kernel_size = 2,4,4 or 4,4,4\r\n )\r\n\r\n def forward(self, x):\r\n return self.trans3d(x)\r\n\r\n\r\nclass Encoder_Decoder(nn.Module):\r\n def __init__(self, n_classes=1):\r\n super().__init__()\r\n self.n_classes = n_classes\r\n\r\n \"\"\"\r\n encoder\r\n \"\"\"\r\n self.encoder = torch.hub.load(\r\n TORCH_R2PLUS1D,\r\n model_name,\r\n num_classes=MODELS[model_name],\r\n pretrained=False,\r\n ).to(device)\r\n\r\n \"\"\"\r\n 5th layer\r\n \"\"\"\r\n self.layer_5 = trans3d_bn(in_ch=512,\r\n out_ch=(128,128),\r\n k=(2, 5, 4),\r\n s=(2, 1, 2),\r\n p=(0, 1, 1)) # 64, 16, 14, 14\r\n self.layer_4 = conv3d_bn(in_ch=256, out_ch=128, k=(2,2,1), p=(1,0,0))\r\n\r\n \"\"\"\r\n 4th layer\r\n \"\"\"\r\n self.layer_54 = trans3d_bn(in_ch=256,\r\n out_ch=(128, 64),\r\n k=(3, 3, 4),\r\n s=(1, 1, 2),\r\n p=(1, 1, 1)) # 64, 32, 28, 28\r\n self.layer_3 = conv3d_bn(in_ch=128, out_ch=64, s=(1,1,1), p=(0,2,0))\r\n\r\n \"\"\"\r\n 3rd layer\r\n \"\"\"\r\n self.layer_543 = trans3d_bn(in_ch=128,\r\n out_ch=(64, 32),\r\n k=(4, 6, 4),\r\n s=(1, 2, 2),\r\n p=(1, 0, 1)) # 32, 32, 56, 56, default kernel_size = 4\r\n self.layer_2 = conv3d_bn(in_ch=64, out_ch=32, s=(1, 1, 1), p=(0,18,0))\r\n\r\n \"\"\"\r\n 2nd layer\r\n \"\"\"\r\n self.layer_5432 = trans3d_bn(in_ch=64,\r\n out_ch=(32, 16),\r\n k=(5, 4, 3),\r\n s=(1, 1, 1),\r\n p=(2, 0, 1)) # 32, 32, 112, 112, default kernel_size = 4\r\n self.layer_1 = conv3d_bn(in_ch=64, out_ch=16, p=(0,18,0))\r\n\r\n \"\"\"\r\n 1st layer\r\n \"\"\"\r\n self.final_2 = nn.ConvTranspose3d(64,32,\r\n kernel_size=(1, 3, 3),\r\n stride=(1, 1, 1),\r\n padding=(0, 1, 1)) # 32, 64, 224, 224\r\n self.final_1 = nn.ConvTranspose3d(32,16,\r\n kernel_size=(1, 3, 3),\r\n stride=(1, 1, 1),\r\n padding=(0, 1, 1)) # 32, 64, 224, 224\r\n self.final_0 = nn.ConvTranspose3d(16,8,\r\n kernel_size=(1, 3, 3),\r\n stride=(1, 1, 1),\r\n padding=(0, 1, 1)) # 32, 64, 224, 224\r\n self.out = nn.Conv3d(\r\n 8,7,\r\n kernel_size=(3, 5, 5),\r\n stride=(1, 1, 1),\r\n padding=(1, 2, 2)) # n*3, 64, 224, 224, default kernel_size = 4,4,4\r\n\r\n\r\n def forward(self, inputs):\r\n \"\"\"\r\n init\r\n \"\"\"\r\n data = inputs['inp'] #prepare data for entry to encoder\r\n pred_this = inputs['pred_this']\r\n pred_that = inputs['pred_that']\r\n flo_this = inputs['flo_this']\r\n\r\n out1 = self.encoder.stem(data) #outputs of encoder model at various points\r\n out2 = self.encoder.layer1(out1)\r\n out3 = self.encoder.layer2(out2)\r\n out4 = self.encoder.layer3(out3)\r\n out5 = self.encoder.layer4(out4)\r\n\r\n out5 = torch.cat([out5, convert_pred(pred_this, (1,512,8,24,1))], 3) #setting inputs for background decoder\r\n out4 = torch.cat([out4, convert_pred(pred_that, (1,256,16,24,1))], 3)\r\n out3 = torch.cat([out3, convert_pred(flo_this, (1,128,32,12,2))], 3)\r\n\r\n inp_5 = out5.permute(0,1,4,3,2)\r\n inp_4 = out4.permute(0,1,4,3,2)\r\n inp_3 = out3.permute(0,1,4,3,2)\r\n inp_2 = out2.permute(0,1,4,3,2)\r\n inp_1 = out1.permute(0,1,4,3,2)\r\n \"\"\"\r\n layer 5\r\n \"\"\"\r\n layer_5 = self.layer_5(inp_5)\r\n layer_4 = self.layer_4(inp_4)\r\n out_54 = torch.cat([layer_5, layer_4], 1)\r\n \"\"\"\r\n layer 4\r\n \"\"\"\r\n layer_54 = self.layer_54(out_54)\r\n layer_3 = self.layer_3(inp_3)\r\n out_543 = torch.cat([layer_54, layer_3], 1)\r\n \"\"\"\r\n layer 3\r\n \"\"\"\r\n layer_543 = self.layer_543(out_543)\r\n layer_2 = self.layer_2(inp_2)\r\n out_5432 = torch.cat([layer_543, layer_2], 1)\r\n\r\n \"\"\"\r\n output layer\r\n \"\"\"\r\n final_2 = self.final_2(out_5432)\r\n final_1 = self.final_1(final_2)\r\n final_0 = self.final_0(final_1)\r\n out = self.out(final_0)\r\n return out\r\n\r\n\r\n# train the model background\r\ndef train_model(layers, epochs):\r\n # define the optimization\r\n # decode_back = Encoder_Decoder(1).to(device) #defining the model\r\n # decode_obs = Encoder_Decoder(1).to(device)\r\n decode_back = torch.load('../../models_2_n/back-ref.pth').to(device)\r\n decode_obs = torch.load('../../models_2_n/obs-ref.pth').to(device)\r\n criterion = MSELoss()\r\n optimizer_back = SGD(decode_back.parameters(), lr=0.01, momentum=0.9)\r\n optimizer_obs = SGD(decode_obs.parameters(), lr=0.01, momentum=0.9)\r\n\r\n # enumerate epochs\r\n for epoch in range(1224,epochs):\r\n running_loss_back = 0\r\n running_loss_obs = 0\r\n # enumerate mini batches\r\n batch = 0\r\n for i in range(batch,batch+100):\r\n # clear the gradients\r\n batch = (batch+100)%1000\r\n optimizer_back.zero_grad()\r\n optimizer_obs.zero_grad()\r\n # compute the model output\r\n data = load_image(mixed[i,:6]) #prepare data for entry to encoder\r\n\r\n pred_back = np.asarray(tf.squeeze(back(tf.expand_dims(inp[i], axis=0))), dtype=np.uint8) #output from pre-trained model\r\n pred_obs = np.asarray(tf.squeeze(obs(tf.expand_dims(inp[i], axis=0))), dtype=np.uint8)\r\n flo_back = get_flow_ini(pred_back)\r\n flo_obs = get_flow_ini(pred_obs)\r\n\r\n flo_back_act = np.squeeze(get_flow(convert_actual(vid1[i]).float().cpu().detach().numpy()))\r\n flo_obs_act = np.squeeze(get_flow(convert_actual(vid2[i]).float().cpu().detach().numpy()))\r\n\r\n for l in range(layers):\r\n inputs_back = {'inp': data,\r\n 'pred_this': pred_back,\r\n 'pred_that': pred_obs,\r\n 'flo_this': flo_back\r\n }\r\n inputs_obs = {'inp': data,\r\n 'pred_this': pred_obs,\r\n 'pred_that': pred_back,\r\n 'flo_this': flo_obs\r\n }\r\n\r\n pred_back = decode_back(inputs_back)\r\n pred_obs = decode_obs(inputs_obs)\r\n\r\n flo_back = np.squeeze(get_flow(pred_back.permute(0,1,4,3,2).cpu().detach().numpy()))\r\n flo_obs = np.squeeze(get_flow(pred_obs.permute(0,1,4,3,2).cpu().detach().numpy()))\r\n\r\n pred_back = pred_back[:,:6]\r\n pred_obs = pred_obs[:,:6]\r\n if l!=layers-1:\r\n pred_back = np.squeeze(pred_back.cpu().detach().numpy())\r\n pred_obs = np.squeeze(pred_obs.cpu().detach().numpy())\r\n\r\n yhat_back = pred_back.permute(0,1,4,3,2)\r\n yhat_obs = pred_obs.permute(0,1,4,3,2)\r\n\r\n # calculate loss\r\n loss_back = criterion(yhat_back, convert_actual(vid1[i]).float())+criterion(torch.from_numpy(flo_back).float(),torch.from_numpy(flo_back_act).float())\r\n loss_obs = criterion(yhat_obs, convert_actual(vid2[i]).float())+criterion(torch.from_numpy(flo_obs).float(),torch.from_numpy(flo_obs_act).float())\r\n # credit assignment\r\n loss_back.backward(retain_graph=True)\r\n loss_obs.backward(retain_graph=True)\r\n\r\n torch.nn.utils.clip_grad_norm_(decode_back.parameters(), 1.0)\r\n torch.nn.utils.clip_grad_norm_(decode_obs.parameters(), 1.0)\r\n running_loss_back += loss_back.item()\r\n running_loss_obs += loss_obs.item()\r\n # update model weights\r\n optimizer_back.step()\r\n optimizer_obs.step()\r\n\r\n print(\"ref, epoch - \"+str(epoch)+\", batch - \"+str(i)+\", running loss background - \"+str(running_loss_back)+\", running loss obstruction - \"+str(running_loss_obs))\r\n\r\n print('**********************************************************************************************************************************************************')\r\n if epoch%5==0:\r\n print('saving reflection model, epoch-'+str(epoch))\r\n torch.save(decode_back, '../../models_2_n/back-ref.pth')\r\n torch.save(decode_obs, '../../models_2_n/obs-ref.pth')\r\n print('********************************************')\r\ntrain_model(6,20000)\r\n","sub_path":"layer2/model_layer2_ref_new.py","file_name":"model_layer2_ref_new.py","file_ext":"py","file_size_in_byte":13970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"445597490","text":"from face import *\nfrom cubie import *\n\nfrom array import * # arrays are much space efficient for storing primitive datatypes\nfrom collections import deque\nimport os\nimport pickle\n\n\nMOVES_PER_FACE = 3\nN_MOVES = N_COLORS * MOVES_PER_FACE\n\ndef _move_idx(face, cnt):\n return MOVES_PER_FACE * face + cnt\n\ndef _gen_movetable(n, coord, mul):\n # Note that we need to create a new object for every entry and hence can't just multiply the list by n.\n moves = [array('i', [-1] * N_MOVES) for _ in range(n)]\n\n c = CubieCube.make_solved()\n for i in range(n):\n c.set_coord(coord, i)\n for face in range(N_COLORS):\n for cnt in range(MOVES_PER_FACE):\n c.mul(mul, MOVES[face])\n moves[i][_move_idx(face, cnt)] = c.get_coord(coord)\n c.mul(mul, MOVES[face]) # restore state before moving this axis\n\n print('Generated move table.')\n return moves\n\nN_COORDS = [\n (MAX_CO + 1) ** (N_CORNERS-1), # TWIST\n (MAX_EO + 1) ** (N_EDGES-1), # FLIP\n FAC[len(FRBR_EDGES)] * CNK[N_EDGES][len(FRBR_EDGES)], # FRBR\n FAC[len(URFDLF_CORNERS)] * CNK[N_CORNERS][len(URFDLF_CORNERS)], # URFDLF\n FAC[len(URUL_EDGES)] * CNK[N_EDGES][len(URUL_EDGES)], # URUL\n FAC[len(UBDF_EDGES)] * CNK[N_EDGES][len(UBDF_EDGES)], # UBDF\n FAC[len(URDF_EDGES)] * CNK[N_EDGES - len(FRBR_EDGES)][len(URDF_EDGES)], # URDF\n 2, # PAR\n FAC[len(URFDRB_CORNERS)], # URFDRB\n FAC[len(URBR_EDGES)] # URBR\n]\n_MUL = [CORNERS, EDGES, EDGES, CORNERS, EDGES, EDGES, EDGES] # TWIST, FLIP, FRBR, URFDLF, URUL, UBDF, URDF\n\n\n# Assumes all bits are set to 1.\ndef _set_prun(table, i, v):\n table[i>>1] &= (v << 4) | 0xf if i & 1 else 0xf0 | v\n\ndef get_prun(table, i):\n tmp = table[i>>1]\n return ((tmp & 0xf0) >> 4) if i & 1 else tmp & 0x0f\n\n_N_FRBR_1 = CNK[N_EDGES][len(FRBR_EDGES)] # the permutation part is irrelevant in phase 1\n_N_FRBR_2 = FAC[len(FRBR_EDGES)] # in phase 2 the orientation part is always 0\n\ndef phase1_prun_idx(c, frbr):\n return _N_FRBR_1 * c + frbr // _N_FRBR_2 # we need to divide out the irrelevant permutation component\n\ndef _gen_phase1_pruntable(n, coord):\n # Make all bits on per default, which allows detecting empty cells as 0xf (possible as all values will be < 15).\n prun = array('B', [0xff] * n)\n\n _set_prun(prun, 0, 0)\n q = deque([0])\n\n while len(q) != 0:\n i = q.popleft()\n c = i // _N_FRBR_1\n frbr = i % _N_FRBR_1\n\n for m in range(MOVES_PER_FACE * N_COLORS):\n # The FRBR move-table assumes that the permutation part is present, so we simply set it to 0.\n j = phase1_prun_idx(MOVE[coord][c][m], MOVE[FRBR][frbr * _N_FRBR_2][m])\n if get_prun(prun, j) == 0xf:\n _set_prun(prun, j, get_prun(prun, i) + 1)\n q.append(j)\n\n print('Generated pruning table.')\n return prun\n\n_N_PER_BYTE = 2\n\n_PHASE2_MOVES = [\n _move_idx(f, c) for f, c in [(U,0), (U,1), (U,2), (R,1), (F,1), (D,0), (D,1), (D,2), (L,1), (B,1)]\n] # U, U2, U', R2, F2, D, D2, D', L2, B2\n\ndef phase2_prun_idx(c, frbr, par):\n return (_N_FRBR_2 * c + frbr) * N_COORDS[PAR] + par\n\ndef _gen_phase2_pruntable(coord):\n prun = array('B', [255] * (_N_FRBR_2 * N_COORDS[coord] * N_COORDS[PAR] / _N_PER_BYTE))\n\n _set_prun(prun, 0, 0)\n q = deque([0])\n\n while len(q) != 0:\n i = q.popleft()\n par = i % N_COORDS[PAR]\n c = (i // N_COORDS[PAR]) // _N_FRBR_2\n frbr = (i // N_COORDS[PAR]) % _N_FRBR_2\n\n for m in _PHASE2_MOVES:\n j = phase2_prun_idx(MOVE[coord][c][m], MOVE[FRBR][frbr][m], MOVE[PAR][par][m])\n if get_prun(prun, j) == 0xf:\n _set_prun(prun, j, get_prun(prun, i) + 1)\n q.append(j)\n\n print('Generated pruning table.')\n return prun\n\n_N_URUL_UBDF_2 = FAC[len(URUL_EDGES)] * CNK[N_EDGES - len(FRBR_EDGES)][len(URUL_EDGES)]\n\n\n_FILE = 'tables'\n\nif os.path.exists(_FILE):\n MOVE, FRBR_TWIST_PRUN, FRBR_FLIP_PRUN, FRBR_URFDLF_PAR_PRUN, FRBR_URDF_PAR_PRUN, URDF_MERG = \\\n pickle.load(open(_FILE, 'rb'))\nelse:\n # TWIST, FLIP, FRBR, URFDLF, URUL, UBDF, URDF\n MOVE = [_gen_movetable(N_COORDS[i], i, _MUL[i]) for i in range(len(N_COORDS) - 3)] # skip PAR, URFDRB and URBR\n\n # Hardcoding this here avoids having to reconstruct the PAR coordinate\n MOVE.append([\n array('i', [1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1]),\n array('i', [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0])\n ]) # ..., PAR\n\n # Number of entries is not even, hence we have to allocate one more cell.\n FRBR_TWIST_PRUN = _gen_phase1_pruntable(N_COORDS[TWIST] * _N_FRBR_1 / _N_PER_BYTE + 1, TWIST)\n FRBR_FLIP_PRUN = _gen_phase1_pruntable(N_COORDS[FLIP] * _N_FRBR_1 / _N_PER_BYTE, FLIP)\n\n FRBR_URFDLF_PAR_PRUN = _gen_phase2_pruntable(URFDLF)\n FRBR_URDF_PAR_PRUN = _gen_phase2_pruntable(URDF)\n\n URDF_MERG = [array('i', [merge_urdf(i, j) for j in range(_N_URUL_UBDF_2)]) for i in range(_N_URUL_UBDF_2)]\n print('Generated merge table.')\n\n pickle.dump(\n (MOVE, FRBR_TWIST_PRUN, FRBR_FLIP_PRUN, FRBR_URFDLF_PAR_PRUN, FRBR_URDF_PAR_PRUN, URDF_MERG),\n open(_FILE, 'wb')\n )\nprint('Tables loaded.')\n","sub_path":"coord.py","file_name":"coord.py","file_ext":"py","file_size_in_byte":5185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509717337","text":"\"\"\"\nSecSTAR visualizer: Processing xml trace data and constructing svg images.\n\nThe class relationships:\n- GraphBuilder uses\n - CombineWorker\n - LookupTableWorker\n - TemporalListWorker\n - StaticGraphWorker\n - AnimationWorker\n\"\"\"\n\nimport logging\nimport os\n\nfrom workers import combine_worker\nfrom workers import lookup_table_worker\nfrom workers import static_graph_worker\nfrom workers import animation_worker\n\nclass GraphBuilder:\n \"\"\"\n Summary:\n\n The builder class to generate graphs.\n\n Description:\n\n The go() method is the only public method to parse XML trace data and\n generate static graph and animation graphs. The detailed steps involve:\n 1. Combine multiple xml files of the same process into one single file;\n 2. Parse those single XML files and build a lookup table to store\n information in memory;\n 3. Build a list of temporal events from the lookup table;\n 4. Generate static graph;\n 5. Generate animation graphs.\n\n Attributes:\n \"\"\"\n\n def __init__(self):\n pass\n\n def package(self, dir_path, dedup = False):\n \"\"\"\n Summary:\n\n Pack svgs / events into a file and zip them\n 1. Zip static.svg\n - output: static.zip\n - delimiter: \"\" (default)\n 2. Cancatenate all svgs, zip them\n - output: svgs.zip\n - delimiter: \"\" (default)\n 3. Cancatenate all events, zip them\n - output: events.zip\n - delimiter: \"===event===\\n\" (additional)\n \"\"\"\n path = \"%s/raw\" % dir_path\n if dedup:\n path = \"%s/dedup\" % dir_path\n\n logging.info(path)\n logging.info(\"Remove all .dot files\")\n os.system(\"rm -f %s/*.dot\" % path)\n\n if not os.path.exists(\"%s/static.zip\" % path):\n logging.info(\"Package static.svg\")\n os.system(\"cd %s;zip -9 static.zip static.svg\" % path)\n os.system(\"rm -f %s/static.svg\" % path)\n\n if not os.path.exists(\"%s/svgs.zip\" % path):\n logging.info(\"Package animation svg files\")\n os.system(\"cd %s;ls *.svg | sort -n | xargs cat >> svgs.svg\" % path)\n os.system(\"cd %s; zip -9 svgs.zip svgs.svg\" % path)\n os.system(\"rm -f %s/svgs.svg\" % path)\n\n if not os.path.exists(\"%s/events.zip\" % path):\n logging.info(\"Package event files\")\n os.system(\"cd %s;ls *.e | sort -n >> event_tmp\" % path)\n fp = open(\"%s/event_tmp\" % path, \"r\")\n for file_name in fp:\n file_name = file_name.rstrip()\n os.system(\"echo \\\"\\n===event===\\n\\\" >> %s/events.e\" % path)\n os.system(\"cat %s/%s >> %s/events.e\" % (path, file_name, path))\n fp.close()\n os.system(\"cd %s;zip -9 events.zip events.e\" % path)\n os.system(\"rm -f %s/event_tmp\" % path)\n os.system(\"rm -f %s/events.e\" % path)\n\n def go(self, input_dir, output_dir, dedup = False):\n \"\"\"\n Summary:\n\n The only public method in this class. It deploys a list of workers to\n build graphs. Each invocation is idempotent.\n\n If any worker fails, the program stops immediately. FAIL-STOP policy.\n\n Args:\n\n input_dir: The root dir path for xml trace data. It can be either\n relative path or absolute path.\n\n output_dir: The root dir path for generated graphs. It can be either\n relative path or absolute path.\n\n groupping: Whether or not to group those leaf nodes that have the same\n parent, the same privilege level, and the same executable. Default\n value is False.\n \"\"\"\n logging.info('Start working ...')\n\n # Step 1\n combine_worker.run(input_dir)\n \n # Step 2\n table = lookup_table_worker.run(input_dir)\n\n # Step 3\n static_graph_worker.run(table, output_dir, dedup)\n\n # Step 4\n animation_worker.run(table, output_dir, dedup)\n \ndef main():\n logging.basicConfig(level=logging.INFO)\n\n input_dir = '../traces'\n output_dir = '../html/images'\n \n builder = GraphBuilder()\n builder.go(input_dir, output_dir, dedup=False)\n builder.go(input_dir, output_dir, dedup=True)\n builder.package(output_dir, dedup=False)\n builder.package(output_dir, dedup=True)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"user_agent/mist_tool/SecSTAR/SecSTAR/SecSTAR.py","file_name":"SecSTAR.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"339087324","text":"from Maze import Maze\nfrom time import sleep\n\nHEURISTIC_NONADMISSIBLE_WEIGHT = 1.5\nHEURISTIC_NONADMISSIBLE_CONVERGANCE_FACTOR = 1.5\n\nclass SensorlessProblem:\n\n def __init__(self, maze, goal_x, goal_y):\n self.goal = (goal_x, goal_y)\n self.maze = maze\n\n # Add all possible robot locations to the starting state\n start_state = set()\n for x in range(maze.width):\n for y in range(maze.height):\n if maze.is_floor(x, y):\n start_state.add((x, y))\n\n self.start_state = self._normalize_state(start_state)\n\n def __str__(self):\n string = \"Blind robot problem: \"\n return string\n\n # given a sequence of states (including robot turn), modify the maze and print it out.\n # (Be careful, this does modify the maze!)\n\n @staticmethod\n def animate_path(maze, path, goal):\n print(\"Sensorless Problem\")\n for state in path: \n print(maze.string_sensorless(state, goal))\n sleep(1)\n\n def get_successors(self, state):\n\n moves = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n successors = []\n\n for dx, dy in moves:\n\n # Set of locations where the robot might be next turn, if it does this move\n next_state = set()\n for x, y in state:\n nx, ny = x + dx, y + dy\n\n # The robot ran into a wall, so it doesn't move\n if not self.maze.is_floor(nx, ny):\n nx = x\n ny = y\n\n if (nx, ny) in next_state:\n # This location is already present in the next state. \n # Hopefully this gets hit a lot so the robot can\n # figure out where it is.\n continue\n \n next_state.add((nx, ny))\n \n \n next_state = self._normalize_state(next_state)\n\n # successors is a list of tuples in the form of (transition cost, succession state)\n successors.append((1, next_state))\n\n # there's no need to filter by legality, because there are no illegal states \n # generated by the above algorithm\n return successors\n\n def is_goal(self, state):\n if len(state) != 1:\n return False\n \n return list(state)[0] == self.goal\n\n def _normalize_state(self, state):\n \"\"\"Normalize the representation of the state so it can be\n hashed and so the potential locations can be iterated through\n\n Args:\n state (set): State to normalize\n\n Returns:\n Tuple[Tuple[int]]: Tuple containing all the potential locations\n \"\"\"\n # We sort the set of options and convert it into a tuple \n # so that it can be hashed and compared by the search algorithms\n state = list(state)\n state.sort()\n return tuple(state)\n \n def heuristic_convergance_distance(self, state):\n \"\"\"Heuristic that calculates the maximum separation between any two \n potential locations in the state. Logic is that we must perform at least\n `delta_x + delta_y` moves to converge the two potential locations before \n we can arrive at a solution.\n\n Args:\n state (Tuple[Tuple[int]]): Problem state to calculate heuristic for\n\n Returns:\n int: Estimate of remaining path cost\n \"\"\"\n assert len(state) >= 1\n\n ref_x, ref_y = state[0]\n max_x_diff = 0\n max_y_diff = 0\n\n for i in range(1, len(state)):\n x, y = state[i]\n max_x_diff = max(max_x_diff, abs(x - ref_x))\n max_y_diff = max(max_y_diff, abs(y - ref_y))\n \n return max_x_diff + max_y_diff\n\n def heuristic_goal_distance(self, state):\n \"\"\"Heuristic that calculates the maximum distance between any\n of the potential locations in the state and the goal. Logic is that \n all potential locations must converage and arrive the goal spot before \n we can find a solution. \n\n Args:\n state (Tuple[Tuple[int]]): Problem state to calculate heuristic for\n\n Returns:\n int: Estimate of remaining path cost\n \"\"\"\n goal_x, goal_y = self.goal\n distance_x = 0\n distance_y = 0\n\n for x, y in state:\n distance_x = max(distance_x, abs(goal_x - x))\n distance_y = max(distance_y, abs(goal_y - y))\n\n\n return distance_x + distance_y\n\n def heuristic_composite(self, state):\n \"\"\"Composite heuristic that combines convergance and goal_reaching heuristics. \n Logic is that before we can arrive at a solution all potential locations must \n converge and must reach the goal location. It's possible that every move will\n do some of both behaviors, so the heuristics can't be simply added together. \n Therefore, the maximum heuristic value is returned.\n\n Args:\n state (Tuple[Tuple[int]]): Problem state to calculate heuristic for\n\n Returns:\n int: Estimate of remaining path cost\n \"\"\"\n return max([\n self.heuristic_goal_distance(state),\n self.heuristic_convergance_distance(state)\n ])\n \n def heuristic_nonadmissible_weighted(self, state, weight=HEURISTIC_NONADMISSIBLE_WEIGHT, convergence_factor=HEURISTIC_NONADMISSIBLE_CONVERGANCE_FACTOR):\n \"\"\"Heuristic designed for fast, but nonoptimal solving of large problem sizes.\n By combining the two heuristics, the algorithm is incentivized to find moves that\n both converge and move the robot closer to the goal. The heuristic is nonadmissible\n as it can easily (and frequently does) overestimate the cost to the goal.\n\n Args:\n state ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n\n return weight * (self.heuristic_convergance_distance(state) * convergence_factor + self.heuristic_goal_distance(state))\n\n## A bit of test code\n\n\n# if __name__ == \"__main__\":\n\n","sub_path":"pa2/SensorlessProblem.py","file_name":"SensorlessProblem.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"396720922","text":"#!/usr/bin/python3\n#coding=utf-8\nimport caffe\nimport cv2\nimport numpy as np\nimport math\n\n##change (11,11) to (21,21)\n##2019/7/8 16:11\n#适配树莓派\n##2019/7/8 14:27\n#更改预处理方式\n##2019/7/7 19:31\n#加入4个排序\n##2019/7/7 17:07\n#限制输出为4个\ndef detect_alpha(frame00):\n \n #ok,frame=cap1.read()\n #if not ok :\n # return alphabet_class\n#cut\n #path = \"./\" #根目录\n #img = cv2.imread(path+\"temp/1.jpg\")\n # img = frame\n # #img = cv2.imread(path+\"test_pic/012.png\")\n # if img is None:\n # return alphabet_class\n # cv2.imshow(\"image\", img)\n # cv2.waitKey(10)\n \n \n\n # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # blurred = cv2.GaussianBlur(gray, (3, 3), 0)\n\n # #gradX = cv2.Sobel(blurred, ddepth=cv2.CV_32F, dx=1, dy=0)\n # #gradY = cv2.Sobel(blurred, ddepth=cv2.CV_32F, dx=0, dy=1)\n # #gradient = cv2.subtract(gradX, gradY)\n # #gradient = cv2.convertScaleAbs(gradient)\n\n # #cv2.imshow(\"sobel_img\", gradient)\n # #cv2.waitKey(10)\n \n\n\n # thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,5,10)\n\n # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n # #closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)\n # closed = cv2.dilate(thresh,kernel)\n\n\n # cv2.imshow(\"closed_img\", closed)\n # cv2.waitKey(10)\n # #cv2.waitKey(0)\n\n # h = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n # contours = h[1]\n # num = len(contours)\n # #judge alpha exist or not\n # if num==0:\n # return alphabet_class\n # if len(contours[0])<50:\n # return alphabet_class\n \n \n \n \n # imgfin = img.copy()\n\n # for i in range(0, num):\n # cnt = contours[i]\n # x,y,w,h = cv2.boundingRect(cnt)\n # #print(cnt)\n # #box = np.int0(cv2.boxPoints(rect))\n # #print(box)\n # #draw_img = cv2.drawContours(imgfin, [box], -1, (0, 0, 255), 2)\n # cv2.rectangle(imgfin,(x,y),(x+w,y+h),(0, 0, 255), 2)\n # #Xs = [ii[0] for ii in box]\n # #Ys = [ii[1] for ii in box]\n # #x1 = min(Xs)\n # #x2 = max(Xs)\n # #y1 = min(Ys)\n # #y2 = max(Ys)\n # #hight = y2 - y1\n # #width = x2 - x1\n # crop_img = img[y:y+h,x:x+w]\n \n # pi = cv2.resize(crop_img,(16,16))\n # cv2.imwrite(path + 'detect_results/' + str(num-i) + '.png', pi)\n\n \n # cv2.imshow(\"draw_img\", imgfin)\n # cv2.waitKey(10)\n # #cv2.waitKey(0)\n\n\n # #cv2.destroyAllWindows()\n alphabet_class=0x00000000\n # sp = frame.shape\n # #cv2.imwrite('' + str(nn) + '.jpg', frame)\n # H = sp[0]\n # W = sp[1]\n\n # hue_image = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n # low_range1 = np.array([110, 15, 150])\n # high_range1 = np.array([180, 30, 200])\n # th1 = cv2.inRange(hue_image, low_range1, high_range1)\n # low_range2 = np.array([100, 10, 70])\n # high_range2 = np.array([150, 110, 140])\n # th2 = cv2.inRange(hue_image, low_range2, high_range2)\n # th = th1+th2\n\n # #cv2.imwrite(\"./display/05.jpg\",th)\n # cv2.imshow(\"detect\", th)\n # cv2.waitKey(0)\n\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(17,17))\n # closed = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel)\n\n # #cv2.imwrite(\"./display/04.jpg\",closed)\n # #cv2.imshow(\"closed\", closed)\n # #cv2.waitKey(0)\n\n # _, contours, hierarchy = cv2.findContours(closed,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n \n # if len(contours)==0:\n # return alphabet_class\n\n # cnt=contours[0]\n # temp=cnt.shape[0]\n # for i in range(len(contours)):\n # if contours[i].shape[0]>temp:\n # temp = contours[i].shape[0]\n # cnt = contours[i]\n \n # if temp<1000:\n # return alphabet_class\n\n # black0=np.zeros((H,W),dtype=np.uint8)\n # black = cv2.copyMakeBorder(black0,160,160,80,80, cv2.BORDER_CONSTANT,value=[0,0,0])\n\n # rect = cv2.minAreaRect(cnt)\n # box = cv2.boxPoints(rect)\n # box = np.int0(box)\n # box = box + np.matrix('80,160;80,160;80,160;80,160')\n\n # cv2.drawContours(black,[box],0,(255,255,255),-1)\n # angle = rect[2]+90\n # #cv2.imwrite(\"./display/03.jpg\",black)\n # #print(angle)\n # #cv2.imshow(\"final\", black)\n # #cv2.waitKey(0)\n # frame = cv2.copyMakeBorder(frame,160,160,80,80, cv2.BORDER_REPLICATE)\n # center = (400, 400) #1\n # M = cv2.getRotationMatrix2D(center, angle, 1.0) #12\n # rotated = cv2.warpAffine(black, M, (800, 800)) #13\n\n # rotated2 = cv2.warpAffine(frame, M, (800, 800)) #13\n # #cv2.imwrite(\"./display/02.jpg\",rotated)\n # #cv2.imshow(\"rot\", rotated)\n # #cv2.waitKey(0)\n\n # _, contours2, hierarchy2 = cv2.findContours(rotated,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n # cnt=contours2[0]\n # x,y,w,h = cv2.boundingRect(cnt)\n # crop_img = rotated2[y:y+h,x:x+w]\n #cv2.imshow(\"crop\", crop_img)\n #cv2.waitKey(0)\n frame0=np.rot90(frame00)\n frame=np.rot90(frame0)\n sp = frame.shape\n cv2.imwrite('./0001.jpg', frame)\n cv2.waitKey(10)\n H = sp[0]\n W = sp[1]\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n ret,thresh1 = cv2.threshold(gray,90,255,cv2.THRESH_BINARY_INV)#change 60to90\n # cv2.imshow(\"thresh\", thresh1)\n # cv2.waitKey(0)\n thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,25,10)\n # cv2.imshow(\"thresh\", thresh2)\n # cv2.waitKey(0)\n thresh = cv2.bitwise_and(thresh1,thresh2)\n #cv2.imshow(\"thresh\", thresh)\n #cv2.waitKey(0)\n\n \n _, contours0, hierarchy0 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n #c_max = []\n for i in range(len(contours0)):\n cnt = contours0[i]\n area = cv2.contourArea(cnt)\n if (area < 300):\n c_min = []\n c_min.append(cnt)\n cv2.drawContours(thresh, c_min, -1, (0, 0, 0), cv2.FILLED)\n # cv2.imshow(\"drawblack\", thresh)\n # cv2.waitKey(0)\n\n kernel0 = cv2.getStructuringElement(cv2.MORPH_RECT,(100,5))\n closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel0)\n #cv2.imshow(\"close\", closed)\n #cv2.waitKey(0)\n\n _, contours1, hierarchy1 = cv2.findContours(closed,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n if len(contours1) == 0:\n return alphabet_class\n cnt=contours1[0]\n temp=cnt.shape[0]\n\n for i in range(len(contours1)):\n if contours1[i].shape[0]>temp:\n temp = contours1[i].shape[0]\n cnt = contours1[i]\n if temp<300: #change 500to300\n return alphabet_class\n\n\n black0=np.zeros((H,W),dtype=np.uint8)\n black = cv2.copyMakeBorder(black0,160,160,80,80, cv2.BORDER_CONSTANT,value=[0,0,0])\n rect = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n box = box + np.matrix('80,160;80,160;80,160;80,160')\n cv2.drawContours(black,[box],0,(255,255,255),-1)\n # cv2.imshow(\"black\",black)\n # cv2.waitKey(0)\n\n kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT,(40,20))\n dilated = cv2.dilate(black,kernel1)\n #cv2.imshow(\"dilate\",dilated)\n #cv2.waitKey(0)\n\n angle = rect[2]\n #cv2.imwrite(\"./display/03.jpg\",black)\n #print(angle)\n #cv2.waitKey(0)\n #cv2.imshow(\"final\", black)\n #cv2.waitKey(0)\n frame = cv2.copyMakeBorder(frame,160,160,80,80, cv2.BORDER_REPLICATE)\n center = (400, 400) #1\n M = cv2.getRotationMatrix2D(center, angle+90, 1.0) #12 change angle to angle+90\n rotated = cv2.warpAffine(dilated, M, (800, 800)) #13\n rotated2 = cv2.warpAffine(frame, M, (800, 800)) #13\n #cv2.imwrite(\"./display/02.jpg\",rotated)\n #cv2.imshow(\"rot\", rotated)\n #cv2.waitKey(0)\n _, contours2, hierarchy2 = cv2.findContours(rotated,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n if len(contours2) == 0:\n return alphabet_class\n cnt=contours2[0]\n x,y,w,h = cv2.boundingRect(cnt)\n crop_img = rotated2[y:y+h,x:x+w]\n # cv2.imshow(\"crop\",crop_img)\n # cv2.waitKey(0)\n\n gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)\n thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,31,10)\n kernel0 = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel0)\n # cv2.imshow(\"thresh\", thresh)\n # cv2.waitKey(0)\n\n _, contours3, hierarchy3 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n #c_max = []\n c_min = []\n for i in range(len(contours3)):\n cnt = contours3[i]\n area = cv2.contourArea(cnt)\n #print(area)\n if (area < 100): #change 1000 to 100\n c_min.append(cnt)\n cv2.drawContours(thresh, c_min, -1, (0, 0, 0), cv2.FILLED)\n\n #thresh=cv2.bitwise_not(thresh)\n kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT,(21,21))\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel2)\n\n #cv2.imshow(\"final\", thresh)\n #cv2.waitKey(0)\n\n _, contours4, hierarchy4 = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n num = len(contours4)\n #print(num)\n ##排序\n cnt_sorted=[]\n for i in range(num):\n cnt = contours4[i]\n x, y, w, h = cv2.boundingRect(cnt)\n #print(x)\n cnt_sorted.append([cnt, x])\n cnt_sorted.sort(key=lambda elem: elem[-1])\n for i in range(num):\n temp = cnt_sorted[i]\n #print(temp.pop())\n cnt_sorted[i] = temp[0]\n\n for i in range(num):\n cnt = cnt_sorted[i]\n x, y, w, h = cv2.boundingRect(cnt)\n #cv2.rectangle(imgfin, (x, y), (x + w, ycaffe + h), (0, 0, 255), 2)\n crop0 = thresh[y:y + h, x:x + w]\n #print(int((1.5*math.sqrt(h*h+w*w)-w)/2), int((1.5*math.sqrt(h*h+w*w)-w)/2), int((1.5*math.sqrt(h*h+w*w)-h)/2), int((1.5*math.sqrt(h*h+w*w)-h)/2))\n crop = cv2.copyMakeBorder(crop0, int((1.2*math.sqrt(h*h+w*w)-h)/2), int((1.2*math.sqrt(h*h+w*w)-h)/2), int((1.2*math.sqrt(h*h+w*w)-w)/2), int((1.2*math.sqrt(h*h+w*w)-w)/2), cv2.BORDER_CONSTANT,value=[0,0,0])\n pi0 = cv2.GaussianBlur(cv2.bitwise_not(crop),(27,27),0)#change 33 to 27\n pi = cv2.resize(pi0, (64, 64))\n cv2.imwrite('/home/pi/Desktop/detect_results/' + str(num-i) + '.png', pi)\n\n\n\n #detect\n path = \"/home/pi/Desktop/\" #根目录\n model = 'trained_model_64'\n deploy= path + model + '/deploy.prototxt' #deploy文件\n caffe_model= path + model + '/lenet_iter_2070.caffemodel' #训练好的 caffemodel\n #img ='test_pics/abc.png' #随机找的一张待测图片\n labels_filename = path + model + '/labels.txt' #类别名称文件,将数字标签转换回类别名称\n\n net = caffe.Net(deploy,caffe_model,caffe.TEST) #加载model和network\n labels = np.loadtxt(labels_filename, str, delimiter='\\t') #读取类别名称文件\n\n #图片预处理设置\n transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) #设定图片的shape格式(1,3,28,28)\n transformer.set_transpose('data', (2,0,1)) #改变维度的顺序,由原始图片(28,28,3)变为(3,28,28)\n #transformer.set_mean('data', np.load(mean_file).mean(1).mean(1)) #减去均值,前面训练模型时没有减均值,这儿就不用\n transformer.set_raw_scale('data', 255) # 缩放到【0,255】之间\n transformer.set_channel_swap('data', (2,1,0)) #交换通道,将图片由RGB变为BGR\n\n \n for i in range(2): #\n im=caffe.io.load_image(path + 'detect_results/' + str(i+1) + '.png') #加载图片\n net.blobs['data'].data[...] = transformer.preprocess('data',im) #执行上面设置的图片预处理操作,并将图片载入到blob中\n\n #执行测试\n out = net.forward()\n\n prob= net.blobs['Softmax1'].data[0].flatten() #取出最后一层(Softmax)属于某个类别的概率值,并打印\n #print(prob)\n output_str=labels[prob.argsort()[-1]] #将概率值排序,取出最大值所在的序号\n alphabet_class += (ord(output_str)-ord('@'))<<(8*i)\n print('the class is:',output_str) #将该序号转换成对应的类别名称,并打印\n return alphabet_class\n\nif __name__ == '__main__': # __name__ �ǵ�ǰģ��������ģ�鱻ֱ������ʱģ����Ϊ __main__ ����仰����˼���ǣ���ģ�鱻ֱ������ʱ�����´���齫�����У���ģ���DZ�����ʱ������鲻�����С�\n \n # cap1=cv2.VideoCapture(1)\n # missframe_count=50\n # while missframe_count:\n # cap1.read()\n # missframe_count=missframe_count-1\n # while cap1.isOpened():\n # ok,frame=cap1.read()\n # if ok :\n # result=detect_alpha(frame)\n # st='%06x'%result\n # print(st)\n # #print(type(order))\n # #print(order)\n # cap1.release()\n # #result=detect_alpha(cap1)\n frame = cv2.imread('./Debug&Config/capture_letter/730ab.jpg')\n alphabet_class = detect_alpha(frame)\n print(alphabet_class)\n\n\n","sub_path":"参考资料/4/一个队顶俩队-速度和图像识别快但不稳定/树莓派代码/back_today/caffe_recognize_texts_old.py","file_name":"caffe_recognize_texts_old.py","file_ext":"py","file_size_in_byte":13044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"246888085","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\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\"\"\"\nNova authentication management\n\"\"\"\n\nimport logging\nimport os\nimport shutil\nimport string\nimport sys\nimport tempfile\nimport uuid\nimport zipfile\n\nfrom nova import crypto\nfrom nova import datastore\nfrom nova import exception\nfrom nova import flags\nfrom nova import objectstore # for flags\nfrom nova import utils\nfrom nova.auth import signer\nFLAGS = flags.FLAGS\n\n# NOTE(vish): a user with one of these roles will be a superuser and\n# have access to all api commands\nflags.DEFINE_list('superuser_roles', ['cloudadmin'],\n 'Roles that ignore rbac checking completely')\n\n# NOTE(vish): a user with one of these roles will have it for every\n# project, even if he or she is not a member of the project\nflags.DEFINE_list('global_roles', ['cloudadmin', 'itsec'],\n 'Roles that apply to all projects')\n\n\nflags.DEFINE_bool('use_vpn', True, 'Support per-project vpns')\nflags.DEFINE_string('credentials_template',\n utils.abspath('auth/novarc.template'),\n 'Template for creating users rc file')\nflags.DEFINE_string('vpn_client_template',\n utils.abspath('cloudpipe/client.ovpn.template'),\n 'Template for creating users vpn file')\nflags.DEFINE_string('credential_key_file', 'pk.pem',\n 'Filename of private key in credentials zip')\nflags.DEFINE_string('credential_cert_file', 'cert.pem',\n 'Filename of certificate in credentials zip')\nflags.DEFINE_string('credential_rc_file', 'novarc',\n 'Filename of rc in credentials zip')\n\nflags.DEFINE_integer('vpn_start_port', 1000,\n 'Start port for the cloudpipe VPN servers')\nflags.DEFINE_integer('vpn_end_port', 2000,\n 'End port for the cloudpipe VPN servers')\n\nflags.DEFINE_string('credential_cert_subject',\n '/C=US/ST=California/L=MountainView/O=AnsoLabs/'\n 'OU=NovaDev/CN=%s-%s',\n 'Subject for certificate for users')\n\nflags.DEFINE_string('vpn_ip', '127.0.0.1',\n 'Public IP for the cloudpipe VPN servers')\n\nflags.DEFINE_string('auth_driver', 'nova.auth.ldapdriver.FakeLdapDriver',\n 'Driver that auth manager uses')\n\nclass AuthBase(object):\n \"\"\"Base class for objects relating to auth\n\n Objects derived from this class should be stupid data objects with\n an id member. They may optionally contain methods that delegate to\n AuthManager, but should not implement logic themselves.\n \"\"\"\n @classmethod\n def safe_id(cls, obj):\n \"\"\"Safe get object id\n\n This method will return the id of the object if the object\n is of this class, otherwise it will return the original object.\n This allows methods to accept objects or ids as paramaters.\n\n \"\"\"\n if isinstance(obj, cls):\n return obj.id\n else:\n return obj\n\n\nclass User(AuthBase):\n \"\"\"Object representing a user\"\"\"\n def __init__(self, id, name, access, secret, admin):\n self.id = id\n self.name = name\n self.access = access\n self.secret = secret\n self.admin = admin\n\n def is_superuser(self):\n return AuthManager().is_superuser(self)\n\n def is_admin(self):\n return AuthManager().is_admin(self)\n\n def has_role(self, role):\n return AuthManager().has_role(self, role)\n\n def add_role(self, role):\n return AuthManager().add_role(self, role)\n\n def remove_role(self, role):\n return AuthManager().remove_role(self, role)\n\n def is_project_member(self, project):\n return AuthManager().is_project_member(self, project)\n\n def is_project_manager(self, project):\n return AuthManager().is_project_manager(self, project)\n\n def generate_key_pair(self, name):\n return AuthManager().generate_key_pair(self.id, name)\n\n def create_key_pair(self, name, public_key, fingerprint):\n return AuthManager().create_key_pair(self.id,\n name,\n public_key,\n fingerprint)\n\n def get_key_pair(self, name):\n return AuthManager().get_key_pair(self.id, name)\n\n def delete_key_pair(self, name):\n return AuthManager().delete_key_pair(self.id, name)\n\n def get_key_pairs(self):\n return AuthManager().get_key_pairs(self.id)\n\n def __repr__(self):\n return \"User('%s', '%s', '%s', '%s', %s)\" % (self.id,\n self.name,\n self.access,\n self.secret,\n self.admin)\n\n\nclass KeyPair(AuthBase):\n \"\"\"Represents an ssh key returned from the datastore\n\n Even though this object is named KeyPair, only the public key and\n fingerprint is stored. The user's private key is not saved.\n \"\"\"\n def __init__(self, id, name, owner_id, public_key, fingerprint):\n self.id = id\n self.name = name\n self.owner_id = owner_id\n self.public_key = public_key\n self.fingerprint = fingerprint\n\n def __repr__(self):\n return \"KeyPair('%s', '%s', '%s', '%s', '%s')\" % (self.id,\n self.name,\n self.owner_id,\n self.public_key,\n self.fingerprint)\n\n\nclass Project(AuthBase):\n \"\"\"Represents a Project returned from the datastore\"\"\"\n def __init__(self, id, name, project_manager_id, description, member_ids):\n self.id = id\n self.name = name\n self.project_manager_id = project_manager_id\n self.description = description\n self.member_ids = member_ids\n\n @property\n def project_manager(self):\n return AuthManager().get_user(self.project_manager_id)\n\n @property\n def vpn_ip(self):\n ip, port = AuthManager().get_project_vpn_data(self)\n return ip\n\n @property\n def vpn_port(self):\n ip, port = AuthManager().get_project_vpn_data(self)\n return port\n\n def has_manager(self, user):\n return AuthManager().is_project_manager(user, self)\n\n def has_member(self, user):\n return AuthManager().is_project_member(user, self)\n\n def add_role(self, user, role):\n return AuthManager().add_role(user, role, self)\n\n def remove_role(self, user, role):\n return AuthManager().remove_role(user, role, self)\n\n def has_role(self, user, role):\n return AuthManager().has_role(user, role, self)\n\n def get_credentials(self, user):\n return AuthManager().get_credentials(user, self)\n\n def __repr__(self):\n return \"Project('%s', '%s', '%s', '%s', %s)\" % (self.id,\n self.name,\n self.project_manager_id,\n self.description,\n self.member_ids)\n\n\nclass NoMorePorts(exception.Error):\n pass\n\n\nclass Vpn(datastore.BasicModel):\n \"\"\"Manages vpn ips and ports for projects\"\"\"\n def __init__(self, project_id):\n self.project_id = project_id\n super(Vpn, self).__init__()\n\n @property\n def identifier(self):\n \"\"\"Identifier used for key in redis\"\"\"\n return self.project_id\n\n @classmethod\n def create(cls, project_id):\n \"\"\"Creates a vpn for project\n\n This method finds a free ip and port and stores the associated\n values in the datastore.\n \"\"\"\n # TODO(vish): get list of vpn ips from redis\n port = cls.find_free_port_for_ip(FLAGS.vpn_ip)\n vpn = cls(project_id)\n # save ip for project\n vpn['project'] = project_id\n vpn['ip'] = FLAGS.vpn_ip\n vpn['port'] = port\n vpn.save()\n return vpn\n\n @classmethod\n def find_free_port_for_ip(cls, ip):\n \"\"\"Finds a free port for a given ip from the redis set\"\"\"\n # TODO(vish): these redis commands should be generalized and\n # placed into a base class. Conceptually, it is\n # similar to an association, but we are just\n # storing a set of values instead of keys that\n # should be turned into objects.\n redis = datastore.Redis.instance()\n key = 'ip:%s:ports' % ip\n # TODO(vish): these ports should be allocated through an admin\n # command instead of a flag\n if (not redis.exists(key) and\n not redis.exists(cls._redis_association_name('ip', ip))):\n for i in range(FLAGS.vpn_start_port, FLAGS.vpn_end_port + 1):\n redis.sadd(key, i)\n\n port = redis.spop(key)\n if not port:\n raise NoMorePorts()\n return port\n\n @classmethod\n def num_ports_for_ip(cls, ip):\n \"\"\"Calculates the number of free ports for a given ip\"\"\"\n return datastore.Redis.instance().scard('ip:%s:ports' % ip)\n\n @property\n def ip(self):\n \"\"\"The ip assigned to the project\"\"\"\n return self['ip']\n\n @property\n def port(self):\n \"\"\"The port assigned to the project\"\"\"\n return int(self['port'])\n\n def save(self):\n \"\"\"Saves the association to the given ip\"\"\"\n self.associate_with('ip', self.ip)\n super(Vpn, self).save()\n\n def destroy(self):\n \"\"\"Cleans up datastore and adds port back to pool\"\"\"\n self.unassociate_with('ip', self.ip)\n datastore.Redis.instance().sadd('ip:%s:ports' % self.ip, self.port)\n super(Vpn, self).destroy()\n\n\nclass AuthManager(object):\n \"\"\"Manager Singleton for dealing with Users, Projects, and Keypairs\n\n Methods accept objects or ids.\n\n AuthManager uses a driver object to make requests to the data backend.\n See ldapdriver for reference.\n\n AuthManager also manages associated data related to Auth objects that\n need to be more accessible, such as vpn ips and ports.\n \"\"\"\n _instance=None\n def __new__(cls, *args, **kwargs):\n \"\"\"Returns the AuthManager singleton with driver set\n\n __init__ is run every time AuthManager() is called, so we need to do\n any constructor related stuff here. The driver that is specified\n in the flagfile is loaded here.\n \"\"\"\n if not cls._instance:\n cls._instance = super(AuthManager, cls).__new__(\n cls, *args, **kwargs)\n mod_str, sep, driver_str = FLAGS.auth_driver.rpartition('.')\n try:\n __import__(mod_str)\n cls._instance.driver = getattr(sys.modules[mod_str],\n driver_str)\n except (ImportError, AttributeError):\n raise exception.Error('Auth driver %s cannot be found'\n % FLAGS.auth_driver)\n return cls._instance\n\n def authenticate(self, access, signature, params, verb='GET',\n server_string='127.0.0.1:8773', path='/',\n check_type='ec2', headers=None):\n \"\"\"Authenticates AWS request using access key and signature\n\n If the project is not specified, attempts to authenticate to\n a project with the same name as the user. This way, older tools\n that have no project knowledge will still work.\n\n @type access: str\n @param access: Access key for user in the form \"access:project\".\n\n @type signature: str\n @param signature: Signature of the request.\n\n @type params: list of str\n @param params: Web paramaters used for the signature.\n\n @type verb: str\n @param verb: Web request verb ('GET' or 'POST').\n\n @type server_string: str\n @param server_string: Web request server string.\n\n @type path: str\n @param path: Web request path.\n\n @type check_type: str\n @param check_type: Type of signature to check. 'ec2' for EC2, 's3' for\n S3. Any other value will cause signature not to be\n checked.\n\n @type headers: list\n @param headers: HTTP headers passed with the request (only needed for\n s3 signature checks)\n\n @rtype: tuple (User, Project)\n @return: User and project that the request represents.\n \"\"\"\n # TODO(vish): check for valid timestamp\n (access_key, sep, project_id) = access.partition(':')\n\n logging.info('Looking up user: %r', access_key)\n user = self.get_user_from_access_key(access_key)\n logging.info('user: %r', user)\n if user == None:\n raise exception.NotFound('No user found for access key %s' %\n access_key)\n\n # NOTE(vish): if we stop using project name as id we need better\n # logic to find a default project for user\n if project_id is '':\n project_id = user.name\n\n project = self.get_project(project_id)\n if project == None:\n raise exception.NotFound('No project called %s could be found' %\n project_id)\n if not self.is_admin(user) and not self.is_project_member(user,\n project):\n raise exception.NotFound('User %s is not a member of project %s' %\n (user.id, project.id))\n if check_type == 's3':\n expected_signature = signer.Signer(user.secret.encode()).s3_authorization(headers, verb, path)\n logging.debug('user.secret: %s', user.secret)\n logging.debug('expected_signature: %s', expected_signature)\n logging.debug('signature: %s', signature)\n if signature != expected_signature:\n raise exception.NotAuthorized('Signature does not match')\n elif check_type == 'ec2':\n # NOTE(vish): hmac can't handle unicode, so encode ensures that\n # secret isn't unicode\n expected_signature = signer.Signer(user.secret.encode()).generate(\n params, verb, server_string, path)\n logging.debug('user.secret: %s', user.secret)\n logging.debug('expected_signature: %s', expected_signature)\n logging.debug('signature: %s', signature)\n if signature != expected_signature:\n raise exception.NotAuthorized('Signature does not match')\n return (user, project)\n\n def is_superuser(self, user):\n \"\"\"Checks for superuser status, allowing user to bypass rbac\n\n @type user: User or uid\n @param user: User to check.\n\n @rtype: bool\n @return: True for superuser.\n \"\"\"\n if not isinstance(user, User):\n user = self.get_user(user)\n # NOTE(vish): admin flag on user represents superuser\n if user.admin:\n return True\n for role in FLAGS.superuser_roles:\n if self.has_role(user, role):\n return True\n\n def is_admin(self, user):\n \"\"\"Checks for admin status, allowing user to access all projects\n\n @type user: User or uid\n @param user: User to check.\n\n @rtype: bool\n @return: True for admin.\n \"\"\"\n if not isinstance(user, User):\n user = self.get_user(user)\n if self.is_superuser(user):\n return True\n for role in FLAGS.global_roles:\n if self.has_role(user, role):\n return True\n\n def has_role(self, user, role, project=None):\n \"\"\"Checks existence of role for user\n\n If project is not specified, checks for a global role. If project\n is specified, checks for the union of the global role and the\n project role.\n\n Role 'projectmanager' only works for projects and simply checks to\n see if the user is the project_manager of the specified project. It\n is the same as calling is_project_manager(user, project).\n\n @type user: User or uid\n @param user: User to check.\n\n @type role: str\n @param role: Role to check.\n\n @type project: Project or project_id\n @param project: Project in which to look for local role.\n\n @rtype: bool\n @return: True if the user has the role.\n \"\"\"\n with self.driver() as drv:\n if role == 'projectmanager':\n if not project:\n raise exception.Error(\"Must specify project\")\n return self.is_project_manager(user, project)\n\n global_role = drv.has_role(User.safe_id(user),\n role,\n None)\n if not global_role:\n return global_role\n\n if not project or role in FLAGS.global_roles:\n return global_role\n\n return drv.has_role(User.safe_id(user),\n role,\n Project.safe_id(project))\n\n def add_role(self, user, role, project=None):\n \"\"\"Adds role for user\n\n If project is not specified, adds a global role. If project\n is specified, adds a local role.\n\n The 'projectmanager' role is special and can't be added or removed.\n\n @type user: User or uid\n @param user: User to which to add role.\n\n @type role: str\n @param role: Role to add.\n\n @type project: Project or project_id\n @param project: Project in which to add local role.\n \"\"\"\n with self.driver() as drv:\n drv.add_role(User.safe_id(user), role, Project.safe_id(project))\n\n def remove_role(self, user, role, project=None):\n \"\"\"Removes role for user\n\n If project is not specified, removes a global role. If project\n is specified, removes a local role.\n\n The 'projectmanager' role is special and can't be added or removed.\n\n @type user: User or uid\n @param user: User from which to remove role.\n\n @type role: str\n @param role: Role to remove.\n\n @type project: Project or project_id\n @param project: Project in which to remove local role.\n \"\"\"\n with self.driver() as drv:\n drv.remove_role(User.safe_id(user), role, Project.safe_id(project))\n\n def get_project(self, pid):\n \"\"\"Get project object by id\"\"\"\n with self.driver() as drv:\n project_dict = drv.get_project(pid)\n if project_dict:\n return Project(**project_dict)\n\n def get_projects(self):\n \"\"\"Retrieves list of all projects\"\"\"\n with self.driver() as drv:\n project_list = drv.get_projects()\n if not project_list:\n return []\n return [Project(**project_dict) for project_dict in project_list]\n\n def create_project(self, name, manager_user,\n description=None, member_users=None):\n \"\"\"Create a project\n\n @type name: str\n @param name: Name of the project to create. The name will also be\n used as the project id.\n\n @type manager_user: User or uid\n @param manager_user: This user will be the project manager.\n\n @type description: str\n @param project: Description of the project. If no description is\n specified, the name of the project will be used.\n\n @type member_users: list of User or uid\n @param: Initial project members. The project manager will always be\n added as a member, even if he isn't specified in this list.\n\n @rtype: Project\n @return: The new project.\n \"\"\"\n if member_users:\n member_users = [User.safe_id(u) for u in member_users]\n with self.driver() as drv:\n project_dict = drv.create_project(name,\n User.safe_id(manager_user),\n description,\n member_users)\n if project_dict:\n if FLAGS.use_vpn:\n Vpn.create(project_dict['id'])\n return Project(**project_dict)\n\n def add_to_project(self, user, project):\n \"\"\"Add user to project\"\"\"\n with self.driver() as drv:\n return drv.add_to_project(User.safe_id(user),\n Project.safe_id(project))\n\n def is_project_manager(self, user, project):\n \"\"\"Checks if user is project manager\"\"\"\n if not isinstance(project, Project):\n project = self.get_project(project)\n return User.safe_id(user) == project.project_manager_id\n\n def is_project_member(self, user, project):\n \"\"\"Checks to see if user is a member of project\"\"\"\n if not isinstance(project, Project):\n project = self.get_project(project)\n return User.safe_id(user) in project.member_ids\n\n def remove_from_project(self, user, project):\n \"\"\"Removes a user from a project\"\"\"\n with self.driver() as drv:\n return drv.remove_from_project(User.safe_id(user),\n Project.safe_id(project))\n\n def get_project_vpn_data(self, project):\n \"\"\"Gets vpn ip and port for project\n\n @type project: Project or project_id\n @param project: Project from which to get associated vpn data\n\n @rvalue: tuple of (str, str)\n @return: A tuple containing (ip, port) or None, None if vpn has\n not been allocated for user.\n \"\"\"\n vpn = Vpn.lookup(Project.safe_id(project))\n if not vpn:\n return None, None\n return (vpn.ip, vpn.port)\n\n def delete_project(self, project):\n \"\"\"Deletes a project\"\"\"\n with self.driver() as drv:\n return drv.delete_project(Project.safe_id(project))\n\n def get_user(self, uid):\n \"\"\"Retrieves a user by id\"\"\"\n with self.driver() as drv:\n user_dict = drv.get_user(uid)\n if user_dict:\n return User(**user_dict)\n\n def get_user_from_access_key(self, access_key):\n \"\"\"Retrieves a user by access key\"\"\"\n with self.driver() as drv:\n user_dict = drv.get_user_from_access_key(access_key)\n if user_dict:\n return User(**user_dict)\n\n def get_users(self):\n \"\"\"Retrieves a list of all users\"\"\"\n with self.driver() as drv:\n user_list = drv.get_users()\n if not user_list:\n return []\n return [User(**user_dict) for user_dict in user_list]\n\n def create_user(self, name, access=None, secret=None, admin=False):\n \"\"\"Creates a user\n\n @type name: str\n @param name: Name of the user to create.\n\n @type access: str\n @param access: Access Key (defaults to a random uuid)\n\n @type secret: str\n @param secret: Secret Key (defaults to a random uuid)\n\n @type admin: bool\n @param admin: Whether to set the admin flag. The admin flag gives\n superuser status regardless of roles specifed for the user.\n\n @type create_project: bool\n @param: Whether to create a project for the user with the same name.\n\n @rtype: User\n @return: The new user.\n \"\"\"\n if access == None: access = str(uuid.uuid4())\n if secret == None: secret = str(uuid.uuid4())\n with self.driver() as drv:\n user_dict = drv.create_user(name, access, secret, admin)\n if user_dict:\n return User(**user_dict)\n\n def delete_user(self, user):\n \"\"\"Deletes a user\"\"\"\n with self.driver() as drv:\n drv.delete_user(User.safe_id(user))\n\n def generate_key_pair(self, user, key_name):\n \"\"\"Generates a key pair for a user\n\n Generates a public and private key, stores the public key using the\n key_name, and returns the private key and fingerprint.\n\n @type user: User or uid\n @param user: User for which to create key pair.\n\n @type key_name: str\n @param key_name: Name to use for the generated KeyPair.\n\n @rtype: tuple (private_key, fingerprint)\n @return: A tuple containing the private_key and fingerprint.\n \"\"\"\n # NOTE(vish): generating key pair is slow so check for legal\n # creation before creating keypair\n uid = User.safe_id(user)\n with self.driver() as drv:\n if not drv.get_user(uid):\n raise exception.NotFound(\"User %s doesn't exist\" % user)\n if drv.get_key_pair(uid, key_name):\n raise exception.Duplicate(\"The keypair %s already exists\"\n % key_name)\n private_key, public_key, fingerprint = crypto.generate_key_pair()\n self.create_key_pair(uid, key_name, public_key, fingerprint)\n return private_key, fingerprint\n\n def create_key_pair(self, user, key_name, public_key, fingerprint):\n \"\"\"Creates a key pair for user\"\"\"\n with self.driver() as drv:\n kp_dict = drv.create_key_pair(User.safe_id(user),\n key_name,\n public_key,\n fingerprint)\n if kp_dict:\n return KeyPair(**kp_dict)\n\n def get_key_pair(self, user, key_name):\n \"\"\"Retrieves a key pair for user\"\"\"\n with self.driver() as drv:\n kp_dict = drv.get_key_pair(User.safe_id(user), key_name)\n if kp_dict:\n return KeyPair(**kp_dict)\n\n def get_key_pairs(self, user):\n \"\"\"Retrieves all key pairs for user\"\"\"\n with self.driver() as drv:\n kp_list = drv.get_key_pairs(User.safe_id(user))\n if not kp_list:\n return []\n return [KeyPair(**kp_dict) for kp_dict in kp_list]\n\n def delete_key_pair(self, user, key_name):\n \"\"\"Deletes a key pair for user\"\"\"\n with self.driver() as drv:\n drv.delete_key_pair(User.safe_id(user), key_name)\n\n def get_credentials(self, user, project=None):\n \"\"\"Get credential zip for user in project\"\"\"\n if not isinstance(user, User):\n user = self.get_user(user)\n if project is None:\n project = user.id\n pid = Project.safe_id(project)\n rc = self.__generate_rc(user.access, user.secret, pid)\n private_key, signed_cert = self._generate_x509_cert(user.id, pid)\n\n vpn = Vpn.lookup(pid)\n if not vpn:\n raise exception.Error(\"No vpn data allocated for project %s\" %\n project.name)\n configfile = open(FLAGS.vpn_client_template,\"r\")\n s = string.Template(configfile.read())\n configfile.close()\n config = s.substitute(keyfile=FLAGS.credential_key_file,\n certfile=FLAGS.credential_cert_file,\n ip=vpn.ip,\n port=vpn.port)\n\n tmpdir = tempfile.mkdtemp()\n zf = os.path.join(tmpdir, \"temp.zip\")\n zippy = zipfile.ZipFile(zf, 'w')\n zippy.writestr(FLAGS.credential_rc_file, rc)\n zippy.writestr(FLAGS.credential_key_file, private_key)\n zippy.writestr(FLAGS.credential_cert_file, signed_cert)\n zippy.writestr(\"nebula-client.conf\", config)\n zippy.writestr(FLAGS.ca_file, crypto.fetch_ca(user.id))\n zippy.close()\n with open(zf, 'rb') as f:\n buffer = f.read()\n\n shutil.rmtree(tmpdir)\n return buffer\n\n def __generate_rc(self, access, secret, pid):\n \"\"\"Generate rc file for user\"\"\"\n rc = open(FLAGS.credentials_template).read()\n rc = rc % { 'access': access,\n 'project': pid,\n 'secret': secret,\n 'ec2': FLAGS.ec2_url,\n 's3': 'http://%s:%s' % (FLAGS.s3_host, FLAGS.s3_port),\n 'nova': FLAGS.ca_file,\n 'cert': FLAGS.credential_cert_file,\n 'key': FLAGS.credential_key_file,\n }\n return rc\n\n def _generate_x509_cert(self, uid, pid):\n \"\"\"Generate x509 cert for user\"\"\"\n (private_key, csr) = crypto.generate_x509_cert(\n self.__cert_subject(uid))\n # TODO(joshua): This should be async call back to the cloud controller\n signed_cert = crypto.sign_csr(csr, pid)\n return (private_key, signed_cert)\n\n def __cert_subject(self, uid):\n \"\"\"Helper to generate cert subject\"\"\"\n return FLAGS.credential_cert_subject % (uid, utils.isotime())\n","sub_path":"nova/auth/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":29815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"240585881","text":"import os\nimport sys\nfrom docx.api import Document\nimport openpyxl\nfrom shutil import copyfile\nfrom tkinter import filedialog\nfrom tkinter import *\nfrom tkinter import ttk\nimport tkinter as tk\n\ntemplates = []\nforms = []\n\nforms_dir = \"asdfghj\"\ntemplates_dirs = []\n\nalias_vals = {}\nconflicts = {}\nlabels = []\n\ndef check_alias(text):\n for arg in labels:\n if (arg.strip().lower() == text.strip().lower()):\n return arg\n return False\n\n\ndef find_all(a_str, sub):\n start = 0\n while True:\n start = a_str.find(sub, start)\n if start == -1:\n return\n yield start\n start += len(sub) # use start += 1 to find overlapping matches\n\n\ndef swap_text(paragraph):\n indicies = list(find_all(paragraph.text, '*'))\n if len(indicies) >= 2:\n for label in alias_vals.keys():\n if type(label) is str:\n for i in range(0, len(indicies) - 1):\n if label.lower().strip() == paragraph.text[(indicies[i] + 1):indicies[i + 1]].lower().strip():\n paragraph.text = paragraph.text[:indicies[i]] + \\\n alias_vals[label] + paragraph.text[indicies[i + 1]:(len(paragraph.text) - 2)]\n\n\ndef get_files(dir, tab):\n for root, subdirs, files in os.walk(dir):\n if len(files) > 0:\n backup_path = os.path.join(root, 'backup')\n # os.mkdir(backup_path)\n for file in files:\n print(file)\n path = os.path.join(root, file)\n # copyfile(path, backup_path + '/' + file)\n tab.append(path)\n\n\ndef clone_values(doc):\n for table in doc.tables:\n for row_i in range(0, len(table.rows)):\n for col_i, cell in enumerate(table.row_cells(row_i)):\n check = check_alias(cell.text) # standard table cell check\n if check != False:\n table.cell(row_i, col_i).text = alias_vals[check]\n else:\n for paragraph in cell.paragraphs: # check for paragraphs in table cell\n swap_text(paragraph)\n\n for paragraph in doc.paragraphs:\n swap_text(paragraph)\n\ndef main():\n print(forms_dir)\n get_files(forms_dir, forms)\n for dir in templates_dirs:\n get_files(dir, templates)\n\n #pull values\n for form_dir in forms:\n print(form_dir)\n if form_dir.endswith('.docx'):\n doc = Document(form_dir)\n for table in doc.tables:\n for i, row in enumerate(table.rows):\n check = False\n try:\n check = check_alias(row.cells[0].text)\n except IndexError:\n continue\n\n if check != False:\n cell_text = row.cells[1].text\n if (check in alias_vals.keys()) and (alias_vals[check] != cell_text):\n if (check in conflicts.keys()) == False:\n conflicts[check] = [row.cells[1].text, alias_vals[check]]\n else:\n conflicts[check].append(row.cells[1].text)\n\n else:\n alias_vals[check] = cell_text\n\n #resolve conflicting values\n # for label in conflicts:\n # print(\"There's conflicting values for label \" + label)\n # for i, value in enumerate(conflicts[label]):\n # print(str(i) + \") \" + value)\n # sys.stdout.flush()\n # s = input(\"Select which value to use: \")\n # print(s)\n # sys.stdout.flush()\n # alias_vals[label] = conflicts[label][int(s)]\n\n for label in conflicts:\n popup = tk.Toplevel()\n popup.title(\"Label value conflict\")\n text = Label(popup, text=(\"There's conflicting values for label \" + label))\n text.grid(row=0, column=0)\n for i, value in enumerate(conflicts[label]):\n def on_press():\n popup.destroy()\n alias_vals[label] = conflicts[label][i]\n button = Button(popup, text=value, command=on_press)\n button.grid(row=(i + 1), column=0)\n global app\n app.wait_window(popup)\n\n #clone values\n for template_dir in templates:\n if template_dir.endswith('.docx') and template_dir.find('~') == -1:\n doc = Document(template_dir)\n clone_values(doc)\n for section in doc.sections:\n clone_values(section.header)\n clone_values(section.footer)\n doc.save(template_dir)\n elif template_dir.endswith('.xlsx'):\n wb = openpyxl.load_workbook(template_dir)\n for sheet_name in wb.sheetnames:\n sheet = wb[sheet_name]\n for row in sheet.iter_rows():\n for cell in row:\n cell_text = cell.value\n if (cell_text != 'None' and cell_text is not None):\n for label in alias_vals:\n val = alias_vals[label]\n if type(label) is str:\n check = list(\n find_all(cell_text.strip().lower(), label.strip().lower()))\n if len(check) > 0:\n # print(cell_text)\n if len(check) == 1:\n if (check[0] == 0 and cell_text.strip().lower() == label.strip().lower()):\n cell.value = val\n elif check[0] != 0:\n cell.value = cell_text[:check[0]] + \\\n val + cell_text[(len(val) + check[0]):]\n else:\n last_index = check[len(check) - 1]\n cell.value = cell_text[:last_index] + \\\n val + cell_text[(len(val) + last_index):]\n wb.save(template_dir)\n\n\n\n\ndef browse_forms():\n global forms_dir \n forms_dir = filedialog.askdirectory()\n forms_label_text.set(forms_dir)\n\ndef browse_templates():\n new_dir = filedialog.askdirectory()\n templates_dirs.append(new_dir)\n templates_label_text.set('\\n'.join(templates_dirs))\n\n\ndef browse_labels():\n file = filedialog.askopenfile(mode='r', filetypes=[('Text Files', '*.txt')])\n if file is not None:\n labels_str = \"\"\n for line in file:\n labels.append(line)\n labels_str = labels_str + line\n labels_text.set(labels_str)\n\n\napp = Tk()\napp.title(\"DOS-AI\")\napp.geometry(\"600x400\")\n\nforms_button = Button(text=\"Select Forms\", command=browse_forms)\nforms_button.grid(row=0, column=0)\nforms_label_text = StringVar()\nforms_label_text.set('forms')\nforms_label = Label(app, textvariable=forms_label_text, font=('bold', 14))\nforms_label.grid(row=0, column = 1)\n\ntemplates_button = Button(text=\"Select Templates\", command=browse_templates)\ntemplates_button.grid(row=1, column=0)\ntemplates_label_text = StringVar()\ntemplates_label_text.set('templates')\ntemplates_label = Label(\n app, textvariable=templates_label_text, font=('bold', 14))\ntemplates_label.grid(row=1, column=1)\n\nlabels_button = Button(text=\"Select Labels\", command=browse_labels)\nlabels_button.grid(row=2, column=0)\nlabels_text = StringVar()\nlabels_text.set('labels')\nlabels_label = Label(\n app, textvariable=labels_text, font=('bold', 14))\nlabels_label.grid(row=2, column=1)\n\nrun_button = Button(text=\"Run\", command=main)\nrun_button.grid(row=3, column=0)\n\napp.mainloop()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610261001","text":"import matplotlib.pyplot as plt\n\nfrom random_walks import RandomWalk\n\n#Keep making new walks, as long as the program is active\nwhile True:\n # Make a random walk and plot the points\n rw = RandomWalk()\n rw.fill_walk()\n \n point_number = list(range(rw.num_points))\n plt.scatter(rw.x_values, rw.y_values, c=point_number, cmap=plt.cm.Blues, edgecolors=\"none\", s=15)\n plt.show()\n\n keep_running = input(\"Make another walk? y/n:\").lower()\n\n if keep_running == \"n\":\n break\n","sub_path":"Data/random_walks_visuals.py","file_name":"random_walks_visuals.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"292719290","text":"#!/usr/bin/python3\nimport json\nfrom datetime import datetime, timedelta, timezone\nimport os\nimport time\nfrom ast import literal_eval\nimport yaml\n\n# Load config file\n#with open(\"config/ns-killer.conf\", 'r') as ymlfile:\nwith open(\"/etc/config/ns-killer.conf\", 'r') as ymlfile:\n cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)\n# Fulfill config params with default values\n\n# Load cluster namespaces\n#with open('namespaces.json', 'r') as outfile:\n# k8s_ns = json.load(outfile)\nk8s_ns = literal_eval(os.popen('kubectl get namespaces -o json').read())\n#print(k8s_ns)\n\n# Time divider units in dict\ntime_divider_units = {\n 'minutes': 60,\n 'hours': 60 * 60,\n 'days': 60 * 60 * 24,\n 'weeks': 60 * 60 * 24 * 7,\n 'months': 60 * 60 * 24 * 30\n}\n\ndef delete_ns(ns_name, ns_creationTimestamp_date):\n date_now = datetime.now(timezone.utc).strftime('%Y-%M-%d %H:%M:%S')\n print(datetime.now(timezone.utc), ns_creationTimestamp_date)\n ns_creation_ago = (datetime.now(timezone.utc) - ns_creationTimestamp_date)\n # Define the time unit and calculte the time divider\n time_divider_unit = time_divider_units.get(cfg['config']['retention']['kind'])\n ns_creation_ago_time = divmod(ns_creation_ago.days * 86400 + ns_creation_ago.seconds, time_divider_unit)[0]\n if ns_creation_ago_time >= cfg['config']['retention']['time']:\n #os.system(\"kubectl delete namespace {}\".format(ns_name))\n print(\"{} | Killed namespace '{}' that lived for {} {}\".format(date_now, ns_name, ns_creation_ago_time, cfg['config']['retention']['kind']))\n\n\n# Iterate on items\nprint(\"Start iterating on namespaces\")\nfor i in k8s_ns.get('items'):\n ns_name = i.get('metadata').get('name')\n ns_creationTimestamp = i.get('metadata').get('creationTimestamp')\n ns_creationTimestamp_date = datetime.strptime(ns_creationTimestamp, \"%Y-%m-%dT%H:%M:%S%z\")\n\n if len(cfg['namespace']['only']) == 0:\n # Test if namespace is in exclude list\n if ns_name not in cfg['namespace']['exclude']:\n delete_ns(ns_name, ns_creationTimestamp_date)\n else:\n if ns_name in cfg['namespace']['only']:\n delete_ns(ns_name, ns_creationTimestamp_date)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"460624504","text":"import sys, os\nthis_dir = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.realpath(this_dir + '/../magphase/src'))\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport libutils as lu\nimport libaudio as la\nimport magphase as mp\nfrom scikits.talkbox import lpc\nfrom scipy.signal import lfilter\n\ndef lpc_to_mag(v_lpc, fft_len=4096):\n '''\n Computed the magnitude spectrum from LPC coefficients using approximation by FFT method.\n '''\n v_imp = np.r_[1, np.zeros(fft_len-1)]\n v_imp_filt = lfilter(np.array([1.0]), v_lpc, v_imp)\n\n v_mag = np.absolute(np.fft.fft(v_imp_filt))\n\n v_mag = la.remove_hermitian_half(v_mag[None,:])[0]\n\n return v_mag\n\n\ndef get_formant_locations_from_spec_env(v_sp_env):\n '''\n v_sp_env could be in db, log, or absolute value.\n '''\n\n v_mag_diff = np.diff(v_sp_env)\n v_mag_diff[v_mag_diff>=0.0] = 1.0\n v_mag_diff[v_mag_diff<0.0] = -1.0\n v_mag_diff_diff = np.diff(v_mag_diff)\n\n v_frmnts_bins = np.where(v_mag_diff_diff<0.0)[0] + 1\n v_frmnts_gains = v_sp_env[v_frmnts_bins]\n return v_frmnts_bins, v_frmnts_gains\n\n\ndef get_formant_locations_from_raw_long_frame(wavfile, nx, fft_len):\n '''\n nx: frame index\n '''\n\n v_sig, fs = la.read_audio_file(wavfile)\n\n # Epoch detection:\n v_pm_sec, v_voi = la.reaper_epoch_detection(wavfile)\n v_pm = lu.round_to_int(v_pm_sec * fs)\n\n # Raw-long Frame extraction:\n\n v_frm_long = v_sig[v_pm[nx-2]:v_pm[nx+2]+1]\n\n # Win:\n left_len = v_pm[nx] - v_pm[nx-2]\n right_len = v_pm[nx+2] - v_pm[nx]\n v_win = la.gen_non_symmetric_win(left_len, right_len, np.hanning, b_norm=False)\n v_frm_long_win = v_frm_long * v_win\n\n\n # Spectrum:\n v_mag = np.absolute(np.fft.fft(v_frm_long_win, n=fft_len))\n v_mag_db = la.db(la.remove_hermitian_half(v_mag[None,:])[0])\n\n # Formant extraction -LPC method:--------------------------------------------------\n v_lpc, v_e, v_refl = lpc(v_frm_long_win, 120)\n\n b_use_lpc_roots = False\n if b_use_lpc_roots:\n v_lpc_roots = np.roots(v_lpc)\n v_lpc_angles = np.angle(v_lpc_roots)\n v_lpc_angles = v_lpc_angles[v_lpc_angles>=0]\n v_lpc_angles = np.sort(v_lpc_angles)\n fft_len_half = 1 + fft_len / 2\n v_lpc_roots_bins = v_lpc_angles * fft_len_half / np.pi\n\n v_lpc_mag = lpc_to_mag(v_lpc, fft_len=fft_len)\n v_lpc_mag_db = la.db(v_lpc_mag)\n v_lpc_mag_db = v_lpc_mag_db - np.mean(v_lpc_mag_db) + np.mean(v_mag_db)\n\n v_frmnts_bins, v_frmnts_gains_db = get_formant_locations_from_spec_env(v_lpc_mag_db)\n\n # Getting bandwidth:\n fft_len_half = 1 + fft_len / 2\n v_vall_bins = get_formant_locations_from_spec_env(-v_lpc_mag_db)[0]\n v_vall_bins = np.r_[0, v_vall_bins, fft_len_half-1]\n\n nfrmnts = v_frmnts_bins.size\n v_frmnts_bw = np.zeros(nfrmnts) - 1.0\n for nx_f in xrange(nfrmnts):\n #Left slope:\n curr_frmnt_bin = v_frmnts_bins[nx_f]\n curr_vall_l_bin = v_vall_bins[nx_f]\n curr_vall_r_bin = v_vall_bins[nx_f+1]\n\n curr_midp_l = int((curr_frmnt_bin + curr_vall_l_bin) / 2.0)\n curr_midp_r = int((curr_frmnt_bin + curr_vall_r_bin) / 2.0)\n\n slope_l = (v_frmnts_gains_db[nx_f] - v_lpc_mag_db[curr_midp_l]) / (v_frmnts_bins[nx_f] - curr_midp_l).astype(float)\n slope_r = (v_frmnts_gains_db[nx_f] - v_lpc_mag_db[curr_midp_r]) / (v_frmnts_bins[nx_f] - curr_midp_r).astype(float)\n\n slope_ave = (slope_l - slope_r) / 2.0\n\n v_frmnts_bw[nx_f] = 1.0 / slope_ave\n\n # Filtering by bandwidth:\n bw_thress = 7.0\n v_frmnts_bins = v_frmnts_bins[v_frmnts_bw bool:\n n = len(nums)\n if n <=1:\n return False\n if k==1:\n return True\n mydict = dict()\n cum_sum =0\n mydict[0]= 0\n for i in range(n):\n cum_sum +=nums[i]\n res = cum_sum%k\n if res not in mydict:\n mydict[res] = i+1\n cum_sum2 = 0\n for i in reversed(range(0,n)):\n res1 = cum_sum2%k\n res2 = (cum_sum-res1)%k\n if res2 in mydict and mydict[res2]<=i-1:\n return True\n cum_sum2 += nums[i]\n return False\n\n## This solution has a drawback that we need 2 visits of the array\n## The following solution reduce number of visit to 1\n\nclass Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n hashmap = {}\n cum_sum = 0\n for i in range(len(nums)):\n cum_sum += nums[i]\n res = cum_sum%k\n if res in hashmap and hashmap[res]=1:\n return True\n if res not in hashmap:\n hashmap[res]=i\n return False\n \n","sub_path":"Problem523_Continuous_Subarray_Sum.py","file_name":"Problem523_Continuous_Subarray_Sum.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"124867106","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nSon classes.\n\"\"\"\nimport PyQt4\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtGui import QDialog\nfrom PyQt4.QtCore import pyqtSignal\n\nimport math\n\nfrom Ui_damage_choose import Ui_DamageChooseDialog\nfrom Ui_morphology import Ui_morphologyDialog\nfrom Ui_section_edit import Ui_SectionEditDialog\nfrom Ui_inpainting import Ui_InpaintingDialog\n\nclass MyQGraphicsView(QtGui.QGraphicsView):\n\n scale_change = pyqtSignal(int, QtCore.QPointF)\n \n def __init__ (self, parent=None):\n super(MyQGraphicsView, self).__init__ (parent)\n self.scale_time = 0\n self.zoomInFactor = 1.25\n \n def wheelEvent(self, event):\n zoomInFactor = 1.25\n zoomOutFactor = 1 / zoomInFactor\n \n # Remove possible Anchors\n self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor)\n self.setResizeAnchor(QtGui.QGraphicsView.NoAnchor)\n\n # Save the scene pos\n oldPos = self.mapToScene(event.pos())\n\n # Zoom\n if event.delta() > 0:\n zoomFactor = zoomInFactor\n self.scale_time += 1\n else:\n zoomFactor = zoomOutFactor\n self.scale_time -= 1\n \n self.scale(zoomFactor, zoomFactor)\n\n # Get the new position\n newPos = self.mapToScene(event.pos())\n \n # Move scene to old position\n delta = newPos - oldPos\n self.translate(delta.x(), delta.y())\n \n # Emit\n self.scale_change.emit(self.scale_time, delta)\n \n def handle_scale(self, time, delta):\n to_scale_time = time - self.scale_time\n ratio = math.pow(self.zoomInFactor, to_scale_time)\n self.scale(ratio, ratio)\n self.translate(delta.x(), delta.y())\n self.scale_time = time\n\nclass DamageChoose(QDialog, Ui_DamageChooseDialog):\n def __init__(self, parent = None):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n \nclass MorphologyDialog(QDialog, Ui_morphologyDialog):\n def __init__(self, parent = None):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n\nclass SectionEdit(QDialog, Ui_SectionEditDialog):\n def __init__(self, parent = None):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n\nclass InpaintingDialog(QDialog, Ui_InpaintingDialog):\n def __init__(self, parent = None):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n","sub_path":"source/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"87681798","text":"import time\r\nimport numpy as np\r\n\r\nimport torch\r\nfrom torch.autograd import Variable\r\nfrom torch.utils.data.sampler import SubsetRandomSampler\r\n\r\nfrom archived.s3.get_object import get_object\r\nfrom archived.s3 import clear_bucket\r\nfrom archived.sync import reduce_epoch, delete_expired_merged_epoch\r\n\r\nfrom archived.old_model.SVM import SVM\r\nfrom data_loader.libsvm_dataset import DenseDatasetWithLines\r\n\r\n# lambda setting\r\nlocal_dir = \"/tmp\"\r\n\r\n# algorithm setting\r\nnum_features = 30\r\nnum_classes = 2\r\nlearning_rate = 0.01\r\nbatch_size = 1000\r\nnum_epochs = 2\r\nvalidation_ratio = .2\r\nshuffle_dataset = True\r\nrandom_seed = 42\r\n\r\n\r\ndef handler(event, context):\r\n start_time = time.time()\r\n bucket = event['bucket_name']\r\n worker_index = event['rank']\r\n num_workers = event['num_workers']\r\n key = event['file']\r\n tmp_bucket = event['tmp_bucket']\r\n merged_bucket = event['merged_bucket']\r\n num_epochs = event['num_epochs']\r\n learning_rate = event['learning_rate']\r\n batch_size = event['batch_size']\r\n\r\n print('bucket = {}'.format(bucket))\r\n print(\"file = {}\".format(key))\r\n print('tmp bucket = {}'.format(tmp_bucket))\r\n print('merged bucket = {}'.format(merged_bucket))\r\n print('number of workers = {}'.format(num_workers))\r\n print('worker index = {}'.format(worker_index))\r\n print('num epochs = {}'.format(num_epochs))\r\n print('learning rate = {}'.format(learning_rate))\r\n print(\"batch size = {}\".format(batch_size))\r\n\r\n # read file from s3\r\n file = get_object(bucket, key).read().decode('utf-8').split(\"\\n\")\r\n print(\"read data cost {} s\".format(time.time() - start_time))\r\n\r\n parse_start = time.time()\r\n dataset = DenseDatasetWithLines(file, num_features)\r\n print(\"parse data cost {} s\".format(time.time() - parse_start))\r\n\r\n preprocess_start = time.time()\r\n # Creating data indices for training and validation splits:\r\n dataset_size = len(dataset)\r\n indices = list(range(dataset_size))\r\n split = int(np.floor(validation_ratio * dataset_size))\r\n if shuffle_dataset:\r\n np.random.seed(random_seed)\r\n np.random.shuffle(indices)\r\n train_indices, val_indices = indices[split:], indices[:split]\r\n\r\n # Creating PT data samplers and loaders:\r\n train_sampler = SubsetRandomSampler(train_indices)\r\n valid_sampler = SubsetRandomSampler(val_indices)\r\n\r\n train_loader = torch.utils.data.DataLoader(dataset,\r\n batch_size=batch_size,\r\n sampler=train_sampler)\r\n validation_loader = torch.utils.data.DataLoader(dataset,\r\n batch_size=batch_size,\r\n sampler=valid_sampler)\r\n\r\n print(\"preprocess data cost {} s, dataset size = {}\"\r\n .format(time.time() - preprocess_start, dataset_size))\r\n\r\n model = SVM(num_features, num_classes)\r\n\r\n # Loss and Optimizer\r\n # Softmax is internally computed.\r\n # Set parameters to be updated.\r\n optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\r\n\r\n # Training the Model\r\n train_start = time.time()\r\n for epoch in range(num_epochs):\r\n epoch_start = time.time()\r\n epoch_loss = 0\r\n for batch_index, (items, labels) in enumerate(train_loader):\r\n # print(\"------worker {} epoch {} batch {}------\".format(worker_index, epoch, batch_index))\r\n batch_start = time.time()\r\n #items = Variable(items.view(-1, num_features))\r\n #labels = Variable(labels)\r\n\r\n items = items.to(torch.device(\"cpu\"))\r\n labels = labels.to(torch.device(\"cpu\")).float()\r\n\r\n # Forward + Backward + Optimize\r\n outputs = model(items)\r\n print(\"outputs type = {}\".format(outputs.type()))\r\n print(\"labels type = {}\".format(labels.type()))\r\n loss = torch.mean(torch.clamp(1 - outputs.t() * labels, min=0)) # hinge loss\r\n loss += 0.01 * torch.mean(model.linear.weight ** 2) / 2.0 # l2 penalty\r\n epoch_loss += loss\r\n\r\n optimizer.zero_grad()\r\n loss.backward()\r\n\r\n optimizer.step()\r\n\r\n # Test the Model\r\n test_start = time.time()\r\n correct = 0\r\n total = 0\r\n test_loss = 0\r\n for items, labels in validation_loader:\r\n items = Variable(items.view(-1, num_features))\r\n labels = Variable(labels)\r\n outputs = model(items)\r\n test_loss = torch.mean(torch.clamp(1 - outputs.t() * labels.float(), min=0)) # hinge loss\r\n test_loss += 0.01 * torch.mean(model.linear.weight ** 2) / 2.0 # l2 penalty\r\n\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum()\r\n test_time = time.time() - test_start\r\n\r\n print('Epoch: [%d/%d], Step: [%d/%d], Time: %.4f, Loss: %.4f, epoch cost %.4f, '\r\n 'batch cost %.4f s: test cost %.4f s, '\r\n 'accuracy of the model on the %d test samples: %d %%, loss = %f'\r\n % (epoch + 1, num_epochs, batch_index + 1, len(train_indices) / batch_size,\r\n time.time() - train_start, epoch_loss.data, time.time() - epoch_start,\r\n time.time() - batch_start, test_time,\r\n len(val_indices), 100 * correct / total, test_loss / total))\r\n\r\n w = model.linear.weight.data.numpy()\r\n w_shape = w.shape\r\n b = model.linear.bias.data.numpy()\r\n b_shape = b.shape\r\n w_and_b = np.concatenate((w.flatten(), b.flatten()))\r\n cal_time = time.time() - epoch_start\r\n print(\"Epoch {} calculation cost = {} s\".format(epoch, cal_time))\r\n\r\n sync_start = time.time()\r\n postfix = \"{}\".format(epoch)\r\n u_w_b_merge = reduce_epoch(w_and_b, tmp_bucket, merged_bucket, num_workers, worker_index, postfix)\r\n\r\n w_mean = u_w_b_merge[: w_shape[0] * w_shape[1]].reshape(w_shape) / float(num_workers)\r\n b_mean = u_w_b_merge[w_shape[0] * w_shape[1]:].reshape(b_shape[0]) / float(num_workers)\r\n model.linear.weight.data = torch.from_numpy(w_mean)\r\n model.linear.bias.data = torch.from_numpy(b_mean)\r\n sync_time = time.time() - sync_start\r\n print(\"Epoch {} synchronization cost {} s\".format(epoch, sync_time))\r\n\r\n if worker_index == 0:\r\n delete_expired_merged_epoch(merged_bucket, epoch)\r\n #\r\n #\r\n # #file_postfix = \"{}_{}\".format(epoch, worker_index)\r\n # if epoch < num_epochs - 1:\r\n # if worker_index == 0:\r\n # w_merge, b_merge = merge_w_b(model_bucket, num_workers, w.dtype,\r\n # w.shape, b.shape, tmp_w_prefix, tmp_b_prefix)\r\n # put_merged_w_b(model_bucket, w_merge, b_merge,\r\n # str(epoch), w_prefix, b_prefix)\r\n # delete_expired_w_b_by_epoch(model_bucket, epoch, tmp_w_prefix, tmp_b_prefix)\r\n # model.linear.weight.data = torch.from_numpy(w_merge)\r\n # model.linear.bias.data = torch.from_numpy(b_merge)\r\n # else:\r\n # w_merge, b_merge = get_merged_w_b(model_bucket, str(epoch), w.dtype,\r\n # w.shape, b.shape, w_prefix, b_prefix)\r\n # model.linear.weight.data = torch.from_numpy(w_merge)\r\n # model.linear.bias.data = torch.from_numpy(b_merge)\r\n\r\n #print(\"weight after sync = {}\".format(model.linear.weight.data.numpy()[0][:5]))\r\n #print(\"bias after sync = {}\".format(model.linear.bias.data.numpy()))\r\n\r\n # print(\"epoch {} synchronization cost {} s\".format(epoch, time.time() - sync_start))\r\n\r\n # Test the Model\r\n correct = 0\r\n total = 0\r\n for items, labels in validation_loader:\r\n items = Variable(items.view(-1, num_features))\r\n # items = Variable(items)\r\n outputs = model(items)\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum()\r\n\r\n print('Accuracy of the model on the %d test samples: %d %%' % (len(val_indices), 100 * correct / total))\r\n\r\n if worker_index == 0:\r\n clear_bucket(merged_bucket)\r\n clear_bucket(tmp_bucket)\r\n\r\n end_time = time.time()\r\n print(\"Elapsed time = {} s\".format(end_time - start_time))\r\n\r\n","sub_path":"archived/functions/higgs/SVM_model_avg_reduce.py","file_name":"SVM_model_avg_reduce.py","file_ext":"py","file_size_in_byte":8478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"78072369","text":"\n\nfrom xai.brain.wordbase.nouns._mermaid import _MERMAID\n\n#calss header\nclass _MERMAIDS(_MERMAID, ):\n\tdef __init__(self,): \n\t\t_MERMAID.__init__(self)\n\t\tself.name = \"MERMAIDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"mermaid\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_mermaids.py","file_name":"_mermaids.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"552311396","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport os, scipy.io\nimport sys\nimport numpy as np\nimport tensorflow.contrib.slim as slim\nimport divide_into_block\nimport matplotlib.pyplot as plt\nimport time\nimport SID\n\nratio = 30\ninput_path = '../dataset/short/00001_00_0.1s.ARW'\ncheckpoint_dir = '../checkpoint/Sony/'\nresult_dir = './result_divide/'\n\nresult_list = []\nvstack_list = []\nhstack_list = []\n\ndef reslut_stack(result_list,flag_block):\n for i in range(flag_block):\n flag = i * 8\n opreate_list = result_list[flag:flag+(flag_block)]\n print (\"flag:{} flag+8:{}\".format(flag, flag+(flag_block)))\n print (len(opreate_list))\n vstak = opreate_list[0]\n for j in range(len(opreate_list)-1):\n vstak = np.hstack((vstak, opreate_list[j+1]))\n vstack_list.append(vstak)\n\n hstack = vstack_list[0]\n for i in range(len(vstack_list)-1):\n hstack = np.vstack((hstack, vstack_list[i+1]))\n # vstak1 = np.hstack((result_list[0], result_list[1],result_list[2], result_list[3]))\n # vstak2 = np.hstack((result_list[4], result_list[5],result_list[6], result_list[7]))\n # vstak3 = np.hstack((result_list[8], result_list[9],result_list[10], result_list[11]))\n # vstak4 = np.hstack((result_list[12], result_list[13],result_list[14], result_list[15]))\n # result = np.vstack((vstak1,vstak2,vstak3,vstak4))\n return hstack\n\n\nsess = tf.Session()\nin_image = tf.placeholder(tf.float32, [None, None, None, 4])\nout_image = SID.network(in_image)\n\nsaver = tf.train.Saver()\nif int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:\n init = tf.initialize_all_variables()\nelse:\n init = tf.global_variables_initializer()\nsess.run(init)\nckpt = tf.train.get_checkpoint_state(checkpoint_dir)\nif ckpt:\n print('loaded ' + ckpt.model_checkpoint_path)\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n#读入图像\nflag_block = 8\ninput_full = divide_into_block.laod_input(input_path, flag_block)\nstart_time = time.time()\nfor i in range(len(input_full)):\n input = np.expand_dims(input_full[i],axis=0)\n input = np.minimum(input, 1.0)\n # in_image = input\n\n output = sess.run(out_image, feed_dict={in_image: input})\n # output = sess.run(out_image)\n output = np.minimum(np.maximum(output, 0), 1)\n output = output[0, :, :, :]\n result_list.append(output)\n\n\n\nend_time = time.time()\nprint (\"the runtime is {}\".format(end_time-start_time)) #the runtime is 5.81841087341\n\n\nprint (len(result_list))\nresult_image = reslut_stack(result_list,flag_block)\nplt.axis(\"off\")\nplt.imshow(result_image)\nsavename = os.path.join(result_dir, 'result_image64.png')\nif not os.path.isdir(result_dir):\n os.makedirs(result_dir)\nplt.savefig(savename, dpi=600)\nprint (savename)\nplt.close()\n","sub_path":"runInGoogleColab/test_multi_blocks.py","file_name":"test_multi_blocks.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508137042","text":"#!/usr/bin/env python\n\n# Calder Phillips-Grafflin - WPI/ARC Lab\n\nimport rospy\nimport math\nimport tf\nfrom tf.transformations import *\nfrom sensor_msgs.msg import *\n\nclass BodyOrientationPublisher:\n\n def __init__(self, target_frame, root_frame, imu_topic, rate):\n self.target_frame = target_frame\n self.root_frame = root_frame\n self.rate = rate\n self.tx = 0.0\n self.ty = 0.0\n self.tz = 0.0\n self.rx = 0.0\n self.ry = 0.0\n self.rz = 0.0\n self.rw = 1.0\n self.broadcaster = tf.TransformBroadcaster()\n self.imu_sub = rospy.Subscriber(imu_topic, Imu, self.orientation_cb)\n rate = rospy.Rate(self.rate)\n while not rospy.is_shutdown():\n self.broadcaster.sendTransform((self.tx, self.ty, self.tz), (self.rx, self.ry, self.rz, self.rw), rospy.Time.now(), self.target_frame, self.root_frame)\n rate.sleep()\n\n def orientation_cb(self, msg):\n ax = -msg.linear_acceleration.x\n ay = -msg.linear_acceleration.y\n # So these values aren't actually acceleration\n # instead, they are estimated roll and pitch\n rq = quaternion_about_axis(ax, (1,0,0))\n pq = quaternion_about_axis(ay, (0,1,0))\n [x, y, z, w] = self.NormalizeQuaternion(self.ComposeQuaternions(rq, pq))\n self.rx = x\n self.ry = y\n self.rz = z\n self.rw = w\n\n def ComposeQuaternions(self, q1, q2):\n x = q1[3]*q2[0] + q2[3]*q1[0] + q1[1]*q2[2] - q2[1]*q1[2]\n y = q1[3]*q2[1] + q2[3]*q1[1] + q2[0]*q1[2] - q1[0]*q2[2]\n z = q1[3]*q2[2] + q2[3]*q1[2] + q1[0]*q2[1] - q2[0]*q1[1]\n w = q1[3]*q2[3] - q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2]\n return [x,y,z,w]\n\n def NormalizeQuaternion(self, q_raw):\n magnitude = math.sqrt(q_raw[0]**2 + q_raw[1]**2 + q_raw[2]**2 + q_raw[3]**2)\n x = q_raw[0] / magnitude\n y = q_raw[1] / magnitude\n z = q_raw[2] / magnitude\n w = q_raw[3] / magnitude\n return [x,y,z,w]\n\nif __name__ == \"__main__\":\n rospy.init_node(\"body_orientation_publisher\")\n rospy.loginfo(\"Starting the body orientation broadcaster...\")\n #Get the parameters from the server\n root_frame = rospy.get_param(\"~root_frame\", \"sensor_imu_frame\")\n target_frame = rospy.get_param(\"~target_frame\", \"world_orientation_frame\")\n imu_topic = rospy.get_param(\"~imu_topic\", \"\")\n rate = rospy.get_param(\"~rate\", 100.0)\n BodyOrientationPublisher(target_frame, root_frame, imu_topic, rate)\n","sub_path":"hubo_ach_ros_bridge/src/hubo_ach_ros_bridge/body_orientation_publisher.py","file_name":"body_orientation_publisher.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54895788","text":"import os\nimport platform\n\n##perform an OS walk of your current directory\n##List out subdirectories and files\n\n\ndef directoryWalk():\n rootDir = '.'\n for dirName, subdirList, fileList in os.walk( rootDir ):\n #cprint ( 'This directory detected: %s' % dirName, 'blue' )\n print ( 'This directory detected: %s' % dirName)\n #print ( 'A subdirectory named: \\t%s' %subdirList )\n for fname in fileList:\n #cprint ( '\\t%s' % fname,'orange' )\n print ( '\\t%s' % fname,)\n\n","sub_path":"walkOS.py","file_name":"walkOS.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128330758","text":"# Definition for singly-linked list.\nclass ListNode(object):\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.next = None\n\nclass Solution(object):\n\tdef oddEvenList(self, head):\n\t\tif not head:\n\t\t\treturn \n\n\t\toddHead = ListNode(0)\n\t\tevenHead = ListNode(0)\n\t\tnode = head\n\t\ti = 1\n\t\twhile node and i < 3:\n\t\t\tif i == 1:\n\t\t\t\toddHead.next = node\n\t\t\telse:\n\t\t\t\tevenHead.next = node\n\t\t\tnode = node.next\n\t\t\ti += 1\n\n\t\tnode = head\n\t\ti = 1\n\t\toddNode = oddHead\n\t\tevenNode = evenHead\n\t\twhile node:\n\t\t\tif i % 2 == 1:\n\t\t\t\toddNode.next = node\n\t\t\t\toddNode = oddNode.next\n\t\t\telse:\n\t\t\t\tevenNode.next = node\n\t\t\t\tevenNode = evenNode.next\n\t\t\ti += 1\n\t\t\tnode = node.next\n\n\t\toddNode.next = None\n\t\tevenNode.next = None\n\t\toddNode.next = evenHead.next\n\t\treturn oddHead.next","sub_path":"Python/Odd Even Linked List.py","file_name":"Odd Even Linked List.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"565731773","text":"import json\nimport logging\nimport requests\nimport pprint\nimport time\n\n# Configure logger.\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n# Define the constants.\ntrack_location = 'raw_pandora_tracks.txt'\no_auth = ''\nbase_url = 'https://api.spotify.com/v1/'\n\nfound_uris = []\ntracks_not_found = []\n\n# Connects to Spotify API.\ntry:\n s = requests.Session()\n s.verify = False\n s.stream = True\n s.trust_env = False\n\n s.headers.update({'Authorization': 'Bearer {}'.format(o_auth)})\n response = s.get(base_url)\n logger.debug('Response is: {}'.format(response.content))\nexcept:\n raise\n\nif(response.status_code == 400):\n\n # Opens the file and stores it as JSON.\n with open(track_location) as file:\n track_file = json.load(file)\n\n # Iterate over the tracks in the file to search on Spotify.\n for track in track_file['tracks']:\n url = base_url + 'search?q=track:{}%20artist:{}&type=track&limit=1'.format(track['track'], track['artist'])\n response = s.get(url)\n\n while response.status_code == 429:\n logger.debug('Status Code {}. Sleeping for {}.'.format(response.status_code, response.headers['Retry-After']))\n time.sleep(int(response.headers['Retry-After']))\n response = s.get(url)\n\n if(response.status_code == 200):\n response = response.json()\n if len(response['tracks']['items']) > 0:\n logger.debug('Found - Artist: {} Track: {}'.format(track['artist'], track['track']))\n found_uris.append(response['tracks']['items'][0]['uri'])\n else:\n logger.debug('MISSED - Artist: {} Track: {}'.format(track['artist'], track['track']))\n tracks_not_found.append(track)\n\n\n pprint.pprint(found_uris)\n pprint.pprint(tracks_not_found)\n","sub_path":"pandora_to_spotify.py","file_name":"pandora_to_spotify.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597934967","text":"import board\nimport displayio\nfrom adafruit_display_shapes.rect import Rect\nfrom adafruit_display_text.label import Label\nfrom adafruit_bitmap_font import bitmap_font\n\nBACKGROUND_COLOR = 0xF76B1C\nTEXT_COLOR = 0x000000\nTITLE_STRING_1 = \"Press A to take\"\nTITLE_STRING_2 = \"a picture\"\nTAKING_PICTURE_STRING = \"Taking picture...\"\nCOUNTING_STRING = \"Counting M&Ms...\"\nFOUND_STRING_START = \"Found \"\nFOUND_STRING_END = \" M&Ms\"\n\nSMALL_FONT_NAME = \"/fonts/Arial-12.bdf\"\n\nclass PyBadgeDisplay:\n def __init__(self, pixels):\n self._pixels = pixels\n\n # Set up the font\n self._small_font = bitmap_font.load_font(SMALL_FONT_NAME)\n self._small_font.load_glyphs(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.&\".encode('utf-8'))\n\n # Set up the display\n self._splash = displayio.Group(max_size=20)\n board.DISPLAY.show(self._splash)\n \n # Set the background\n rect = Rect(0, 0, 160, 120, fill=BACKGROUND_COLOR)\n self._splash.append(rect)\n\n # Set up some labels\n self._title_label_1 = None\n self._title_label_2 = None\n\n self.show_take_picture_message()\n\n def _replace_label_1(self, text:str):\n # Replace the top label with a new one\n\n # Remove the existing label\n if self._title_label_1 is not None:\n self._splash.remove(self._title_label_1)\n\n # Create a new label with the given text\n self._title_label_1 = Label(self._small_font, text=text)\n (x, y, w, h) = self._title_label_1.bounding_box\n self._title_label_1.x = (80 - w // 2)\n self._title_label_1.y = 35\n self._title_label_1.color = TEXT_COLOR\n\n # Add the label to the display\n self._splash.append(self._title_label_1)\n\n def _replace_label_2(self, text:str):\n # Replace the lower label with a new one\n\n # Remove the existing label\n if self._title_label_2 is not None:\n self._splash.remove(self._title_label_2)\n\n # Create a new label with the given text\n self._title_label_2 = Label(self._small_font, text=text)\n (x, y, w, h) = self._title_label_2.bounding_box\n self._title_label_2.x = (80 - w // 2)\n self._title_label_2.y = 40 + h\n self._title_label_2.color = TEXT_COLOR\n\n # Add the label to the display\n self._splash.append(self._title_label_2)\n\n def show_take_picture_message(self) -> None:\n self._replace_label_1(TITLE_STRING_1)\n self._replace_label_2(TITLE_STRING_2)\n self._pixels[4] = (0,255,0)\n\n def show_taking_picture_message(self) -> None:\n self._replace_label_1(TAKING_PICTURE_STRING)\n self._replace_label_2(\" \")\n self._pixels[4] = (0,0,255)\n\n def show_counting_message(self) -> None:\n self._replace_label_1(COUNTING_STRING)\n self._replace_label_2(\" \")\n self._pixels[4] = (50,50,50)\n\n def show_found_message(self, count:int) -> None:\n self._replace_label_1(FOUND_STRING_START + str(count) + FOUND_STRING_END)\n self._replace_label_2(\" \")\n self._pixels[4] = (0,255,0)","sub_path":"PyBadge_MandMCounter/pybadge_display.py","file_name":"pybadge_display.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"292304419","text":"import asyncio\nimport logging\nimport os\nimport socket\nimport uuid\n\nimport pika\nimport pika.adapters.asyncio_connection\n\nfrom .subscription import QueueSubscriptionObject, ExchangeSubscriptionObject\nfrom ..broker import Broker\n\n#\n\nL = logging.getLogger(__name__)\n\n#\n\n\nclass AMQPBroker(Broker):\n\n\t'''\nThe broker that uses Advanced Message Queuing Protocol (AMQP) and it can be used with e.g. RabbitMQ as a message queue.\n\t'''\n\n\tConfigDefaults = {\n\t\t'url': 'amqp://username:password@localhost/virtualhost',\n\t\t'appname': 'asab.mom',\n\t\t'reconnect_delay': 10.0,\n\t\t'prefetch_count': 5,\n\n\t\t'exchange': 'amq.fanout',\n\t\t'reply_exchange': '',\n\t}\n\n\tdef __init__(self, app, accept_replies=False, task_service=None, config_section_name=\"asab:mom:amqp\", config=None):\n\t\tsuper().__init__(app, accept_replies, task_service, config_section_name, config)\n\n\t\tself.Origin = '{}#{}'.format(socket.gethostname(), os.getpid())\n\n\t\tself.Connection = None\n\t\tself.SubscriptionObjects = {}\n\t\tself.ReplyTo = None\n\n\t\tself.InboundQueue = asyncio.Queue(loop=app.Loop)\n\t\tself.OutboundQueue = asyncio.Queue(loop=app.Loop)\n\n\t\tself.SenderFuture = None\n\n\t\tself.Exchange = self.Config['exchange']\n\t\tself.ReplyExchange = self.Config['reply_exchange']\n\n\n\tasync def finalize(self, app):\n\t\tawait super().finalize(app)\n\t\tif self.SenderFuture is not None:\n\t\t\tself.SenderFuture.cancel()\n\t\t\tself.SenderFuture = None\n\n\n\tdef _reconnect(self):\n\t\tif self.Connection is not None:\n\t\t\tif not (self.Connection.is_closing or self.Connection.is_closed):\n\t\t\t\tself.Connection.close()\n\t\t\tself.Connection = None\n\n\t\tif self.SenderFuture is not None:\n\t\t\tself.SenderFuture.cancel()\n\t\t\tself.SenderFuture = None\n\n\t\tparameters = pika.URLParameters(self.Config['url'])\n\t\tif parameters.client_properties is None:\n\t\t\tparameters.client_properties = dict()\n\t\tparameters.client_properties['application'] = self.Config['appname']\n\n\t\tself.SubscriptionObjects.clear()\n\t\tself.ReplyTo = None\n\n\t\tself.Connection = pika.adapters.asyncio_connection.AsyncioConnection(\n\t\t\tparameters=parameters,\n\t\t\ton_open_callback=self._on_connection_open,\n\t\t\ton_open_error_callback=self._on_connection_open_error,\n\t\t\ton_close_callback=self._on_connection_close\n\t\t)\n\n\t# Connection callbacks\n\n\tdef _on_connection_open(self, connection):\n\t\tL.info(\"AMQP connected\")\n\t\tasyncio.ensure_future(self.ensure_subscriptions(), loop=self.Loop)\n\t\tself.Connection.channel(on_open_callback=self._on_sending_channel_open)\n\n\tdef _on_connection_close(self, connection, *args):\n\t\ttry:\n\t\t\tcode, reason = args\n\t\t\tL.warning(\"AMQP disconnected ({}): {}\".format(code, reason))\n\t\texcept ValueError:\n\t\t\terror, = args\n\t\t\tL.warning(\"AMQP disconnected: {}\".format(error))\n\t\tself.Loop.call_later(float(self.Config['reconnect_delay']), self._reconnect)\n\n\n\tdef _on_connection_open_error(self, connection, error_message=None):\n\t\tL.error(\"AMQP error: {}\".format(error_message if error_message is not None else 'Generic error'))\n\t\tself.Loop.call_later(float(self.Config['reconnect_delay']), self._reconnect)\n\n\n\tdef _on_sending_channel_open(self, channel):\n\t\tself.SenderFuture = asyncio.ensure_future(self._sender_future(channel), loop=self.Loop)\n\n\n\tasync def ensure_subscriptions(self):\n\t\tif self.Connection is None:\n\t\t\treturn\n\t\tif not self.Connection.is_open:\n\t\t\treturn\n\n\t\tfor s, pkwargs in self.Subscriptions.items():\n\t\t\tif s in self.SubscriptionObjects:\n\t\t\t\tcontinue\n\t\t\tif pkwargs.get('exchange', False):\n\t\t\t\tself.SubscriptionObjects[s] = ExchangeSubscriptionObject(self, s, **pkwargs)\n\t\t\telse:\n\t\t\t\tself.SubscriptionObjects[s] = QueueSubscriptionObject(self, s, **pkwargs)\n\n\n\tasync def main(self):\n\t\tself._reconnect()\n\t\twhile True:\n\t\t\tchannel, method, properties, body = await self.InboundQueue.get()\n\n\t\t\ttry:\n\t\t\t\tif self.AcceptReplies and (method.routing_key == self.ReplyTo):\n\t\t\t\t\tawait self.dispatch(\"reply\", properties, body)\n\t\t\t\telse:\n\t\t\t\t\tawait self.dispatch(method.routing_key, properties, body)\n\t\t\texcept BaseException:\n\t\t\t\tL.exception(\"Error when processing inbound message\")\n\t\t\t\tchannel.basic_nack(method.delivery_tag, requeue=False)\n\t\t\telse:\n\t\t\t\tchannel.basic_ack(method.delivery_tag)\n\n\n\tasync def publish(\n\t\tself,\n\t\tbody,\n\t\ttarget: str = '',\n\t\tcontent_type: str = None,\n\t\tcontent_encoding: str = None,\n\t\tcorrelation_id: str = None,\n\t\treply_to: str = None,\n\t\texchange: str = None\n\t):\n\t\tawait self.OutboundQueue.put((\n\t\t\texchange if exchange is not None else self.Exchange, # Where to publish\n\t\t\ttarget, # Routing key\n\t\t\tbody,\n\t\t\tpika.BasicProperties(\n\t\t\t\tcontent_type=content_type,\n\t\t\t\tcontent_encoding=content_encoding,\n\t\t\t\tdelivery_mode=1,\n\t\t\t\tcorrelation_id=correlation_id,\n\t\t\t\treply_to=self.ReplyTo,\n\t\t\t\tmessage_id=uuid.uuid4().urn, # id\n\t\t\t\tapp_id=self.Origin, # origin\n\t\t\t\t# headers = { }\n\t\t\t)\n\t\t))\n\n\n\tasync def reply(\n\t\tself,\n\t\tbody,\n\t\treply_to: str,\n\t\tcontent_type: str = None,\n\t\tcontent_encoding: str = None,\n\t\tcorrelation_id: str = None,\n\t):\n\t\tawait self.OutboundQueue.put((\n\t\t\tself.ReplyExchange, # Where to publish\n\t\t\treply_to, # Routing key\n\t\t\tbody,\n\t\t\tpika.BasicProperties(\n\t\t\t\tcontent_type=content_type,\n\t\t\t\tcontent_encoding=content_encoding,\n\t\t\t\tdelivery_mode=1,\n\t\t\t\tcorrelation_id=correlation_id,\n\t\t\t\tmessage_id=uuid.uuid4().urn, # id\n\t\t\t\tapp_id=self.Origin, # origin\n\t\t\t\t# headers = { }\n\t\t\t)\n\t\t))\n\n\n\tasync def _sender_future(self, channel):\n\t\tif self.AcceptReplies:\n\t\t\tself.ReplyTo = await self._create_exclusive_queue(channel, \"~R@\" + self.Origin)\n\n\t\twhile True:\n\t\t\texchange, routing_key, body, properties = await self.OutboundQueue.get()\n\t\t\tchannel.basic_publish(exchange, routing_key, body, properties)\n\n\n\tasync def _create_exclusive_queue(self, channel, queue_name):\n\t\tlock = asyncio.Event()\n\t\tlock.set()\n\n\t\tdef on_queue_declared(method):\n\t\t\tlock.clear()\n\t\t\tassert(method.method.queue == queue_name)\n\t\t\tself.SubscriptionObjects[queue_name] = QueueSubscriptionObject(self, queue_name)\n\n\t\tchannel.queue_declare(\n\t\t\tqueue=queue_name,\n\t\t\texclusive=True,\n\t\t\tauto_delete=True,\n\t\t\tcallback=on_queue_declared,\n\t\t)\n\n\t\tawait lock.wait()\n\n\t\treturn queue_name\n","sub_path":"asab/mom/amqp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"399327626","text":"import subprocess\nimport os\n\npath = os.getcwd()\npath = \"octave \" + path + '/'\n\n\ndef call_octave_file(filename, *args):\n cmd = path + 'benchop/' + filename + ' '\n if len(args) != 0:\n for arg in args:\n cmd += str(arg)\n cmd += ' '\n data = subprocess.check_output(cmd, shell=True)\n data = str(data, encoding='utf-8')\n data = data.split('\\t')\n data.pop()\n return data\n\n\n#if __name__ == \"__main__\":\n# call_octave_file(\"a1.m\")\n","sub_path":"code/benchop/call_octave.py","file_name":"call_octave.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"25225087","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import unicode_literals, absolute_import, print_function, division\nfrom pyowm import OWM\nimport json\n\n# sopel imports\nimport sopel.module\n\n\n# imports for system and OS access, directories\nimport os\nimport sys\n\n# imports based on THIS file\nmoduledir = os.path.dirname(__file__)\nshareddir = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(shareddir)\nfrom BotShared import *\n\n\n\n\n\ncomdict = {\n \"author\": \"jimender2\",\n \"contributors\": [],\n \"description\": \"version 1.0\",\n 'privs': [],\n \"example\": \"\",\n \"exampleresponse\": \"\",\n }\n\n\n@sopel.module.commands('weathertest')\ndef mainfunction(bot, trigger):\n\n botcom = bot_module_prerun(bot, trigger)\n if not botcom.modulerun:\n return\n\n if not botcom.multiruns:\n execute_main(bot, trigger, botcom)\n else:\n # IF \"&&\" is in the full input, it is treated as multiple commands, and is split\n commands_array = spicemanip.main(botcom.triggerargsarray, \"split_&&\")\n if commands_array == []:\n commands_array = [[]]\n for command_split_partial in commands_array:\n botcom.triggerargsarray = spicemanip.main(command_split_partial, 'create')\n execute_main(bot, trigger, botcom)\n\n botdict_save(bot)\n\n\ndef execute_main(bot, trigger, botcom):\n owm = OWM(API_key=\"347db727b53caea97419c02f17f4fdf5\", version='2.5')\n# obs = owm.weather_at_place('London,GB')\n\n try:\n location = spicemanip.main(botcom.triggerargsarray, '1+') or \"\"\n if location == \"\":\n bot.say(\"Please tell me where you live\")\n valid = False\n else:\n obs = owm.weather_at_place(location)\n valid = True\n except:\n bot.say(\"Sorry invalid location\")\n valid = False\n\n if valid:\n w = obs.get_weather()\n t = w.get_wind()\n u = w.to_JSON()\n\n weather = json.loads(u.decode('utf-8'))\n# osd(bot, botcom.channel_current, 'say', str(u))\n wind = weather[\"wind\"]\n speed = str( wind[\"speed\"] )\n status = str( weather[\"status\"] )\n temp = weather[\"temperature\"]\n high = temp[\"temp_max\"]\n high = str((( 1.8 * (high - 273) + 32)))\n low = temp[\"temp_min\"]\n low = str((( 1.8 * (low - 273) + 32)))\n temperature = temp[\"temp\"]\n temperature = str((( 1.8 * (temperature - 273) + 32)))\n\n string = botcom.instigator + \" the weather at \" + location + \" is as follows:\"\n bot.say(str(string))\n\n string = status + \" with a current temperature of \" + temperature + \" degrees. The high is \" + high + \" and the low is \" + low + \". The wind is blowing at \" + speed + \" miles an hour.\"\n bot.say(string)\n","sub_path":"Modules/Development/weathertest.py","file_name":"weathertest.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"573711918","text":"import cv2\nimport numpy as np\n\nclass FindPaperReturnFrame:\n\n lowW=[]\n highW=[]\n width=[]\n height=[]\n VisionArea=[]\n\n def __init__(self, width, height):\n self.lowW=int(float(1)/3*width)\n self.highW=int(float(2)/3*width)\n self.VisionArea=width*height\n self.width=width\n self.height=height\n\n def detectRectangle(self, c):\n shape=False\n peri=cv2.arcLength(c,True)\n approx=cv2.approxPolyDP(c,0.04*peri,True)\n\n if len(approx)==4:\n (x,y,w,h)=cv2.boundingRect(approx)\n shape = True\n\n return shape\n\n def trackPaper(self, frame):\n\n resized = cv2.resize(frame, (0,0), fx=0.2, fy=0.2)\n ratio=frame.shape[0]/float(resized.shape[0])\n\n gray=cv2.cvtColor(resized,cv2.COLOR_BGR2GRAY)\n blurred=cv2.GaussianBlur(gray,(5,5),0)\n\n cv2.normalize(blurred,blurred,0,255,cv2.NORM_MINMAX)\n thresh=cv2.threshold(blurred,150,255,cv2.THRESH_BINARY)[1]\n\n contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\n areaMax=0\n cXMax=-1\n cYMax=-1\n cX=-1\n cY=-1\n contourMax=[]\n for c in contours:\n shape = self.detectRectangle(c)\n if shape == True:\n c = np.float32(c)\n M = cv2.moments(c)\n if M[\"m00\"]!=0:\n cX = int((M[\"m10\"]/M[\"m00\"]) * ratio)\n cY = int((M[\"m01\"]/M[\"m00\"]) * ratio)\n else:\n cX=-1\n cY=-1\n\n if cX != -1:\n area = cv2.contourArea(c)\n if area>areaMax:\n areaMax=area\n contourMax=c\n cXMax=cX\n cYMax=cY\n\n if areaMax != 0:\n contourMax = contourMax*ratio\n contourMax=np.int0(contourMax)\n cv2.drawContours(frame, [contourMax], 0, (0, 255, 0), 5)\n cv2.circle(frame,(cXMax,cYMax),5,(0,0,255),-1)\n return (frame, cXMax, cYMax, areaMax, contourMax)\n\n def ReadCameraDataReturnJPG(self, frame):\n\n # get the 4 corners of the paper\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n FourCorners = cv2.goodFeaturesToTrack(gray,4,0.01,10)\n FourCorners = np.int0(FourCorners)\n\n # get the frame to show\n (frameTrack, cx, cy, areaMax, contourMax)=self.trackPaper(frame)\n cv2.rectangle(frameTrack,(self.lowW,0),(self.highW,int(self.height)),(0,0,255),5)\n ctr=-1\n if cx != -1:\n if cx>=self.lowW and cx<= self.highW:\n cv2.putText(frameTrack,\"Go Straight\",(cx-150,cy-50),cv2.FONT_HERSHEY_SIMPLEX,3,(0,0,255),5)\n ctr=0\n elif cx 0.1:\n cv2.putText(frameTrack,\"Stop\",(cx-150,cy-50),cv2.FONT_HERSHEY_SIMPLEX,3,(0,0,255),5)\n ctr=3\n\n for i in FourCorners:\n x,y = i.ravel()\n cv2.circle(frameTrack, (x,y), 15, (0,0,255), -1)\n\n # encode to jpg\n retval, buf=cv2.imencode('.jpg',frameTrack)\n\n # buf is the jpg to show and ctr is the control predicted\n\n return (buf, ctr, FourCorners)\n\n\n","sub_path":"Backend/FindPaperReturnFrame.py","file_name":"FindPaperReturnFrame.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"138111521","text":"\"\"\"Main views for sitewide search data. api/search/?*\n All these views return :class:`JsonResponse`s\n These should be general enough to handle various type of public data\n and for authenticated users any private data that they can\n access.\n\"\"\"\nimport logging\nfrom elasticsearch_dsl import Q, Search\nfrom elasticsearch import TransportError, ConnectionTimeout\nfrom django.http import (HttpResponseBadRequest,\n JsonResponse)\n\nfrom designsafe.apps.api.views import BaseApiView\nfrom designsafe.apps.api.agave.filemanager.public_search_index import (\n PublicElasticFileManager)\nfrom designsafe.apps.api.agave.filemanager.search_index import ElasticFileManager\n\nlogger = logging.getLogger(__name__)\n\n\nclass SearchView(BaseApiView):\n \"\"\"Main view to handle sitewise search requests\"\"\"\n def get(self, request):\n \"\"\"GET handler.\"\"\"\n q = request.GET.get('q')\n system_id = PublicElasticFileManager.DEFAULT_SYSTEM_ID\n offset = int(request.GET.get('offset', 0))\n limit = int(request.GET.get('limit', 10))\n if (limit > 500):\n return HttpResponseBadRequest(\"limit must not exceed 500\")\n type_filter = request.GET.get('type_filter', 'cms')\n\n if type_filter == 'public_files':\n es_query = self.search_public_files(q, offset, limit)\n elif type_filter == 'published':\n es_query = self.search_published(q, offset, limit)\n elif type_filter == 'cms':\n es_query = self.search_cms_content(q, offset, limit)\n elif type_filter == 'private_files':\n es_query = self.search_my_data(self.request.user.username, q, offset, limit)\n\n try:\n res = es_query.execute()\n except (TransportError, ConnectionTimeout) as err:\n if getattr(err, 'status_code', 500) == 404:\n raise\n res = es_query.execute()\n\n results = [r for r in res]\n out = {}\n hits = []\n if (type_filter != 'publications'):\n for r in results:\n d = r.to_dict()\n d[\"doc_type\"] = r.meta.doc_type\n if hasattr(r.meta, 'highlight'):\n highlight = r.meta.highlight.to_dict()\n d[\"highlight\"] = highlight\n hits.append(d)\n\n out['total_hits'] = res.hits.total\n out['hits'] = hits\n out['public_files_total'] = self.search_public_files(q, offset, limit).count()\n out['published_total'] = self.search_published(q, offset, limit).count()\n out['cms_total'] = self.search_cms_content(q, offset, limit).count()\n out['private_files_total'] = 0\n if request.user.is_authenticated:\n out['private_files_total'] = self.search_my_data(self.request.user.username, q, offset, limit).count()\n\n return JsonResponse(out, safe=False)\n\n def search_cms_content(self, q, offset, limit):\n \"\"\"search cms content \"\"\"\n search = Search(index=\"cms\").query(\n \"query_string\",\n query=q,\n default_operator=\"and\",\n fields=['title', 'body']).extra(\n from_=offset,\n size=limit).highlight(\n 'body',\n fragment_size=100).highlight_options(\n pre_tags=[\"\"],\n post_tags=[\"\"],\n require_field_match=False)\n return search\n\n def search_public_files(self, q, offset, limit):\n\n split_query = q.split(\" \")\n for i, c in enumerate(split_query):\n if c.upper() not in [\"AND\", \"OR\", \"NOT\"]:\n split_query[i] = \"*\" + c + \"*\"\n \n q = \" \".join(split_query)\n\n filters = Q('term', system=\"nees.public\") | \\\n Q('term', system=\"designsafe.storage.published\") | \\\n Q('term', system=\"designsafe.storage.community\")\n search = Search(index=\"des-files\")\\\n .query(\"query_string\", query=q, default_operator=\"and\")\\\n .filter(filters)\\\n .filter(\"term\", type=\"file\")\\\n .extra(from_=offset, size=limit)\n logger.info(search.to_dict())\n return search\n\n\n def search_published(self, q, offset, limit):\n query = Q(\n 'bool',\n must=[\n Q('query_string', query=q),\n ],\n must_not=[\n Q('term', status='unpublished'),\n Q('term', status='saved')\n ]\n )\n\n search = Search(index=\"des-publications_legacy,des-publications\")\\\n .query(query)\\\n .extra(from_=offset, size=limit)\n return search\n\n def search_my_data(self, username, q, offset, limit):\n\n split_query = q.split(\" \")\n for i, c in enumerate(split_query):\n if c.upper() not in [\"AND\", \"OR\", \"NOT\"]:\n split_query[i] = \"*\" + c + \"*\"\n \n q = \" \".join(split_query)\n\n search = Search(index='des-files')\n search = search.filter(\"nested\", path=\"permissions\", query=Q(\"term\", permissions__username=username))\n search = search.query(\"query_string\", query=q, fields=[\"name\", \"name._exact\", \"keywords\"])\n search = search.query(Q('bool', must=[Q({'prefix': {'path._exact': username}})]))\n search = search.filter(\"term\", system='designsafe.storage.default')\n search = search.query(Q('bool', must_not=[Q({'prefix': {'path._exact': '{}/.Trash'.format(username)}})]))\n search = search.extra(from_=offset, size=limit)\n logger.info(search.to_dict())\n return search\n","sub_path":"designsafe/apps/api/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"564443245","text":"import requests\nimport time\n\ndomains = (\"baidu.com\",)\nftqqskey = \"SCU76694T262427b2a6a252669369cb134a12f7b75e15b745eebc5\"\n\n\ndef if_domain_registed(domain: str) -> bool:\n url = f'https://whois.263.tw/{domain}'\n resp = requests.get(url=url)\n\n return(not \"No match for\" in resp.text)\n\n\ndef send_to_ftqq(title: str, text: str = '') -> bool:\n url = f'https://sc.ftqq.com/{ftqqskey}.send'\n data = {\n 'text': str(title),\n 'desp': str(text)\n }\n resp = requests.post(url=url, data=data)\n\n try:\n jsondict = resp.json()\n errno = int(jsondict.get('errno', -1))\n if errno == 0:\n return(True)\n else:\n return(False)\n except ValueError as e:\n print(f'FTQQ推送出错[{e}]')\n return(False)\n\n\nwhile True:\n try:\n for domain in domains:\n if not if_domain_registed(domain):\n current_time = time.asctime(time.localtime(time.time()))\n send_to_ftqq('域名可注册', f'域名:{domain}\\n时间:{current_time}')\n finally:\n time.sleep(30)","sub_path":"moredomain.py","file_name":"moredomain.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"278593152","text":"# Kari Green\n# cngreen\n# languageIdentification.py\n#----------------------------------------\n\nimport sys\nimport os\nimport re\nimport math\n\ndef trainBigramLanguageModel(input):\n\tcharFreq = {}\n\tbigramFreq = {}\n\n\tinput = input.lower()\n\n\tfor i in range (len(input)):\n\t\tif input[i] not in charFreq.keys():\n\t\t\tcharFreq[input[i]] = 1\n\t\telse:\n\t\t\tcharFreq[input[i]] += 1\n\n\t\tif ( i + 1 < len(input)):\n\t\t\tbigram = input[i] + input[i + 1]\n\t\t\tif bigram not in bigramFreq.keys():\n\t\t\t\tbigramFreq[bigram] = 1\n\t\t\telse:\n\t\t\t\tbigramFreq[bigram] += 1\n\n\treturn charFreq, bigramFreq\n\n\ndef calculateProbabilityStart(freq, V):\n\tprobability = float(freq + 1)/float(1 + V)\n\tprobability = math.log(probability)\n\treturn probability\n\ndef calculateProbBigram(charFreq, bigramFreq, V):\n\t# print(\"CF: \", charFreq, \" BF: \", bigramFreq, \" V: \", V)\n\t# print (charFreq + V)\n\t# print (bigramFreq + 1)\n\tprobability = float(bigramFreq + 1)/float(charFreq + V)\n\tprobability = math.log(probability)\n\treturn probability\n\ndef identifyLanguage(input, charFreq, bigramFreq):\n\tenglishProb = 0\n\tfrenchProb = 0\n\titalianProb = 0\n\n\tenglishV = len(charFreq[0])\n\tfrenchV = len(charFreq[1])\n\titalianV = len(charFreq[2])\n\n\tif (len(input) != 0): #probability of the first character given \n\t\tc = input[0]\n\t\tif c not in charFreq[0].keys():\n\t\t\tenglishProb += calculateProbabilityStart(0, englishV)\n\t\telse:\n\t\t\tenglishProb += calculateProbabilityStart(charFreq[0][c], englishV)\n\t\tif c not in charFreq[1].keys():\n\t\t\tfrenchProb += calculateProbabilityStart(0, frenchV)\n\t\telse:\n\t\t\tfrenchProb += calculateProbabilityStart(charFreq[1][c], frenchV)\n\t\tif c not in charFreq[2].keys():\n\t\t\titalianProb += calculateProbabilityStart(0, italianV)\n\t\telse:\n\t\t\titalianProb += calculateProbabilityStart(charFreq[2][c], italianV)\n\t\n\ti = 1\n\n\twhile (i < len(input)): #probability of bigrams\n\t\tb = input[i - 1] + input[i]\n\t\tc = input[i]\n\n\t\tif c in charFreq[0].keys() and b in bigramFreq[0].keys(): #character and bigram both in dictionaries\n\t\t\tenglishProb += calculateProbBigram(charFreq[0][c], bigramFreq[0][b], englishV)\n\t\tif b not in bigramFreq[0].keys(): #bigram not in dictionary\n\t\t\tif c not in charFreq[0].keys(): #neither in dictionary\n\t\t\t\tenglishProb += calculateProbBigram(0, 0, englishV)\n\t\t\telse:\n\t\t\t\tenglishProb += calculateProbBigram(charFreq[0][c], 0, englishV)\n\t\t\n\t\tif c in charFreq[1].keys() and b in bigramFreq[1].keys():\n\t\t\tfrenchProb += calculateProbBigram(charFreq[1][c], bigramFreq[1][b], frenchV)\n\t\tif b not in bigramFreq[1].keys():\n\t\t\tif c not in charFreq[1].keys():\n\t\t\t\tfrenchProb += calculateProbBigram(0, 0, frenchV)\n\t\t\telse:\n\t\t\t\tfrenchProb += calculateProbBigram(charFreq[1][c], 0, frenchV)\n\n\t\tif c in charFreq[2].keys() and b in bigramFreq[2].keys():\n\t\t\titalianProb += calculateProbBigram(charFreq[2][c], bigramFreq[2][b], italianV)\n\t\tif b not in bigramFreq[2].keys():\n\t\t\tif c not in charFreq[2].keys():\n\t\t\t\titalianProb += calculateProbBigram(0, 0, italianV)\n\t\t\telse:\n\t\t\t\titalianProb += calculateProbBigram(charFreq[2][c], 0, italianV)\n\n\t\ti += 1\n\n\toutput = ''\n\n\tif (englishProb >= frenchProb and englishProb >= italianProb):\n\t\toutput = 'English'\n\telif (frenchProb >= englishProb and frenchProb >= italianProb):\n\t\toutput = 'French'\n\telse:\n\t\toutput = 'Italian'\n\n\treturn output\n\n\ndef main():\n\t#dictionaries:\n\t# english_charFreq = {}\n\t# english_bigramFreq= {}\n\t# french_charFreq = {}\n\t# french_bigramFreq = {}\n\t# italian_charFreq = {}\n\t# italian_bigramFreq = {}\n\n\tcharFreq = [{}, {}, {}] \n\t#0 = english, 1 = french, 2 = italian\n\tbigramFreq = [{}, {}, {}]\n\n\t#training file location\n\tfoldername = 'languageIdentification.data/training/'\n\tpath = os.path.join(os.getcwd(), foldername)\n\n\n#train english data--------------------------------------\n\tpath2file = os.path.join(path, 'English')\n\tlines = [line.rstrip('\\n') for line in open(path2file)]\n\n\tfor line in lines:\n\t\tchars, bigrams = trainBigramLanguageModel(line)\n\t\tfor c in chars:\n\t\t\tif c not in charFreq[0].keys():\n\t\t\t\tcharFreq[0][c] = chars[c]\n\t\t\telse:\n\t\t\t\tcharFreq[0][c] += chars[c]\n\n\t\tfor b in bigrams:\n\t\t\tif b not in bigramFreq[0].keys():\n\t\t\t\tbigramFreq[0][b] = bigrams[b]\n\t\t\telse:\n\t\t\t\tbigramFreq[0][b] += bigrams[b]\n\n#train french data--------------------------------------\n\tpath2file = os.path.join(path, 'French')\n\tlines = [line.rstrip('\\n') for line in open(path2file)]\n\n\tfor line in lines:\n\t\tchars, bigrams = trainBigramLanguageModel(line)\n\t\tfor c in chars:\n\t\t\tif c not in charFreq[1].keys():\n\t\t\t\tcharFreq[1][c] = chars[c]\n\t\t\telse:\n\t\t\t\tcharFreq[1][c] += chars[c]\n\n\t\tfor b in bigrams:\n\t\t\tif b not in bigramFreq[1].keys():\n\t\t\t\tbigramFreq[1][b] = bigrams[b]\n\t\t\telse:\n\t\t\t\tbigramFreq[1][b] += bigrams[b]\n\n#train italian data--------------------------------------\n\tpath2file = os.path.join(path, 'Italian')\n\tlines = [line.rstrip('\\n') for line in open(path2file)]\n\n\tfor line in lines:\n\t\tchars, bigrams = trainBigramLanguageModel(line)\n\t\tfor c in chars:\n\t\t\tif c not in charFreq[2].keys():\n\t\t\t\tcharFreq[2][c] = chars[c]\n\t\t\telse:\n\t\t\t\tcharFreq[2][c] += chars[c]\n\n\t\tfor b in bigrams:\n\t\t\tif b not in bigramFreq[2].keys():\n\t\t\t\tbigramFreq[2][b] = bigrams[b]\n\t\t\telse:\n\t\t\t\tbigramFreq[2][b] += bigrams[b]\n\n\t\n#obtain test data----------------------------------------------\n#--------------------------------------------------------------\n\t#find name of testfile\n\tfilename = str(sys.argv[1])\n\tpath = os.path.join(os.getcwd(), filename)\n\n\tlines = [line.rstrip('\\n') for line in open(path)]\n\n\ti = 0\n\n\ttargetFile = open('languageIdentification.output', 'w+')\n\n\twhile (i < len(lines)):\n\t\tlines[i] = lines[i].lower()\n\t\tlanguage = identifyLanguage(lines[i], charFreq, bigramFreq)\n\t\ti += 1\n\t\toutput = str(i) + ' ' + language + '\\n'\n\t\ttargetFile.write(output)\n\t\t\n\n\n\n\nif __name__ == \"__main__\": \n\tmain()","sub_path":"languageIdentification.py","file_name":"languageIdentification.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"162831963","text":"# -*- encoding: utf-8 -*-\n# Copyright (c) 2015 b<>com\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utilities and helper functions.\"\"\"\n\nimport datetime\nimport random\nimport re\nimport string\n\nfrom croniter import croniter\n\nfrom jsonschema import validators\nfrom oslo_config import cfg\nfrom oslo_log import log\nfrom oslo_utils import strutils\nfrom oslo_utils import uuidutils\n\nfrom watcher.common import exception\n\nCONF = cfg.CONF\n\nLOG = log.getLogger(__name__)\n\n\nclass Struct(dict):\n \"\"\"Specialized dict where you access an item like an attribute\n\n >>> struct = Struct()\n >>> struct['a'] = 1\n >>> struct.b = 2\n >>> assert struct.a == 1\n >>> assert struct['b'] == 2\n \"\"\"\n\n def __getattr__(self, name):\n try:\n return self[name]\n except KeyError:\n raise AttributeError(name)\n\n def __setattr__(self, name, value):\n try:\n self[name] = value\n except KeyError:\n raise AttributeError(name)\n\n\ngenerate_uuid = uuidutils.generate_uuid\nis_uuid_like = uuidutils.is_uuid_like\nis_int_like = strutils.is_int_like\n\n\ndef is_cron_like(value):\n \"\"\"Return True is submitted value is like cron syntax\"\"\"\n try:\n croniter(value, datetime.datetime.now())\n except Exception as e:\n raise exception.CronFormatIsInvalid(message=str(e))\n return True\n\n\ndef safe_rstrip(value, chars=None):\n \"\"\"Removes trailing characters from a string if that does not make it empty\n\n :param value: A string value that will be stripped.\n :param chars: Characters to remove.\n :return: Stripped value.\n\n \"\"\"\n if not isinstance(value, str):\n LOG.warning(\n \"Failed to remove trailing character. Returning original object.\"\n \"Supplied object is not a string: %s,\", value)\n return value\n\n return value.rstrip(chars) or value\n\n\ndef is_hostname_safe(hostname):\n \"\"\"Determine if the supplied hostname is RFC compliant.\n\n Check that the supplied hostname conforms to:\n * http://en.wikipedia.org/wiki/Hostname\n * http://tools.ietf.org/html/rfc952\n * http://tools.ietf.org/html/rfc1123\n\n :param hostname: The hostname to be validated.\n :returns: True if valid. False if not.\n\n \"\"\"\n m = r'^[a-z0-9]([a-z0-9\\-]{0,61}[a-z0-9])?$'\n return (isinstance(hostname, str) and\n (re.match(m, hostname) is not None))\n\n\ndef get_cls_import_path(cls):\n \"\"\"Return the import path of a given class\"\"\"\n module = cls.__module__\n if module is None or module == str.__module__:\n return cls.__name__\n return module + '.' + cls.__name__\n\n\n# Default value feedback extension as jsonschema doesn't support it\ndef extend_with_default(validator_class):\n validate_properties = validator_class.VALIDATORS[\"properties\"]\n\n def set_defaults(validator, properties, instance, schema):\n for prop, subschema in properties.items():\n if \"default\" in subschema and instance is not None:\n instance.setdefault(prop, subschema[\"default\"])\n\n for error in validate_properties(\n validator, properties, instance, schema\n ):\n yield error\n\n return validators.extend(validator_class,\n {\"properties\": set_defaults})\n\n\n# Parameter strict check extension as jsonschema doesn't support it\ndef extend_with_strict_schema(validator_class):\n validate_properties = validator_class.VALIDATORS[\"properties\"]\n\n def strict_schema(validator, properties, instance, schema):\n if instance is None:\n return\n\n for para in instance.keys():\n if para not in properties.keys():\n raise exception.AuditParameterNotAllowed(parameter=para)\n\n for error in validate_properties(\n validator, properties, instance, schema\n ):\n yield error\n\n return validators.extend(validator_class, {\"properties\": strict_schema})\n\n\nStrictDefaultValidatingDraft4Validator = extend_with_default(\n extend_with_strict_schema(validators.Draft4Validator))\n\nDraft4Validator = validators.Draft4Validator\n\n\ndef random_string(n):\n return ''.join([random.choice(\n string.ascii_letters + string.digits) for i in range(n)])\n","sub_path":"watcher/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"502563744","text":"from itertools import combinations\r\nn = int(input('Quantos numeros possiveis há na sua loteria?: '))\r\np = int(input('Quantas numeros você deve marcar?: '))\r\n\r\nf = open('combinations7.txt', 'w')\r\n\r\nfor comb in combinations(range(1,n+1), p):\r\n f.write(str(comb))\r\n f.write('\\n')\r\nf.close()","sub_path":"MegaSena.py","file_name":"MegaSena.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245628831","text":"\n# coding: utf-8\n\"\"\"CHECK IF BEAR STRING IS READ WELL\"\"\"\n# In[15]:\n\nwith open(\"mbr.txt\") as f:\n data=f.readlines()\n\n\n# In[33]:\nimport re\nimport pandas as pd\ntmp=[x.rstrip(\",\\n\").replace(\"{\",\"\").replace(\"}\",\"\").split(\",\") for x in data][:-1]\ndf=pd.DataFrame(tmp)\n\n\n# In[ ]:\n#S splits in L|R\nmap_7let={'jklmnopqrstuvwxyz^':'H', 'abcdefghi=':'S',\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ~?_|/\\\\@\\{\\}':'M', '!\"#$%&\\'()+1234567890>':'T', \n '[]':'B', ':':'E' }\n\nmap_db_2_7let={'(':'L', ')':'R', '.':'U'}\n\n# In[44]:\n\ndef subscore(a,b):\n BEAR_string=\"abcdefghi=lmnopqrstuvwxyz^!\\\"#$%&\\'()+234567890>[]:ABCDEFGHIJKLMNOPQRSTUVW{YZ~?_|/\\\\}@\"\n if a == '-' or b == '-':\n \treturn -2\n\n return float(df.iloc[BEAR_string.index(a),BEAR_string.index(b)])\n\ndef subscoreNT(a,b):\n\t###STUB\n\tif a == '-' or b == '-':\n\t\treturn -2\n\treturn 3 if a==b else -2\n\n# In[45]:\n\ndef __identifyHloops(s):\n\t#how many loops: (start,end) list\n\tpattern=\"H+\"\n\tloops = [m.span() for m in re.finditer(pattern, s)]\n\treturn loops\n\ndef __replH(m):\n return m.group().replace('U','H')\ndef __replB(m):\n return m.group().replace('U','B')\ndef __replT(m):\n return m.group().replace('U','T')\ndef __replM(m):\n return m.group().replace('U','M')\ndef __replExtraH(m):\n return m.group().replace('U','H')\ndef __replExtraM(m):\n return m.group().replace('U','M')\n\n\n\ndef __identifyElements_db(s):\n\t#how many loops: (start,end) list\n\tpatternH=r'L(U+)R'\n\tpatternB=r'LUL|RUR'\n\tpatternT=r'RU+R|LU+L'\n\tpatternM=r'RU+L|LU+R'\n\tpatternExtraH=r'U+R|LU+'\n\tpatternExtraM=r'RU+|U+L|^U+$'\n\t\n\n\ts = re.sub(patternH, __replH, s)\n\ts = re.sub(patternB, __replB, s)\n\ts = re.sub(patternT, __replT, s)\n\ts = re.sub(patternM, __replM, s)\n\ts = re.sub(patternExtraH, __replExtraH, s)\n\ts = re.sub(patternExtraM, __replExtraM, s)\n\treturn s\n\ndef __fix(res, Hloops, original):\n\t# if no loops are present, fix the 'S' characters\n\tif Hloops: #some ref loops\n\t\tidx=res.find('S')\n\t\tif idx < Hloops[0][0]: #S is left of the first loops: it's an R\n\t\t\treturn res[:idx] + 'R' + res[idx+1:]\n\t\telif idx >= Hloops[-1][-1]:\n\t\t\treturn res[:idx] + 'L' + res[idx+1:]\n\t\telse: #dangling stem, missing one extreme\n\t\t\tif idx >= Hloops[-2][-1]:\n\t\t\t\treturn res[:idx] + 'L' + res[idx+1:]\n\t\t\telif idx < Hloops[1][0]:\n\t\t\t\treturn res[:idx] + 'R' + res[idx+1:]\n\t\t\telse:\n\t\t\t\treturn \n\telse:\n\t#no ref loops, must refer to original? cccdddd can be a stem-change...\n\t#but what if 'dddddddd'? problems\n\t#leave them undefined stems 's'\n\t\treturn res.replace('S','s')\n\ndef decode(bear, option=\"7letters\"):\n\t#it only works with the full sequence BEARed\n\tresult=\"\"\n\tif option == \"7letters\":\n\t\t\"\"\"2 steps decoding\"\"\"\n\t\tfor ch in bear:\n\t\t\tfor key in map_7let:\n\t\t\t\tif ch in key:\n\t\t\t\t\tresult += map_7let[key]\n\n\n\t\tHloops=__identifyHloops(result)\n\t\tprint(Hloops)\n\t\tfor start,end in Hloops:\n\t\t\t \n\t\t\tlindex=start-1\n\t\t\trindex=end\n\n\t\t\twhile(lindex != -1 and result[lindex] not in 'EM' and rindex < len(result) and result[rindex] not in 'ER'):\n\t\t\t\tif result[lindex] is 'S' and result[rindex] is 'S': \n\t\t\t\t\t#Strings ARE IMMuTABLE!!\n\t\t\t\t\tresult = result[:lindex] + 'L' + result[lindex+1:rindex] + 'R' + result[rindex+1:]\n\n\t\t\t\t\tlindex -= 1\n\t\t\t\t\trindex += 1\n\t\t\t\telif result[lindex] is 'S' and result[rindex] is not 'S':\n\t\t\t\t\trindex += 1\n\t\t\t\telif result[lindex] is not 'S' and result[rindex] is 'S':\n\t\t\t\t\t#stop one index untile next pair\n\t\t\t\t\tlindex -= 1\n\t\t\t\telif result[lindex] is not 'S' and result[rindex] is not 'S':\n\t\t\t\t\t#double internal loop\n\t\t\t\t\tlindex -= 1\n\t\t\t\t\trindex += 1\n\t\t\tprint(result)\n\t\tprint(result)\n\t\twhile(result.find('S') != -1):\n\t\t\tresult=__fix(result, Hloops, bear)\n\t\treturn result\n\ndef encode(db, option=\"7letters\"):\n\tresult=\"\"\n\tif option == \"7letters\":\n\t\tfor ch in db:\n\t\t\tfor key in map_db_2_7let:\n\t\t\t\tif ch in key:\n\t\t\t\t\tresult += map_db_2_7let[key]\n\t\tresult=__identifyElements_db(result)\t\n\t\t#non-terminal characters + regex rulez\n\t\treturn result\n\t\t\nif __name__==\"__main__\":\n#\tprint(decode('cccmmmmcccddddmmmmddddbblllbb'))\n#\tprint(decode('::::bb[dddd[cccmmmmccc333dddd]bbcccddddnnnnndddd]ccc::EEEEEKKFFFFFF:ffffff[bb!!cccqqqqqqqqcccbbffffff::::::::::==========mmmm==========:::::ccc\"\"\"cccooooooccc22cccbb[ffffffdddd[a[bbcccbbmmmmbb]ccc55555bb]a]dddd333ffffff]bbFFFFFFYYEEEEE'))\n#\tprint(decode('eee22bbeeeee]ggggggg:bb[bb#')) #doppio stem without loop\n#\tprint(decode(\"eee22bbeeemmmmmgggg:bb[bb#\")) \t#un loop di riferimento\n#\tprint(decode('cccmmmmcccddddmmmmddddbblllb')) #un pezzo mancante\n#\tprint(decode('ppppppffffffcccmmmmcccdddd[==========####bb[bboooooobb]bb22==========]ddddiiiiiiiiieeeeebb[bb[ccc[dddd[bbmmmmbbddddccc333bb]bb]eeeee55555iiiiiiiii::::::::::iiiiiiiii!!dddd[bboooooobbdddd]iiiiiiii'))\n\tprint(encode('.....((((..))..)).....'))\n\tprint(encode('.....))))))....((((...))).....'))\n\tprint(encode(')))))))((((...(((('))\n\tprint(encode('.....................'))\n# In[ ]:\n\n\n\n","sub_path":"pssm_proj/scripts/subscoreMBR.py","file_name":"subscoreMBR.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"255720461","text":"import pygame\n\nclass NineSlice:\n def __init__(self):\n pass\n\n @staticmethod\n def get_nine(image, slices = (0,0,0,0), width = 64, height = 64, stretch = False):\n left, top, right, bottom = slices\n w, h = image.get_size()\n w_mid = w - (left + right)\n h_mid = h - (top + bottom)\n width_mid = width - (left + right)\n height_mid = height - (top + bottom)\n\n to_return = pygame.Surface((width, height))\n to_return.fill((0, 0, 0))\n\n repeat_w = w_mid\n while(round((width_mid / float(repeat_w)), 6) != round((width_mid / float(repeat_w)))):\n repeat_w -= 1\n\n repeat_h = h_mid\n while (round((height_mid / float(repeat_h)), 6) != round((height_mid / float(repeat_h)))):\n repeat_h -= 1\n\n\n # top row\n to_return.blit(image, (0,0,left, top), area=(0, 0, left, top))\n for i in range(int(width_mid / repeat_w)):\n to_return.blit(image, (left + (repeat_w * i), 0, repeat_w, top), area=(left, 0, repeat_w, top))\n to_return.blit(image, (width - right, 0, right, top), area=(w - right, 0, right, top))\n\n\n # middle row\n for i in range(int(height_mid / repeat_h)):\n to_return.blit(image, (0, top + i * repeat_h, left, repeat_h), area=(0, top, left, repeat_h))\n if (stretch):\n center_slice = pygame.Surface((w_mid, h_mid))\n center_slice.blit(image, (0,0,w_mid, h_mid), area=(left, top, w_mid, h_mid))\n to_return.blit(pygame.transform.scale(center_slice, (width_mid, height_mid)), (left, top, width_mid, height_mid))\n else:\n for i in range(int(width_mid / repeat_w)):\n for j in range(int(height_mid / repeat_h)):\n to_return.blit(image, (left + (i * repeat_w), top + (j * repeat_h), w_mid, h_mid), area=(left, top, repeat_w, repeat_h))\n for i in range(int(height_mid / repeat_h)):\n to_return.blit(image, (width - right, top + i * repeat_h, right, repeat_h), area=(w - right, top, right, repeat_h))\n\n # bottom row\n to_return.blit(image, (0, height-bottom, left, bottom), area=(0, h - bottom, left, bottom))\n for i in range(int(width_mid / repeat_w)):\n to_return.blit(image, (left + (repeat_w * i), height - bottom, repeat_w, bottom), area=(left, h - bottom, repeat_w, bottom))\n to_return.blit(image, (width - right, height - bottom, right, bottom), area=(w - right, h - bottom, right, bottom))\n\n return to_return","sub_path":"nineslice.py","file_name":"nineslice.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"2098205","text":"import os\nimport time\nimport cv2\nimport numpy as np\nfrom pykeyboard import PyKeyboardEvent, PyKeyboard\nfrom auto_press_gun.my_timer import MyTimer\nfrom auto_hold_breath.win32_screen_shot import Screen\n\nclass Key_listern(PyKeyboardEvent):\n def __init__(self):\n PyKeyboardEvent.__init__(self)\n self.i = 0\n self.t = MyTimer(0.04, self.screen_shot)\n self.k = PyKeyboard()\n self.sc = Screen()\n\n def screen_shot(self):\n self.sc.shot()\n\n def tap(self, keycode, character, press):\n print(keycode, press)\n if keycode == 160 and not press:\n self.t.start()\n self.t0 = time.time()\n\n if keycode == 48 and press:\n self.t.cancel()\n self.t1 = time.time()\n print(self.t1-self.t0)\n self.sc.save('scar/')\n\n\nkl = Key_listern()\nkl.run()","sub_path":"auto_hold_breath/screen_shot_after_shift.py","file_name":"screen_shot_after_shift.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"537829718","text":"from __future__ import print_function\n\nimport os\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.optim as optim\nimport torch.utils.data\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\n\nfrom workflow import WorkFlow, TorchFlow\n\nfrom DataLoader.SceneFlow import Loader as DA\nfrom DataLoader import PreProcess\nfrom DataLoader.SceneFlow.utils import list_files_sceneflow_FlyingThings, read_string_list\n\nRECOMMENDED_MIN_INTERMITTENT_PLOT_INTERVAL = 100\n\nDATASET_LIST_TRAINING_IMG_L = \"InputImageTrainL.txt\"\nDATASET_LIST_TRAINING_IMG_R = \"InputImageTrainR.txt\"\nDATASET_LIST_TRAINING_DSP_L = \"InputDisparityTrain.txt\"\n\nDATASET_LIST_TESTING_IMG_L = \"InputImageTestL.txt\"\nDATASET_LIST_TESTING_IMG_R = \"InputImageTestR.txt\"\nDATASET_LIST_TESTING_DSP_L = \"InputDisparityTest.txt\"\n\nDATASET_LIST_INFERRING_IMG_L = \"InputImageInferL.txt\"\nDATASET_LIST_INFERRING_IMG_R = \"InputImageInferR.txt\"\nDATASET_LIST_INFERRING_Q = \"InputQ.txt\"\n\nclass TrainTestBase(object):\n def __init__(self, workingDir, frame=None, modelName='Stereo'):\n self.wd = workingDir\n self.frame = frame\n self.modelName = modelName\n\n # NN.\n self.countTrain = 0\n self.countTest = 0\n\n self.flagGrayscale = False\n self.flagSobelX = False\n\n self.trainIntervalAccWrite = 10 # The interval to write the accumulated values.\n self.trainIntervalAccPlot = 1 # The interval to plot the accumulate values.\n self.flagUseIntPlotter = False # The flag of intermittent plotter.\n\n self.imgTrainLoader = None\n self.imgTestLoader = None\n self.imgInferLoader = None\n self.datasetRootDir = \"./\"\n self.dataFileList = False # Once set to be true, the files contain the list of input dataset will be used.\n self.dataFileListDir = None # If self.dataFileList is True, then this variable must be set properly.\n self.dataEntries = 0 # 0 for using all the data.\n self.datasetTrain = None # Should be an object of torch.utils.data.Dataset.\n self.datasetTest = None # Should be an object of torch.utils.data.Dataset.\n self.datasetInfer = None # Should be an object of torch.utils.data.Dataset.\n self.dlBatchSize = 2\n self.dlShuffle = True\n self.dlNumWorkers = 2\n self.dlDropLast = False\n self.dlNewSize = (0, 0) # (0, 0) for disable.\n self.dlCropTrain = (0, 0) # (0, 0) for disable.\n self.dlCropTest = (0, 0) # (0, 0) for disable.\n\n self.maxDisp = 0 # Real disparity, not scaled.\n\n self.model = None\n self.flagCPU = False\n self.multiGPUs = False\n\n self.readModelString = \"\"\n self.readOptimizerString = \"\"\n self.autoSaveModelLoops = 0 # The number of loops to perform an auto-saving of the model. 0 for disable.\n\n self.optimizer = None\n self.learningRate = 0.001\n\n self.testResultSubfolder = \"TestResults\"\n\n self.flagTest = False # Should be set to True when testing.\n self.flagInfer = False # Should be set to True when inferring.\n\n def initialize(self):\n self.check_frame()\n\n # Over load these functions if nessesary.\n self.init_base()\n self.init_workflow()\n self.init_torch()\n self.init_data()\n self.init_model()\n self.post_init_model()\n self.init_optimizer()\n \n def train(self):\n self.check_frame()\n \n def test(self):\n self.check_frame()\n \n def finialize(self):\n self.check_frame()\n\n def infer(self):\n self.check_frame()\n\n def set_frame(self, frame):\n self.frame = frame\n \n def check_frame(self):\n if ( self.frame is None ):\n raise Exception(\"self.frame must not be None.\")\n \n def enable_grayscale(self):\n self.check_frame()\n\n self.flagGrayscale = True\n\n self.frame.logger.info(\"Grayscale image enabled.\")\n\n def enable_Sobel_x(self):\n self.check_frame()\n\n self.flagSobelX = True\n self.flagGrayscale = True\n\n self.frame.logger.info(\"Sobel-x image enabled. Image will be converted into grayscale first.\")\n\n def set_learning_rate(self, lr):\n self.check_frame()\n\n self.learningRate = lr\n\n if ( self.learningRate >= 1.0 ):\n self.frame.logger.warning(\"Large learning rate (%f) is set.\" % (self.learningRate))\n\n def set_max_disparity(self, md):\n self.maxDisp = md\n\n def enable_multi_GPUs(self):\n self.check_frame()\n\n self.flagCPU = False\n self.multiGPUs = True\n\n self.frame.logger.info(\"Enable multi-GPUs.\")\n\n def set_cpu_mode(self):\n self.check_frame()\n\n self.flagCPU = True\n self.multiGPUs = False\n\n self.frame.logger.warning(\"CPU mode is selected.\")\n\n def unset_cpu_mode(self):\n self.check_frame()\n\n self.flagCPU = False\n self.multiGPUs = False\n\n self.frame.logger.warning(\"Back to GPU mode.\")\n\n def set_dataset_root_dir(self, d, nEntries=0, flagFileList=False, fileListDir=None):\n self.check_frame()\n\n if ( False == os.path.isdir(d) ):\n raise Exception(\"Dataset directory (%s) not exists.\" % (d))\n \n self.datasetRootDir = d\n self.dataEntries = nEntries\n\n self.frame.logger.info(\"Data root directory is %s.\" % ( self.datasetRootDir ))\n if ( 0 != nEntries ):\n self.frame.logger.warning(\"Only %d entries of the training dataset will be used.\" % ( nEntries ))\n\n self.dataFileList = flagFileList\n self.dataFileListDir = fileListDir\n\n if ( self.dataFileList ):\n if ( self.dataFileListDir is None ):\n raise Exception(\"The directory of the file-lists files must be set.\")\n else:\n if ( not os.path.isdir( self.dataFileListDir ) ):\n raise Exception(\"File-lists directory %s does not exist. \" % ( self.dataFileListDir ))\n\n if ( True == self.dataFileList ):\n self.frame.logger.info(\"Data loader will use the pre-defined files to load the input data.\")\n self.frame.logger.info(\"The file-lists directory is %s. \" % ( self.dataFileListDir ))\n\n def set_data_loader_params(self, batchSize=2, shuffle=True, numWorkers=2, dropLast=False, \\\n newSize=(0, 0), cropTrain=(0, 0), cropTest=(0, 0)):\n \n self.check_frame()\n\n self.dlBatchSize = batchSize\n self.dlShuffle = shuffle\n self.dlNumWorkers = numWorkers\n self.dlDropLast = dropLast\n self.dlNewSize = newSize\n self.dlCropTrain = cropTrain\n self.dlCropTest = cropTest\n\n def set_read_model(self, readModelString):\n self.check_frame()\n \n self.readModelString = readModelString\n\n if ( \"\" != self.readModelString ):\n self.frame.logger.info(\"Read model from %s.\" % ( self.readModelString ))\n\n def set_read_optimizer(self, readOptimizerString):\n self.check_frame()\n\n self.readOptimizerString = readOptimizerString\n\n if ( \"\" != self.readOptimizerString ):\n self.frame.logger.info(\"Read optimizer from %s. \" % ( self.readOptimizerString ))\n\n def enable_auto_save(self, loops):\n self.check_frame()\n \n self.autoSaveModelLoops = loops\n\n if ( 0 != self.autoSaveModelLoops ):\n self.frame.logger.info(\"Auto save enabled with loops = %d.\" % (self.autoSaveModelLoops))\n\n def set_training_acc_params(self, intervalWrite, intervalPlot, flagInt=False):\n self.check_frame()\n \n self.trainIntervalAccWrite = intervalWrite\n self.trainIntervalAccPlot = intervalPlot\n self.flagUseIntPlotter = flagInt\n\n if ( True == self.flagUseIntPlotter ):\n if ( self.trainIntervalAccPlot <= RECOMMENDED_MIN_INTERMITTENT_PLOT_INTERVAL ):\n self.frame.logger.warning(\"When using the intermittent plotter. It is recommended that the plotting interval (%s) is higher than %d.\" % \\\n ( self.trainIntervalAccPlot, RECOMMENDED_MIN_INTERMITTENT_PLOT_INTERVAL ) )\n\n def switch_on_test(self):\n self.flagTest = True\n\n def set_count_test(self, c):\n self.countTest = int(c)\n\n def switch_off_test(self):\n self.flagTest = False\n\n def switch_on_infer(self):\n self.flagInfer = True\n\n def switch_off_infer(self):\n self.flagInfer = False\n\n def init_base(self):\n # Make the subfolder for the test results.\n self.frame.make_subfolder(self.testResultSubfolder)\n\n def init_workflow(self):\n raise Exception(\"init_workflow() virtual interface.\")\n\n def init_torch(self):\n self.check_frame()\n\n self.frame.logger.info(\"Configure Torch.\")\n\n # torch.manual_seed(1)\n # torch.cuda.manual_seed(1)\n\n def init_data(self):\n # Get all the sample images.\n # imgTrainL, imgTrainR, dispTrain, imgTestL, imgTestR, dispTest \\\n # = list_files_sample(\"/home/yyhu/expansion/OriginalData/SceneFlow/Sampler/FlyingThings3D\")\n # imgTrainL, imgTrainR, dispTrain, imgTestL, imgTestR, dispTest \\\n # = list_files_sample(\"/media/yaoyu/DiskE/SceneFlow/Sampler/FlyingThings3D\")\n\n if ( False == self.flagInfer ):\n if ( True == self.dataFileList ):\n imgTrainL = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_TRAINING_IMG_L, self.datasetRootDir )\n imgTrainR = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_TRAINING_IMG_R, self.datasetRootDir )\n dispTrain = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_TRAINING_DSP_L, self.datasetRootDir )\n imgTestL = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_TESTING_IMG_L , self.datasetRootDir )\n imgTestR = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_TESTING_IMG_R , self.datasetRootDir )\n dispTest = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_TESTING_DSP_L , self.datasetRootDir )\n else:\n imgTrainL, imgTrainR, dispTrain, imgTestL, imgTestR, dispTest \\\n = list_files_sceneflow_FlyingThings( self.datasetRootDir )\n\n if ( 0 != self.dataEntries ):\n imgTrainL = imgTrainL[0:self.dataEntries]\n imgTrainR = imgTrainR[0:self.dataEntries]\n dispTrain = dispTrain[0:self.dataEntries]\n imgTestL = imgTestL[0:self.dataEntries]\n imgTestR = imgTestR[0:self.dataEntries]\n dispTest = dispTest[0:self.dataEntries]\n else:\n if ( True == self.dataFileList ):\n imgInferL = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_INFERRING_IMG_L, self.datasetRootDir )\n imgInferR = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_INFERRING_IMG_R, self.datasetRootDir )\n Q = read_string_list( self.dataFileListDir + \"/\" + DATASET_LIST_INFERRING_Q , self.datasetRootDir )\n else:\n raise Exception(\"Please use data file list when inferring.\")\n \n if ( 0 != self.dataEntries ):\n imgInferL = imgInferL[0:self.dataEntries]\n imgInferR = imgInferR[0:self.dataEntries]\n Q = Q[0:self.dataEntries]\n\n # Dataloader.\n if ( True == self.flagSobelX ):\n preprocessor = transforms.Compose( [ \\\n PreProcess.GrayscaleNoTensor(), \\\n PreProcess.SobelXNoTensor(), \\\n transforms.ToTensor(), \\\n PreProcess.SingleChannel() ] )\n elif ( True == self.flagGrayscale ):\n # preprocessor = transforms.Compose( [ \\\n # transforms.ToTensor(), \\\n # PreProcess.Grayscale(), \\\n # PreProcess.SingleChannel() ] )\n\n preprocessor = transforms.Compose( [ \\\n PreProcess.GrayscaleNoTensor(), \\\n transforms.ToTensor(), \\\n PreProcess.SingleChannel() ] )\n else:\n preprocessor = PreProcess.get_transform(augment=False)\n\n if ( False == self.flagInfer ):\n self.datasetTrain = DA.myImageFolder( imgTrainL, imgTrainR, dispTrain, True, preprocessor=preprocessor, newSize=self.dlNewSize, cropSize=self.dlCropTrain )\n self.datasetTest = DA.myImageFolder( imgTestL, imgTestR, dispTest, False, preprocessor=preprocessor, newSize=self.dlNewSize, cropSize=self.dlCropTest )\n\n self.imgTrainLoader = torch.utils.data.DataLoader( \\\n self.datasetTrain, \\\n batch_size=self.dlBatchSize, shuffle=self.dlShuffle, num_workers=self.dlNumWorkers, drop_last=self.dlDropLast )\n\n self.imgTestLoader = torch.utils.data.DataLoader( \\\n self.datasetTest, \\\n batch_size=1, shuffle=False, num_workers=self.dlNumWorkers, drop_last=self.dlDropLast )\n else:\n self.datasetInfer = DA.inferImageFolder( imgInferL, imgInferR, Q, preprocessor=preprocessor, newSize=self.dlNewSize, cropSize=self.dlCropTest )\n\n self.imgInferLoader = torch.utils.data.DataLoader( \\\n self.datasetInfer, \\\n batch_size=1, shuffle=False, num_workers=self.dlNumWorkers, drop_last=self.dlDropLast )\n\n def init_model(self):\n raise Exception(\"init_model() virtual interface.\")\n\n def post_init_model(self):\n if ( not self.flagCPU ):\n if ( True == self.multiGPUs ):\n self.model = nn.DataParallel(self.model)\n\n self.model.cuda()\n \n def init_optimizer(self):\n raise Exception(\"init_optimizer() virtual interface.\")\n","sub_path":"TrainTestBase.py","file_name":"TrainTestBase.py","file_ext":"py","file_size_in_byte":13949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"112792183","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 29 22:39:57 2020\n\n@author: hiroyasu\n\"\"\"\n\nimport cvxpy as cp\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport control\nimport SCPmulti as scp\nimport pickle\nimport TrainRNN as trnn\nimport torch\nimport pandas as pd\n\nDT = scp.DT\nTSPAN = scp.TSPAN\nM = scp.M\nII = scp.II\nL = scp.L\nbb = scp.bb\nFMIN = scp.FMIN\nFMAX = scp.FMAX\nRungeNum = scp.RungeNum\nAA = scp.AA\nRobs = scp.Robs\nRsafe = scp.Rsafe\nXOBSs = scp.XOBSs\nXXd0 = np.load('data/params/desired_n/Xhis.npy')\nUUd0 = np.load('data/params/desired_n/Uhis.npy')\ndratio = 0.2\nd_over = np.sqrt(3)*dratio\nX0 = scp.X0\nXf = scp.Xf\nn_input = trnn.n_input\nn_hidden = trnn.n_hidden\nn_output = trnn.n_output\nn_layers = trnn.n_layers\n\nclass Spacecraft:\n def __init__(self,XXd0,UUd0,tspan=TSPAN,dt=DT,runge_num=RungeNum,m=M,I=II,l=L,b=bb,A=AA,fmin=FMIN,fmax=FMAX):\n self.XXd = XXd0\n self.UUd = UUd0\n self.tspan = tspan\n self.dt = dt\n self.runge_num = runge_num\n self.h = dt/runge_num\n self.m = m\n self.I = I\n self.l = l\n self.b = b\n self.A = A\n self.fmin = fmin\n self.fmax = fmax\n self.net = trnn.RNN(n_input,n_hidden,n_output,n_layers)\n self.net.load_state_dict(torch.load('data/trained_nets/RNNLorenz.pt'))\n self.net.eval()\n self.YC = np.load('data/trained_nets/Y_params.npy')\n self.ns = 6\n self.RNN = 1\n\n def GetP(self,X):\n Xnet = self.Np2Var(X)\n if self.RNN == 1:\n cP = self.net(Xnet.view(1,1,-1))\n cP = cP.data.numpy()*self.YC\n P = self.cP2P(cP[0,0,:])\n else:\n cP = self.net(Xnet)\n cP = cP.data.numpy()\n P = self.cP2P(cP)\n return P\n \n def GetK(self,X):\n P = self.GetP(X)\n B = self.GetB(X)\n K = B.T@P\n return K\n \n def Np2Var(self,X):\n X = X.astype(np.float32)\n X = torch.from_numpy(X)\n return X\n \n def cP2P(self,cP):\n cPnp = 0\n for i in range(self.ns):\n lb = i*(i+1)/2\n lb = int(lb)\n ub = (i+1)*(i+2)/2\n ub = int(ub)\n Di = cP[lb:ub]\n Di = np.diag(Di,self.ns-(i+1))\n cPnp += Di\n P = (cPnp.T)@cPnp\n return P\n \n \n def GetPdot(self,X,Ud,Xdp1):\n dX = Xdp1-X\n P = self.GetP(X)\n Pdot = 0\n dXdt = self.dynamics(0,X,Ud)\n for i in range(self.ns):\n dx = np.zeros(self.ns)\n dx[i] = dX[i]\n Pdot += (self.GetP(X+dx)-P)/np.linalg.norm(dx)*dXdt[i]\n return Pdot\n \n def dynamics(self,t,states,inputs):\n A = self.A\n B = self.GetB(states)\n Xv = np.transpose(np.array([states]))\n Uv = np.transpose(np.array([inputs]))\n dXdt = A.dot(Xv)+B.dot(Uv)\n dXdt = dXdt[:,0]\n return dXdt\n \n def GetB(self,states):\n m = self.m\n I = self.I\n l = self.l\n b = self.b\n th = states[2]\n T = np.array([[np.cos(th)/m,np.sin(th)/m,0],[-np.sin(th)/m,np.cos(th)/m,0],[0,0,1/2./I]])\n H = np.array([[-1,-1,0,0,1,1,0,0],[0,0,-1,-1,0,0,1,1],[-l,l,-b,b,-l,l,-b,b]])\n B = np.vstack((np.zeros((3,8)),T@H))\n return B\n \n def rk4(self,t,X,U):\n h = self.h\n k1 = self.dynamics(t,X,U)\n k2 = self.dynamics(t+h/2.,X+k1*h/2.,U)\n k3 = self.dynamics(t+h/2.,X+k2*h/2.,U)\n k4 = self.dynamics(t+h,X+k3*h,U)\n return t+h,X+h*(k1+2.*k2+2.*k3+k4)/6.\n\n def one_step_sim(self,t,X,U):\n runge_num = self.runge_num\n for num in range(0, runge_num):\n t,X = self.rk4(t,X,U)\n return t,X\n\n def GetCCM(self,alp):\n dt = self.dt\n epsilon = 0.\n XX = self.XXd\n N = XX.shape[0]-1\n I = np.identity(6)\n WW = {}\n for i in range(N+1):\n WW[i] = cp.Variable((6,6),PSD=True)\n nu = cp.Variable(nonneg=True)\n chi = cp.Variable(nonneg=True)\n constraints = [chi*I-WW[0] >> epsilon*I,WW[0]-I >> epsilon*I]\n for k in range(N):\n Xk = XX[k,:]\n Ax = self.A\n Bx = self.GetB(Xk)\n Wk = WW[k]\n Wkp1 = WW[k+1]\n constraints += [-2*alp*Wk-(-(Wkp1-Wk)/dt+Ax@Wk+Wk@Ax.T-2*nu*Bx@Bx.T) >> epsilon*I]\n constraints += [chi*I-Wkp1 >> epsilon*I,Wkp1-I >> epsilon*I]\n prob = cp.Problem(cp.Minimize(chi),constraints)\n prob.solve(solver=cp.MOSEK)\n cvx_status = prob.status\n print(cvx_status)\n WWout = {}\n MMout = {}\n for i in range(N+1):\n WWout[i] = WW[i].value/nu.value\n MMout[i] = np.linalg.inv(WWout[i])\n chi = chi.value\n nu = nu.value\n cvx_optval = chi/alp\n return cvx_status,cvx_optval,WWout,MMout,chi,nu\n\n def CLFQP(self,X,Xd,Xdp1,M,Ud,alp):\n dt = self.dt\n U = cp.Variable((8,1))\n Ud = np.array([Ud]).T\n p = cp.Variable((1,1))\n fmin = self.fmin\n fmax = self.fmax\n A = self.A\n Bx = self.GetB(X)\n Bxd = self.GetB(Xd)\n evec = np.array([X-Xd]).T\n Mdot = self.GetPdot(X,Ud,Xdp1)\n constraints = [evec.T@(Mdot+M@A+A.T@M)@evec+2*evec.T@M@Bx@U-2*evec.T@M@Bxd@Ud <= -2*alp*evec.T@M@evec+p]\n for i in range(8):\n constraints += [U[i,0] <= fmax, U[i,0] >= fmin]\n prob = cp.Problem(cp.Minimize(cp.sum_squares(U-Ud)+p**2),constraints)\n prob.solve()\n cvx_status = prob.status\n U = U.value\n U = np.ravel(U)\n return U\n\n def FinalTrajectory(self,MM,alp,XXdRCT,UUdRCT):\n dt = self.dt\n XXd = self.XXd\n UUd = self.UUd\n N = UUd.shape[0]\n X0 = XXd[0,:]\n B = self.GetB(X0)\n t = 0\n t1 = 0\n t2 = 0\n X1 = X0\n X2 = X0\n X3 = X0\n Xd = XXd[0,:]\n XdRCT = XXdRCT[0,:]\n this = np.zeros(N+1)\n X1his = np.zeros((N+1,X0.size))\n X2his = np.zeros((N+1,X0.size))\n X3his = np.zeros((N+1,X0.size))\n this[0] = t\n X1his[0,:] = X1\n U1his = np.zeros((N,B.shape[1]))\n X2his[0,:] = X2\n U2his = np.zeros((N,B.shape[1]))\n X3his[0,:] = X3\n U3his = np.zeros((N,B.shape[1]))\n U1hisN = np.zeros(N)\n U2hisN = np.zeros(N)\n U3hisN = np.zeros(N)\n U1hisND = np.zeros(N)\n U2hisND = np.zeros(N)\n U3hisND = np.zeros(N)\n dnMs = np.zeros(N)\n dnUs = np.zeros(N)\n dnXs = np.zeros(N)\n for i in range(N):\n M = MM[i]\n A = self.A\n Bx3 = self.GetB(X3)\n Q = 2.4*np.identity(6)\n R = 1*np.identity(8)\n K,P,E = control.lqr(A,Bx3,Q,R)\n P1 = self.GetP(X1)\n U3 = UUd[i,:]-Bx3.T@P@(X3-Xd)\n for j in range(8):\n if U3[j] >= self.fmax:\n U3[j] = self.fmax\n elif U3[j] <= self.fmin:\n U3[j] = self.fmin\n #U1 = self.CLFQP(X1,Xd,XXd[i+1,:],P,UUd[i,:],alp)\n U1 = self.CLFQP(X1,XdRCT,XXdRCT[i+1,:],P1,UUdRCT[i,:],alp)\n U2 = self.CLFQP(X2,XdRCT,XXdRCT[i+1,:],M,UUdRCT[i,:],alp)\n t,X1 = self.one_step_sim(t,X1,U1)\n t1,X2 = self.one_step_sim(t1,X2,U2)\n t2,X3 = self.one_step_sim(t2,X3,U3)\n Xd = XXd[i+1,:]\n XdRCT = XXdRCT[i+1,:]\n d1 = np.random.choice(np.array([-1,1]),1)[0]\n d2 = np.random.choice(np.array([-1,1]),1)[0]\n d3 = np.random.choice(np.array([-1,1]),1)[0]\n d1 = np.array([0,0,0,d1,d2,d3])*2\n #d1 = 0\n #d1 = np.hstack((np.zeros(3),(np.random.rand(3)*2-1)))*dratio*20\n #d1 = (np.random.rand(6)*2-1)*0.1\n X1 = X1+d1*dt\n X2 = X2+d1*dt\n X3 = X3+d1*dt\n this[i+1] = t\n X1his[i+1,:] = X1\n U1his[i,:] = U1\n X2his[i+1,:] = X2\n U2his[i,:] = U2\n X3his[i+1,:] = X3\n U3his[i,:] = U3\n U1hisN[i] = np.linalg.norm(U1)\n U2hisN[i] = np.linalg.norm(U2)\n U3hisN[i] = np.linalg.norm(U3)\n U1hisND[i] = np.linalg.norm(U1-UUd[i,:])\n U2hisND[i] = np.linalg.norm(U2-UUdRCT[i,:])\n U3hisND[i] = np.linalg.norm(U3-UUdRCT[i,:])\n dnMs[i] = np.linalg.norm(M-P1,ord=2)\n dnUs[i] = np.linalg.norm(U1-U2)\n dnXs[i] = np.linalg.norm(X1-X2)\n return this,X1his,U1his,X2his,U2his,X3his,U3his,U1hisN,U2hisN,U3hisN,U1hisND,U2hisND,U3hisND,dnMs,dnUs,dnXs\n\ndef Rot2d(th):\n R = np.array([[np.cos(th),-np.sin(th)],[np.sin(th),np.cos(th)]])\n return R\n \ndef GetTubePlot(XXdRCT,alp,chi,d_over,th):\n Rtube = d_over*np.sqrt(chi)/alp\n xxdRCT = XXdRCT[:,0:2]\n dxxdRCT = np.diff(xxdRCT,axis=0)\n for i in range(dxxdRCT.shape[0]):\n dxxdRCT[i,:] = Rot2d(th)@(dxxdRCT[i,:]/np.linalg.norm(dxxdRCT[i,:]))\n return xxdRCT[0:dxxdRCT.shape[0],:]+dxxdRCT*Rtube\n\ndef SaveDict(filename,var):\n output = open(filename,'wb')\n pickle.dump(var,output)\n output.close()\n pass\n \ndef LoadDict(filename):\n pkl_file = open(filename,'rb')\n varout = pickle.load(pkl_file)\n pkl_file.close()\n return varout\n\nif __name__ == \"__main__\":\n sc = Spacecraft(XXd0,UUd0)\n alp = np.load('data/params/alpha_mmicro/alp.npy')\n XXdRCT = np.load('data/params/desiredRCT/XXdRCT.npy')\n UUdRCT = np.load('data/params/desiredRCT/UUdRCT.npy')\n np.random.seed(seed=32)\n cvx_status,cvx_optval,WW,MM,chi,nu = sc.GetCCM(alp)\n this,X1his,U1his,X2his,U2his,X3his,U3his,U1hisN,U2hisN,U3hisN,U1hisND,U2hisND,U3hisND,dnMs,dnUs,dnXs = sc.FinalTrajectory(MM,alp,XXdRCT,UUdRCT)\n xxTube1 = GetTubePlot(XXdRCT,alp,chi,d_over,np.pi/2)\n xxTube2 = GetTubePlot(XXdRCT,alp,chi,d_over,-np.pi/2)\n Nplot = xxTube1.shape[0]\n plt.figure()\n plt.plot(X1his[:,0],X1his[:,1])\n plt.plot(X2his[:,0],X2his[:,1])\n plt.plot(X3his[:,0],X3his[:,1])\n #plt.plot(xxTube1[:,0],xxTube1[:,1])\n #plt.plot(xxTube2[:,0],xxTube2[:,1])\n plt.plot(XXdRCT[:,0],XXdRCT[:,1],'--k')\n plt.fill_between(xxTube1[:,0],xxTube1[:,1],np.zeros(Nplot),facecolor='black',alpha=0.2)\n plt.fill_between(xxTube2[:,0],xxTube2[:,1],np.zeros(Nplot),facecolor='white')\n plt.fill_between(np.linspace(19.347,22,100),16.9*np.ones(100),np.zeros(100),facecolor='white')\n plt.fill_between(np.linspace(-1.03228,1.03228,100),-0.2*np.ones(100),np.zeros(100),facecolor='black',alpha=0.2)\n for i in range(XOBSs.shape[0]):\n x,y=[],[]\n for _x in np.linspace(0,2*np.pi):\n x.append(Robs*np.cos(_x)+XOBSs[i,0])\n y.append(Robs*np.sin(_x)+XOBSs[i,1])\n plt.plot(x,y,'k')\n plt.axes().set_aspect('equal')\n plt.show()\n \n \n data1 = {'score': U1hisN}\n data2 = {'score': U2hisN}\n data3 = {'score': U3hisN}\n # Create dataframe\n df1 = pd.DataFrame(data1)\n df2 = pd.DataFrame(data2)\n df3 = pd.DataFrame(data3)\n dfU1hisN = df1.rolling(window=50).mean()\n dfU2hisN = df2.rolling(window=50).mean()\n dfU3hisN = df3.rolling(window=50).mean()\n \n plt.figure()\n plt.plot(this[0:500],np.cumsum(U1hisN**2)*DT)\n plt.plot(this[0:500],np.cumsum(U2hisN**2)*DT)\n plt.plot(this[0:500],np.cumsum(U3hisN**2)*DT)\n plt.show()\n \n plt.figure()\n plt.plot(this[0:500],U1hisND)\n plt.plot(this[0:500],U2hisND)\n plt.plot(this[0:500],U3hisND)\n plt.show()\n \n plt.figure()\n plt.plot(this[0:500],U1his)\n plt.plot(this[0:500],U2his)\n plt.plot(this[0:500],U3his)\n plt.show()\n \n this,X1his,U1his,X2his,U2his,X3his,U3his,U1hisN,U2hisN,U3hisN,U1hisND,U2hisND,U3hisND\n np.save('data/simulation/this.npy',this)\n np.save('data/simulation/X1his.npy',X1his)\n np.save('data/simulation/U1his.npy',U1his)\n np.save('data/simulation/X2his.npy',X2his)\n np.save('data/simulation/U2his.npy',U2his)\n np.save('data/simulation/X3his.npy',X3his)\n np.save('data/simulation/U3his.npy',U3his)\n np.save('data/simulation/U1hisN.npy',U1hisN)\n np.save('data/simulation/U2hisN.npy',U2hisN)\n np.save('data/simulation/U3hisN.npy',U3hisN)\n np.save('data/simulation/U1hisND.npy',U1hisND)\n np.save('data/simulation/U2hisND.npy',U2hisND)\n np.save('data/simulation/U3hisND.npy',U3hisND)\n np.save('data/simulation/xxTube1.npy',xxTube1)\n np.save('data/simulation/xxTube2.npy',xxTube2)\n '''\n dnMs_ave = []\n dnUs_ave = []\n dnXs_ave = []\n for r in range(100):\n np.random.seed(seed=r)\n this,X1his,U1his,X2his,U2his,X3his,U3his,U1hisN,U2hisN,U3hisN,U1hisND,U2hisND,U3hisND = sc.FinalTrajectory(MM,alp,XXdRCT,UUdRCT)\n np.sum(dnMs)*dT/TSPAN[1]\n '''","sub_path":"sourcecodes/motionplan/Simulationb.py","file_name":"Simulationb.py","file_ext":"py","file_size_in_byte":12790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125739783","text":"\"\"\"\nThe module is designed by team Robokit of Phystech Lyceum and team Starkit\nof MIPT under mentorship of Azer Babaev.\nThe module is designed for strategy of soccer game by forward and goalkeeper.\n\"\"\"\n\nimport time\nimport logging\nfrom gcreceiver import ThreadedGameStateReceiver\nfrom Soccer.Localisation.class_Glob import Glob\nfrom Soccer.Localisation.class_Local import *\nfrom Soccer.strategy import Player\nfrom Soccer.Motion.class_Motion_Webots_PB import Motion_sim\n\n\ndef init_gcreceiver(team, player, is_goalkeeper):\n \"\"\"\n The function creates and object receiver of Game Controller messages. Game Controller messages are broadcasted to \n teams and to referee. Format of messages can be seen in module gamestate.py. Messages from Game Controller \n contains Robot info, Team info and Game state info.\n usage of function:\n object: receiver = init_gcreceiver(int: team, int: player, bool: is_goalkeeper)\n team - number of team id. For junior competitions it is recommended to use unique id\n for team in range 60 - 127\n player - number of player displayed at his trunk\n is_goalkeeper - True if player is appointed to play role of goalkeeper\n \"\"\"\n receiver = ThreadedGameStateReceiver(team, player, is_goalkeeper) \n receiver.start() # Strat receiving and answering\n return receiver\n\ndef player_super_cycle(falling, team_id, robot_color, player_number, SIMULATION, current_work_directory, robot, pause, logger):\n \"\"\"\n The function is called player_super_cycle because during game player can change several roles. Each role\n appointed to player put it into cycle connected to playing it's role. Cycles of roles are defined in strategy.py\n module. player_super_cycle is cycle of cycles. For example player playing role of 'forward' can change role to\n 'penalty_shooter' after main times and extra times of game finished. In some situations you may decide to switch\n roles between forward player and goalkeeper. \n Usage:\n player_super_cycle(object: falling, int: team_id, str: robot_color, int: player_number, int: SIMULATION,\n Path_object: current_work_directory, object: robot, object: pause)\n falling - class object which contains int: falling.Flag which is used to deliver information about falling from\n low level logic to high level logic. falling.Flag can take \n 0 - nothing happend, 1 -falling on stomach, -1 - falling face up,\n 2 - falling to left, -2 - falling to right, 3 - exit from playing fase\n team_id - can take value from 60 to 127\n robot_color - can be 'red' or 'blue'\n player_number - can be from 1 to 5, with 1 to be assigned to goalkeeper\n SIMULATION - used for definition of simulation enviroment. value 4 is used for Webots simulation,\n value 2 is used for playing in real robot\n current_work_directory - is Path type object \n robot - object of class which is used for communication between robot model in simulation and controller\n program. In case of external controller program 'ProtoBuf' communication manager is used. \n 'ProtoBuf' - is protocol developed by Google.\n pause - object of class Pause which contains pause.Flag boolean variable. It is used to transfer pressing \n pause button on player's dashboard event to player's high level logic. \n\n\n \"\"\"\n with open('../referee/game.json', \"r\") as f: # extracting data from game.json file which have \n game_data = json.loads(f.read()) # to be created by human referee\n\n with open('../referee/' + game_data[ robot_color]['config'], \"r\") as f: # extracting data from team.json file \n team_data = json.loads(f.read())\n \n # below 4 lines are initial coordinates of players depending on game fase\n initial_coord_goalkeeper = team_data['players']['1']['readyStartingPose']['pf_coord'] \n initial_coord_forward = team_data['players']['2']['readyStartingPose']['pf_coord']\n initial_coord_goalkeeper_at_penalty = team_data['players']['1']['goalKeeperStartingPose']['pf_coord']\n initial_coord_forward_at_penalty = team_data['players']['2']['shootoutStartingPose']['pf_coord']\n if player_number == 1: is_goalkeeper = True\n else: is_goalkeeper = False\n receiver = init_gcreceiver(team_id, player_number, is_goalkeeper)\n robot.receiver = receiver\n former_game_state = 'STATE_SET'\n former_player_penalty = 0\n logger.info('waiting for game controller launch')\n playing_allowed = False\n current_secondary_state = None\n while True: # this is main cycle of supercycle\n #if receiver.team_state == None:\n # if current_secondary_state == 'STATE_PENALTYSHOOT':\n # print('simulator reset')\n # robot.simulationReset()\n seconds = 0\n while True:\n if receiver.team_state == None:\n if seconds == 0:\n message = '\\n Game Controller is not launched. Waiting..'\n logger.info(message)\n else:\n print('.', end = '')\n seconds += 1\n else: \n break\n time.sleep(1)\n seconds = 0\n while True:\n if receiver.team_state != None:\n if receiver.state.game_state == 'STATE_INITIAL':\n former_game_state = 'STATE_INITIAL'\n if seconds == 0:\n message = '\\n Game Controller STATE_INITIAL. Waiting for READY..'\n logger.info(message)\n else:\n print('.', end = '')\n seconds += 1\n else:\n break\n #robot.step(200)\n time.sleep(0.2)\n seconds = 0\n while True:\n if receiver.team_state != None:\n if receiver.state.game_state == 'STATE_READY':\n former_game_state = 'STATE_READY'\n if seconds == 0:\n message = '\\n Game Controller STATE_READY. Waiting for SET..'\n logger.info(message)\n else:\n print('.', end = '')\n seconds += 1\n else:\n break\n #robot.step(200)\n time.sleep(0.2)\n seconds = 0\n while True:\n if receiver.team_state != None:\n if receiver.state.game_state == 'STATE_SET':\n former_game_state = 'STATE_SET'\n if seconds == 0:\n message = '\\n Game Controller STATE_SET. Waiting for PLAYING..'\n logger.info(message)\n else:\n print('.', end = '')\n seconds += 1\n else:\n break\n #robot.step(200)\n time.sleep(0.2)\n if receiver.team_state != None:\n current_game_state = receiver.state.game_state\n current_secondary_state = receiver.state.secondary_state\n current_player_penalty = receiver.player_state.penalty\n if current_game_state == 'STATE_PLAYING' and current_secondary_state != 'STATE_PENALTYSHOOT' and current_player_penalty== 0:\n second_pressed_button = 1\n logger.info('start playing')\n if former_game_state == 'STATE_SET':\n if receiver.state.kick_of_team != receiver.team_state.team_number:\n second_pressed_button = 4\n logger.info('former_game_state == \"STATE_SET\"')\n if player_number == 1:\n initial_coord = initial_coord_goalkeeper\n if receiver.team_state.team_color == 'BLUE':\n role = 'goalkeeper_old_style'\n else:\n role = 'goalkeeper'\n playing_allowed = True\n logger.info('playing allowed')\n else: \n initial_coord = initial_coord_forward\n if receiver.team_state.team_color == 'BLUE':\n role = 'forward_old_style'\n else:\n role = 'forward'\n playing_allowed = True\n logger.info('playing allowed')\n if former_player_penalty !=0:\n statement1 = 2* (player_number == 1) - 1\n statement2 = 2* (receiver.state.first_half) - 1\n statement3 = 2* (receiver.team_state.team_color == 'RED') -1\n statement4 = 2* (game_data['side_left'] == game_data['blue']['id']) - 1\n if statement1 * statement2 * statement3 * statement4 == 1:\n initial_coord = [-0.9, 1.3, -math.pi/2]\n else:\n initial_coord = [-0.9, -1.3, math.pi/2]\n playing_allowed = True\n second_pressed_button = 1\n logger.info('playing allowed')\n elif current_game_state == 'STATE_PLAYING' and current_secondary_state == 'STATE_PENALTYSHOOT' and current_player_penalty== 0:\n second_pressed_button = 1\n #print('start playing')\n if former_game_state == 'STATE_SET':\n logger.info('former_game_state == \"STATE_SET\"')\n if player_number == 1:\n initial_coord = initial_coord_goalkeeper_at_penalty\n #if receiver.team_state.team_color == 'BLUE':\n # role = 'goalkeeper_old_style'\n #else:\n role = 'penalty_Goalkeeper'\n playing_allowed = True\n logger.info('playing allowed')\n else: \n initial_coord = initial_coord_forward_at_penalty\n #if receiver.team_state.team_color == 'BLUE':\n # role = 'forward_old_style'\n #else:\n role = 'penalty_Shooter'\n playing_allowed = True\n logger.info('playing allowed')\n if playing_allowed:\n logger.info ('current_game_state =' + str(current_game_state) + ' current_player_penalty =' + str(current_player_penalty))\n logger.info ('former_game_state ='+ str(former_game_state) + ' former_player_penalty =' + str(former_player_penalty))\n glob = Glob(SIMULATION, current_work_directory)\n glob.pf_coord = initial_coord\n motion = Motion_sim(glob, robot, receiver, pause, logger)\n motion.sim_Start()\n motion.direction_To_Attack = -initial_coord[2]\n motion.activation()\n local = Local(logger, motion, glob, coord_odometry = initial_coord)\n motion.local = local\n local.coordinate_record()\n motion.falling_Flag = 0\n player = Player(logger, role, second_pressed_button, glob, motion, local)\n player.play_game()\n playing_allowed = False\n former_game_state = receiver.state.game_state\n former_player_penalty = receiver.player_state.penalty\n time.sleep(0.02)\n\n\n\n\n\n\n","sub_path":"controllers/SAMPLE_TEAM/launcher_pb.py","file_name":"launcher_pb.py","file_ext":"py","file_size_in_byte":11708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"406916397","text":"# encoding=utf-8\nfrom GRU import GRU\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pandas as pd\nfrom random import shuffle\n\n\nclass GANFD():\n def __init__(self, timeStep, hiddenUnit, GeneratorInputSize, GeneratorOutputSize,\n discriminatorInputSize, dim, c=0.01, learningRate=0.00001, k=1, epochs=50,\n outputGraph=False, **kwargs):\n self.timeStep = timeStep\n self.hiddenUnit = hiddenUnit\n self.genInputSize = GeneratorInputSize\n self.genOutputSize = GeneratorOutputSize\n\n self.disInputSize = discriminatorInputSize\n self.dim = dim\n self.c = c\n self.lr = learningRate\n self.k = k\n self.epochs = epochs\n\n self.my_config = tf.ConfigProto()\n self.my_config.log_device_placement = False # 输出设备和tensor详细信息\n self.my_config.gpu_options.allow_growth = True # 基于运行需求分配显存(自动增长)\n\n self.graph = tf.Graph()\n self.KD = 3 # of discrim updates for each gen update\n self.KG = 1 # of discrim updates for each gen update\n self.ncandi = 1 # 种群大小\n self.beta = 0.0005\n self.nloss = 3 # 生成器三种loss类型\n self.loss = ['trickLogD', 'minimax', 'ls']\n\n\n\n with self.graph.as_default():\n self.buildModel()\n\n if outputGraph:\n with tf.Session(graph=self.graph, config=self.my_config).as_default() as sess:\n with self.graph.as_default():\n tf.summary.FileWriter('logs/', sess.graph)\n\n def get_all_step_index(self, batchLen):\n id_index = []\n for epoch in range(self.epochs):\n id = [i for i in range(batchLen)]\n shuffle(id)\n id_index.append(id)\n id_index = np.reshape(id_index, -1)\n id_len = len(id_index)\n id_len_reminder = id_len % 3\n id_len_division = int(id_len / 3)\n if (id_len_reminder == 0):\n step_index = np.reshape(id_index, (id_len_division, 3)).tolist()\n else:\n first_id_index = id_index[0: id_len_reminder]\n step_index = np.reshape(id_index[id_len_reminder:], (id_len_division, 3)).tolist()\n step_index.insert(0, first_id_index.tolist())\n\n return step_index, len(step_index)\n\n def generator(self, generatorInput):\n lstm = GRU(rnn_unit = self.hiddenUnit, input_size = self.genInputSize,\n output_size = self.genOutputSize, X=generatorInput)\n # lstm.pred (None, 20, 1.2.1.2)\n # print('111')\n # print(lstm.pred)\n # print(lstm.pred[:, -1.2.1.2, tf.newaxis])\n # print(self.realData[:, :-1.2.1.2, :])\n\n # (None, 21, 1.2.1.2)\n # print(fakeData)\n return lstm.pred\n\n def discriminator(self, disInput):\n with tf.name_scope('layer1'):\n conv1 = tf.layers.conv1d(disInput, filters=self.dim, kernel_size=5, strides=2,\n padding='SAME', name='conv1')\n\n conv1Lr = tf.nn.leaky_relu(tf.layers.batch_normalization(conv1))\n # (None, 11, dim)\n # print(conv1Lr)\n\n with tf.name_scope('layer2'):\n conv2 = tf.layers.conv1d(conv1Lr, filters=self.dim * 2, kernel_size=5, strides=2,\n padding='SAME', name='conv2')\n\n conv2Lr = tf.nn.leaky_relu(tf.layers.batch_normalization(conv2))\n # (None, 6, 2 * dim)\n # print(conv2Lr)\n\n with tf.name_scope('layer3'):\n conv3 = tf.layers.conv1d(conv2Lr, filters=self.dim * 4, kernel_size=5, strides=2,\n padding='valid', name='conv3')\n conv3Lr = tf.nn.leaky_relu(tf.layers.batch_normalization(conv3))\n # (None, 1.2.1.2, 4 * dim)\n # print(conv3Lr)\n\n with tf.name_scope('fc1'):\n fc1 = tf.layers.dense(conv3Lr, self.dim * 2, activation=tf.nn.leaky_relu, name='fc1')\n # (None, 1.2.1.2, dim * 2)\n # print(fc1)\n\n with tf.name_scope('fc2'):\n fc2 = tf.layers.dense(fc1, self.dim, activation=tf.nn.leaky_relu, name='fc2')\n # (None, 1.2.1.2, dim)\n # print(fc2)\n\n with tf.name_scope('output'):\n output = tf.nn.sigmoid(tf.layers.dense(fc2, 1), name='output')\n # (None, 1.2.1.2, 1.2.1.2)\n # print(output)\n\n return output\n\n def buildModel(self):\n self.genInput = tf.placeholder(tf.float32, [None, self.timeStep - 1, self.genInputSize],\n name='GeneratorInput')\n\n self.realData = tf.placeholder(tf.float32, [None, self.timeStep, self.disInputSize],\n name='realData')\n\n with tf.variable_scope(\"Discriminator\", reuse=False):\n self.dLogitsReal = self.discriminator(self.realData)\n\n self.realOut = tf.reduce_mean(self.dLogitsReal)\n\n self.pReal = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=self.dLogitsReal, labels=tf.ones_like(self.dLogitsReal)), name='realLoss')\n\n # self.pReal = -tf.reduce_mean(tf.multiply(tf.ones_like(self.dLogitsReal), tf.log(self.dLogitsReal)) +\n # tf.multiply((1.-tf.ones_like(self.dLogitsReal)), tf.log(1.-self.dLogitsReal)),\n # name='realLoss')\n\n with tf.variable_scope('Generator', reuse=False):\n self.predictValue = self.generator(self.genInput)\n\n self.fakeData = tf.concat((self.realData[:, :-1, :], self.predictValue[:, -1, tf.newaxis]), axis=1, name='fakeData')\n # print(self.predictValue)\n with tf.variable_scope(\"Discriminator\", reuse=True):\n self.dLogitsFake = self.discriminator(self.fakeData)\n\n self.fakeOut = tf.reduce_mean(self.dLogitsFake)\n # self.pGen = tf.reduce_mean(self.dLogitsFake, name='fakeLoss')\n\n self.pGen = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=self.dLogitsFake, labels=tf.zeros_like(self.dLogitsFake)), name='fakeLoss')\n\n # self.pGen = -tf.reduce_mean(tf.multiply(tf.zeros_like(self.dLogitsFake), tf.log(self.dLogitsFake))+\n # tf.multiply((1.-tf.zeros_like(self.dLogitsFake)), tf.log(1.-self.dLogitsFake)),\n # name='fakeLoss')\n\n self.squareLoss = tf.reduce_mean(\n tf.square(tf.reshape(self.realData, [-1]) - tf.reshape(self.fakeData, [-1]))) # 文中公式(4)\n\n self.directLoss = tf.reduce_mean(tf.abs(\n tf.sign(self.fakeData[:, -1, :] - self.realData[:, -2, :]) - # 文中公式(5)\n tf.sign(self.realData[:, -1, :] - self.realData[:, -2, :]))) # 这一段代码好好检查一下逻辑有没有错误\n\n self.dLoss = self.pReal + self.pGen\n # self.dLoss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dLogitsReal,\n # labels=tf.ones_like(self.dLogitsReal)) +\n # tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dLogitsFake,\n # labels=tf.zeros_like(self.dLogitsFake)),\n # name='dLoss')\n\n self.gLoss_trickLogD = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=self.dLogitsFake, labels=tf.ones_like(self.dLogitsFake))) # + self.squareLoss + self.directLoss\n self.gLoss_minimax = -tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=self.dLogitsFake,\n labels=tf.zeros_like(self.dLogitsFake))) # + self.squareLoss + self.directLoss\n\n self.gLoss_ls = tf.reduce_mean(tf.square(self.dLogitsFake-1.)) # + self.squareLoss + self.directLoss\n\n # self.gLoss_trickLogD = -tf.reduce_mean(tf.multiply(tf.ones_like(self.dLogitsFake), tf.log(self.dLogitsFake)))\n # self.gLoss_minimax = tf.reduce_mean(tf.multiply(1., tf.log(1.-self.dLogitsFake)))\n\n\n TVars = tf.trainable_variables()\n self.GVars = [var for var in TVars if var.name.startswith('Generator')]\n self.DVars = [var for var in TVars if var.name.startswith('Discriminator')]\n\n self.Gweight = []\n self.Gweight_value = []\n\n for i in range(len(self.GVars)):\n self.Gweight.append(tf.placeholder(tf.float32, self.GVars[i].shape.as_list()))\n self.Gweight_value.append(tf.assign(self.GVars[i], self.Gweight[i]))\n\n self.clipD = [p.assign(tf.clip_by_value(p, -self.c, self.c)) for p in self.DVars]\n\n self.dOptim = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(self.dLoss, var_list=self.DVars)\n\n self.gOptim_ls = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(self.gLoss_ls, var_list=self.GVars)\n self.gOptim_minimax = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(self.gLoss_minimax, var_list=self.GVars)\n self.gOptim_trickLogD = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(self.gLoss_trickLogD, var_list=self.GVars)\n\n # 计算FD分数\n self.FD = tf.gradients(ys=self.dLoss, xs=self.DVars)\n self.grad_sum = [tf.reduce_sum(tf.square(x))for x in self.FD]\n self.Fd_score = self.beta * tf.log(tf.reduce_sum(self.grad_sum))\n\n def trainAndPredict(self, data, dataProcessor, day):\n \"\"\"\n 传入的需要参与到训练的数据,使得模型进行训练\n :param data:\n :param dataProcessor:\n :return:\n \"\"\"\n # print(np.array(data))\n\n \"\"\"\n data : 为正则化后的数据\n indicators 去除最后一列之后为Generator的输入\n realData 为真实数据,作为Dis的一个输入,是data 的最后一列\n \"\"\"\n\n # print(data[-25:, :])\n # print(data.shape)\n batchIndex, indicators, realData = dataProcessor.getTrainData(data)\n batchLen = len(batchIndex)-1\n genInputs = np.array(indicators)[:, :-1, :] # batch\n testInput = np.array(indicators)[np.newaxis, -1, 1:, :] # batch 种的最后一个timestep\n # print(testInput)\n # print(testInput.shape)\n\n trainHist = {}\n trainHist['DLoss'] = []\n trainHist['GLoss'] = []\n trainHist['pReal'] = []\n trainHist['pFake'] = []\n\n gen_new_params = []\n gen_tem_param = []\n population_param = []\n GLosses, DLosses, pReal, pFake = [], [], [], []\n n_updates = 0\n\n with tf.Session(graph=self.graph, config=self.my_config).as_default() as self.sess:\n with self.graph.as_default():\n\n # 初始化参数\n for i in range(1, 11):\n self.sess.run(tf.global_variables_initializer())\n Gvar_value = self.sess.run(self.GVars)\n gen_tem_param.append(Gvar_value)\n if i % 10 == 0:\n gen_new_params.append(np.mean(gen_tem_param, axis=0))\n\n # get all step_index\n step_index, step_index_len = self.get_all_step_index(batchLen)\n epoch = 1\n\n for st_index in range(step_index_len):\n print('day %d Epoch %d of %d' % (day, epoch, self.epochs))\n genIn, real = [], []\n for i in range(len(step_index[st_index])):\n step = step_index[st_index][i]\n genIn.append(genInputs[batchIndex[step]: batchIndex[step + 1]])\n real.append(np.array(realData[batchIndex[step]: batchIndex[step + 1]]))\n # 在batchIndex[step]: batchIndex[step +1] 处理成多个\n if st_index == 0:\n self.sess.run([self.Gweight_value[0],\n self.Gweight_value[1],\n self.Gweight_value[2],\n self.Gweight_value[3]],\n feed_dict={self.Gweight[0]: gen_new_params[0][0],\n self.Gweight[1]: gen_new_params[0][1],\n self.Gweight[2]: gen_new_params[0][2],\n self.Gweight[3]: gen_new_params[0][3],\n })\n for can_i in range(0, self.ncandi):\n for step in range(len(step_index[st_index])):\n _, gLossVal, pFakeVal = self.sess.run([self.gOptim_trickLogD,\n self.gLoss_trickLogD,\n self.pGen],\n feed_dict={\n self.genInput: genIn[step],\n self.realData: real[step]\n })\n gen_new_params[can_i] = self.sess.run(self.GVars)\n\n else:\n gen_old_params = gen_new_params\n for can_i in range(0, self.ncandi):\n frScore = []\n for type_i in range(self.nloss):\n self.sess.run([self.Gweight_value[0],\n self.Gweight_value[1],\n self.Gweight_value[2],\n self.Gweight_value[3]],\n feed_dict={self.Gweight[0]: gen_old_params[can_i][0],\n self.Gweight[1]: gen_old_params[can_i][1],\n self.Gweight[2]: gen_old_params[can_i][2],\n self.Gweight[3]: gen_old_params[can_i][3]})\n\n if self.loss[type_i] == 'trickLogD':\n _, gLossVal = self.sess.run([self.gOptim_trickLogD, self.gLoss_trickLogD],\n feed_dict={self.genInput: genIn[type_i],\n self.realData: real[type_i]})\n elif self.loss[type_i] == 'minimax':\n _, gLossVal = self.sess.run([self.gOptim_minimax, self.gLoss_minimax],\n feed_dict={self.genInput: genIn[type_i],\n self.realData: real[type_i]})\n elif self.loss[type_i] == 'ls':\n _, gLossVal = self.sess.run([self.gOptim_ls, self.gLoss_ls],\n feed_dict={self.genInput: genIn[type_i],\n self.realData: real[type_i]})\n # 计算适应度函数值\n fr_score, fd_score, dlossvalue, pFakeVal, gradSum, = self.sess.run(\n [self.fakeOut, self.Fd_score, self.dLoss, self.pGen, self.grad_sum, ],\n feed_dict={\n self.genInput: genIn[type_i],\n self.realData: real[type_i]\n })\n frScore.append(fr_score)\n # print(gradSum[0:6])\n # print(gradSum[6:12])\n # print(gradSum[12:18])\n # print(len(gradSum))\n print(\"gloss: %r ,Fq : %r, fd : %r, dloss : %r\" % (gLossVal, fr_score, fd_score, dlossvalue))\n\n fit = fr_score - fd_score\n\n if can_i * self.nloss + type_i < self.ncandi:\n idx = can_i * self.nloss + type_i\n fitness[idx] = fit\n fake_rate[idx] = fr_score\n gen_new_params[idx] = self.sess.run(self.GVars)\n else:\n fit_com = fitness - fit\n if min(fit_com) < 0:\n ids_replace = np.where(fit_com == min(fit_com))\n idr = ids_replace[0][0]\n fitness[idr] = fit\n fake_rate[idr] = fr_score\n gen_new_params[idr] = self.sess.run(self.GVars)\n\n if frScore[0] < 5*1e-5 and frScore[1] < 5*1e-5 and frScore[2] < 5*1e-5:\n return _, True\n\n print(\"epoch: %d,fake_rate:%r,fitness:%r\" % (epoch, fake_rate, fitness))\n\n # train Discriminator\n for step in range(len(step_index[st_index])):\n _, dLossVal, pRealVal = self.sess.run([self.dOptim, self.dLoss, self.pReal],\n feed_dict={\n self.genInput: genIn[step],\n self.realData: real[step]\n })\n\n for i in range(0, self.ncandi):\n tr, fr, fd = self.sess.run([self.realOut, self.fakeOut, self.Fd_score],\n feed_dict={\n self.genInput: genIn[0],\n self.realData: real[0]\n })\n if i == 0:\n fake_rate = np.array([fr])\n fitness = np.array([0.])\n real_rate = np.array([tr])\n FDL = np.array([fd])\n else:\n fake_rate = np.append(fake_rate, fr)\n fitness = np.append(fitness, [0.])\n real_rate = np.append(real_rate, tr)\n FDL = np.append(FDL, fd)\n\n print(\"real_rate: %f, fake_rate : %f, FDL :%f\" % (real_rate, fake_rate, FDL))\n\n # sess.run(self.clipD)\n\n GLosses.append(gLossVal)\n DLosses.append(dLossVal)\n pReal.append(pRealVal)\n pFake.append(pFakeVal)\n\n for _ in range(len(step_index[st_index])):\n n_updates += 1\n if (n_updates % (batchLen) == 0):\n epoch += 1\n trainHist['DLoss'].append(np.mean(DLosses))\n trainHist['GLoss'].append(np.mean(GLosses))\n trainHist['pReal'].append(np.mean(pReal))\n trainHist['pFake'].append(np.mean(pFake))\n GLosses, DLosses, pReal, pFake = [], [], [], []\n\n\n if not os.path.isdir('./loss_GRU_GAN/'):\n os.mkdir('./loss_GRU_GAN/')\n\n if not os.path.isdir('./loss_GRU_GAN/%d/' % day):\n os.mkdir('./loss_GRU_GAN/%d/' % day)\n\n dataframe = pd.DataFrame({'real': trainHist['pReal'], 'fake': trainHist['pFake']})\n dataframe.to_csv('./loss_GRU_GAN/%d/realFakeLoss.csv' % day, index=False, sep=',')\n\n dataframe = pd.DataFrame({'D': trainHist['DLoss'], 'G': trainHist['GLoss']})\n dataframe.to_csv('./loss_GRU_GAN/%d/GANLoss.csv' % day, index=False, sep=',')\n\n # 至此模型的训练以及相关数据的保存已经完毕,接下来预测后一天的价格\n price = self.sess.run(self.predictValue,\n feed_dict={self.genInput: testInput})\n\n return price, False\n\n\nif __name__ == '__main__':\n para = dict(timeStep=21, hiddenUnit=32, GeneratorInputSize=13, GeneratorOutputSize=1,\n discriminatorInputSize=1, dim=16, c=0.01, learningRate=0.00001, epochs=5, outputGraph=True)\n model = GANFD(**para)\n model.trainAndPredict()","sub_path":"GAN_2/GRU+GAN/ALEGANFD_GRU.py","file_name":"ALEGANFD_GRU.py","file_ext":"py","file_size_in_byte":21101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"428059445","text":"# coding: utf-8\nimport os\nimport mxnet as mx\nimport numpy as np\nimport math\nimport cv2\nfrom multiprocessing import Pool\nfrom itertools import repeat\n#from itertools import izip \nfrom helper import nms, adjust_input, generate_bbox, detect_first_stage_warpper, detect_first_stage\n\n\nclass MtcnnDetector(object):\n \"\"\"\n Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Neural Networks\n see https://github.com/kpzhang93/MTCNN_face_detection_alignment\n this is a mxnet version\n \"\"\"\n def __init__(self,\n model_folder='.',\n minsize = 30,\n threshold = [0.7, 0.7, 0.8],\n factor = 0.709,\n num_worker = 1,\n accurate_landmark = False,\n ctx=mx.cpu()):\n \"\"\"\n Initialize the detector\n\n Parameters:\n ----------\n model_folder : string\n path for the models\n minsize : float number\n minimal face to detect\n threshold : float number\n detect threshold for 3 stages\n factor: float number\n scale factor for image pyramid\n num_worker: int number\n number of processes we use for first stage\n accurate_landmark: bool\n use accurate landmark localization or not\n\n \"\"\"\n self.num_worker = num_worker\n self.accurate_landmark = accurate_landmark\n\n # load 4 models from folder\n models = ['det1', 'det2', 'det3','det4']\n models = [ os.path.join(model_folder, f) for f in models]\n \n self.PNets = []\n for i in range(num_worker):\n workner_net = mx.model.FeedForward.load(models[0], 1, ctx=ctx)\n self.PNets.append(workner_net)\n\n self.Pool = Pool(num_worker)\n\n self.RNet = mx.model.FeedForward.load(models[1], 1, ctx=ctx)\n self.ONet = mx.model.FeedForward.load(models[2], 1, ctx=ctx)\n self.LNet = mx.model.FeedForward.load(models[3], 1, ctx=ctx)\n \n self.minsize = float(minsize)\n self.factor = float(factor)\n self.threshold = threshold\n \n def convert_to_square(self, bbox):\n \"\"\"\n convert bbox to square\n\n Parameters:\n ----------\n bbox: numpy array , shape n x 5\n input bbox\n\n Returns:\n -------\n square bbox\n \"\"\"\n square_bbox = bbox.copy()\n\n h = bbox[:, 3] - bbox[:, 1] + 1\n w = bbox[:, 2] - bbox[:, 0] + 1\n max_side = np.maximum(h,w)\n square_bbox[:, 0] = bbox[:, 0] + w*0.5 - max_side*0.5\n square_bbox[:, 1] = bbox[:, 1] + h*0.5 - max_side*0.5\n square_bbox[:, 2] = square_bbox[:, 0] + max_side - 1\n square_bbox[:, 3] = square_bbox[:, 1] + max_side - 1\n return square_bbox\n\n def calibrate_box(self, bbox, reg):\n \"\"\"\n calibrate bboxes\n\n Parameters:\n ----------\n bbox: numpy array, shape n x 5\n input bboxes\n reg: numpy array, shape n x 4\n bboxex adjustment\n\n Returns:\n -------\n bboxes after refinement\n\n \"\"\"\n w = bbox[:, 2] - bbox[:, 0] + 1\n w = np.expand_dims(w, 1)\n h = bbox[:, 3] - bbox[:, 1] + 1\n h = np.expand_dims(h, 1)\n reg_m = np.hstack([w, h, w, h])\n aug = reg_m * reg\n bbox[:, 0:4] = bbox[:, 0:4] + aug\n return bbox\n\n \n def pad(self, bboxes, w, h):\n \"\"\"\n pad the the bboxes, alse restrict the size of it\n\n Parameters:\n ----------\n bboxes: numpy array, n x 5\n input bboxes\n w: float number\n width of the input image\n h: float number\n height of the input image\n Returns :\n ------s\n dy, dx : numpy array, n x 1\n start point of the bbox in target image\n edy, edx : numpy array, n x 1\n end point of the bbox in target image\n y, x : numpy array, n x 1\n start point of the bbox in original image\n ex, ex : numpy array, n x 1\n end point of the bbox in original image\n tmph, tmpw: numpy array, n x 1\n height and width of the bbox\n\n \"\"\"\n tmpw, tmph = bboxes[:, 2] - bboxes[:, 0] + 1, bboxes[:, 3] - bboxes[:, 1] + 1\n num_box = bboxes.shape[0]\n\n dx , dy= np.zeros((num_box, )), np.zeros((num_box, ))\n edx, edy = tmpw.copy()-1, tmph.copy()-1\n\n x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]\n\n tmp_index = np.where(ex > w-1)\n edx[tmp_index] = tmpw[tmp_index] + w - 2 - ex[tmp_index]\n ex[tmp_index] = w - 1\n\n tmp_index = np.where(ey > h-1)\n edy[tmp_index] = tmph[tmp_index] + h - 2 - ey[tmp_index]\n ey[tmp_index] = h - 1\n\n tmp_index = np.where(x < 0)\n dx[tmp_index] = 0 - x[tmp_index]\n x[tmp_index] = 0\n\n tmp_index = np.where(y < 0)\n dy[tmp_index] = 0 - y[tmp_index]\n y[tmp_index] = 0\n\n return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]\n return_list = [item.astype(np.int32) for item in return_list]\n\n return return_list\n\n def slice_index(self, number):\n \"\"\"\n slice the index into (n,n,m), m < n\n Parameters:\n ----------\n number: int number\n number\n \"\"\"\n def chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n num_list = range(number)\n return list(chunks(num_list, self.num_worker))\n \n\n def detect_face(self, img):\n \"\"\"\n detect face over img\n Parameters:\n ----------\n img: numpy array, bgr order of shape (1, 3, n, m)\n input image\n Retures:\n -------\n bboxes: numpy array, n x 5 (x1,y2,x2,y2,score)\n bboxes\n points: numpy array, n x 10 (x1, x2 ... x5, y1, y2 ..y5)\n landmarks\n \"\"\"\n\n # check input\n MIN_DET_SIZE = 12\n\n if img is None:\n return None\n\n # only works for color image\n if len(img.shape) != 3:\n return None\n \n #print('img.shape=', img.shape)\n\n # detected boxes\n total_boxes = []\n\n height, width, _ = img.shape\n minl = min( height, width)\n\n # get all the valid scales\n scales = []\n m = MIN_DET_SIZE/self.minsize\n minl *= m\n factor_count = 0\n while minl > MIN_DET_SIZE:\n scales.append(m*self.factor**factor_count)\n minl *= self.factor\n factor_count += 1\n #print('factor_count=', factor_count)\n #print('scales=', scales)\n #############################################\n # first stage\n #############################################\n for scale in scales:\n return_boxes = detect_first_stage(img, self.PNets[0], scale, self.threshold[0])\n if return_boxes is not None:\n total_boxes.append(return_boxes)\n '''\n sliced_index = self.slice_index(len(scales))\n total_boxes = []\n for batch in sliced_index:\n local_boxes = self.Pool.map( detect_first_stage_warpper, \\\n zip(repeat(img), self.PNets[:len(batch)], [scales[i] for i in batch], repeat(self.threshold[0])) )\n total_boxes.extend(local_boxes)\n\n # remove the Nones \n total_boxes = [ i for i in total_boxes if i is not None]\n '''\n\n if len(total_boxes) == 0:\n return None\n \n total_boxes = np.vstack(total_boxes)\n\n if total_boxes.size == 0:\n return None\n\n # merge the detection from first stage\n pick = nms(total_boxes[:, 0:5], 0.7, 'Union')\n total_boxes = total_boxes[pick]\n\n bbw = total_boxes[:, 2] - total_boxes[:, 0] + 1\n bbh = total_boxes[:, 3] - total_boxes[:, 1] + 1\n\n # refine the bboxes\n total_boxes = np.vstack([total_boxes[:, 0]+total_boxes[:, 5] * bbw,\n total_boxes[:, 1]+total_boxes[:, 6] * bbh,\n total_boxes[:, 2]+total_boxes[:, 7] * bbw,\n total_boxes[:, 3]+total_boxes[:, 8] * bbh,\n total_boxes[:, 4]\n ])\n\n total_boxes = total_boxes.T\n total_boxes = self.convert_to_square(total_boxes)\n total_boxes[:, 0:4] = np.round(total_boxes[:, 0:4])\n\n #############################################\n # second stage\n #############################################\n num_box = total_boxes.shape[0]\n\n # pad the bbox\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(total_boxes, width, height)\n # (3, 24, 24) is the input shape for RNet\n input_buf = np.zeros((num_box, 3, 24, 24), dtype=np.float32)\n\n for i in range(num_box):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i]+1, dx[i]:edx[i]+1, :] = img[y[i]:ey[i]+1, x[i]:ex[i]+1, :]\n input_buf[i, :, :, :] = adjust_input(cv2.resize(tmp, (24, 24)))\n\n output = self.RNet.predict(input_buf)\n\n # filter the total_boxes with threshold\n passed = np.where(output[1][:, 1] > self.threshold[1])\n total_boxes = total_boxes[passed]\n\n if total_boxes.size == 0:\n return None\n\n total_boxes[:, 4] = output[1][passed, 1].reshape((-1,))\n reg = output[0][passed]\n\n # nms\n pick = nms(total_boxes, 0.7, 'Union')\n total_boxes = total_boxes[pick]\n total_boxes = self.calibrate_box(total_boxes, reg[pick])\n total_boxes = self.convert_to_square(total_boxes)\n total_boxes[:, 0:4] = np.round(total_boxes[:, 0:4])\n\n #############################################\n # third stage\n #############################################\n num_box = total_boxes.shape[0]\n\n # pad the bbox\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(total_boxes, width, height)\n # (3, 48, 48) is the input shape for ONet\n input_buf = np.zeros((num_box, 3, 48, 48), dtype=np.float32)\n\n for i in range(num_box):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.float32)\n tmp[dy[i]:edy[i]+1, dx[i]:edx[i]+1, :] = img[y[i]:ey[i]+1, x[i]:ex[i]+1, :]\n input_buf[i, :, :, :] = adjust_input(cv2.resize(tmp, (48, 48)))\n\n output = self.ONet.predict(input_buf)\n\n # filter the total_boxes with threshold\n passed = np.where(output[2][:, 1] > self.threshold[2])\n total_boxes = total_boxes[passed]\n\n if total_boxes.size == 0:\n return None\n\n total_boxes[:, 4] = output[2][passed, 1].reshape((-1,))\n reg = output[1][passed]\n points = output[0][passed]\n\n # compute landmark points\n bbw = total_boxes[:, 2] - total_boxes[:, 0] + 1\n bbh = total_boxes[:, 3] - total_boxes[:, 1] + 1\n points[:, 0:5] = np.expand_dims(total_boxes[:, 0], 1) + np.expand_dims(bbw, 1) * points[:, 0:5]\n points[:, 5:10] = np.expand_dims(total_boxes[:, 1], 1) + np.expand_dims(bbh, 1) * points[:, 5:10]\n\n # nms\n total_boxes = self.calibrate_box(total_boxes, reg)\n pick = nms(total_boxes, 0.7, 'Min')\n total_boxes = total_boxes[pick]\n points = points[pick]\n \n if not self.accurate_landmark:\n return total_boxes, points\n\n #############################################\n # extended stage\n #############################################\n num_box = total_boxes.shape[0]\n patchw = np.maximum(total_boxes[:, 2]-total_boxes[:, 0]+1, total_boxes[:, 3]-total_boxes[:, 1]+1)\n patchw = np.round(patchw*0.25)\n\n # make it even\n patchw[np.where(np.mod(patchw,2) == 1)] += 1\n\n input_buf = np.zeros((num_box, 15, 24, 24), dtype=np.float32)\n for i in range(5):\n x, y = points[:, i], points[:, i+5]\n x, y = np.round(x-0.5*patchw), np.round(y-0.5*patchw)\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(np.vstack([x, y, x+patchw-1, y+patchw-1]).T,\n width,\n height)\n for j in range(num_box):\n tmpim = np.zeros((tmpw[j], tmpw[j], 3), dtype=np.float32)\n tmpim[dy[j]:edy[j]+1, dx[j]:edx[j]+1, :] = img[y[j]:ey[j]+1, x[j]:ex[j]+1, :]\n input_buf[j, i*3:i*3+3, :, :] = adjust_input(cv2.resize(tmpim, (24, 24)))\n\n output = self.LNet.predict(input_buf)\n\n pointx = np.zeros((num_box, 5))\n pointy = np.zeros((num_box, 5))\n\n for k in range(5):\n # do not make a large movement\n tmp_index = np.where(np.abs(output[k]-0.5) > 0.35)\n output[k][tmp_index[0]] = 0.5\n\n pointx[:, k] = np.round(points[:, k] - 0.5*patchw) + output[k][:, 0]*patchw\n pointy[:, k] = np.round(points[:, k+5] - 0.5*patchw) + output[k][:, 1]*patchw\n\n points = np.hstack([pointx, pointy])\n points = points.astype(np.int32)\n\n return total_boxes, points\n\n def list2colmatrix(self, pts_list):\n \"\"\"\n convert list to column matrix\n Parameters:\n ----------\n pts_list:\n input list\n Retures:\n -------\n colMat: \n\n \"\"\"\n assert len(pts_list) > 0\n colMat = []\n for i in range(len(pts_list)):\n colMat.append(pts_list[i][0])\n colMat.append(pts_list[i][1])\n colMat = np.matrix(colMat).transpose()\n return colMat\n\n def find_tfrom_between_shapes(self, from_shape, to_shape):\n \"\"\"\n find transform between shapes\n Parameters:\n ----------\n from_shape: \n to_shape: \n Retures:\n -------\n tran_m:\n tran_b:\n \"\"\"\n assert from_shape.shape[0] == to_shape.shape[0] and from_shape.shape[0] % 2 == 0\n\n sigma_from = 0.0\n sigma_to = 0.0\n cov = np.matrix([[0.0, 0.0], [0.0, 0.0]])\n\n # compute the mean and cov\n from_shape_points = from_shape.reshape(from_shape.shape[0]//2, 2)\n to_shape_points = to_shape.reshape(to_shape.shape[0]//2, 2)\n mean_from = from_shape_points.mean(axis=0)\n mean_to = to_shape_points.mean(axis=0)\n\n for i in range(from_shape_points.shape[0]):\n temp_dis = np.linalg.norm(from_shape_points[i] - mean_from)\n sigma_from += temp_dis * temp_dis\n temp_dis = np.linalg.norm(to_shape_points[i] - mean_to)\n sigma_to += temp_dis * temp_dis\n cov += (to_shape_points[i].transpose() - mean_to.transpose()) * (from_shape_points[i] - mean_from)\n\n sigma_from = sigma_from / to_shape_points.shape[0]\n sigma_to = sigma_to / to_shape_points.shape[0]\n cov = cov / to_shape_points.shape[0]\n\n # compute the affine matrix\n s = np.matrix([[1.0, 0.0], [0.0, 1.0]])\n u, d, vt = np.linalg.svd(cov)\n\n if np.linalg.det(cov) < 0:\n if d[1] < d[0]:\n s[1, 1] = -1\n else:\n s[0, 0] = -1\n r = u * s * vt\n c = 1.0\n if sigma_from != 0:\n c = 1.0 / sigma_from * np.trace(np.diag(d) * s)\n\n tran_b = mean_to.transpose() - c * r * mean_from.transpose()\n tran_m = c * r\n\n return tran_m, tran_b\n\n def extract_image_chips(self, img, points, desired_size=256, padding=0):\n \"\"\"\n crop and align face\n Parameters:\n ----------\n img: numpy array, bgr order of shape (1, 3, n, m)\n input image\n points: numpy array, n x 10 (x1, x2 ... x5, y1, y2 ..y5)\n desired_size: default 256\n padding: default 0\n Retures:\n -------\n crop_imgs: list, n\n cropped and aligned faces \n \"\"\"\n crop_imgs = []\n for p in points:\n shape =[]\n for k in range(len(p)//2):\n shape.append(p[k])\n shape.append(p[k+5])\n\n if padding > 0:\n padding = padding\n else:\n padding = 0\n # average positions of face points\n mean_face_shape_x = [0.224152, 0.75610125, 0.490127, 0.254149, 0.726104]\n mean_face_shape_y = [0.2119465, 0.2119465, 0.628106, 0.780233, 0.780233]\n\n from_points = []\n to_points = []\n\n for i in range(len(shape)//2):\n x = (padding + mean_face_shape_x[i]) / (2 * padding + 1) * desired_size\n y = (padding + mean_face_shape_y[i]) / (2 * padding + 1) * desired_size\n to_points.append([x, y])\n from_points.append([shape[2*i], shape[2*i+1]])\n\n # convert the points to Mat\n from_mat = self.list2colmatrix(from_points)\n to_mat = self.list2colmatrix(to_points)\n\n # compute the similar transfrom\n tran_m, tran_b = self.find_tfrom_between_shapes(from_mat, to_mat)\n\n probe_vec = np.matrix([1.0, 0.0]).transpose()\n probe_vec = tran_m * probe_vec\n\n scale = np.linalg.norm(probe_vec)\n angle = 180.0 / math.pi * math.atan2(probe_vec[1, 0], probe_vec[0, 0])\n\n from_center = [(shape[0]+shape[2])/2.0, (shape[1]+shape[3])/2.0]\n to_center = [0, 0]\n to_center[1] = desired_size * 0.4\n to_center[0] = desired_size * 0.5\n\n ex = to_center[0] - from_center[0]\n ey = to_center[1] - from_center[1]\n\n rot_mat = cv2.getRotationMatrix2D((from_center[0], from_center[1]), -1*angle, scale)\n rot_mat[0][2] += ex\n rot_mat[1][2] += ey\n\n chips = cv2.warpAffine(img, rot_mat, (desired_size, desired_size))\n crop_imgs.append(chips)\n\n return crop_imgs\n\n\n def transform(self, x, y, ang, s0, s1):\n '''\n x y position\n ang angle\n s0 size of original image\n s1 size of target image\n '''\n\n x0 = x - s0[1]/2\n y0 = y - s0[0]/2\n xx = x0*math.cos(ang) - y0*math.sin(ang) + s1[1]/2\n yy = x0*math.sin(ang) + y0*math.cos(ang) + s1[0]/2\n #print('x=', x, 'y=', y, 'x0=', x0, 'y0=',y0, 'ang=', ang, 's0=', s0, 's1=', s1)\n return xx, yy\n\n def align(self, img, f5pt, crop_size, ec_mc_y, ec_y):\n \n #print('orgin f5pt=', f5pt)\n f5pt = np.reshape(f5pt, (5,2))\n #print('reshaped f5pt=', f5pt)\n if f5pt[0, 1] == f5pt[1, 1]:\n ang = 0\n else:\n # (y0-y1) / (x0-x1)\n ang_tan = (f5pt[0,1]-f5pt[1,1]) / (f5pt[0,0] - f5pt[1,0])\n ang = math.atan(ang_tan) / math.pi * 180\n\n img_rot = self.rotate_bound(img, ang)\n #print('img_rot shape=', img_rot.shape)\n\n #eye center\n x = (f5pt[0,0] + f5pt[1,0]) / 2\n y = (f5pt[0,1] + f5pt[1,1]) / 2\n\n ang = -ang/180 * math.pi\n xx, yy = self.transform(x, y, ang, img.shape, img_rot.shape)\n eyec = np.array([xx, yy])\n eyec = np.round(eyec)\n #print('eyec=', eyec)\n\n tem = f5pt.shape\n if tem[0] == 5:\n x = (f5pt[3,0]+f5pt[4,0]) / 2\n y = (f5pt[3,1]+f5pt[4,1]) / 2\n elif tem[0] == 4:\n x = f5pt[3,0]\n y = f5pt[3,1]\n\n xx, yy = self.transform(x, y, ang, img.shape, img_rot.shape)\n mouthc = np.array([round(xx), round(yy)])\n #print('mouthc=', mouthc)\n\n resize_scale = ec_mc_y / (mouthc[1]-eyec[1])\n if resize_scale < 0:\n resize_scale = 1\n #print('resize_scale=', resize_scale)\n\n img_resize = cv2.resize(img_rot, None, fx=resize_scale, fy=resize_scale);\n #print('img_resize shape=', img_resize.shape)\n\n eyec2 = (eyec - [img_rot.shape[1]/2, img_rot.shape[0]/2]) * resize_scale + [img_resize.shape[1]/2, img_resize.shape[0]/2];\n eyec2 = np.round(eyec2)\n #print('eyec2=', eyec2)\n \n #build trans_points centers for five parts\n trans_points = np.zeros(f5pt.shape)\n [trans_points[:,0],trans_points[:,1]] = self.transform(f5pt[:,0],f5pt[:,1], ang, img.shape, img_rot.shape)\n trans_points = np.round(trans_points)\n #print('trans_points=', trans_points)\n\n trans_points[:,0] = trans_points[:,0] - img_rot.shape[1] / 2\n trans_points[:,1] = trans_points[:,1] - img_rot.shape[0] / 2\n trans_points = trans_points * resize_scale\n trans_points[:,0] = trans_points[:,0] + img_resize.shape[1] / 2\n trans_points[:,1] = trans_points[:,1] + img_resize.shape[0] / 2\n trans_points = np.round(trans_points)\n #print('trans_points=', trans_points)\n\n img_crop = np.zeros((crop_size, crop_size, img_rot.shape[2])) \n crop_y = eyec2[1] - ec_y\n crop_y_end = crop_y + crop_size - 1\n crop_x = eyec2[0]-math.floor(crop_size/2)\n crop_x_end = crop_x + crop_size - 1\n\n box = self.guard([crop_x, crop_x_end, crop_y, crop_y_end], img_resize.shape)\n #print('box=', box, 'crop_y=', crop_y, 'crop_y_end=', crop_y_end, 'crop_x=', crop_x, 'crop_x_end=', crop_x_end)\n #print('[box[2]-crop_y+1=', box[2]-crop_y+1, 'box[3]-crop_y+1=', box[3]-crop_y+1, 'box[0]-crop_x+1=', box[0]-crop_x+1, 'crop_x+1=', crop_x+1)\n #print('img_resize shape=', img_resize.shape, '[%d:%d, %d:%d,:]'%(box[2],box[3],box[0],box[1]))\n \n img_crop[int(box[2]-crop_y+1):int(box[3]-crop_y+1), int(box[0]-crop_x+1):int(box[1]-crop_x+1),:] \\\n = img_resize[int(box[2]):int(box[3]),int(box[0]):int(box[1]),:];\n \n #calculate relative coordinate\n trans_points[:,0] = trans_points[:,0] - box[0] + 1\n trans_points[:,1] = trans_points[:,1] - box[2] + 1\n\n return img_crop, trans_points\n\n def normal_array(self, x):\n for i in range(len(x)):\n if x[i] < 1:\n x[i] = 1\n return x\n\n def guard(self, x, N):\n x = self.normal_array(x)\n\n if N[1] > 0:\n for i in range(0, 2):\n if x[i] > N[1]:\n x[i] = N[1]\n #x[eng.logical((x>N[1]) * [1, 1, 0, 0])]=N[1]\n\n if N[0] > 0:\n for i in range(2, 4):\n if x[i] > N[0]:\n x[i] = N[0]\n #x[eng.logical((x>N[0]) * [0, 0, 1, 1])]=N[0]\n\n x = self.normal_array(x)\n return x\n\n def rotate_bound(self, image, angle):\n # grab the dimensions of the image and then determine the\n # center\n (h, w) = image.shape[:2]\n (cX, cY) = (w // 2, h // 2)\n \n # grab the rotation matrix (applying the negative of the\n # angle to rotate clockwise), then grab the sine and cosine\n # (i.e., the rotation components of the matrix)\n M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)\n cos = np.abs(M[0, 0])\n sin = np.abs(M[0, 1])\n \n # compute the new bounding dimensions of the image\n nW = int((h * sin) + (w * cos))\n nH = int((h * cos) + (w * sin))\n \n # adjust the rotation matrix to take into account translation\n M[0, 2] += (nW / 2) - cX\n M[1, 2] += (nH / 2) - cY\n \n # perform the actual rotation and return the image\n return cv2.warpAffine(image, M, (nW, nH))\n","sub_path":"mtcnn_detector.py","file_name":"mtcnn_detector.py","file_ext":"py","file_size_in_byte":23895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"487537659","text":"import sys\ninput = sys.stdin.readline\ndef find(A,x):\n p = A[x]\n if p == x:\n return x\n a = find(A,p)\n A[x] = a\n return a\n\ndef union(A, x, y):\n if find(A,x) > find(A,y):\n bx, by = find(A,y), find(A,x)\n else:\n bx, by = find(A,x), find(A,y)\n A[y] = bx\n A[by] = bx\n\ndef main():\n N, Q = map( int, input().split())\n TUV = [ tuple( map( int, input().split())) for _ in range(Q)]\n G = [ i for i in range(N)]\n ANS = []\n for t, u, v in TUV:\n if t == 0:\n union(G,u,v)\n else:\n if find(G,u) == find(G,v):\n ANS.append(1)\n else:\n ANS.append(0)\n print(\"\\n\".join( map( str, ANS)))\n \nif __name__ == '__main__':\n main()\n","sub_path":"typical/ALPC/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"580560577","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom GlobalTools import *\n\nParentStockRequest = SuperClass(\"StockRequest\",\"Transaction\",__file__)\nclass StockRequest(ParentStockRequest):\n\n def defaults(self):\n ParentStockRequest.defaults(self)\n from StockDepo import StockDepo\n self.RequestUser = currentUser()\n self.StockDepo = StockDepo.default()\n self.FrStockDepo = StockDepo.default()\n self.PlanReceiptDate = self.TransDate\n self.Status = 0\n self.OrderedFlag = False\n\n def afterCopy(self):\n ParentStockRequest.afterCopy(self)\n self.Status = 0\n self.Closed = False\n self.User = currentUser()\n for rline in self.Items:\n rline.Approved = None\n rline.PlanReceiptDate = None\n rline.OrderedQty = None\n self.AuthorizedBy = None\n self.OrderedFlag = False\n\n def check(self):\n res = ParentStockRequest.check(self)\n if (not res): return res\n if not self.Office:\n return self.FieldErrorResponse(\"NONBLANKERR\",\"Office\")\n from StockSettings import StockSettings\n ss = StockSettings.bring()\n if (ss):\n if (ss.RequireStockRequestType and not self.Type):\n return self.FieldErrorResponse(\"NONBLANKERR\",\"Type\")\n self.updateOrderedFlag()\n return True\n\n def confirmed(self):\n if self.Status == 1:\n return True\n else:\n return False\n\n def sumUp(self):\n self.TotalQty = 0\n for eachrow in self.Items:\n self.TotalQty += eachrow.Qty\n\n def fieldIsEditable(self, fieldname, rowfieldname=None, rownr=None):\n res = ParentStockRequest.fieldIsEditable(self, fieldname, rowfieldname, rownr)\n if (not res): return res\n if (self.Closed):\n res = False\n return res\n\n def genStockMovement(self):\n if (self.Closed):\n return ErrorResponse(\"This Record is closed\")\n srquery = Query()\n srquery.sql = \"SELECT SRIr.ArtCode, SRIr.Name, SRIr.rowNr, SRIr.Qty, SRIr.Approved \"\n srquery.sql += \" FROM StockRequestItemRow SRIr \"\n srquery.sql += \" INNER JOIN StockRequest SR ON SR.internalId = SRIr.masterId \"\n srquery.sql += \" WHERE?AND SR.SerNr = i|%s| \" %self.SerNr\n\n smquery = Query()\n smquery.sql = \"SELECT SMr.ArtCode, SMr.Name, SMr.OriginRowNr rowNr, 0 Qty , -SMr.Qty Approved \"\n smquery.sql += \" FROM StockMovementRow SMr \"\n smquery.sql += \" INNER JOIN StockMovement SM ON (SM.internalId = SMr.masterId \"\n smquery.sql += \" AND SM.OriginNr = i|%s| AND SM.OriginType = i|%s|) \" %(self.SerNr,self.Origin[self.name()])\n\n bigquery = Query()\n bigquery.sql = \"SELECT T1.ArtCode,T1.Name,T1.rowNr, T1.Qty, SUM(T1.Approved) Approved \"\n bigquery.sql += \" FROM (%s UNION ALL %s) AS T1 \" %(srquery.sql,smquery.sql)\n bigquery.sql += \" GROUP BY T1.rowNr \"\n\n from User import User\n from StockMovement import StockMovement,StockMovementRow\n from Transaction import Transaction\n stockm = StockMovement()\n stockm.defaults()\n stockm.FrStockDepo = self.FrStockDepo\n stockm.ToStockDepo = self.ToStockDepo\n stockm.Comment = tr(\"Stock Request\")\n stockm.Labels = self.Labels\n stockm.OriginNr = self.SerNr\n stockm.OriginType = self.Origin[self.name()]\n if (bigquery.open()):\n for eachrow in bigquery:\n if (eachrow.Approved > 0):\n stockmrow = StockMovementRow()\n stockmrow.ArtCode = eachrow.ArtCode\n stockmrow.pasteArtCode(stockm)\n stockmrow.Qty = eachrow.Approved\n stockmrow.pasteQty(stockm)\n stockmrow.OriginRowNr = eachrow.rowNr\n stockm.Items.append(stockmrow)\n if (stockm.Items.count() == 0):\n self.appendMessage(tr(\"No more items to deliver\"))\n return None\n stockm.sumUp()\n return stockm\n\n def genPurchaseOrder(self):\n if (self.Closed):\n self.appendMessage(tr(\"This Record is closed\"))\n return None\n if (not self.AuthorizedBy):\n self.appendMessage(\"TRANSNOTAUTHORIZED\")\n return None\n lines = 0\n from User import User\n from PurchaseOrder import PurchaseOrder,PurchaseOrderItemRow\n porder = PurchaseOrder()\n porder.defaults()\n porder.StockDepo = self.ToStockDepo\n porder.Labels = self.Labels\n porder.OriginNr = self.SerNr\n porder.OriginType = self.Origin[self.name()]\n porder.Office = self.Office\n porder.pasteSupCode()\n orderedItems = self.findOrderedItems()\n for rline in self.Items:\n if (not orderedItems.has_key(rline.ArtCode) or orderedItems[rline.ArtCode] < rline.Approved):\n porow = PurchaseOrderItemRow()\n porow.ArtCode = rline.ArtCode\n porow.pasteArtCode(porder)\n porow.Qty = rline.Approved - orderedItems[rline.ArtCode]\n porow.Labels = rline.Labels\n porow.OriginRowNr = rline.rowNr\n porow.OriginSerNr = self.SerNr\n porow.ReceiptDate = rline.PlanReceiptDate\n porow.sumUp(porder)\n if (porow.Qty > 0):\n porder.Items.append(porow)\n lines += 1\n if (porder.Items.count() > 0):\n porder.sumUp()\n return porder\n else:\n self.appendMessage(\"There Is No More Items to Order\")\n return None\n\n def findOrderedItems (self):\n query = Query()\n query.sql = \"SELECT [pi].{ArtCode}, SUM([pi].{Qty}) AS {Qty}\"\n query.sql += \"FROM [PurchaseOrderItemRow] [pi] \"\n query.sql += \"INNER JOIN [PurchaseOrder] [p] ON [p].{InternalId} = [pi].{MasterId} \"\n query.sql += \"WHERE [p].{OriginType} = i|%s| AND [p].{OriginNr} = i|%s| \" % (self.Origin[self.name()], self.SerNr )\n query.sql += \"GROUP BY [pi].{ArtCode}\"\n if query.open():\n artQty = {}\n for rec in query:\n artQty[rec.ArtCode] = rec.Qty\n return artQty\n return {}\n\n @classmethod\n def getPendantQty(self, SerNr, RowNr):\n srquery = Query()\n srquery.sql = \"SELECT SUM(T1.Qty) Qty FROM ( \"\n srquery.sql += \"SELECT SR.SerNr SerNr,SRIr.rowNr RowNr, SRIr.ArtCode,SRIr.Approved Qty FROM StockRequestItemRow SRIr \"\n srquery.sql += \"INNER join StockRequest SR ON SRIr.masterId = SR.internalId \"\n srquery.sql += \"UNION ALL \"\n srquery.sql += \"SELECT POIr.OriginSerNr SerNr, POIr.OriginRowNr RowNr, POIr.ArtCode, -POIr.Qty from PurchaseOrderItemRow POIr \"\n srquery.sql += \"INNER join PurchaseOrder PO on POIr.masterId = PO.internalId) as T1 \"\n srquery.sql += \"WHERE T1.SerNr = i|%s| AND T1.RowNr = i|%s| \" %(SerNr,RowNr)\n srquery.sql += \"GROUP BY T1.SerNr,T1.RowNr \"\n res = 0\n if (srquery.open() and srquery.count() > 0):\n res = srquery[0].Qty\n return res\n\n def updateOrderedFlag(self):\n fullordered = False\n fullsent = False\n for rline in self.Items:\n if (rline.Approved !=0 and rline.MovedQty >= rline.Approved):\n fullsent = True\n if (rline.Approved !=0 and rline.OrderedQty >= rline.Approved):\n fullordered = True\n self.OrderedFlag = fullordered\n if fullsent: \n self.Status = 1\n elif fullordered:\n self.Status = 2\n else:\n self.Status = 0\n\n def removeEmptyRows(self):\n for dn in self.detailNames():\n detail = self.details(dn)\n try:\n for i in range(detail.count()-1, -1, -1):\n row = detail[i]\n for fn in row.fieldNames():\n if fn != 'rowNr' and fn != 'masterId' and fn != 'PlanReceiptDate':\n field = row.fields(fn)\n if not (field.isNone() or not field.getValue()):\n raise \"\"\n detail.remove(i)\n except:\n pass\n\nParentStockRequestItemRow = SuperClass(\"StockRequestItemRow\",\"Record\",__file__)\nclass StockRequestItemRow(ParentStockRequestItemRow):\n\n def pasteQty(self):\n if (not self.Approved):\n self.Approved = self.Qty\n\n def pasteArtCode(self, stockRequest, stockdepo=None):\n from Item import Item\n from StockSettings import StockSettings\n sset = StockSettings()\n sset.load()\n art = Item.bring(self.ArtCode)\n if art:\n self.ArtCode = art.Code\n self.Name = art.Name\n self.QtyInOffice = art.getStock(stockdepo)\n self.QtyInCentral = art.getStock(sset.CentralStockDepo)\n self.PackageCode = art.Package\n self.Unit = art.Unit\n self.Labels = getMasterRecordField(\"ItemGroup\",\"Labels\",art.ItemGroup)\n else:\n self.Name = None\n self.QtyInOffice = None\n self.QtyInCentral = None\n self.PackageCode = None\n self.Unit = None","sub_path":"standard/records/StockRequest.py","file_name":"StockRequest.py","file_ext":"py","file_size_in_byte":9327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311568312","text":"#!/usr/bin/env python\nimport os\nimport subprocess\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport time\nimport threading\nimport gobject\n\ngobject.threads_init()\n\nclass LogViewer(threading.Thread):\n\n mInFile = \"\"\n mTextBuffer = None\n mOldStrings = \"\"\n mStoped = False\n\n def close_application(self, widget):\n gtk.main_quit()\n self.mStoped = True\n\n def __init__(self, pathFile):\n threading.Thread.__init__(self)\n self.mInFile = pathFile\n window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n window.set_resizable(True)\n window.set_title(self.mInFile)\n window.set_border_width(10)\n window.set_default_size(800, 600)\n window.set_position(gtk.WIN_POS_CENTER_ALWAYS)\n window.connect(\"destroy\", self.close_application)\n\n box1 = gtk.VBox(False, 10)\n window.add(box1)\n\n #box2 = gtk.VBox(False, 10)\n #box2.set_border_width(10)\n #box1.pack_start(box2, True, True, 0)\n #box2.show()\n\n sw = gtk.ScrolledWindow()\n sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)\n textview = gtk.TextView()\n textview.set_editable(False)\n textview.set_cursor_visible(False)\n textview.set_wrap_mode(gtk.WRAP_NONE)\n self.mTextBuffer = textview.get_buffer()\n sw.add(textview)\n sw.show()\n\n box1.pack_start(sw)\n #box2.pack_start(sw)\n\n textview.show()\n box1.show()\n window.show()\n\n def refreshFile(self):\n # Load the file into the text window\n infile = open(self.mInFile, \"r\")\n if infile:\n string = infile.read()\n infile.close()\n if cmp(string, self.mOldStrings) != 0:\n self.mTextBuffer.set_text(string)\n self.mOldStrings = string\n\n def run(self):\n while not self.mStoped:\n gobject.idle_add(self.refreshFile)\n time.sleep(1)\n\ndef main():\n subprocess.Popen('mkdir -p /tmp/logs', shell=True)\n # selected = os.environ.get('NAUTILUS_SCRIPT_SELECTED_URIS', '')\n selected = os.environ.get('NAUTILUS_SCRIPT_SELECTED_FILE_PATHS', '')\n curdir = os.environ.get('NAUTILUS_SCRIPT_CURRENT_URI', os.curdir)\n if selected:\n orig_targets = selected.splitlines()\n else:\n orig_targets = [curdir]\n\n converted = \"\"\n\n for target in orig_targets:\n if target.startswith('file:///'):\n target = target[7:]\n converted += (target + \" \")\n\n foutput = \"/tmp/logs/nautilus_fg3.\" + time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))\n f = open(foutput, \"w\");\n # Using pygtk\n # p = subprocess.Popen(\"/home/finalx/mybin/myflash.sh --oneshot \" + converted, shell=True, stdout=f)\n # app = LogViewer(foutput)\n # app.start()\n\n # Or using gnome-terminal\n subprocess.Popen('gnome-terminal -e \"/home/finalx/mybin/myflash.sh ' + converted + '\"', shell=True, stdout=f)\n\nif __name__ == \"__main__\":\n main()\n #gtk.main()\n","sub_path":"other_files/common_shell_scripts/flash_with_fg3.py","file_name":"flash_with_fg3.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213731037","text":"import sys\nimport board\nimport operator\n\nclass Player:\n BOARD_NAME = 'board.txt'\n __board = None\n playerNumber = None\n\n def __init__(self, playerNumber, remainingTime):\n self.__board = board.readBoard(self.BOARD_NAME)\n self.playerNumber = playerNumber\n\n def playGreedyAddStrategy(self):\n # Moves are (location, weight, torque1, torque2)\n moves = self.__board.getPlayableAddMoves(self.playerNumber)\n\n # Sort the torques so that (torque1, torque2) torque1 goes from highest to lowest. This means of\n # course that torque2 will go fomr lowest to highest.\n sortedMoves = sorted(moves, key = operator.itemgetter(2), reverse = True)\n\n # Remove the torques\n sortedMoves = [(x,y) for (x,y,a,b) in sortedMoves]\n\n if len(sortedMoves) > 0:\n bestMove = self.balancePlayerOneTorque(sortedMoves)\n else:\n bestMove = self.playRandomAddStrategy()\n return bestMove\n\n def balancePlayerOneTorque(self, sortedMoves):\n (playerOneTorque1, playerOneTorque2) = self.__board.getTorque(self.__board.playerOneMoves)\n if self.playerNumber == 1:\n # We want to balance the weights that player one placed as much as possible.\n if abs(playerOneTorque1) > abs(playerOneTorque2):\n bestMove = sortedMoves[-1]\n else:\n bestMove = sortedMoves[0]\n else:\n # Otherwise we want to unbalance the weights that player one placed as much as possible.\n bestMove = sortedMoves[0]\n return bestMove\n\n def playRandomAddStrategy(self):\n weight = self.__board.getRandomWeightToAdd(self.playerNumber)\n location = self.__board.getRandomUnoccupiedLocation()\n bestMove = (location, weight)\n return bestMove\n\n def playGreedyRemoveStrategy(self):\n remainingPlayerOneMoves = set(self.__board.playerOneMoves)\n # This tells us to not remove player two's weights if we are player one, unless we are forced\n # to do so.\n if remainingPlayerOneMoves == {0}:\n # This tells us to not remove player two's weights if we are player one, unless we are forced\n # to do so.\n playerNumber = None\n else:\n playerNumber = self.playerNumber\n\n # Moves are (location, weight, torque1, torque2)\n moves = self.__board.getPlayableRemoveMoves(playerNumber)\n\n # Sort the torques so that (torque1, torque2) torque1 goes from highest to lowest. This means of\n # course that torque2 will go fomr lowest to highest.\n sortedMoves = sorted(moves, key = operator.itemgetter(2), reverse = True)\n\n # Remove the torques\n sortedMoves = [(x,y) for (x,y,a,b) in sortedMoves]\n\n if len(sortedMoves) > 0:\n #bestMove = sortedMoves[0]\n bestMove = self.balancePlayerOneTorque(sortedMoves)\n else:\n bestMove = self.playRandomRemoveStrategy(playerNumber)\n return bestMove\n\n def playRandomRemoveStrategy(self, playerNumber):\n location = self.__board.getRandomOccupiedLocation(playerNumber)\n weight = self.__board.getWeightAtLocation(location)\n bestMove = (location, weight)\n return bestMove\n\n def play(self, mode):\n if mode == 1:\n (location, weight) = self.playGreedyAddStrategy()\n elif mode == 2:\n (location, weight) = self.playGreedyRemoveStrategy()\n else:\n raise Exception(\"Invalid Mode\")\n return (location, weight)\n\nif __name__ == '__main__':\n if len(sys.argv) < 4:\n remainingTime = float('Inf')\n else:\n remainingTime = float(sys.argv[3])\n\n mode = int(sys.argv[1])\n playerNumber = int(sys.argv[2])\n\n thisPlayer = Player(playerNumber, remainingTime)\n (location, weight) = thisPlayer.play(mode)\n print(str(location) + ' ' + str(weight))\n","sub_path":"NoTipping/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176428982","text":"import math\n\nclass Dinosaur:\n def __init__(self, type_dino):\n self.type = type_dino\n self.attack = 'Stomp'\n self.health = 100\n self.energy = math.ceil(100)\n self.attack_power = 80\n self.status = 'Active'\n\n def attack_robo(self, robo_obj):\n if self.health != 0 and self.energy <= 0:\n self.status = 'Resting'\n return 'Resting, cannot attack'\n if self.health <= 0:\n self.status = 'Defeated'\n return 'Defeated, cannot attack'\n elif robo_obj.health <= 0:\n robo_obj.health = 0\n robo_obj.attack_power = 0\n robo_obj.power_level = 0\n robo_obj.status = 'Defeated'\n return 'Defeated, cannot attack'\n else:\n robo_obj.health -= math.ceil(self.attack_power / 4)\n self.energy -= 10\n\n def __repr__(self):\n return f'Dino * {self.type} - Attack: {self.attack}, Health: {self.health}, ' \\\n f'Energy: {self.energy}, Attack Power: {self.attack_power}, Status: {self.status}'\n","sub_path":"dinosaurs.py","file_name":"dinosaurs.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"609863524","text":"# SUMMARY: parse_plot.py\n# USAGE: parse plot output file of eSTOMP, save as json file\n# ORG: Pacific Northwest National Laboratory\n# AUTHOR: Xuehang Song\n# E-MAIL: xuehang.song@pnnl.gov\n# ORIG-DATE: June-2019\n# DESCRIPTION:\n# DESCRIP-END.\n# COMMENTS: only deal cartesian sturtured grids\n#\n# Last Change: 2019-08-13\nimport numpy as np\nimport re\nimport argparse\nimport h5py as h5\nimport glob\nimport os.path\nfrom xml.etree import ElementTree as ET\nfrom xml.dom import minidom\n\n\ndef prettify(element):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ET.tostring(element, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\n\ndef length_conversion(x):\n \"\"\"\n convert length unit to m\n \"\"\"\n return {\n 'a': 1e-10,\n 'ang': 1e-10,\n 'angstrom': 1e-10,\n 'ao': 1e-10,\n 'cm': 0.01,\n 'ffl': 109.728,\n 'ft': 0.3048,\n 'furlong': 201.168,\n 'm': 1,\n 'mi': 1609.344,\n 'mile': 1609.344,\n \"mm\": 0.001,\n 'rod': 5.0292,\n 'yd': 0.9144\n }.get(x, 1)\n\n\ndef time_conversion(x):\n \"\"\"\n convert time unit to s\n \"\"\"\n return {\n 'year': 60*60*24*365.25,\n 'y': 60*60*24*365.25,\n 'yr': 60*60*24*365.25,\n 'd': 60*60*24,\n 'day': 60*60*24,\n \"hour\": 60*60,\n \"hr\": 60*60,\n \"h\": 60*60,\n \"m\": 60,\n \"min\": 60,\n \"minute\": 60,\n \"s\": 1,\n \"sec\": 1,\n \"second\": 1\n }.get(x, 1)\n\n\ndef parse_boundary_card(boundary_in):\n \"\"\"\n Parse estomp source card\n only works for \n \"\"\"\n\n boundary = dict()\n # read file\n with open(boundary_in, \"r\") as f:\n estomp_input = f.readlines()\n\n # remove comments and blank lines in input deck\n estomp_input = [x.lstrip() for x in estomp_input]\n estomp_input = [x.lower() for x in estomp_input if x]\n estomp_input = [x for x in estomp_input if x[0] != \"#\"]\n estomp_input = [re.split('[#!\\n]', x)[0] for x in estomp_input]\n\n # locate start of source card\n bc_line = [i for i, s in enumerate(estomp_input) if \"~boundary\" in s]\n if len(bc_line) > 0:\n bc_line = bc_line[0]\n bc_line += 1\n nbc_zone = int(estomp_input[bc_line].split(\",\")[0])\n zone_files = []\n bc_type = []\n bc_data = []\n for izone in range(nbc_zone):\n bc_line += 1\n line_decompose = estomp_input[bc_line].split(\",\")\n bc_type.append(\"_\".join(line_decompose[1:]))\n zone_files.append(line_decompose[1])\n bc_line += 1\n line_decompose = estomp_input[bc_line].split(\",\")\n ntime = int(line_decompose[-2])\n bc_line += 1\n bc_data.append(estomp_input[bc_line:(bc_line+ntime)])\n bc_line += (ntime-1)\n bc_loc = []\n for ifile in zone_files:\n bc_loc.append(np.genfromtxt(simu_dir+ifile, dtype=\"i8\"))\n boundary[\"type\"] = bc_type\n boundary[\"loc\"] = bc_loc\n boundary[\"data\"] = bc_data\n return(boundary)\n\n\ndef parse_source_card(source_in):\n \"\"\"\n This is to parse estomp source card\n \"\"\"\n source = dict()\n # read file\n with open(source_in, \"r\") as f:\n estomp_input = f.readlines()\n\n # remove comments and blank lines in input deck\n estomp_input = [x.lstrip() for x in estomp_input]\n estomp_input = [x.lower() for x in estomp_input if x]\n estomp_input = [x for x in estomp_input if x[0] != \"#\"]\n estomp_input = [re.split('[#!\\n]', x)[0] for x in estomp_input]\n\n # locate start of source card\n source_line = [i for i, s in enumerate(estomp_input) if \"~source\" in s]\n if len(source_line) > 0:\n source_line = source_line[0]\n # source zone number\n source_line += 1\n nsource_zone = int(estomp_input[source_line].split(\",\")[0])\n\n # read source data\n source_type = []\n zone_loc = []\n source_data = []\n for izone in range(nsource_zone):\n source_line += 1\n line_decompose = estomp_input[source_line].split(\",\")\n source_type.append(\"_\".join(line_decompose[0:-8]))\n zone_loc.append([int(x) for x in line_decompose[-8:-2]])\n ntime = int(line_decompose[-2])\n source_line += 1\n source_data.append(estomp_input[source_line:(source_line+ntime)])\n source_line += (ntime-1)\n\n # wrap data\n source_time = [[float(y.split(\",\")[0])*time_conversion(y.split(\",\")[1])\n for y in x] for x in source_data]\n source_time = [[min(x), max(x)] if len(x) > 1 else [\n min(x), np.inf] for x in source_time]\n\n source[\"type\"] = source_type\n source[\"loc\"] = zone_loc\n source[\"data\"] = source_data\n source[\"time\"] = source_time\n\n return(source)\n\n\ndef read_args():\n \"\"\"\n read parameters\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-dir',\n '--simu_dir',\n type=str,\n default=\"\")\n parser.add_argument('-boundary',\n action='store_true')\n parser.add_argument('-source',\n action='store_true')\n args = vars(parser.parse_args())\n return(args)\n\n\ndef retrieve_grids(grids_in):\n \"\"\"\n read grid information from eSTOMP input\n \"\"\"\n\n # read raw input deck\n input_file = open(grids_in, \"r\")\n estomp_input = input_file.readlines()\n input_file.close()\n\n # remove comments and blank lines in input deck\n estomp_input = [x.lstrip() for x in estomp_input]\n estomp_input = [x.lower() for x in estomp_input if x]\n estomp_input = [x for x in estomp_input if x[0] != \"#\"]\n estomp_input = [re.split('[#!\\n]', x)[0] for x in estomp_input]\n\n # locate start of grid card\n grid_line = [i for i, s in enumerate(estomp_input) if \"~grid\" in s][0]\n\n if \"cartesian\" in estomp_input[grid_line + 1].lower():\n print(\"Cartesian grids\")\n else:\n sys.exit(\"Unfortunately, this scripts only can deal with cartesian grids\")\n\n # read nx, ny, nz\n nx, ny, nz = map(int, re.split('[,]', estomp_input[grid_line + 2])[0:3])\n grid_value = []\n iline = 3\n d_flag = 0\n # loop lines of etomp inputs until have enough entry for grids\n # while estomp_input[grid_line + iline][0] != \"~\":\n while len(grid_value) < (1 + nx + 1 + ny + 1 + nz):\n line_data = estomp_input[grid_line + iline].split(\",\")\n ndata = int(np.floor(len(line_data) / 2))\n for idata in range(ndata):\n if (\"@\" in line_data[idata * 2]):\n d_flag = 1\n temp_n, temp_d = line_data[idata * 2].split(\"@\")\n grid_value += [float(temp_d) *\n length_conversion(line_data[idata * 2 + 1])] * int(temp_n)\n else:\n grid_value += [float(line_data[idata * 2]) *\n length_conversion(line_data[idata * 2 + 1])]\n iline += 1\n\n # assign flatten grids values to x, y, z\n if d_flag == 1:\n xo = grid_value[0]\n dx = np.asarray(grid_value[1:1 + nx])\n yo = grid_value[1 + nx]\n dy = np.asarray(grid_value[1 + nx + 1:1 + nx + 1 + ny])\n zo = grid_value[1 + nx + 1 + ny]\n dz = np.asarray(\n grid_value[1 + nx + 1 + ny + 1:1 + nx + 1 + ny + 1 + nz])\n x = xo + np.cumsum(dx) - 0.5 * dx\n y = yo + np.cumsum(dy) - 0.5 * dy\n z = zo + np.cumsum(dz) - 0.5 * dz\n xe = xo + sum(dx)\n ye = yo + sum(dy)\n ze = zo + sum(dz)\n else:\n xo = grid_value[0]\n xe = grid_value[nx]\n dx = np.diff(grid_value[0:(nx+1)])\n yo = grid_value[nx+1]\n ye = grid_value[nx+1+ny]\n dy = np.diff(grid_value[nx+1:(nx+1+ny+1)])\n zo = grid_value[nx+1+ny+1]\n ze = grid_value[nx+1+ny+1+nz]\n dz = np.diff(grid_value[nx+1+ny+1:(nx+1+ny+1+nz+1)])\n x = xo + np.cumsum(dx) - 0.5 * dx\n y = yo + np.cumsum(dy) - 0.5 * dy\n z = zo + np.cumsum(dz) - 0.5 * dz\n print(\"Grid retrived from eSTOMP input\")\n return xo, yo, zo, xe, ye, ze, dx, dy, dz, nx, ny, nz, x, y, z\n\n\nsimu_dir = \"/pic/projects/dvz/xhs_simus/bcomplex/fy19/marks/demo0/\"\nboundary = True\nsource = True\nzon_file = simu_dir\n\ngrid_in = simu_dir+\"input\"\nsource_in = simu_dir+\"input\"\nbc_in = simu_dir+\"input\"\nzon_file = simu_dir+\"bcomplex_fred_tanks_perchsilt.zon\"\nh5_file = simu_dir+\"input.h5\"\n\nxo, yo, zo, xe, ye, ze, dx, dy, dz, nx, ny, nz, x, y, z = retrieve_grids(\n grid_in)\n\n# find unique source location\nif source:\n source = parse_source_card(source_in)\n source_loc = []\n for s in source[\"loc\"]:\n if s not in source_loc:\n source_loc.append(s)\nelse:\n source_loc = []\n\n# find unique boundary location\nif boundary:\n boundary = parse_boundary_card(bc_in)\n bc_loc = boundary[\"loc\"]\nelse:\n bc_loc = []\n\n# get zonation\nwith open(zon_file) as f:\n zon = np.asarray([int(x) for x in re.split(\" |\\n\", f.read()) if x])\nrock = zon.reshape((nx, ny, nz), order=\"F\")\n\nhdf5 = h5.File(h5_file, 'w')\nhdf5_dim = hdf5.create_group(\"dimension\")\nhdf5_dim.create_dataset(\"x\", data=x)\nhdf5_dim.create_dataset(\"y\", data=y)\nhdf5_dim.create_dataset(\"z\", data=z)\nhdf5_dim.create_dataset(\"dx\", data=dx)\nhdf5_dim.create_dataset(\"dy\", data=dy)\nhdf5_dim.create_dataset(\"dz\", data=dz)\nhdf5_dim.create_dataset(\"xo\", data=xo)\nhdf5_dim.create_dataset(\"yo\", data=yo)\nhdf5_dim.create_dataset(\"zo\", data=zo)\nhdf5_dim.create_dataset(\"xe\", data=xe)\nhdf5_dim.create_dataset(\"ye\", data=ye)\nhdf5_dim.create_dataset(\"ze\", data=ze)\nhdf5_varis = hdf5.create_group(\"varis\")\nhdf5_varis.create_dataset(\"rock\", data=np.swapaxes(rock, 0, 2))\nif len(source_loc) > 0:\n source_indicator = np.empty((nz, ny, nx))\n source_indicator.fill(np.nan)\n source_cells = [[[x, y, z] for z in np.arange(s[4], s[5]+1)\n for y in np.arange(s[2], s[3]+1)\n for x in np.arange(s[0], s[1]+1)]\n for s in source_loc]\n for source_index, isource in enumerate(source_cells):\n for icell in isource:\n source_indicator[icell[2]-1][icell[1]-1\n ][icell[0]-1] = int(source_index+1)\n hdf5_varis.create_dataset(\"source indicator\",\n data=source_indicator)\nif len(bc_loc) > 0:\n bc_indicator = np.empty((nz, ny, nx))\n bc_indicator.fill(np.nan)\n for bc_index, ibc in enumerate(bc_loc):\n for icell in ibc:\n bc_indicator[icell[2]-1][icell[1] -\n 1][icell[0]-1] = int(bc_index+1)\n hdf5_varis.create_dataset(\"bc indicator\",\n data=bc_indicator)\nhdf5.close()\n\n# extract model dimension variable name\nhdf5 = h5.File(h5_file, 'r')\nx = hdf5[\"dimension\"][\"x\"][:]\ny = hdf5[\"dimension\"][\"y\"][:]\nz = hdf5[\"dimension\"][\"z\"][:]\nnx = len(x)\nny = len(y)\nnz = len(z)\nvaris = list(hdf5[\"varis\"].keys())\nhdf5.close()\n\n# initialize xdmf\nxml_root = ET.Element(\"Xdmf\", Version=\"3.0\")\nxml_domain = ET.SubElement(xml_root, \"Domain\")\n\n# geometry is defined by VXVYVZ mode, three vectors\n# assume toplogy geometry is time invariant\nxml_toplogoy = ET.SubElement(xml_domain, \"Topology\",\n {'TopologyType': '3DRECTMesh',\n 'Dimensions': \"{0} {1} {2}\".format(nz, ny, nx)})\nxml_geometry = ET.SubElement(xml_domain, 'Geometry',\n {'GeometryType': \"VXVYVZ\"})\nxml_geometry_x = ET.SubElement(xml_geometry, 'DataItem',\n {'Dimensions': str(nx),\n \"NumberType\": \"Float\",\n \"Precision\": \"8\",\n \"Format\": \"XML\"})\nxml_geometry_x.text = np.array_str(x).strip(\"[]\").replace(\"\\n\", \" \")\nxml_geometry_y = ET.SubElement(xml_geometry, 'DataItem',\n {'Dimensions': str(ny),\n \"NumberType\": \"Float\",\n \"Precision\": \"8\",\n \"Format\": \"XML\"})\nxml_geometry_y.text = np.array_str(y).strip(\"[]\").replace(\"\\n\", \" \")\nxml_geometry_z = ET.SubElement(xml_geometry, 'DataItem',\n {'Dimensions': str(nz),\n \"NumberType\": \"Float\",\n \"Precision\": \"8\",\n \"Format\": \"XML\"})\nxml_geometry_z.text = np.array_str(z).strip(\"[]\").replace(\"\\n\", \" \")\n\ngrid = ET.SubElement(xml_domain, \"Grid\",\n {'Name': \"STOMP\",\n 'GridType': 'Uniform'})\ntopology_ref = ET.SubElement(\n grid, \"Topology\", {\"Reference\": \"/Xdmf/Domain/Topology\"})\ngeometry_ref = ET.SubElement(\n grid, \"Geometry\", {\"Reference\": \"/Xdmf/Domain/Geometry\"})\n\nscalars = varis\nscalar_handle = {}\nscalar_data_handle = {}\nfor iscalar in range(len(scalars)):\n scalar_handle[iscalar] = ET.SubElement(\n grid, \"Attribute\",\n {\"Name\": scalars[iscalar],\n \"AttributeType\": \"Scalar\",\n \"Center\": \"Node\"})\n scalar_data_handle[iscalar] = ET.SubElement(\n scalar_handle[iscalar], \"DataItem\",\n {\"Format\": \"HDF\",\n \"NumberType\": \"Float\",\n \"Precision\": \"8\",\n \"Dimensions\": \"{0} {1} {2}\".format(nz, ny, nx)})\n scalar_data_handle[iscalar].text = h5_file.split(\"/\")[-1] + \\\n \":/varis/\" + scalars[iscalar]\n# dump xdmf\nfname = simu_dir + \"input.xdmf\"\nwith open(fname, 'w') as f:\n f.write(prettify(xml_root))\n","sub_path":"stomp_input_vis.py","file_name":"stomp_input_vis.py","file_ext":"py","file_size_in_byte":13625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"33884425","text":"import json\nimport os\nimport re\nimport time\nimport webbrowser\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom termcolor import colored\n\n\nclass Menu:\n def __init__(self):\n self.products = json.load(open(\"products.json\"))\n self.profile = json.load(open(\"profile.json\"))\n\n def start(self):\n print(colored(\"Main Menu\", \"yellow\"))\n print(\"1: Product\")\n print(\"2: Profile\")\n print(\"3: Run\\n\")\n\n selection = input(\"> \")\n\n if selection == \"1\":\n menu.product_menu()\n elif selection == \"2\":\n menu.profile_menu()\n elif selection == \"3\":\n confirmation = input(\"\\nrun all? [y/n] \")\n if confirmation == \"y\" or confirmation == \"\":\n for i in range(20):\n print(\".\")\n time.sleep(0.05)\n bot.main()\n elif confirmation == \"n\":\n print(colored(\"\\nreturning to menu...\\n\", \"red\"))\n menu.start()\n else:\n print(colored(\"\\nreturning to menu...\\n\", \"red\"))\n menu.start()\n elif selection == \"q\":\n exit(0)\n else:\n print(colored(\"\\nEnter a Valid Selection\\n\", \"red\"))\n menu.start()\n\n def product_menu(self):\n print(colored(\"\\nProducts\", \"yellow\"))\n print(\"0: Back\")\n print(\"1: Enter Products\")\n print(\"2: View Products\\n\")\n\n selection = input(\"> \")\n\n if selection == \"0\":\n print()\n menu.start()\n elif selection == \"1\":\n menu.enter_product()\n menu.product_menu()\n elif selection == \"2\":\n self.products = json.load(open(\"products.json\"))\n menu.view_product()\n menu.product_menu()\n else:\n print(colored(\"\\nEnter a Valid Selection\", \"red\"))\n menu.product_menu()\n\n def profile_menu(self):\n print(colored(\"\\nProfile\", \"yellow\"))\n print(\"0: Back\")\n print(\"1: Edit Profile\")\n print(\"2: View Profile\\n\")\n\n selection = input(\"> \")\n\n if selection == \"0\":\n print()\n menu.start()\n elif selection == \"1\":\n menu.edit_profile()\n menu.start()\n elif selection == \"2\":\n self.profile = json.load(open(\"profile.json\"))\n menu.view_profile()\n menu.start()\n else:\n print(colored(\"\\nEnter a Valid Selection\", \"red\"))\n menu.profile_menu()\n\n def enter_product(self):\n number_of_products = input(\"\\nNumber of Products (1-3): \")\n\n if number_of_products == \"1\":\n products = {\n \"number_of_products\": number_of_products,\n \"product 1\": input(\"Product Name: \"),\n \"category 1\": input(\"Enter Category: \"),\n \"color 1\": input(\"Enter Product Color: \"),\n }\n elif number_of_products == \"2\":\n products = {\n \"number_of_products\": number_of_products,\n \"product 1\": input(\"Product Name: \"),\n \"category 1\": input(\"Enter Category: \"),\n \"color 1\": input(\"Enter Product Color: \"),\n \"product 2\": input(\"Product Name: \"),\n \"category 2\": input(\"Enter Category: \"),\n \"color 2\": input(\"Enter Product Color: \"),\n }\n elif number_of_products == \"3\":\n products = {\n \"number_of_products\": number_of_products,\n \"product 1\": input(\"Product Name: \"),\n \"category 1\": input(\"Enter Category: \"),\n \"color 1\": input(\"Enter Product Color: \"),\n \"product 2\": input(\"Product Name: \"),\n \"category 2\": input(\"Enter Category: \"),\n \"color 2\": input(\"Enter Product Color: \"),\n \"product 3\": input(\"Product Name: \"),\n \"category 3\": input(\"Enter Category: \"),\n \"color 3\": input(\"Enter Product Color: \"),\n }\n\n with open(\"products.json\", \"w\") as f:\n json.dump(products, f)\n print()\n\n menu.start()\n\n def view_product(self):\n print()\n for key in self.products:\n if key != \"number_of_products\":\n capitalized_key = \" \".join(k.capitalize() for k in key.split(\"_\"))\n key_value = self.products[key]\n print(\"{}: {}\".format(colored(capitalized_key, \"magenta\"), key_value))\n print()\n\n menu.start()\n\n def edit_profile(self):\n print()\n name = re.compile(r\"[A-Z][a-z]*\\s[A-Z][a-z]*(\\s[A-Z])?\")\n email = re.compile(r\"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\")\n phone = re.compile(r\"(\\+\\d{1,2}\\s)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\")\n address = re.compile(\n r\"\\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St)\\.?\"\n )\n zipcode = re.compile(r\"\\d{5}\")\n card = re.compile(r\"(?:\\d[ -]*?){13,16}\")\n month = re.compile(r'\"0[1-9]\"|\"1[0-2]\"')\n year = re.compile(r'\"20\\d{2}\"')\n cvv = re.compile(r'\"\\d{3}\"')\n\n profile = {\n \"name\": input(\"Cardholder's Name: \"),\n \"email\": input(\"Email: \"),\n \"phone\": input(\"Phone: \"),\n \"address\": input(\"Address: \"),\n \"zip\": input(\"Zipcode: \"),\n \"card\": input(\"Card Number: \"),\n \"month\": input(\"Card Expiration Month: \"),\n \"year\": input(\"Card Expiration Year: \"),\n \"cvv\": input(\"Card CVV: \"),\n }\n\n with open(\"profile.json\", \"w\") as f:\n json.dump(profile, f)\n\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(name.sub(profile[\"name\"], contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(email.sub(profile[\"email\"], contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(phone.sub(profile[\"phone\"], contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(address.sub(profile[\"address\"], contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(zipcode.sub(profile[\"zip\"], contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(card.sub(profile[\"card\"], contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(month.sub('\"{}\"'.format(profile[\"month\"]), contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(year.sub('\"{}\"'.format(profile[\"year\"]), contents))\n with open(\"autofill.js\") as f:\n contents = f.read()\n with open(\"autofill.js\", \"w\") as f:\n f.write(cvv.sub('\"{}\"'.format(profile[\"cvv\"]), contents))\n print()\n\n menu.start()\n\n def view_profile(self):\n print()\n for key in self.profile:\n capitalized_key = \" \".join(k.capitalize() for k in key.split(\"_\"))\n key_value = self.profile[key]\n print(\"{}: {}\".format(colored(capitalized_key, \"magenta\"), key_value))\n print()\n\n menu.start()\n\n\nclass Bot:\n def __init__(self):\n self.base = \"https://www.supremenewyork.com\"\n self.shop_ext = \"/shop/all\"\n self.checkout_ext = \"/checkout\"\n self.products = json.load(open(\"products.json\"))\n self.browser = webbrowser.get(\"chrome\")\n\n def find_product(self, x):\n try:\n category = self.products[f\"category {x}\"].lower().replace(\"/\", \"_\")\n\n r = requests.get(\"{}{}/{}\".format(self.base, self.shop_ext, category), headers=headers).text\n soup = BeautifulSoup(r, \"lxml\")\n\n temp_tuple = []\n temp_link = []\n\n for link in soup.find_all(\"a\", href=True):\n temp_tuple.append((link[\"href\"], link.text))\n\n for i in temp_tuple:\n if self.products[f\"product {x}\"] in i[1] or self.products[f\"color {x}\"] in i[1]:\n temp_link.append(i[0])\n\n self.final_link = list(set([x for x in temp_link if temp_link.count(x) == 2]))[0]\n return True\n except:\n return False\n\n def main(self):\n self.products = json.load(open(\"products.json\"))\n products = list(range(1, int(self.products[\"number_of_products\"]) + 1))\n found_product = False\n max_count = 10\n count = 0\n if not found_product and count < max_count:\n # print(\"---------------------------\")\n print(colored(\"Looking for Product...\", attrs=[\"bold\"]))\n while not found_product and count < max_count:\n found_product = bot.find_product(1)\n count += 1\n time.sleep(0.2)\n if found_product:\n print(colored(\"Product found!\", \"green\"))\n for i in products:\n bot.find_product(i)\n self.browser.open(f\"{self.base}{self.final_link}\")\n print(colored(\"Opening Chrome...done!\", \"cyan\"))\n exit(0)\n else:\n bot.main()\n\n\nif __name__ == \"__main__\":\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)\"\n \"CriOS/80.0.3987.95 Mobile/15E148 Safari/604.1\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"DNT\": \"1\",\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\",\n \"TE\": \"Trailers\",\n }\n bot = Bot()\n menu = Menu()\n os.system(\"clear\")\n menu.start()\n","sub_path":"JavaScript/Bot/supremeBot/findProduct.py","file_name":"findProduct.py","file_ext":"py","file_size_in_byte":10331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"443626210","text":"# Copyright 2021 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff\n# This software is distributed under the 3-clause BSD License.\n# Code that is producing a xhat and a confidence interval using sequantial sampling \n# This extension of SeqSampling works for multistage, using independant \n# scenarios instead of a single scenario tree.\n\nimport pyomo.environ as pyo\nimport mpi4py.MPI as mpi\nimport mpisppy.utils.sputils as sputils\nimport numpy as np\nimport scipy.stats\nimport importlib\nfrom mpisppy import global_toc\n \nfullcomm = mpi.COMM_WORLD\nglobal_rank = fullcomm.Get_rank()\n\nimport mpisppy.utils.amalgomator as amalgomator\nimport mpisppy.utils.xhat_eval as xhat_eval\nimport mpisppy.confidence_intervals.ciutils as ciutils\nfrom mpisppy.confidence_intervals.seqsampling import SeqSampling\nfrom mpisppy.tests.examples.aircond_submodels import xhat_generator_aircond\nimport mpisppy.confidence_intervals.sample_tree as sample_tree\nimport mpisppy.confidence_intervals.ciutils as ciutils\n\nclass IndepScens_SeqSampling(SeqSampling):\n def __init__(self,\n refmodel,\n xhat_generator,\n options,\n stopping_criterion = \"BM\",\n stochastic_sampling = False,\n ):\n super().__init__(\n refmodel,\n xhat_generator,\n options,\n stochastic_sampling = stochastic_sampling,\n stopping_criterion = stopping_criterion,\n solving_type = \"EF-mstage\")\n \n self.numstages = len(self.options['branching_factors'])+1\n self.batch_branching_factors = [1]*(self.numstages-1)\n self.batch_size = 1\n \n #TODO: Add a override specifier if it exists\n def run(self,maxit=200):\n refmodel = self.refmodel\n mult = self.sample_size_ratio # used to set m_k= mult*n_k\n scenario_denouement = refmodel.scenario_denouement if hasattr(refmodel, \"scenario_denouement\") else None\n #----------------------------Step 0 -------------------------------------#\n #Initialization\n k=1\n \n if self.stopping_criterion == \"BM\":\n #Finding a constant used to compute nk\n r = 2 #TODO : we could add flexibility here\n j = np.arange(1,1000)\n if self.q is None:\n s = sum(np.power(j,-self.p*np.log(j)))\n else:\n if self.q<1:\n raise RuntimeError(\"Parameter q should be greater than 1.\")\n s = sum(np.exp(-self.p*np.power(j,2*self.q/r)))\n self.c = max(1,2*np.log(s/(np.sqrt(2*np.pi)*(1-self.confidence_level))))\n \n lower_bound_k = self.sample_size(k, None, None, None)\n \n #Computing xhat_1.\n \n #We use sample_size_ratio*n_k observations to compute xhat_k\n xhat_branching_factors = ciutils.scalable_branching_factors(mult*lower_bound_k, self.options['branching_factors'])\n mk = np.prod(xhat_branching_factors)\n self.xhat_gen_options['start_seed'] = self.SeedCount #TODO: Maybe find a better way to manage seed\n xhat_scenario_names = refmodel.scenario_names_creator(mk)\n\n xgo = self.xhat_gen_options.copy()\n xgo.pop(\"solver_options\", None) # it will be given explicitly\n xgo.pop(\"scenario_names\", None) # it will be given explicitly\n xhat_k = self.xhat_generator(xhat_scenario_names,\n solver_options=self.solver_options,\n **xgo)\n self.SeedCount += sputils.number_of_nodes(xhat_branching_factors)\n\n #----------------------------Step 1 -------------------------------------#\n #Computing n_1 and associated scenario names\n \n nk = np.prod(ciutils.scalable_branching_factors(lower_bound_k, self.options['branching_factors'])) #To ensure the same growth that in the one-tree seqsampling\n estimator_scenario_names = refmodel.scenario_names_creator(nk)\n \n #Computing G_nk and s_k associated with xhat_1\n \n Gk, sk = self.gap_estimators_with_independant_scenarios(xhat_k,\n nk,\n estimator_scenario_names,\n scenario_denouement)\n\n \n #----------------------------Step 2 -------------------------------------#\n\n while( self.stop_criterion(Gk,sk,nk) and k1)\n Gk = ciutils.correcting_numeric(G,objfct=obj_at_xhat,\n relative_error=use_relative_error)\n \n self.SeedCount = start\n \n return Gk,sk\n \n\nif __name__ == \"__main__\":\n solvername = \"cplex\"\n #An example of sequential sampling for the aircond model\n import mpisppy.tests.examples.aircond_submodels\n bfs = [3,3,2]\n num_scens = np.prod(bfs)\n scenario_names = mpisppy.tests.examples.aircond_submodels.scenario_names_creator(num_scens)\n xhat_gen_options = {\"scenario_names\": scenario_names,\n \"solvername\": solvername,\n \"solver_options\": None,\n \"branching_factors\": bfs,\n \"mudev\": 0,\n \"sigmadev\": 40,\n \"start_ups\": False,\n \"start_seed\": 0,\n }\n\n optionsBM = {'h':0.55,\n 'hprime':0.5, \n 'eps':0.5, \n 'epsprime':0.4, \n \"p\":0.2,\n \"q\":1.2,\n \"solvername\": solvername,\n \"xhat_gen_options\": xhat_gen_options,\n \"start_ups\": False,\n \"branching_factors\": bfs}\n \n optionsFSP = {'eps': 15.0,\n 'solvername': solvername,\n \"c0\":50,\n \"xhat_gen_options\": xhat_gen_options,\n \"start_ups\": False,\n \"branching_factors\": bfs}\n \n aircondpb = IndepScens_SeqSampling(\"mpisppy.tests.examples.aircond_submodels\",\n xhat_generator_aircond, \n optionsBM,\n stopping_criterion=\"BM\"\n )\n\n res = aircondpb.run(maxit=50)\n print(res)\n\n \n \n","sub_path":"mpisppy/confidence_intervals/multi_seqsampling.py","file_name":"multi_seqsampling.py","file_ext":"py","file_size_in_byte":14318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"57103991","text":"class Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n finalArr = []\n oddArr = []\n \n for i in A:\n if i % 2 == 0:\n finalArr.append(i)\n else:\n oddArr.append(i)\n \n for i in oddArr:\n finalArr.append(i)\n \n return finalArr\n","sub_path":"LeetCode/Sort Array By Parity.py","file_name":"Sort Array By Parity.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"36470637","text":"from flask_login import LoginManager\nfrom flask_migrate import Migrate\nfrom flask_sqlalchemy import SQLAlchemy\n\n\nmodel = SQLAlchemy()\nmigrate = Migrate()\nloginManager= LoginManager()\n\ndef init_ext(app):\n model.init_app(app=app)\n migrate.init_app(app=app,db=model)\n loginManager.init_app(app)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"app/ext.py","file_name":"ext.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521281997","text":"# ============================================================\n# Copyright (c) 2012, Lawrence Livermore National Security, LLC.\n# Produced at the Lawrence Livermore National Laboratory.\n# Written by Joel Bernier and others.\n# LLNL-CODE-529294.\n# All rights reserved.\n#\n# This file is part of HEXRD. For details on dowloading the source,\n# see the file COPYING.\n#\n# Please also see the file LICENSE.\n#\n# This program is free software; you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License (as published by the Free Software\n# Foundation) version 2.1 dated February 1999.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this program (see file LICENSE); if not, write to\n# the Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n# Boston, MA 02111-1307 USA or visit .\n# ============================================================\nfrom distutils.core import setup, Extension\nimport os\nimport sys\nimport numpy\n\nnp_include_dir = os.path.join(numpy.get_include(), 'numpy')\n\n# for SgLite\nsrclist = ['sgglobal.c','sgcb.c','sgcharmx.c','sgfile.c',\n 'sggen.c','sghall.c','sghkl.c','sgltr.c','sgmath.c','sgmetric.c',\n 'sgnorm.c','sgprop.c','sgss.c','sgstr.c','sgsymbols.c',\n 'sgtidy.c','sgtype.c','sgutil.c','runtests.c','sglitemodule.c']\nsrclist = [os.path.join('hexrd/sglite', f) for f in srclist]\n\nsglite_mod = Extension('hexrd.xrd.sglite', sources=srclist,\n define_macros=[('PythonTypes', 1)])\n\n# for transforms\nsrclist = ['transforms_CAPI.c', 'transforms_CFUNC.c']\nsrclist = [os.path.join('hexrd/transforms', f) for f in srclist]\n\ntransforms_mod = Extension('hexrd.xrd._transforms_CAPI', sources=srclist,\n include_dirs=[np_include_dir])\n\n# all modules\next_modules = [sglite_mod, transforms_mod]\n\npackages = []\nfor dirpath, dirnames, filenames in os.walk('hexrd'):\n if '__init__.py' in filenames:\n packages.append('.'.join(dirpath.split(os.sep)))\n else:\n del(dirnames[:])\n\nwith open('hexrd/__init__.py') as f:\n for line in f:\n if line[:11] == '__version__':\n exec(line)\n break\n\nscripts = []\nif sys.platform.startswith('win'):\n # scripts calling multiprocessing must be importable\n import shutil\n shutil.copy('scripts/hexrd', 'scripts/hexrd_app.py')\n scripts.append('scripts/hexrd_app.py')\nelse:\n scripts.append('scripts/hexrd')\nif ('bdist_wininst' in sys.argv) or ('bdist_msi' in sys.argv):\n scripts.append('scripts/hexrd_win_post_install.py')\n\nsetup(\n name = 'hexrd',\n version = '0.0.0',\n author = 'Joel Bernier, et al.',\n author_email = 'bernier2@llnl.gov',\n description = 'High energy diffraction microscopy',\n license = 'LGPL',\n ext_modules = ext_modules,\n packages = packages,\n requires = (\n 'python (>=2.6)',\n 'numpy (>=1.4.0)',\n 'scipy (>=0.7.0)',\n 'wxpython (>= 2.8)',\n ),\n scripts = scripts,\n package_data = {'hexrd': ['COPYING', 'wx/hexrd.png', 'data/materials.cfg'] }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"518182761","text":"from copy import deepcopy\n####################################################################\n#Problem for CSE 630 | Theory of Algorithms #\n#Homework 4 Problem 3 #\n#This problem demonstrates a dynamic programming solution of an NP #\n#problem #\n#The program returns the amount of unique combinations, and #\n#the arrays of the combinations of teams. #\n####################################################################\ndef team_builder(v,n,total,seen):\n answer = 0\n if len(v) == n:\n print (v)\n if v in seen:\n return 0\n if sum(v) == total:\n print(\"returning 1\")\n seen.append(v)\n return 1\n else:\n return 0\n else:\n for x in v:\n copyv = deepcopy(v)\n copyv.remove(x)\n answer += team_builder(deepcopy(copyv),n,total,seen)\n return answer\n\ndef main():\n v = [19,17,16,13,11,10,9,7,6,2]\n seen = []\n n = len(v)/2\n team_size = 0\n total = sum(v)/2\n print(team_builder(deepcopy(v),n,total,seen))\n print (seen)\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"Homework4/hw4p3.py","file_name":"hw4p3.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416715841","text":"def solution(table, languages, preference):\r\n table.sort() # 사전순을 위해 정렬\r\n\r\n # 2차원 배열로 변경\r\n list = []\r\n for arr in table:\r\n list.append(arr.split())\r\n\r\n # 점수 계산\r\n score = []\r\n for i in list:\r\n sum = 0\r\n for j in range(len(languages)):\r\n if languages[j] in i:\r\n sum += (6 - i.index(languages[j])) * preference[j]\r\n score.append(sum)\r\n\r\n max_score = max(score)\r\n idx = score.index(max_score)\r\n\r\n return list[idx][0]\r\n\r\nprint(solution([\"SI JAVA JAVASCRIPT SQL PYTHON C#\", \"CONTENTS JAVASCRIPT JAVA PYTHON SQL C++\", \"HARDWARE C C++ PYTHON JAVA JAVASCRIPT\", \"PORTAL JAVA JAVASCRIPT PYTHON KOTLIN PHP\", \"GAME C++ C# JAVASCRIPT C JAVA\"], [\"PYTHON\", \"C++\", \"SQL\"], [7, 5, 5]))\r\n","sub_path":"ans4572/6주차/프로그래머스 직업군 추천하기.py","file_name":"프로그래머스 직업군 추천하기.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"434335680","text":"\"Wasm module messages.\"\n\nfrom __future__ import annotations\n\nimport copy\n\nimport attr\n\nfrom terra_sdk.core import AccAddress, Coins\nfrom terra_sdk.core.msg import Msg\nfrom terra_sdk.util.contract import b64_to_dict, dict_to_b64\nfrom terra_sdk.util.json import dict_to_data\n\n__all__ = [\n \"MsgStoreCode\",\n \"MsgInstantiateContract\",\n \"MsgExecuteContract\",\n \"MsgMigrateContract\",\n \"MsgUpdateContractOwner\",\n]\n\n\n@attr.s\nclass MsgStoreCode(Msg):\n \"\"\"Upload a new smart contract WASM binary to the blockchain.\n\n Args:\n sender: address of sender\n wasm_byte_code: base64-encoded string containing bytecode\n \"\"\"\n\n type = \"wasm/MsgStoreCode\"\n \"\"\"\"\"\"\n\n sender: AccAddress = attr.ib()\n wasm_byte_code: str = attr.ib(converter=str)\n\n @classmethod\n def from_data(cls, data: dict) -> MsgStoreCode:\n data = data[\"value\"]\n return cls(sender=data[\"sender\"], wasm_byte_code=data[\"wasm_byte_code\"])\n\n\n@attr.s\nclass MsgInstantiateContract(Msg):\n \"\"\"Creates a new instance of a smart contract from existing code on the blockchain.\n\n Args:\n owner: address of contract owner\n code_id (int): code ID to use for instantiation\n init_msg: InitMsg to initialize contract\n init_coins (Coins): initial amount of coins to be sent to contract\n migratable: whether the owner can change contract code IDs\"\"\"\n\n type = \"wasm/MsgInstantiateContract\"\n \"\"\"\"\"\"\n\n owner: AccAddress = attr.ib()\n code_id: int = attr.ib(converter=int)\n init_msg: dict = attr.ib()\n init_coins: Coins = attr.ib(converter=Coins, factory=Coins)\n migratable: bool = attr.ib(default=False)\n\n def to_data(self) -> dict:\n d = copy.deepcopy(self.__dict__)\n d[\"code_id\"] = str(d[\"code_id\"])\n d[\"init_msg\"] = dict_to_b64(d[\"init_msg\"])\n return {\"type\": self.type, \"value\": dict_to_data(d)}\n\n @classmethod\n def from_data(cls, data: dict) -> MsgInstantiateContract:\n data = data[\"value\"]\n return cls(\n owner=data[\"owner\"],\n code_id=data[\"code_id\"],\n init_msg=b64_to_dict(data[\"init_msg\"]),\n init_coins=Coins.from_data(data[\"init_coins\"]),\n migratable=data[\"migratable\"],\n )\n\n\n@attr.s\nclass MsgExecuteContract(Msg):\n \"\"\"Execute a state-mutating function on a smart contract.\n\n Args:\n sender: address of sender\n contract: address of contract to execute function on\n execute_msg: ExecuteMsg (aka. HandleMsg) to pass\n coins: coins to be sent, if needed by contract to execute.\n Defaults to empty ``Coins()``\n \"\"\"\n\n type = \"wasm/MsgExecuteContract\"\n \"\"\"\"\"\"\n\n sender: AccAddress = attr.ib()\n contract: AccAddress = attr.ib()\n execute_msg: dict = attr.ib()\n coins: Coins = attr.ib(converter=Coins, factory=Coins)\n\n def to_data(self) -> dict:\n d = copy.deepcopy(self.__dict__)\n d[\"execute_msg\"] = dict_to_b64(d[\"execute_msg\"])\n return {\"type\": self.type, \"value\": dict_to_data(d)}\n\n @classmethod\n def from_data(cls, data: dict) -> MsgExecuteContract:\n data = data[\"value\"]\n return cls(\n sender=data[\"sender\"],\n contract=data[\"contract\"],\n execute_msg=b64_to_dict(data[\"execute_msg\"]),\n coins=Coins.from_data(data[\"coins\"]),\n )\n\n\n@attr.s\nclass MsgMigrateContract(Msg):\n \"\"\"Migrate the contract to a different code ID.\n\n Args:\n owner: address of owner\n contract: address of contract to migrate\n new_code_id (int): new code ID to migrate to\n migrate_msg (dict): MigrateMsg to execute\n \"\"\"\n\n type = \"wasm/MsgMigrateContract\"\n \"\"\"\"\"\"\n\n owner: AccAddress = attr.ib()\n contract: AccAddress = attr.ib()\n new_code_id: int = attr.ib(converter=int)\n migrate_msg: dict = attr.ib()\n\n def to_data(self) -> dict:\n d = copy.deepcopy(self.__dict__)\n d[\"new_code_id\"] = str(d[\"new_code_id\"])\n d[\"migrate_msg\"] = dict_to_b64(d[\"migrate_msg\"])\n return {\"type\": self.type, \"value\": dict_to_data(d)}\n\n @classmethod\n def from_data(cls, data: dict) -> MsgMigrateContract:\n data = data[\"value\"]\n return cls(\n owner=data[\"owner\"],\n contract=data[\"contract\"],\n new_code_id=data[\"new_code_id\"],\n migrate_msg=b64_to_dict(data[\"migrate_msg\"]),\n )\n\n\n@attr.s\nclass MsgUpdateContractOwner(Msg):\n \"\"\"Update a smart contract's owner.\n\n Args:\n owner: address of current owner (sender)\n new_owner: address of new owner\n contract: address of contract to change\n \"\"\"\n\n type = \"wasm/MsgUpdateContractOwner\"\n \"\"\"\"\"\"\n\n owner: AccAddress = attr.ib()\n new_owner: AccAddress = attr.ib()\n contract: AccAddress = attr.ib()\n\n @classmethod\n def from_data(cls, data: dict) -> MsgUpdateContractOwner:\n data = data[\"value\"]\n return cls(\n owner=data[\"owner\"],\n new_owner=data[\"new_owner\"],\n contract=data[\"contract\"],\n )\n","sub_path":"terra_sdk/core/wasm/msgs.py","file_name":"msgs.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383439143","text":"\n# coding: utf-8\n\n# In[125]:\n\nimport threading\nthreading.stack_size(0x2000000)\n\nimport os\nimport re\nimport pandas as pd\n\ndirectory = os.getcwd() # setting working directory\n\n\n\n# In[134]:\n\n\nnames = os.listdir(directory)\nnames = [x for x in names if re.match(r\".+.tab\", x)]\nprint(len(names), \"files in the directory\")\n#print(directory)\n\n\n# In[128]:\n\n\nwith open(names[0], 'r') as f1:\n lines = [x.strip() for x in f1.readlines()]\n #print(len(lines)/2)\n col_names = [x for x in range(int(len(lines)/2))]\ndf = pd.DataFrame({'Names':col_names})\n#print(df)\n\n\n# In[130]:\n\n\no = 0\nfor file in names:\n #print(file)\n with open(file, 'r') as f:\n line = f.readline()\n col = []\n while len(line) > 0:\n line_str = line.split()\n #print(line_str)\n if len(line_str) > 2:\n col.append(line_str[1])\n line = f.readline()\n o += 1\n #print(o)\n #print(file)\n #print(col)\n df[file.split(\"#\")[1][1:-22]] = col\n#print(df.bottom())\n\n\n# In[133]:\n\n\n\n#print(df)\ndf.to_csv(\"merged.tab\", sep='\\t')\nprint(\"All\", len(names), \"rows were saved into merged.tab file\")\nprint(\"End!\")\n\n","sub_path":"Python_tabs_merger.py","file_name":"Python_tabs_merger.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"27518068","text":"import os, sys\r\nfrom gui.gui import GUI\r\nfrom PyQt5.QtWidgets import QApplication\r\n\r\ndef run():\r\n app = QApplication(sys.argv)\r\n gui = GUI()\r\n gui.showMaximized()\r\n sys.exit(app.exec_())\r\n\r\nif __name__ == '__main__':\r\n run()","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"131399030","text":"# Copyright 2017 The Bazel 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\"\"\"Repo rule to register toolchains required for py_image and py3_image rules.\n\"\"\"\n\nload(\n \"@bazel_tools//tools/cpp:lib_cc_configure.bzl\",\n \"get_cpu_value\",\n \"resolve_labels\",\n)\nload(\"@bazel_tools//tools/osx:xcode_configure.bzl\", \"run_xcode_locator\")\n\ndef _impl(repository_ctx):\n \"\"\"Core implementation of _py_toolchains.\"\"\"\n\n cpu_value = get_cpu_value(repository_ctx)\n env = repository_ctx.os.environ\n if \"BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN\" in env and env[\"BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN\"] == \"1\":\n # Create an alias to the bazel_tools local toolchain as no cpp toolchain will be produced\n repository_ctx.file(\"BUILD\", content = (\"\"\"# Alias to local toolchain\npackage(default_visibility = [\"//visibility:public\"])\n\nlicenses([\"notice\"]) # Apache 2.0\n\nalias(\n name = \"container_cc_toolchain\",\n actual = \"@bazel_tools//tools/cpp:cc-toolchain-local\",\n)\n\n\"\"\"), executable = False)\n\n else:\n if cpu_value == \"x64_windows\":\n # Note this is not well tested\n cpu_value = \"x64_windows_msys\"\n toolchain = \"@local_config_cc//:cc-compiler-%s\" % cpu_value\n if cpu_value == \"darwin\":\n # This needs to be carefully kept in sync with bazel/tools/cpp/cc_configure.bzl\n should_use_xcode = \"BAZEL_USE_XCODE_TOOLCHAIN\" in env and env[\"BAZEL_USE_XCODE_TOOLCHAIN\"] == \"1\"\n xcode_toolchains = []\n paths = resolve_labels(repository_ctx, [\n \"@bazel_tools//tools/osx:xcode_locator.m\",\n ])\n if not should_use_xcode:\n (xcode_toolchains, _xcodeloc_err) = run_xcode_locator(\n repository_ctx,\n paths[\"@bazel_tools//tools/osx:xcode_locator.m\"],\n )\n if should_use_xcode or xcode_toolchains:\n toolchain = \"@local_config_cc//:cc-compiler-darwin_x86_64\"\n else:\n toolchain = \"@local_config_cc//:cc-compiler-darwin\"\n\n repository_ctx.file(\"BUILD\", content = (\"\"\"# Toolchain required for xx_image targets that rely on xx_binary\n# which transitively require a C/C++ toolchain (currently only\n# py_binary). This one is for local execution and will be required\n# with versions of Bazel > 1.0.0\npackage(default_visibility = [\"//visibility:public\"])\n\nlicenses([\"notice\"]) # Apache 2.0\n\nload(\"@local_config_platform//:constraints.bzl\", \"HOST_CONSTRAINTS\")\n\ntoolchain(\n name = \"container_cc_toolchain\",\n exec_compatible_with = HOST_CONSTRAINTS + [\"@io_bazel_rules_docker//platforms:run_in_container\"],\n target_compatible_with = HOST_CONSTRAINTS,\n toolchain = \"%s\",\n toolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n) \n\"\"\") % toolchain, executable = False)\n\npy_toolchains = repository_rule(\n attrs = {},\n implementation = _impl,\n)\n","sub_path":"toolchains/py_toolchains.bzl","file_name":"py_toolchains.bzl","file_ext":"bzl","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402510004","text":"\nfrom flask import jsonify\nfrom app import Ads, session\nfrom app.Exeptions import *\n\n\ndef get_ad_info(id=None, name=None, fields=False):\n if name is not None:\n ad = session.query(Ads).filter_by(name=name).first()\n if ad:\n session.expire_all()\n ad = {'id': ad.id}\n return jsonify(ad), 200\n else:\n raise AdNotFoundException\n else:\n ad = session.query(Ads).filter_by(id=id).first()\n if ad:\n session.expire_all()\n if fields:\n ad = {'id': ad.id, 'name': ad.name, 'price': ad.price, 'description': ad.description, 'main_url': ad.main_url, 'url2': ad.url2, 'url3': ad.url3}\n else:\n ad = {'id': ad.id, 'name': ad.name, 'price': ad.price, 'description': ad.description}\n return jsonify(ad), 200\n else:\n raise AdNotFoundException\n\n\ndef add_ad_info(name, price, description=None, main_url=None, url2=None, url3=None):\n if name is not None and price is not None:\n ad = Ads(\n name=name,\n price=price,\n description=description,\n main_url=main_url,\n url2=url2,\n url3=url3\n )\n session.add(ad)\n session.flush()\n return get_ad_info(name=name)\n else:\n raise IncorrectInputException\n\n\ndef get_ads_info(page=None, sort=None):\n sort_list = {\n \"price_asc\": Ads.price.asc(),\n \"price_desc\": Ads.price.desc(),\n \"date_asc\": Ads.data_create.asc(),\n \"date_desc\": Ads.data_create.desc(),\n }\n if sort is None:\n ads = session.query(Ads).all()\n elif sort in sort_list:\n ads = session.query(Ads).order_by(sort_list[sort]).all()\n if ads:\n ads_list = []\n if page is not None:\n for ad in ads[(page-1)*10:(page)*10]:\n ad = {'name': ad.name, 'price': ad.price, 'url': ad.main_url}\n ads_list.append(ad)\n session.expire_all()\n return jsonify(f'page {page}. Ads from {(page-1)*10+1} to {(page)*10}', ads_list), 200\n else:\n for ad in ads:\n ad = {'name': ad.name, 'price': ad.price, 'url': ad.main_url}\n ads_list.append(ad)\n session.expire_all()\n return ads_list, 200\n else:\n raise TableIsEmpty\n\n\ndef del_ad(id):\n ad = session.query(Ads).filter_by(id=id).one()\n session.delete(ad)\n session.flush()\n return f'ok', 200","sub_path":"app/interaction.py","file_name":"interaction.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547288090","text":"import requests\n\nfile_name = 'dataset_3378_2.txt'\nwith open(file_name) as file:\n dataset = file.read().strip()\nr = requests.get(dataset)\nlist_data = r.text\nnum = len(list_data.splitlines())\nprint(num)\nwith open('answer', 'w') as out:\n for i in list_data.splitlines(True):\n out.write(i)","sub_path":"py4_9.py","file_name":"py4_9.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"285966080","text":"#first\nmy_list =[0,1,2,3,4,5,6,7]\n\nimport numpy as np\narr = np.array(my_list)\n\narr2= np.arange(0,10,3)\n\nlin_sp = np.linspace(0,1,20)\n\nranarr = np.random.randint(0,50, 10)\n\narr2.reshape(2,2)\narr2.dtype\n\n# second\narr = np.arange(0,11)\n\narr_2d = np.array([[5,6,7],[8,9,10],[11,12,13]])\n\narr_2d[1:,:-1]\n\nbool_arr = arr>5\n\narr[bool_arr]\n\narr_2d_2 = np.arange(50).reshape(5,10)\n\narr_2d_2[3:5,2:4]\n\narr = np.arange(0,11).reshape(2,2)\narr.sum()\nhelp(arr.sum)\n\n","sub_path":"machine_learn/ml_libraries/ml_01.py","file_name":"ml_01.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427181610","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 7 18:23:30 2017\n\n@author: zan\n\"\"\"\n\n\"\"\"\n Healthcare Analytics – \n Recommender system for hospitals based on Medicare ratings and patient surveys\n\"\"\"\n\n# Download the Medicare Hospital Compare data from the website\nimport requests\nimport os\nimport zipfile\nimport openpyxl\nimport pandas as pd\nimport glob\nimport sqlite3\n\n\nurl = 'https://data.medicare.gov/views/bg9k-emty/files/0a9879e0-3312-4719-a1db-39fd114890f1?content_type=application%2Fzip%3B%20charset%3Dbinary&filename=Hospital_Revised_Flatfiles.zip'\nr = requests.get(url)\n\n# Create the staging directory\nstaging_dir = \"staging\"\nos.mkdir(staging_dir)\n\n# Confirm the staging directory path\nos.path.isdir(staging_dir)\n\n# Machine independent path to create files\nzip_file = os.path.join(staging_dir, \"Hospital_Revised_Flatfiles.zip\")\n\n# Write the files to the computer\nzf = open(zip_file,\"wb\")\nzf.write(r.content)\nzf.close()\n\n# Program to unzip the files\nz = zipfile.ZipFile(zip_file,\"r\")\nz.extractall(staging_dir)\nz.close()\n\n# Delete the corrupt csv\nos.listdir(os.getcwd())\n\nos.remove(\"staging/FY2015_Percent_Change_in_Medicare_Payments.csv\")\n\n# Download the proprietary in-house information\nk_url = \"http://kevincrook.com/utd/hospital_ranking_focus_states.xlsx\"\nr = requests.get(k_url)\n\n# Open the excel files with the proprietary in-house information\nxf = open(\"hospital_ranking_focus_states.xlsx\",\"wb\")\nxf.write(r.content)\nxf.close()\n\n# Read the proprietary excel files\nwb = openpyxl.load_workbook(\"hospital_ranking_focus_states.xlsx\")\n\n# Write the rows of the hospital_ranking sheet\nhospital_national_ranking = wb.get_sheet_by_name(\"Hospital National Ranking\")\n\ni = 1\nwhile hospital_national_ranking.cell(row=i, column = 1).value != None:\n print(hospital_national_ranking.cell(row=i, column = 1).value, \"|\", hospital_national_ranking.cell(row = i, column = 2).value)\n i += 1\n\n# Write the rows of the focus_states sheet\nfocus_states = wb.get_sheet_by_name(\"Focus States\")\n\ni = 1\nwhile focus_states.cell(row=i, column=1).value != None:\n print(focus_states.cell(row=i, column=1).value, \"|\", focus_states.cell(row = i, column = 2).value)\n i += 1\n\n# Convert the proprietary information to Pandas\nhospital_national_ranking = pd.DataFrame(hospital_national_ranking.values, dtype = str)\nhospital_national_ranking.columns = ['provider_id','ranking']\n\nfocus_states = pd.DataFrame(focus_states.values, dtype = str)\nfocus_states.columns = ['state_name','state_abbreviation']\n\n# Convert all letters to lower case\nhospital_national_ranking.columns = hospital_national_ranking.columns.str.lower()\nfocus_states.columns = focus_states.columns.str.lower()\n\n# Drop the first row containing the old column headers\nhospital_national_ranking.drop(hospital_national_ranking.head(1).index, inplace=True)\nfocus_states.drop(focus_states.head(1).index, inplace = True)\n\n# Write the excel files to the staging directory\nhospital_national_ranking.to_csv(os.path.join(staging_dir,r'hospital_national_ranking.csv'), encoding = 'utf-8')\nfocus_states.to_csv(os.path.join(staging_dir,r'focus_states.csv'), encoding = 'utf-8')\n\n# Format the file names\n\"\"\"\nConvert all letters to lower case DONE\nReplace each blank “ “ with an underscore “_” DONE\nReplace each dash or hyphen “-“ with an underscore “_” DONE\nReplace each percent sign “%” with the string “pct” DONE\nReplace each forward slash “/” with an underscore “_” DONE\nIf a table name starts with anything other than a letter “a” through “z” then prepend “t_” to the front of the table name\nIf a column name starts with anything other than a letter “a” through “z” then prepend “c_” to the front of the column name\n\"\"\"\nos.listdir(\"staging\")\n\n# Seperate filename from extension\nsep = os.sep\n\n# Change the casing\nfor n in os.listdir(\"staging\"):\n print(n)\n if os.path.isfile(\"staging\" + sep + n):\n filename_one, extension = os.path.splitext(n)\n os.rename(\"staging\" + sep + n, \"staging\" + sep + filename_one.lower() + extension)\n\n# Remove the blanks, -, %, and /\nfor n in os.listdir(\"staging\"):\n print (n)\n if os.path.isfile(\"staging\" + sep + n):\n filename_zero, extension = os.path.splitext(n)\n os.rename(\"staging\" + sep + n , \"staging\" + sep + filename_zero.replace(' ','_').replace('-','_').replace('%','pct').replace('/','_') + extension)\n\n# Show the new file names\nprint ('\\n--------------------------------\\n')\nfor n in os.listdir(\"staging\"):\n print (n)\n\n\"\"\"\nIn order to fix all of the column headers and to solve the encoding issues and remove nulls, \nfirst read in all of the CSV's to python as dataframes, then make changes and rewrite the old files\n\"\"\"\nfiles = glob.glob(os.path.join(\"staging\" + \"/*.csv\"))\n\nprint(files)\n\n# Create an empty dictionary to hold the dataframes from csvs\ndict_ = {}\n\n# Write the files into the dictionary\nfor file in files:\n fname = os.path.basename(file)\n fname = fname.replace('.csv', '')\n dict_[fname] = pd.read_csv(file, header = 0, dtype = str, encoding = 'cp1252').fillna('')\n\n\"\"\"\nConvert all letters to lower case \nReplace each blank “ “ with an underscore “_” \nReplace each dash or hyphen “-“ with an underscore “_” \nReplace each percent sign “%” with the string “pct” \nReplace each forward slash “/” with an underscore “_” \nIf a table name starts with anything other than a letter “a” through “z” then prepend “t_” to the front of the table name\nIf a column name starts with anything other than a letter “a” through “z” then prepend “c_” to the front of the column name\n\"\"\"\n# Convert all letters to lower case\nfor file in files:\n fname = os.path.basename(file)\n fname = fname.replace('.csv', '')\n dict_[fname].columns = dict_[fname].columns.str.lower()\n\n# Fix the column headers \nfor file in files:\n fname = os.path.basename(file)\n fname = fname.replace('.csv', '')\n dict_[fname].rename(columns = lambda x: x.replace(' ', '_').replace('-', '_').replace('%', 'pct').replace('/', '_'), inplace = True)\n # Add the prefix to columns beginning with non-alpha characters\n mask = dict_[fname].columns.str[0].str.isalpha()\n dict_[fname].columns = dict_[fname].columns.where(mask, 'c_' + dict_[fname].columns) \n\n\"\"\"\nRewrite the dataframes to csv in utf8, overwriting old values \n\nfor file in dict_:\n dict_[file].to_csv(file, encoding = 'utf-8')\n\"\"\"\n\n# Create the SQL Lite database\nconn = sqlite3.connect(\"medicare_hospital_compare.db\")\n\n# Convert the dict_[file]'s to SQL tables\nfor key, df in dict_.items(): \n df.to_sql(key, conn, flavor = None, schema = None, if_exists = 'replace', \n index = False, index_label = None, chunksize = None, dtype = None)\n\n# Queries\n\ncur = conn.cursor()\n\n# Top 100 hospitals nationwide\nnational_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\ngroup by hospital_national_ranking.ranking\nhaving cast(hospital_national_ranking.ranking as decimal) < 101\norder by cast(hospital_national_ranking.ranking as decimal) asc;\"\"\", conn)\n\n# Top 100 hospitals California\nca_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%CA%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Florida\nfl_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%FL%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Georgia\nga_results = pd.read_sql_query(\"\"\"select \n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%GA%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Illinois\nil_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%IL%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Kansas\nks_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%KS%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Michigan\nmi_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%MI%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals New York\nny_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%NY%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Ohio\noh_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%OH%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# Top 100 hospitals Pennsylvania\npa_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%PA%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\n# # Top 100 hospitals Texas\ntx_results = pd.read_sql_query(\"\"\"select\n\t\t hospital_general_information.provider_id as 'Provider ID',\n\t\t hospital_name as 'Hospital Name',\n city as 'City',\n state as 'State',\n county_name as 'County'\nfrom hospital_general_information left join hospital_national_ranking\non hospital_general_information.provider_id = hospital_national_ranking.provider_id\nwhere state like '%TX%'\ngroup by hospital_national_ranking.ranking\norder by cast(hospital_national_ranking.ranking as decimal) asc\nlimit 100;\"\"\", conn)\n\nranking_results_list = [national_results, ca_results, fl_results, ga_results, il_results, ks_results, mi_results, ny_results, oh_results, pa_results, tx_results]\n\n# Nationwide measure statistics\nnationwide_measures = pd.read_sql_query(\"\"\"select state,\n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital;\"\"\", conn)\n\n# CA measure statistics\nca_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%CA%\";\"\"\", conn)\n\n# FL measure statistics\nfl_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%FL%\";\"\"\", conn)\n\n# GA measure statistics\nga_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%GA%\";\"\"\", conn)\n\n# IL measure statistics\nil_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%IL%\";\"\"\", conn)\n\n# KS measure statistics\nks_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%KS%\";\"\"\", conn)\n\n# MI measure statistics\nmi_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%MI%\";\"\"\", conn)\n\n# NY measure statistics\nny_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%NY%\";\"\"\", conn)\n\n# OH measure statistics\noh_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%OH%\";\"\"\", conn)\n\n# PA measure statistics\npa_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%PA%\";\"\"\", conn)\n\n# TX measure statistics\ntx_stat = pd.read_sql_query(\"\"\"select \n\t\t measure_id,\n\t\t measure_name,\n\t\t score\nfrom timely_and_effective_care___hospital\nwhere state like \"%TX%\";\"\"\", conn)\n\nmeasure_results_list = [nationwide_measures, ca_stat, fl_stat, ga_stat, il_stat, ks_stat, mi_stat, ny_stat, oh_stat, pa_stat, tx_stat]\n\ndef fix_result(lst):\n fixed_list = []\n measures_list = []\n for result in lst:\n # Remove the non-numeric string values from 'score'\n result1 = result[result['score'].astype(str).str.isdigit()]\n # Change score to numeric\n result1['score'] = pd.to_numeric(result1['score'])\n fixed_list.append(result1)\n for lst in fixed_list:\n # Calculate the measure statistics\n lst_measure_results = (lst.groupby(['measure_id','measure_name'])['score'].agg(['min','max','mean','std'])\n .rename(columns={'measure_id':'Measure ID','measure_name':'Measure Name','min':'Minimum','max':'Maximum','mean':'Average','std':'Standard Deviation'})\n .rename_axis(['Measure ID','Measure Name'])\n .reset_index())\n measures_list.append(lst_measure_results)\n return measures_list\n\nmeasure_results_list1 = fix_result(measure_results_list) \n\nmeasure_statistics = pd.ExcelWriter(\"measure_statistics.xlsx\")\n\nlist_sheet_name = ['Nationwide','California', 'Florida', 'Georgia', 'Illinois', 'Kansas', 'Michigan', 'New York', 'Ohio', 'Pennsylvania', 'Texas']\nfor df, sheetname in zip(measure_results_list1,list_sheet_name):\n df.to_excel(measure_statistics, sheet_name=sheetname)\n\nmeasure_statistics.save()\n\nhospital_ranking = pd.ExcelWriter(\"hospital_ranking.xlsx\")\nfor df, sheetname in zip(ranking_results_list,list_sheet_name):\n df.to_excel(hospital_ranking, sheet_name=sheetname)\n\nhospital_ranking.save()\n\n","sub_path":"archive/hospital_performance_review/analyze_medicare_data.py","file_name":"analyze_medicare_data.py","file_ext":"py","file_size_in_byte":16864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"312857206","text":"import time\nimport pandas as pd\nimport numpy as np\nimport csv\nimport datetime\nfrom datetime import date\nimport calendar\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\nmonths = ['january', 'february', 'march', 'april',\n 'may', 'june']\n\ndays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',\n 'saturday', 'sunday']\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n \n \n cities = ''\n for item in CITY_DATA:\n if cities == '':\n cities += item.title()\n else:\n cities += ', ' + item.title()\n \n city = input('Please enter one of the following cities: {}\\n'.format(cities)).lower()\n while city not in CITY_DATA:\n city = input('Invalid input. ' +\n 'please enter one of the following cities:\\n{}\\n'.format(cities)).lower()\n \n \n# print('***********************start**********************') \n data_display = input('Would you like to show the first 5 rows of the data-> Yes or NO \\n').lower()\n newcity= city+'.csv'\n if(datadisplay == 'yes'):\n \n with open(newcity, 'r') as file:\n reader = csv.reader(file)\n line_count = 0\n for row in reader:\n if line_count <= 5:\n line_count = line_count+1\n print(row)\n line_count = 0\n# print('***********************End**********************') \n \n x = ''\n for item in months:\n if x == '':\n x += item\n else:\n x += ', ' + item.title()\n \n month = input('Please enter one of the following to filter by month:\\n{}\\n'.format(x)).lower()\n while month not in months and month != 'all':\n month = input(\"\\nInvalid selection. \" +\n \"Please enter one of the following options to filter by month. \" +\n \"\\n(All, {})\\n\".format(x)).lower()\n \n tempmonth= month\n month_num = datetime.datetime.strptime(month, '%B').month\n if month_num <10:\n \n month_num= str( month_num)\n month = '-0'+month_num+'-'\n else:\n month_num= str( month_num)\n month = '-'+month_num+'-'\n newMonth=[] \n with open(newcity, 'r') as file:\n reader = csv.reader(file)\n line_count = 0\n data_display = input('Would you like to show the first 5 rows of the data-> Yes or NO \\n').lower()\n if(datadisplay == 'yes'):\n for row in reader:\n\n # print('start')\n\n if month in row[1]:\n if line_count <=+ 5:\n line_count = line_count+1\n print(row)\n line_count = 0\n\n# If the string you want to search is in the row\n# print(\"String found in first row of csv\")\n# break\n\n x = ''\n for item in days:\n if x == '':\n x += item.title()\n else:\n x += ', ' + item.title()\n \n day = input('Please enter one of the following to filter by day:\\nAll, {}\\n'.format(x)).lower()\n while day not in days and day != 'all':\n day = input(\"\\nInvalid selection. \" +\n \"Please enter one of the following options to filter by day.\" +\n \"\\n(All, {})\\n\".format(x)).lower()\n \n with open(newcity, 'r') as file:\n reader = csv.reader(file)\n line_count = 0\n datadisplay = input('Would you like to show the first 5 rows of the data-> Yes or NO \\n').lower()\n newcity= city+'.csv'\n if(datadisplay == 'yes'):\n for row in reader:\n\n # print('start')\n \n if month in row[1]:\n li=list(row[1].split(\" \"))\n li=li[0]\n df = pd.Timestamp(li)\n# print('start')\n# print(day)\n y=df.weekday_name\n \n y.replace(\" \", \"\")\n day.replace(\" \", \"\")\n if day == y:\n if line_count <= 5:\n print(df.day_name)\n line_count = line_count+1\n else:\n print('not found')\n line_count = 0\n\n print('-'*40)\n month= tempmonth\n return city, month, day\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n \n df = pd.read_csv(CITY_DATA.get(city))\n \n if 'Start Time' in df.columns:\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n if month != 'all':\n df = df[df['month'] == (months.index(month) + 1) ]\n \n if day != 'all':\n df = df[df['day_of_week'] == day.title()]\n \n if 'End Time' in df.columns:\n df['End Time'] = pd.to_datetime(df['End Time'])\n \n print('\\nFILTER SECTION:\\nCity: {}\\nMonth: {}\\n Day: {}'.format(city, month, day))\n \n return df\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nThe Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n common_month = df['month'].mode()[0]\n print('Most common month', common_month)\n\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n frequent_day = df['day_of_week'].mode()[0]\n print('Most frequent day', frequent_day)\n\n df['Start_hour'] = df['Start Time'].dt.hour\n frequent_hour = df['Start_hour'].mode()[0]\n print('Most frequent hour', frequent_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n df['Start Station'].mode()[0]\n\n df['Start Station'].mode()[0]\n\n df['Combined Trip Station'] = df['Start Station'] + 'travelling to ' + df['End Station']\n combined_stations = df['Combined Trip Station'].mode()[0]\n print(combined_stations)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nTrip Duration...\\n')\n start_time = time.time()\n\n total_travel_time = df['Trip Duration'].sum()\n print('Total time travelled', total_travel_time)\n\n mean_travel_time = df['Trip Duration'].mean()\n print('Average time travelled', mean_travel_time)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n user_types = df['User Type'].value_counts()\n print(user_types)\n\n if 'Gender' in df:\n gender = df['Gender'].value_counts()\n print(gender)\n else:\n print('There is no gender information')\n\n if 'Birth Year' in df:\n earliest = df['Birth Year'].max()\n print(earliest)\n most_recent = df['Birth Year'].min()\n print(most_recent)\n common_year_birth = df['Birth Year'].mode()[0]\n print(common_year_birth)\n else:\n print('There is no year of birth')\n \n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511009754","text":"import requests, json, static_vars, pytz\nfrom datetime import datetime, date, timedelta, time\nfrom pytz import timezone, datetime, tzinfo\nfrom bs4 import BeautifulSoup\n\n# Connectwise headers for connecting to API throughout\nheaders = static_vars.BASE_HEADERS\n\n# Table of Contents - Ctrl + F > Function Name \n# def qotd(): - Web scrap for QOTD.\n# def dateback(): - Checks for staff return date on In/Out board in connectwise, and deletes the entry if they're meant to be back today.\n# def l1phones(): - Phone agents rostered today.\n# def sched(): - Scheduled Site Visits for the day.\n# def ead(): - checks for escalation time.\n# def leave(): - checks for sick, vacation, other leave.\n# def training(): - checks for training schedules.\n# def close(): - adds wait on input section, purely for compiled exe.\n\n# Performs a web scrape using module BeautifulSoup4 and gathers alt text from the image to give the quote of the day.\n\n# global variables\n\ndef qotd():\n global quote\n res = requests.get('https://www.brainyquote.com/quotes_of_the_day.html')\n soup = BeautifulSoup(res.text, 'lxml')\n quote = soup.find('img',{'class':'p-qotd'})\n quote = str((quote['alt']))\n print('Quote:')\n print(quote)\n print(\"\")\n l1phones()\n\n# Verifies which phone agents are in the office (checking a team tied to service board (Service\\Teams\\L1Phones)) also checks in and out board)\ndef l1phones():\n print(\"Phone Agents\")\n print(\"Service engineers not assigned to project tickets or site visits.\")\n print(\"\")\n print(\"Overflow Phone Agents\")\n print(\"Systems Engineers and Senior Systems Engineers currently in the office not working on project work are expected to take overflow calls.\")\n print(\"\")\n dateback()\n\ndef dateback():\n i = 0\n\n inOutURL = static_vars.BASE_URL+\"/system/inOutBoards/\"\n response = requests.request(\"GET\", inOutURL, headers=headers)\n inOutData = json.loads(response.text)\n \n # Section performs a number of string and time conversions so that it's human readable, but also Connectwise Readable\n while i < len(inOutData):\n dateback = inOutData[i]['dateBack']\n translation_table = dict.fromkeys(map(ord, 'T'), ' ')\n translation_table2 = dict.fromkeys(map(ord, 'Z'), ' UTC+0000')\n dateback = dateback.translate(translation_table)\n dateback = dateback.translate(translation_table2)\n dateback = datetime.datetime.strptime(dateback, \"%Y-%m-%d %H:%M:%S %Z%z\")\n today = date.today()\n fmt = \"%Y-%m-%d\"\n\n if dateback.strftime(fmt) <= today.strftime(fmt):\n inOutURL = static_vars.BASE_URL+\"/system/inOutBoards/\"\n response = requests.request(\"GET\", inOutURL, headers=headers)\n j = 0\n inOutData = json.loads(response.text)\n IODataCrumb = str(inOutData[i]['id'])\n patchurl = static_vars.BASE_URL+\"/system/inOutBoards/\"+IODataCrumb\n today = date.today()\n fmt = \"%Y-%m-%d\"\n translation_table = dict.fromkeys(map(ord, 'T'), ' ')\n translation_table2 = dict.fromkeys(map(ord, 'Z'), ' UTC+0000')\n adelaide = timezone('Australia/Adelaide')\n \n # Checks for a return date of today in the InOutBoard, and deletes if it's today or older, making less manual handling on the InOutBoard.\n while j < len(inOutData):\n dateback = inOutData[i]['dateBack']\n dateback = dateback.translate(translation_table)\n dateback = dateback.translate(translation_table2)\n dateback = datetime.datetime.strptime(dateback, \"%Y-%m-%d %H:%M:%S %Z%z\")\n dateback = dateback.astimezone(adelaide) \n \n if dateback.strftime(fmt) <= today.strftime(fmt):\n requests.request(\"DELETE\", patchurl, headers=headers)\n j += 1\n else:\n j += 1\n i += 1\n else:\n i += 1\n sched()\n\n# Checks for Site Visits using the Schedule Location / On-Site, does a number of time conversions based on UTC times to get it in to Adelaide.\ndef sched():\n # For time conversions\n today = date.today()\n today = str(today)\n yesterday = date.today() - timedelta(1)\n yesterday = str(yesterday)\n fmt = '%H:%M' \n translation_table = dict.fromkeys(map(ord, 'T'), ' ')\n translation_table2 = dict.fromkeys(map(ord, 'Z'), ' UTC+0000')\n adelaide = timezone('Australia/Adelaide')\n\n # For JSON data\n j = 0\n url = static_vars.BASE_URL+\"/schedule/entries?conditions=dateStart > [\"+ yesterday +\"T13:30:00Z] and dateEnd < [\"+ today +\"T13:29:59Z]&pageSize=1000\"\n response = requests.request(\"GET\", url, headers=headers)\n jsondata = json.loads(response.text)\n \n inOutURL = static_vars.BASE_URL+\"/system/inOutBoards/\"\n response = requests.request(\"GET\", inOutURL, headers=headers)\n inOutData = json.loads(response.text)\n sitevisit = []\n global siteVisitBody\n siteVisitBody = \"\"\n\n print(\"Today's Site Visits -\", today)\n while j < len(jsondata):\n if 'where' not in jsondata[j]:\n j += 1\n elif 'C' in jsondata[j]['type']['identifier'] and 'On-Site' in jsondata[j]['where']['name']:\n cwdatestart = jsondata[j]['dateStart']\n cwdateend = jsondata[j]['dateEnd']\n\n cwdatestart = cwdatestart.translate(translation_table)\n cwdateend = cwdateend.translate(translation_table)\n\n cwdatestart = cwdatestart.translate(translation_table2)\n cwdateend = cwdateend.translate(translation_table2)\n \n cwdatestart = datetime.datetime.strptime(cwdatestart, \"%Y-%m-%d %H:%M:%S %Z%z\")\n cwdateend = datetime.datetime.strptime(cwdateend, \"%Y-%m-%d %H:%M:%S %Z%z\")\n\n cwdatestart = cwdatestart.astimezone(adelaide)\n cwdateend = cwdateend.astimezone(adelaide)\n print(cwdatestart.strftime(fmt), '-', cwdateend.strftime(fmt), jsondata[j]['name'], \" : \", jsondata[j]['member']['name'])\n siteVisitBody = siteVisitBody + str(cwdatestart.strftime(fmt) + ' - ' + cwdateend.strftime(fmt) + \" \" + jsondata[j]['name'] + \" : \" + jsondata[j]['member']['name'] + \"
\")\n sitevisit.append(jsondata[j]['member']['name'])\n j += 1\n elif 'C' in jsondata[j]['type']['identifier']: # C is sales tickets\n j += 1 \n elif 'On-Site' in jsondata[j]['where']['name']: \n cwdatestart = jsondata[j]['dateStart']\n cwdateend = jsondata[j]['dateEnd']\n\n cwdatestart = cwdatestart.translate(translation_table)\n cwdateend = cwdateend.translate(translation_table)\n\n cwdatestart = cwdatestart.translate(translation_table2)\n cwdateend = cwdateend.translate(translation_table2)\n \n cwdatestart = datetime.datetime.strptime(cwdatestart, \"%Y-%m-%d %H:%M:%S %Z%z\")\n cwdateend = datetime.datetime.strptime(cwdateend, \"%Y-%m-%d %H:%M:%S %Z%z\")\n\n cwdatestart = cwdatestart.astimezone(adelaide)\n cwdateend = cwdateend.astimezone(adelaide)\n \n print(cwdatestart.strftime(fmt), '-', cwdateend.strftime(fmt), jsondata[j]['name'], \" : \", jsondata[j]['member']['name'])\n siteVisitBody = siteVisitBody + str(cwdatestart.strftime(fmt) + ' - ' + cwdateend.strftime(fmt) + \" \" + jsondata[j]['name'] + \" : \" + jsondata[j]['member']['name'] + \"
\")\n sitevisit.append(jsondata[j]['member']['name'])\n j += 1\n elif 'In-house' in jsondata[j]['where']['name'] :\n j += 1\n elif 'Remote' in jsondata[j]['where']['name'] :\n j += 1\n else:\n j += 1\n \n j = 0\n while j < len(inOutData):\n if 'Client' in inOutData[j]['inOutType']['name']:\n if inOutData[j]['member']['name'] in sitevisit:\n sitevisit.remove(inOutData[j]['member']['name'])\n j += 1\n elif 'additionalInfo' not in inOutData[j]:\n print(inOutData[j]['member']['name'] + \" : Onsite - No Additional Detail\")\n siteVisitBody = siteVisitBody + str(inOutData[j]['member']['name'] + \" : Onsite - No Additional Detail
\")\n sitevisit.append(inOutData[j]['member']['name'])\n j += 1\n else:\n print(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'])\n j += 1\n else:\n j += 1\n \n if len(sitevisit) == 0:\n print(\"No scheduled visits today.\")\n siteVisitBody = \"No scheduled visits today.\"\n print(\"\")\n ead()\n\n# Checks for Escalation assist time existence - May become legacy and moved in to building block\ndef ead():\n j = 0\n today = date.today()\n today = str(today)\n print(\"Escalation Assistance and Documentation Time -\", today)\n print(\"No escalation resource assigned today. Please see Service Coordinator for escalations.\")\n print(\"\")\n leave()\n\n# Checks for schedule entry in calendar with appropriate tag line (Annual, Sick, Other) and lists out, then checks InOutboard. InOutBoard used for Multi-Day Span schedules.\ndef leave():\n j = 0\n today = date.today()\n today = str(today)\n yesterday = date.today() - timedelta(1)\n yesterday = str(yesterday)\n url = static_vars.BASE_URL+\"/schedule/entries?conditions=dateStart > [\"+ yesterday +\"T13:30:00Z] and dateEnd < [\"+ today +\"T13:29:59Z]&pageSize=1000\"\n response = requests.request(\"GET\", url, headers=headers)\n jsondata = json.loads(response.text)\n inOutURL = static_vars.BASE_URL+\"/system/inOutBoards/\"\n response = requests.request(\"GET\", inOutURL, headers=headers)\n inOutData = json.loads(response.text)\n leave = []\n global inOutName\n inOutName = \"\"\n # Section checks schedule entry's for specific types on the Schedule hold and lists, also adds them to list in case of double up.\n print(\"Leave - \", today)\n while j < len(jsondata):\n if 'X' in jsondata[j]['type']['identifier']: # X is personal leave\n print(jsondata[j]['member']['name'], \" - Personal Leave\")\n inOutName = inOutName + str(jsondata[j]['member']['name'] + \" - Personal Leave
\")\n leave.append(jsondata[j]['member']['name'])\n j += 1\n elif 'V' in jsondata[j]['type']['identifier']: # V is annual leave\n print(jsondata[j]['member']['name'], \" - Annual Leave\")\n inOutName = inOutName + str(jsondata[j]['member']['name'] + \" - Annual Leave
\")\n leave.append(jsondata[j]['member']['name'])\n j += 1\n else:\n j += 1\n \n # Checks the InOutBoard for information that could have been skipped due to MultiDay Span. All items written to list and checks for duplicate.\n j = 0\n while j < len(inOutData):\n if 'Vacation' in inOutData[j]['inOutType']['name']:\n if inOutData[j]['member']['name'] in leave:\n j += 1\n elif 'additionalInfo' not in inOutData[j]:\n try:\n print(inOutData[j]['member']['name'] + \" - Leave - no additional detail\")\n inOutName = inOutName + str(inOutData[j]['member']['name'] + \" - Leave - no additional detail
\")\n leave.append(inOutData[j]['member']['name'])\n j += 1\n except KeyError:\n j += 1\n break\n else:\n print(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'])\n inOutName = inOutName + str(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'] + \"
\")\n leave.append(inOutData[j]['member']['name'])\n j += 1\n elif 'Sick' in inOutData[j]['inOutType']['name']:\n if inOutData[j]['member']['name'] in leave:\n j += 1\n elif 'additionalInfo' not in inOutData[j]:\n try:\n print(inOutData[j]['member']['name'] + \" - Sick Leave\")\n inOutName = inOutName + str(inOutData[j]['member']['name'] + \" - Sick Leave
\")\n leave.append(inOutData[j]['member']['name'])\n j += 1\n except KeyError:\n j += 1\n break\n else:\n print(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'])\n inOutName = inOutName + str(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'] + \"
\")\n leave.append(inOutData[j]['member']['name'])\n j += 1\n elif 'Other' in inOutData[j]['inOutType']['name']:\n if inOutData[j]['member']['name'] in leave:\n j += 1\n elif 'additionalInfo' not in inOutData[j]:\n try:\n print(inOutData[j]['member']['name'] + \" - Other\")\n inOutName = inOutName + str(inOutData[j]['member']['name'] + \" - Other
\")\n leave.append(inOutData[j]['member']['name'])\n j += 1\n except KeyError:\n j += 1\n break\n else:\n print(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'])\n inOutName = inOutName + str(inOutData[j]['member']['name']+ \" - \" + inOutData[j]['additionalInfo'] + \"
\")\n leave.append(inOutData[j]['member']['name'])\n j += 1\n else:\n j +=1\n \n if len(leave) == 0:\n inOutName = \"No leave today.\"\n print(\"No leave today.\")\n print(\"\")\n training()\n\ndef training():\n global trainingName\n today = date.today()\n today = str(today)\n j = 0\n yesterday = date.today() - timedelta(1)\n yesterday = str(yesterday)\n \n # Checks for training type schedule holds\n trainingName = \"\"\n trainingUrl = static_vars.BASE_URL+\"/schedule/entries?conditions=dateStart > [\"+ yesterday +\"T13:30:00Z] and dateEnd < [\"+ today +\"T13:29:59Z]&pageSize=1000\"\n trainingResponse = requests.request(\"GET\", trainingUrl, headers=headers)\n trainingdata = json.loads(trainingResponse.text)\n training = []\n print(\"Training - \", today)\n \n while j < len(trainingdata):\n if 'T' in trainingdata[j]['type']['identifier']: # T is Training\n if 'name' in trainingdata[j]:\n print(trainingdata[j]['member']['name'], \" - \", trainingdata[j]['name'])\n trainingName = trainingName + str(trainingdata[j]['member']['name'] + \" - \" + str(trainingdata[j]['name'])) + \"
\"\n else:\n print(trainingdata[j]['member']['name'])\n trainingName = trainingName + str(trainingdata[j]['member']['name']) + \"
\"\n training.append(j)\n j += 1\n else:\n j += 1\n\n if len(training) == 0:\n print(\"No training today.\")\n print(\"\")\n trainingName = \"No Training today
\"\n sendMail()\n\ndef sendMail():\n # Variable Import\n global qotd\n global inOutName\n global siteVisitBody\n global trainingName\n today = date.today()\n today = str(today)\n # Email to Mother to send email\n payload = {\n \"APIKey\": static_vars.MOTHER_KEY,\n \"Subject\": \"[Briefing] \" + today,\n \"emailBody\": '''\n \n
\n
\n
\n Quote of the Day
\n ''' + quote + '''\n
\n
\n Phone Agents
\n Service engineers not assigned to project tickets or site visits.
\n
\n Overflow Phone Agents
\n Systems Engineers and Senior Systems Engineers currently in the office not working on project work are expected to take overflow calls.

\n\n Escalation Assistance and Documentation Time - ''' + today + '''
\n No escalation resource assigned today. Please see Service Coordinator for escalations.

\n Today's Site Visits -''' + today + '''
\n '''\n + siteVisitBody +\n '''\n
\n Training -''' + today + '''
\n '''\n + trainingName +\n '''\n
\n Leave -''' + today + '''
\n '''\n + inOutName +\n '''\n

For issues with the briefing, email: ''' + static_vars.MY_EMAIL + '''
\n \n ''',\n \"To\": static_vars.ALLSTAFF_EMAIL,\n \"BCC\": static_vars.MY_EMAIL\n }\n\n MotherData = json.dumps(payload)\n\n MotherURI = static_vars.MOTHER_URI\n response = requests.post(MotherURI, data=MotherData)\n print(response)\n\n# Pause section for compiled version, stops the window instantly closing. Unrequired for CLI version.\ndef close():\n print()\n print()\n input(\"Press Enter to continue...\")\n\n\n#calls the first function\nqotd()","sub_path":"Autobrief/autobrief.py","file_name":"autobrief.py","file_ext":"py","file_size_in_byte":17383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195965529","text":"#!/usr/bin/python3\nimport socket\n\n# No IP to connect to needed for a server\nIP = \"::\"\nPORT = 3000\n\n# Creates a socket using IPV6 and accepting datagrams\nsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\nsock.bind((IP, PORT))\n\nwhile True:\n data, address = sock.recvfrom(2)\n # Decode the client data\n temperature = data[0] + data[1]/100\n print(\"Address:\", address[0])\n print(\"Temperature:\", temperature)\n print(\"============\")\n","sub_path":"examples/thermo3_client/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"368443361","text":"from . import app\nfrom flask import flash, render_template, request, send_file, redirect, url_for\nfrom os.path import join\nfrom os import listdir\n\napp_directory = join(app.static_folder, 'apps')\n\n'''def file_allowed(filename):\n\n if filename.endswith('.jad') or filename.endswith('.jar'):\n\n return True\n\n return False'''\n\n@app.route('/')\ndef index():\n listing = sorted(listdir(app_directory))\n\n return render_template('wap.index.html', listing = listing)\n\n@app.route('/upload', methods = ['GET', 'POST'])\ndef upload():\n\n return '

Under Construction

'\n\n if request.method == 'POST':\n\n if 'file' not in request.files:\n flash('No file part found')\n return redirect(request.url)\n\n file = request.files['file']\n\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n\n if not file_allowed(file.filename):\n flash('Invalid filename %s!' % file.filename)\n return redirect(request.url)\n\n if file and file_allowed(file.filename):\n file.save(join(app.static_folder, file.filename))\n\n return redirect(url_for('wap.index'))\n\n else:\n flash('An error occured...')\n return redirect(request.url)\n else:\n\n return render_template('wap.upload.html')","sub_path":"blueprints/wap/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545742069","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport sys\nsys.path.append(\"/data/migo/athena/lib\")\nfrom athena_variable import *\nfrom athena_luigi import *\n \nclass Activeness(MigoLuigiHdfs): \n src_nes = luigi.Parameter(default=\"/user/athena/able/nes_tag_week/20150210\")\n period = luigi.IntParameter(default=7)\n\n def requires(self):\n return PreAct(use_hadoop=self.use_hadoop, keep_temp=self.keep_temp, period=self.period, cal_date=self.cal_date, src=self.src, src_nes=self.src_nes, shop_id=self.shop_id, is_add_ta=self.is_add_ta)\n \n def mapper(self, line):\n infos = line.strip().split(MIGO_SEPARATOR_LEVEL1) \n yield infos[0], infos[1]\n \n def combiner(self, shop_id, values):\n child, mother = 0, 0\n\n for value in values:\n kind, num = value.split(MIGO_TMP_SEPARATOR)\n\n if kind == \"child\":\n child += int(num)\n else:\n mother += int(num)\n\n yield shop_id, \"child{}{}\".format(MIGO_TMP_SEPARATOR, child)\n yield shop_id, \"mother{}{}\".format(MIGO_TMP_SEPARATOR, mother)\n \n def reducer(self, shop_id, values):\n child, mother = 0, 0\n\n for value in values:\n kind, num = value.split(MIGO_TMP_SEPARATOR)\n\n if kind == \"child\":\n child += int(num)\n else:\n mother += int(num) \n \n if mother == 0:\n yield shop_id, MIGO_ERROR_NUMBER\n else:\n yield shop_id, float(child)/mother\n \nclass PreAct(MigoPeriodHdfs):\n \"\"\"\n #Job Name: PreAct \n #Objectives: calculate KPI-PreAct\n ==>(transaction times) / (nes tag exclude \"S3\")\n #Author: Cindy Tseng\n #Created Date: 2015.01.12\n #Source: 1. /user/athena/data_prepare_member\n ==> [shop^store] [member] [order_date] [amount]\n 2. /user/athena/nes_tag_week \n ==> [shop^store] [member] [nestag] \n #Destination: /user/cindy/activeness/\n ==> [shop^store] [activeness]\n #Usage: python activeness.py Act --use-hadoop --src \"/user/athena/able/data_prepare_member\" --src-nes /user/athena/able/nes_tag_week/20150210 --dest user/cindy/act --cal-date 20150210 --period 7\n \"\"\"\n\n src_nes = luigi.Parameter()\n \n def requires(self):\n t = super(PreAct, self).requires()\n t.extend([CleanerHDFS(self.src_nes)])\n\n return t \n \n def mapper(self, line):\n infos = line.strip().split(MIGO_SEPARATOR_LEVEL1) \n if len(infos) == 4:\n shop_id, member_id, ordate, amount = infos\n if (shop_id[-5:] != \"^-999\" ) and (member_id != \"-999\"):\n yield \"{}_{}\".format(shop_id, member_id) , ordate \n self.count_success += 1\n elif len(infos) == 3:\n shop_id, member_id, nes = infos\n if nes not in [MIGO_NES_TAG_S3, MIGO_NES_TAG_EB, MIGO_NES_TAG_N]:\n yield \"{}_{}\".format(shop_id, member_id) , \"!{}\".format(nes) \n self.count_success += 1\n else: \n self.count_fail += 1\n \n def reducer(self, shop_id, values): \n values_list = list(values)\n shop, member_id = shop_id.split(\"_\", 1)\n tag = \"L{}D\".format(self.period)\n \n if (\"~\".join(values_list).find(\"!\")) > -1 :\n if len(values_list[1:]) > 0:\n for x in values_list[1:]:\n self.add_ta(shop, self.cal_date, tag, member_id, MIGO_TAG1_ACTIVENESS, 0, 0) \n yield shop, \"child{}{}\".format(MIGO_TMP_SEPARATOR, str(len(values_list[1:])))\n yield shop, \"mother{}1\".format(MIGO_TMP_SEPARATOR)\n\nif __name__ == \"__main__\":\n luigi.run()\n","sub_path":"modules/kpi/bin/activeness.py","file_name":"activeness.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259785894","text":"'''\nReturns total price paid for individual rentals\n'''\nimport argparse\nimport json\nimport datetime\nimport math\nimport logging\nimport sys\n\n\nLOGGER = logging.getLogger('rental_logger')\n\n\ndef parse_cmd_arguments():\n \"\"\"\n Parses all arguments provided to the script at runtime.\n :return:\n \"\"\"\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('-i', '--input', help='input JSON file', required=True)\n parser.add_argument('-o', '--output', help='output JSON file', required=True)\n parser.add_argument('-d', '--debug', help='debug level 0-3', required=False)\n\n return parser.parse_args()\n\n\ndef set_logging_level(level):\n \"\"\"\n Sets debug level for the program based on the argument passed at runtime.\n :param level:\n :return:\n \"\"\"\n\n level_dict = {\n 1: logging.ERROR,\n 2: logging.WARNING,\n 3: logging.DEBUG\n }\n\n try:\n # set debug level for which the logger will capture\n debug_level = level_dict[int(level)]\n LOGGER.setLevel(debug_level)\n\n # create file handler which logs even debug messages\n log_file = logging.FileHandler('datetime.datetime.now().strftime(\"%Y-%m-%d\")' + '.log')\n\n # create console handler with a higher log level\n log_stdout = logging.StreamHandler(sys.stdout)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s %(filename)s:%(lineno)-3d \\\n %(levelname)s %(message)s')\n log_stdout.setFormatter(formatter)\n log_file.setFormatter(formatter)\n\n if debug_level == logging.DEBUG:\n log_file.setLevel(logging.WARNING)\n\n LOGGER.addHandler(log_stdout)\n LOGGER.addHandler(log_file)\n\n except KeyError:\n print(\"Invalid Logging level. Disabling logging.\")\n logging.disable(logging.CRITICAL)\n\n\n\ndef load_rentals_file(filename):\n \"\"\"\n Loads the input file to be parsed by the rest of the program. Exits\n if the file is not found.\n :param filename:\n :return:\n \"\"\"\n LOGGER.debug('function call \\\"load_rentals_file()\\\" starts here')\n LOGGER.debug(f'filename to be loaded: {filename}')\n try:\n with open(filename) as file:\n data = json.load(file)\n except FileNotFoundError:\n LOGGER.error(f\"Specified file {filename} was not found. Please specify another input file.\")\n sys.exit()\n return data\n\n\ndef calculate_additional_fields(data):\n \"\"\"\n Parses through data and calculates all fields needed to for rental\n data metrics.\n :param input_data: dictionary of rental transactions\n :return:\n \"\"\"\n LOGGER.debug('function call \\\"calculate_additional_fields()\\\" starts here')\n\n for value in data.values():\n try:\n LOGGER.debug(f\"Full product entry: {value}\")\n rental_start = datetime.datetime.strptime(value['rental_start'], '%m/%d/%y')\n LOGGER.debug(f\"rental_start: {rental_start}\")\n\n rental_end = datetime.datetime.strptime(value['rental_end'], '%m/%d/%y')\n LOGGER.debug(f\"rental_end: {rental_end}\")\n\n value['total_days'] = (rental_end - rental_start).days\n LOGGER.debug(f\"total_days: {value['total_days']}\")\n\n value['total_price'] = value['total_days'] * value['price_per_day']\n LOGGER.debug(f\"total_price calculated value: {value['total_price']}\")\n\n # Sometimes a negative value is calculated for \"total_price\". When this occurs\n # the following expressions will throw an error.\n value['sqrt_total_price'] = math.sqrt(value['total_price'])\n LOGGER.debug(f\"total_price calculated value: {value['sqrt_total_price']}\")\n\n value['unit_cost'] = value['total_price'] / value['units_rented']\n LOGGER.debug(f\"unit_cost calculated value: {value['unit_cost']}\")\n\n # ValueError's will be thrown if the error value is negative or the rental_end\n # value doesn't exist. This is captured in the ValueError value present below\n except ValueError:\n if value['rental_end']:\n LOGGER.error(f\"Trying to calculate negative square root \\\n with total price of {value['total_price']}\")\n else:\n LOGGER.warning('Missing rental_end value. Cannot calculate further values.')\n\n else:\n LOGGER.debug(\"All fields updated successfully.\")\n\n LOGGER.debug(f'Updated rental item entry: {value}')\n return data\n\n\ndef save_to_json(filename, updated_data):\n \"\"\"\n Takes all calculated data and writes to a file specified from the\n command line argument when running the script\n\n :param filename: file to write\n :param updated_data: data to write to filename\n \"\"\"\n\n LOGGER.debug('function call \\\"save_to_json()\\\" starts here')\n LOGGER.debug(f'filename to be created: {filename}')\n with open(filename, 'w') as file:\n json.dump(updated_data, file)\n\n\nif __name__ == \"__main__\":\n args = parse_cmd_arguments()\n\n if args.debug:\n set_logging_level(args.debug)\n else:\n logging.disable(logging.CRITICAL)\n\n input_data = load_rentals_file(args.input)\n calculated = calculate_additional_fields(input_data)\n save_to_json(args.output, calculated)\n","sub_path":"students/mgummel/lesson02/assignment/code/charges_calc.py","file_name":"charges_calc.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"457967339","text":"# -*- coding: utf-8 -*-\n__author__ = 'ŁOKIEĆ'\n__version__ = \"1.0\"\n__copyright__ = \"Copyright 2015, Marcin Kolano\"\n## ***************************************************************************************************************\n## ***************************************************************************************************************\n# libraries required\nimport gc\nimport MySQLdb\nfrom MySQLdb.cursors import Cursor\n## ***************************************************************************************************************\n## ***************************************************************************************************************\nclass BetterExecuteMixin(object):\n \"\"\"\n This mixin class provides an implementation of the execute method\n that properly handles sequence arguments for use with IN tests.\n Examples:\n execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))\n # Notice that when the sequence is the only argument, you still need\n # a surrounding tuple:\n execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))\n EXAMPLES:\n cursor.execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))\n cursor.execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))\n cursor.execute('SELECT * FROM foo WHERE type IN (%s)', (['bar', 'moo'],))\n cursor.execute('SELECT * FROM foo WHERE type=%s', 'bar')\n cursor.execute('SELECT * FROM foo WHERE type=%s', ('bar',))\n \"\"\"\n def execute(self, query, args=None):\n if args is not None:\n try:\n iter(args)\n except TypeError:\n args = (args,)\n else:\n if isinstance(args, basestring):\n args = (args,)\n real_params = []\n placeholders = []\n for arg in args:\n # sequences that we treat as a single argument\n if isinstance(arg, basestring):\n real_params.append(arg)\n placeholders.append('%s')\n continue\n try:\n real_params.extend(arg)\n placeholders.append(','.join(['%s']*len(arg)))\n except TypeError:\n real_params.append(arg)\n placeholders.append('%s')\n args = real_params\n query = query % tuple(placeholders)\n return super(BetterExecuteMixin, self).execute(query, args)\n\nclass BetterCursor(BetterExecuteMixin, Cursor):\n pass\n## ***************************************************************************************************************\n## ***************************************************************************************************************\n# establishing database connection\ndb_connection = MySQLdb.connect(host=\"sql.marcinkolano.nazwa.pl\",port=3307,user=\"marcinkolano_7\",passwd=\"t31ef0nyT\",db=\"marcinkolano_7\", cursorclass=BetterCursor)\ncursor = db_connection.cursor()\n# checking how many rows already\ncursor.execute(\"SELECT count(*) from telefony\")\nrow_count = cursor.fetchone()\nprint(\"Current number of phone numbers: \" + str(row_count[0]))\ncursor.execute(\"SELECT phone_number from telefony\")\n# fetch all the rows in a list of lists\nexisting_row_numbers = cursor.fetchall()\n# list to hold existing numbers\nexisting_ph_numbers_list = []\nfor row in existing_row_numbers:\n existing_ph_numbers_list.append(int(row[0]))\nexisting_ph_numbers_list = sorted(set(existing_ph_numbers_list))\n## -------------------------------------------------------------\n# closing database connection\ncursor.close()\ndb_connection.close()\n## ***************************************************************************************************************\n## ***************************************************************************************************************\n# writing up to 100 phone numbers to each of multiple CSV files in a \"column\" based format\nrequired = row_count[0] / 100 + 2\noutput_file = [open('output/telefony_%i.csv' %i, 'w') for i in range(1,required)]\n# writing 100 phone numbers to each output file\ncomma_counter = 0\nfor number in range(len(existing_ph_numbers_list)):\n if (comma_counter == 99 or number == len(existing_ph_numbers_list)-1):\n number_to_write = str(existing_ph_numbers_list[number])\n comma_counter = 0\n else:\n number_to_write = str(existing_ph_numbers_list[number]) + str(',') + str('\\n')\n comma_counter += 1\n output_file[number/100].write(number_to_write)\n# closing file handlers to output files\nfor phone_file in output_file:\n phone_file.close()\n## ***************************************************************************************************************\n# garbage collection\ngc.collect()\n## ***************************************************************************************************************\n## ***************************************************************************************************************\n","sub_path":"phones_gen.py","file_name":"phones_gen.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155517956","text":"import ipaddress\nimport os\nimport shlex\nimport signal\nimport subprocess\nimport re\n\nfrom .netif import netif\nfrom .type_base import InterfaceType\n\nfrom middlewared.service import private, Service\nfrom middlewared.utils import osc\n\n\nclass InterfaceService(Service):\n\n class Config:\n namespace_alias = 'interfaces'\n\n @private\n def configure(self, data, aliases, wait_dhcp=False, options=None):\n options = options or {}\n\n name = data['int_interface']\n\n iface = netif.get_interface(name)\n\n addrs_database = set()\n addrs_configured = set([\n a for a in iface.addresses\n if a.af != netif.AddressFamily.LINK\n ])\n\n has_ipv6 = data['int_ipv6auto'] or False\n\n if (\n not self.middleware.call_sync('system.is_freenas') and\n self.middleware.call_sync('failover.node') == 'B'\n ):\n ipv4_field = 'int_ipv4address_b'\n ipv6_field = 'int_ipv6address'\n alias_ipv4_field = 'alias_v4address_b'\n alias_ipv6_field = 'alias_v6address_b'\n else:\n ipv4_field = 'int_ipv4address'\n ipv6_field = 'int_ipv6address'\n alias_ipv4_field = 'alias_v4address'\n alias_ipv6_field = 'alias_v6address'\n\n dhclient_running, dhclient_pid = self.middleware.call_sync('interface.dhclient_status', name)\n if dhclient_running and data['int_dhcp']:\n leases = self.middleware.call_sync('interface.dhclient_leases', name)\n if leases:\n reg_address = re.search(r'fixed-address\\s+(.+);', leases)\n reg_netmask = re.search(r'option subnet-mask\\s+(.+);', leases)\n if reg_address and reg_netmask:\n addrs_database.add(self.alias_to_addr({\n 'address': reg_address.group(1),\n 'netmask': reg_netmask.group(1),\n }))\n else:\n self.logger.info('Unable to get address from dhclient')\n if data[ipv6_field] and has_ipv6 is False:\n addrs_database.add(self.alias_to_addr({\n 'address': data[ipv6_field],\n 'netmask': data['int_v6netmaskbit'],\n }))\n else:\n if data[ipv4_field] and not data['int_dhcp']:\n addrs_database.add(self.alias_to_addr({\n 'address': data[ipv4_field],\n 'netmask': data['int_v4netmaskbit'],\n }))\n if data[ipv6_field] and has_ipv6 is False:\n addrs_database.add(self.alias_to_addr({\n 'address': data[ipv6_field],\n 'netmask': data['int_v6netmaskbit'],\n }))\n has_ipv6 = True\n\n carp_vhid = carp_pass = None\n if data['int_vip']:\n addrs_database.add(self.alias_to_addr({\n 'address': data['int_vip'],\n 'netmask': '32',\n 'vhid': data['int_vhid'],\n }))\n carp_vhid = data['int_vhid']\n carp_pass = data['int_pass'] or None\n\n for alias in aliases:\n if alias[alias_ipv4_field]:\n addrs_database.add(self.alias_to_addr({\n 'address': alias[alias_ipv4_field],\n 'netmask': alias['alias_v4netmaskbit'],\n }))\n if alias[alias_ipv6_field]:\n addrs_database.add(self.alias_to_addr({\n 'address': alias[alias_ipv6_field],\n 'netmask': alias['alias_v6netmaskbit'],\n }))\n\n if alias['alias_vip']:\n addrs_database.add(self.alias_to_addr({\n 'address': alias['alias_vip'],\n 'netmask': '32',\n 'vhid': data['int_vhid'],\n }))\n\n if carp_vhid:\n advskew = None\n for cc in iface.carp_config:\n if cc.vhid == carp_vhid:\n advskew = cc.advskew\n break\n\n if has_ipv6:\n iface.nd6_flags = iface.nd6_flags - {netif.NeighborDiscoveryFlags.IFDISABLED}\n iface.nd6_flags = iface.nd6_flags | {netif.NeighborDiscoveryFlags.AUTO_LINKLOCAL}\n else:\n iface.nd6_flags = iface.nd6_flags | {netif.NeighborDiscoveryFlags.IFDISABLED}\n iface.nd6_flags = iface.nd6_flags - {netif.NeighborDiscoveryFlags.AUTO_LINKLOCAL}\n\n if dhclient_running and not data['int_dhcp']:\n self.logger.debug('Killing dhclient for {}'.format(name))\n os.kill(dhclient_pid, signal.SIGTERM)\n\n # Remove addresses configured and not in database\n for addr in addrs_configured:\n if has_ipv6 and str(addr.address).startswith('fe80::'):\n continue\n if addr not in addrs_database:\n self.logger.debug('{}: removing {}'.format(name, addr))\n iface.remove_address(addr)\n else:\n if osc.IS_LINUX and not data['int_dhcp']:\n self.logger.debug('{}: removing possible valid_lft and preferred_lft on {}'.format(name, addr))\n iface.replace_address(addr)\n\n # carp must be configured after removing addresses\n # in case removing the address removes the carp\n if carp_vhid:\n if self.middleware.call_sync('failover.licensed') and not advskew:\n if 'NO_FAILOVER' in self.middleware.call_sync('failover.disabled_reasons'):\n if self.middleware.call_sync('failover.vip.get_states')[0]:\n advskew = 20\n else:\n advskew = 80\n elif self.middleware.call_sync('failover.node') == 'A':\n advskew = 20\n else:\n advskew = 80\n\n # FIXME: change py-netif to accept str() key\n iface.carp_config = [netif.CarpConfig(carp_vhid, advskew=advskew, key=carp_pass.encode())]\n\n # Add addresses in database and not configured\n for addr in (addrs_database - addrs_configured):\n self.logger.debug('{}: adding {}'.format(name, addr))\n iface.add_address(addr)\n\n # Apply interface options specified in GUI\n if data['int_options']:\n self.logger.info('{}: applying {}'.format(name, data['int_options']))\n proc = subprocess.Popen(['/sbin/ifconfig', name] + shlex.split(data['int_options']),\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n close_fds=True)\n err = proc.communicate()[1].decode()\n if err:\n self.logger.info('{}: error applying: {}'.format(name, err))\n\n # In case there is no MTU in interface and it is currently\n # different than the default of 1500, revert it\n if not options.get('skip_mtu'):\n if data['int_mtu']:\n if iface.mtu != data['int_mtu']:\n iface.mtu = data['int_mtu']\n elif iface.mtu != 1500:\n iface.mtu = 1500\n\n if data['int_name'] and iface.description != data['int_name']:\n try:\n iface.description = data['int_name']\n except Exception:\n self.logger.warn(f'Failed to set interface {name} description', exc_info=True)\n\n if netif.InterfaceFlags.UP not in iface.flags and 'down' not in data['int_options'].split():\n iface.up()\n\n # If dhclient is not running and dhcp is configured, lets start it\n if not dhclient_running and data['int_dhcp']:\n self.logger.debug('Starting dhclient for {}'.format(name))\n self.middleware.call_sync('interface.dhclient_start', data['int_interface'], wait_dhcp)\n\n if osc.IS_FREEBSD:\n if data['int_ipv6auto']:\n iface.nd6_flags = iface.nd6_flags | {netif.NeighborDiscoveryFlags.ACCEPT_RTADV}\n subprocess.call(['/etc/rc.d/rtsold', 'onerestart'], stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL, close_fds=True)\n else:\n iface.nd6_flags = iface.nd6_flags - {netif.NeighborDiscoveryFlags.ACCEPT_RTADV}\n\n @private\n def autoconfigure(self, iface, wait_dhcp):\n dhclient_running = self.middleware.call_sync('interface.dhclient_status', iface.name)[0]\n if not dhclient_running:\n # Make sure interface is UP before starting dhclient\n # NAS-103577\n if netif.InterfaceFlags.UP not in iface.flags:\n iface.up()\n return self.middleware.call_sync('interface.dhclient_start', iface.name, wait_dhcp)\n\n @private\n def unconfigure(self, iface, cloned_interfaces, parent_interfaces):\n name = iface.name\n\n # Interface not in database lose addresses\n for address in iface.addresses:\n iface.remove_address(address)\n\n dhclient_running, dhclient_pid = self.middleware.call_sync('interface.dhclient_status', name)\n # Kill dhclient if its running for this interface\n if dhclient_running:\n os.kill(dhclient_pid, signal.SIGTERM)\n\n # If we have bridge/vlan/lagg not in the database at all\n # it gets destroy, otherwise just bring it down.\n if (name not in cloned_interfaces and\n self.middleware.call_sync('interface.type', iface.__getstate__()) in [\n InterfaceType.BRIDGE, InterfaceType.LINK_AGGREGATION, InterfaceType.VLAN,\n ]):\n netif.destroy_interface(name)\n elif name not in parent_interfaces:\n iface.down()\n\n @private\n def alias_to_addr(self, alias):\n addr = netif.InterfaceAddress()\n ip = ipaddress.ip_interface('{}/{}'.format(alias['address'], alias['netmask']))\n addr.af = getattr(netif.AddressFamily, 'INET6' if ':' in alias['address'] else 'INET')\n addr.address = ip.ip\n addr.netmask = ip.netmask\n addr.broadcast = ip.network.broadcast_address\n if 'vhid' in alias:\n addr.vhid = alias['vhid']\n return addr\n","sub_path":"src/middlewared/middlewared/plugins/interface/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":10216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"531245195","text":"#!/usr/bin/env python\n#-*-coding:utf-8 -*-\n#\n#Author: tony - birdaccp at gmail.com\n#Create by:2016-08-30 13:39:23\n#Last modified:2016-08-30 16:05:51\n#Filename:calc.py\n#Description:\n\nimport re\n\n#思路:\n#先分解(),然后*/,最后+-\n\ndef format(strObj):\n _mapping = [('+-', '-'), ('--', '+'), ('-+', '-'), ('++', '+')]\n for _map in _mapping:\n strObj = strObj.replace(_map[0], _map[1])\n return strObj\n\ndef getResult(strs):\n #判断如果有()则说明格式错误\n if re.search(r\"\\(*\\)\", strs):\n return \"格式错误\"\n\n #将重复的操作符取代\n strs = format(strs)\n _reg = re.compile(r\"(\\d+(\\.\\d+)?[\\*/][-]?\\d+(\\.\\d+)?)\")\n _flag = True\n while _flag:\n strs = format(strs)\n res = _reg.search(strs)\n if res:\n strs = strs.replace(res.group(), str(eval(str(res.group()))), 1)\n else:\n _flag = False\n\n #处理之后只有+-了\n _flag = True\n oper = ['+', '-']\n _reg = re.compile(r\"(^[-]?\\d+(\\.\\d+)?[\\+\\-]\\d+(\\.\\d+)?)\")\n while _flag:\n strs = format(strs)\n res = _reg.search(strs)\n if res:\n _find = res.group()\n strs = strs.replace(_find, str(eval(str(_find))), 1)\n\n for o in oper:\n if o not in strs:\n _flag = False\n else:\n if strs.startswith(o) and o not in strs[1:]:\n _flag = False\n else:\n _flag = True\n break\n return strs\n\n\ndef calc(reg):\n reg = re.sub('\\s', '', reg) #将空格去掉\n flag = True\n #搜索最里面的(), 以(开头,以)结尾的,并且不包含有(和)的字符串\n #import pdb;pdb.set_trace()\n _reg = re.compile(r\"\\(([^()]*)\\)\")\n while flag:\n _list = _reg.split(reg, 1)\n if len(_list) == 1: #说明没有括号了\n print('最后结果是:%s' % getResult(_list[0]))\n break\n else:\n _list[1] = getResult(_list[1])\n reg = \"\".join(_list)\n\n\nif __name__ == '__main__':\n #reg = \"8*12+(((6-5*6-2+9/3)/77+2)+(33-22*11))*(3-7)+8\" #933.194\n #reg = \"8*12+((77-22)-(77-22)+(((6-5*6-2)/77+2)+(33-22*11))*(3-7)+8)\" #933.35\n reg = \" 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )\" #2776672.695\n calc(reg)\n\n\n\n","sub_path":"02/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547642573","text":"\"\"\"This module implements a time series class with related methods.\"\"\"\n\n\nfrom collections import deque\nfrom datetime import datetime, timedelta\nfrom IPython.display import display\nfrom matplotlib.axes import Axes\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple\n\n\nfrom waad.utils.asset import Asset\nfrom waad.utils.config import ANOMALIES_SCORES\nfrom waad.utils.postgreSQL_utils import Table\n\n\nclass StatSeries:\n \"\"\"This class defines a statistical series and implements some computing and plotting methods on it.\n\n Attributes:\n name (str): Name of the series.\n series(List[float]): Contains the actual data of the series.\n \"\"\"\n\n def __init__(self, name: str, series: List[float]):\n self.name = name\n self.series = series\n self.anomalies: List = []\n\n def IQR_outlier_detection(self, factor: float = 1.5) -> List[int]:\n \"\"\"Implement IQR outliers detection.\n\n Args:\n factor: IQR outliers detection factor (1.5 for standard method, up to 2 or 3 for only extrem outliers).\n \"\"\"\n series = pd.Series(self.series)\n\n Q1 = series.quantile(0.25)\n Q3 = series.quantile(0.75)\n IQR = Q3 - Q1\n\n self.anomalies = series[((series < Q1 - factor * IQR) | (series > Q3 + factor * IQR))].index.values.tolist()\n\n return self.anomalies\n\n def std_outlier_detection(self, factor: float = 2) -> List[int]:\n \"\"\"Implement std outliers detection.\n\n Args:\n factor: std outliers detection factor (2 for standard method 95%, up to 3 for only extrem outliers).\n\n Returns:\n A ``List`` containing indexes of outlier values detected.\n \"\"\"\n series = pd.Series(self.series)\n\n std = series.std()\n mean = series.mean()\n\n self.anomalies = series[((series < mean - factor * std) | (series > mean + factor * std))].index.values.tolist()\n\n return self.anomalies\n\n def custom_outlier_detection(self, indicator_bound: Optional[float] = None, IQR_factor: float = 2, sigma_factor: float = 3):\n \"\"\"Implement custom IQR detection, enriched by a std criterion to be more robust.\n\n Args:\n indicator_bound: Physical criterion that helps remove False Positives. For example with a series representing the number of authentications over time and containing\n a vast majority of zeros, the IQR would raise a lot of outliers even if it they only represent an increase of 2 authentications from the median (apparently 0). This\n is due to the fact that an attacker work pattern is highly non gaussiann.\n IQR_factor: IQR outliers detection factor (1.5 for standard method, up to 2 or 3 for only extrem outliers).\n sigma_factor: std outliers detection factor (2 for standard method 95%, up to 3 for only extrem outliers).\n\n Returns:\n A ``List`` containing indexes of outlier values detected.\n \"\"\"\n series = pd.Series(self.series)\n\n std = series.std()\n mean = series.mean()\n median = series.median()\n Q1 = series.quantile(0.25)\n Q3 = series.quantile(0.75)\n IQR = Q3 - Q1\n\n # Combination of a custom (stricter) IQR method and the 3-sigma rule. Even if distributions over time are not gaussians, this is supposed to show up outliers\n outliers = series[((series < Q1 - IQR_factor * IQR) | (series > Q3 + IQR_factor * IQR)) & ((series < mean - sigma_factor * std) | (series > mean + sigma_factor * std))].index.values.tolist()\n\n # Apply ``indicator_bound``\n if indicator_bound is not None:\n to_remove = []\n for index in outliers:\n if (indicator_bound > 0) and (series[index] < median + indicator_bound):\n to_remove.append(index)\n elif (indicator_bound < 0) and (series[index] > median + indicator_bound):\n to_remove.append(index)\n for index in to_remove:\n outliers.remove(index)\n\n self.anomalies = outliers\n\n return outliers\n\n def contains_isolated_values(self, percentage_null_values: int = 90) -> bool:\n \"\"\"Detect if a series contains isolated values.\n\n Args:\n percentage_null_values: Percentage of zero values used as a threshold to evaluate if the series contains isolated points.\n\n Returns:\n A ``bool`` describing whether a time series contains isolated values or not.\n \"\"\"\n nb_non_null_values = np.flatnonzero(self.series).size\n if nb_non_null_values < (1 - percentage_null_values / 100) * len(self.series) and len(self.series) >= 1:\n return True\n return False\n\n def detect_isolated_groups(self) -> List[List[int]]:\n \"\"\"Detect isolated groups of values in ``time_series``.\n\n Returns:\n Groups of consecutive indices, corresponding to the isolated values (separated by zeros).\n \"\"\"\n indices = np.flatnonzero(self.series)\n groups: List = []\n if indices.size == 0:\n return groups\n\n current_group = [indices[0]]\n for index in indices[1:]:\n if index - current_group[-1] == 1:\n current_group.append(index)\n else:\n groups.append(current_group)\n current_group = [index]\n return groups\n\n def detect_abnormal_outbreak(self, legitimate_model_duration: int = 50):\n \"\"\"Detect if there is an abnormal outbreak values in ``time_series`` if the first\n `legitimate_model_duration` percentage of the series is zero.\"\"\"\n index = next((i for i, x in enumerate(self.series) if x), None)\n if index is not None and index > legitimate_model_duration / 100 * len(self.series):\n self.anomalies = [index]\n\n @staticmethod\n def detect_abnormal_outbreak_static(series: List[float], legitimate_model_duration: int = 50):\n \"\"\"Detect if there is an abnormal outbreak values in ``time_series`` if the first\n `legitimate_model_duration` percentage of the series is zero.\"\"\"\n index = next((i for i, x in enumerate(series) if x), None)\n if index is not None and index > legitimate_model_duration / 100 * len(series):\n return [index]\n else:\n return []\n\n def compute_anomalies(self, anomalies_detector: Optional[Callable] = None, config: Optional[Dict[str, Dict]] = None):\n if anomalies_detector is not None:\n self.anomalies = anomalies_detector(self.series)\n\n else:\n if config is not None:\n self.custom_outlier_detection(indicator_bound=config[self.name][\"indicator_bound\"])\n else:\n self.custom_outlier_detection()\n\n def plot_series(self, ax: Axes):\n \"\"\"Plot a series.\n\n Examples:\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from waad.utils.indicators import plot_series\n >>>\n >>> data = [355, 368, 0, 0, 0, 447, 466, 250, 367, 0, 0, 0, 320,\n 307, 395, 601, 258, 0, 0, 0, 382, 400, 326, 319, 0, 0,\n 304, 360, 327, 368, 0, 0, 0, 383, 327, 422, 290, 253, 0,\n 0, 446, 414, 381, 393, 0, 0, 0, 0, 373, 387, 312, 327,\n 0, 0, 370, 275, 436, 348]\n >>>\n >>> demo = StatSeries('demo', data)\n >>> fig, ax = plt.subplots(figsize=(30, 5))\n >>> demo.plot_series(ax)\n\n .. testcleanup::\n\n fig.savefig(f'{DOCTEST_FIGURES_PATH}/test.png')\n\n .. figure:: ../../_static/doctest_figures/time_series_plot_example.png\n :align: center\n :alt: time series plot example\n\n Args:\n ax: ``Axes`` to plot series on.\n \"\"\"\n ax.plot([i for i in range(1, len(self.series) + 1)], self.series)\n ax.set_title(self.name)\n\n def get_figure(self, figsize: Tuple[int, int] = (20, 4)) -> Figure:\n fig, ax = plt.subplots(figsize=figsize)\n self.plot_series(ax)\n return fig\n\n def display(self):\n fig = self.get_figure()\n fig.axes[0].vlines(np.array(self.anomalies) + 1, *fig.axes[0].get_ylim(), colors=\"r\")\n display(fig)\n\n\nclass TimeSeries(StatSeries):\n \"\"\"This class is a child of ``StatSeries`` taking into account a notion of time.\n\n Attributes:\n time_step (float): Time step in seconds between each index.\n start_time (Optional[str]): Start time of the series in ISO format.\n intermediary_content (Optional[Any]): Helper that keeps in memory intermediary content used during previous computations.\n \"\"\"\n\n def __init__(self, name: str, series: List[float], time_step: float, start_time: Optional[str] = None, intermediary_content: Optional[Any] = None):\n super().__init__(name, series)\n self.time_step = time_step\n self.start_time = start_time\n self.intermediary_content = intermediary_content\n\n def get_anomalies_date(self):\n res = []\n for anomaly in self.anomalies:\n try:\n start = datetime.fromisoformat(self.start_time) + timedelta(seconds=self.time_step * anomaly)\n end = start + timedelta(seconds=self.time_step)\n res.append(f'{start.isoformat()} - {end.isoformat()}')\n except Exception as e:\n print(e)\n pass\n return res\n\n def detailed_display(self):\n self.display()\n anomalies_date = self.get_anomalies_date()\n for i, anomaly in enumerate(self.anomalies):\n print(f\"Anomaly found at time step {anomaly} / {anomalies_date[i]}\")\n print(f\"Pic value of {self.series[anomaly]} on indicator\")\n if self.intermediary_content is not None:\n print(f\"Intermediary content : {self.intermediary_content[anomaly]}\")\n print()\n","sub_path":"waad/utils/time_series_utils.py","file_name":"time_series_utils.py","file_ext":"py","file_size_in_byte":10144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"303631382","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 24 12:37:24 2021\r\n\r\n@author: aruna\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\nfrom flask import Flask, jsonify, render_template, request, redirect, url_for\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\nimport selenium\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait as wdw\r\nfrom selenium.webdriver.common.by import By as by\r\nfrom selenium.webdriver.support import expected_conditions as ec\r\nfrom pandas.tseries.offsets import BDay\r\nimport time\r\nfrom selenium.webdriver.support.ui import Select\r\nimport os\r\nimport sys\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'secret!!'\r\napp.debug = True\r\n\r\n@app.route(\"/\")\r\n@app.route(\"/sendetails\", methods=['GET','POST'])\r\ndef home():\r\n \r\n if request.method == 'POST':\r\n print(\"-- got POST --\")\r\n \r\n sdatestr = request.form['sdt']\r\n edatestr = request.form['edt']\r\n stockcode = request.form['stock']\r\n \r\n thresh = request.form['threshold']\r\n \r\n errors = []\r\n sdate = datetime.datetime.strptime(sdatestr,'%Y-%m-%d')\r\n edate = datetime.datetime.strptime(edatestr, '%Y-%m-%d')\r\n \r\n if sdate > edate:\r\n errors.append(\"Startdate is after the end date\")\r\n \r\n if len(stockcode) != 5:\r\n errors.append(\"Stock code needs to be 5 characters: Pad zeroes\")\r\n \r\n if thresh != \"\":\r\n try: \r\n thresh = float(thresh)\r\n except:\r\n errors.append(\"Invalid Price.\")\r\n if errors:\r\n return('The following errors have occured' + str(errors))\r\n \r\n if request.form['submit_button'] == 'Thresh':\r\n \r\n threshhold = thresholdchange(stockcode,sdate,edate,thresh)\r\n return render_template('threshold.html', title='Possible transaction for '+stockcode +' for threshold '+str(thresh), tables = [threshhold.to_html(classes='threshold')], titles=threshhold.columns.values)\r\n\r\n \r\n elif request.form['submit_button'] == 'Table':\r\n print('Getting table, scraping')\r\n allholders,lastopholders = getallholders(stockcode,sdate,edate)\r\n maxHold = lastopholders.shareholding_pct.max()\r\n labels = list(lastopholders['participant_name'])\r\n values = list(lastopholders['shareholding_pct'])\r\n return render_template('top_holders.html', title='Top Holders for '+stockcode, max=maxHold, labels=labels, values=values, tables = [allholders.to_html(classes='allholders')], titles=allholders.columns.values)\r\n\r\n \r\n return render_template('home.html')\r\n\r\n\r\ndef get_holders(stock, date):\r\n page = selenium.webdriver.Chrome()\r\n page.get('https://www.hkexnews.hk/sdw/search/searchsdw.aspx')\r\n wdw(page, 5).until(ec.presence_of_element_located((by.CSS_SELECTOR, 'input[name*=\"txtStockCode\"]')))\r\n \r\n scode_element = page.find_element_by_id('txtStockCode')\r\n scode_element.send_keys(stock)\r\n \r\n dateelement = page.find_element_by_id(\"txtShareholdingDate\")\r\n dateelement.click()\r\n allholders = pd.DataFrame()\r\n yearbutton = page.find_element_by_css_selector('b[class*=\"year\"]')\r\n yearbutton.find_element_by_css_selector('button[data-value*=\"' + date.strftime('%Y') + '\"]').click()\r\n monthbutton = page.find_element_by_css_selector('b[class*=\"month\"]')\r\n monthbottontarget = monthbutton.find_element_by_css_selector('button[data-value*=\"' + str(int(date.strftime('%#m')) - 1) + '\"]')\r\n daybutton = page.find_element_by_css_selector('b[class*=\"day\"]')\r\n daybutton.find_element_by_css_selector('button[data-value*=\"' + date.strftime('%#d') + '\"]').click()\r\n dateelement.click() \r\n searchelement = page.find_element_by_css_selector('a[id*=\"btnSearch\"]')\r\n searchelement.click()\r\n wdw(page, 5).until(ec.presence_of_element_located((by.CSS_SELECTOR, 'table[class*=\"table table-scroll table-sort table-mobile-list \"]')))\r\n tableelement = page.find_element_by_css_selector('table[class*=\"table table-scroll table-sort table-mobile-list \"]')\r\n holders = pd.read_html(tableelement.get_attribute('outerHTML'), parse_dates=False)[0]\r\n holders.columns = ['participant_id','participant_name','participant_address','shareholding','shareholding_pct']\r\n holders['date'] = date\r\n holders['participant_name'] = [n.replace(',', '').replace('.', '').replace('\"', '').replace(\"'\", '').replace('Name of CCASS Participant (* for Consenting Investor Participants ): ', '') for n in holders['participant_name']]\r\n holders['shareholding_pct'] = [float(p.replace('% of the total number of Issued Shares/ Warrants/ Units:', '').replace('%', ''))/100 for p in holders['shareholding_pct']]\r\n holders['participant_address'] = [''.join([c for c in a.replace('Address: ', '') if c not in ['/','\\\\',',','!','.',';','@','%','^','&','*',')','(','\"',\"'\"]]) for a in holders['participant_address']]\r\n holders['participant_id'] = [n.replace(' ', '')[:10] if i == 'Participant ID:' else i for n,i in zip(holders['participant_name'], holders['participant_id'].str.replace('Participant ID: ', ''))]\r\n holders['shareholding'] = holders['shareholding'].str.replace('Shareholding: ', '').str.replace(',', '')\r\n page.close() \r\n \r\n return holders\r\n\r\n\r\ndef getallholders(stockcode,sdate,edate):\r\n dates = pd.date_range(sdate,edate)\r\n allholders = pd.DataFrame()\r\n for date in dates:\r\n print('Scraping stockcode ' + stockcode + ' for date: ' +str(date))\r\n holders = get_holders(stockcode,date)\r\n allholders = allholders.append(holders)\r\n lastholders = allholders.loc[allholders['date'] == edate]\r\n lastholderstop = lastholders.sort_values('shareholding_pct',ascending=False).head(10)\r\n \r\n return allholders,lastholderstop\r\n \r\ndef thresholdchange(stockcode,sdate,edate,thresh):\r\n#\r\n# thresh = 0.00001\r\n# stockcode = '00012'\r\n allholders,lastholderstop = getallholders(stockcode,sdate,edate)\r\n allhold_change = pd.DataFrame()\r\n for i,g in allholders.groupby('participant_id'):\r\n g['shareholding_delta'] = g[['date','shareholding_pct']].sort_values('date').shareholding_pct.diff()\r\n \r\n g['shareholding_delta'] = [round(x,5) for x in g['shareholding_delta']]\r\n allhold_change = allhold_change.append(g)\r\n reqdf = pd.DataFrame()\r\n for d in allhold_change.date.unique():\r\n currdf = allhold_change.loc[allhold_change['date'] == d]\r\n buy = currdf.loc[currdf.shareholding_delta > thresh]\r\n buy['transaction'] = 'Buy'\r\n sell = currdf.loc[currdf.shareholding_delta < (-1*thresh)]\r\n sell['transaction'] = 'Sell'\r\n if len(buy)>0 and len(sell)>0:\r\n reqdf = reqdf.append(buy)\r\n reqdf = reqdf.append(sell)\r\n \r\n return reqdf[['date','transaction','participant_name','shareholding_pct','shareholding_delta']]\r\n \r\ndef main(argv):\r\n\r\n if len(argv) > 0:\r\n port = int(argv[0])\r\n else:\r\n port = 8818\r\n\r\n app.run()\r\n\r\nif __name__ == '__main__':\r\n\r\n main(sys.argv[1:])\r\n\r\n\r\n \r\n ","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":7268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"368466545","text":"import utils\nimport normalizr\nfrom random import seed\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, TimeDistributed, RepeatVector\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\ninputSize = 50\noutputSize = 75\nnormalizeInput = normalizr.createNormalizr(inputSize)\nnormalizeOutput = normalizr.createNormalizr(outputSize)\n\ndef main():\n # define LSTM configuration\n batchSize = 10\n nEpochs = 30\n\n # define dataset\n seed(1)\n valsplit = 0.1\n nChars = len(normalizr.chars)\n\n data = utils.importCsvAsDictArray('../data/validationData_v2.csv')\n x_inversenormal = [row['inputFirstName'] + '|' + row['inputLastName'] for row in data]\n y_inversenormal = [row['outputFirstName'] + '|' + row['outputLastName'] + '|' + row['outputInitials'] + '|' + row['outputPrefix'] for row in data]\n x_inversenormal = [row for row in x_inversenormal if len(row) <= inputSize]\n y_inversenormal = [row for row in y_inversenormal if len(row) <= outputSize]\n x_normal = [normalizeInput(row) for row in x_inversenormal]\n y_normal = [normalizeOutput(row) for row in y_inversenormal]\n x_train = x_normal[:200000]\n y_train = y_normal[:200000]\n x_test = x_normal[200000:]\n y_test = y_normal[200000:]\n\n # create LSTM\n model = Sequential([\n LSTM(100, input_shape=(inputSize, nChars)),\n RepeatVector(outputSize),\n LSTM(50, return_sequences=True),\n TimeDistributed(Dense(nChars, activation='softmax'))\n ])\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n earlyStopping = EarlyStopping(monitor='loss', patience=10)\n checkpointer = ModelCheckpoint(filepath='../data/optiweights.hdf5', verbose=2, save_best_only=True, monitor='val_loss', mode='auto')\n\n # train LSTM\n for i in range(nEpochs):\n print('Epoch ' + str(i + 1) + '/' + str(nEpochs))\n model.fit(\n x_train,\n y_train,\n epochs=1,\n batch_size=batchSize,\n verbose=1,\n shuffle=True,\n callbacks=[earlyStopping, checkpointer],\n validation_split=valsplit\n )\n\n # evaluate on some new patterns\n # print(y_test)\n # result = model.predict(x_test, batch_size=batchSize, verbose=0)\n\nmain()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610761514","text":"\"\"\"Auth0 callback URL\"\"\"\n\nfrom bottle import request, response, redirect\nfrom faunadb.errors import NotFound\nfrom .app import app, auth0, AUTH0_DOMAIN, APP_URL, SECRET\nfrom .app.utils import (\n timestamp_sign,\n jsonify,\n user_login_or_signup,\n)\n\n\n@app.get(\"/api/callback\")\ndef callback():\n \"\"\"Add docstring later\"\"\"\n\n try:\n # Fetch Auth0 JWT token from Auth0's API\n token = auth0.fetch_access_token(\n f\"{AUTH0_DOMAIN}/oauth/token\",\n authorization_response=request.url,\n redirect_uri=f\"{APP_URL}/api/callback\",\n )\n\n # Generate a Fauna ABAC token from a given Auth0 JWT\n id_token = token[\"id_token\"]\n secret = user_login_or_signup(id_token)\n print(\"secret from exchange\", secret)\n\n # Timestamp the Fauna ABAC token\n signed_token = timestamp_sign(secret, SECRET)\n print(\"timestamped signed token\", signed_token)\n except NotFound as e:\n print(\"User not found in FaunaDB.\")\n return jsonify(status=404, message=\"User not found.\")\n except Exception as e:\n print(\"something went wrong\", e)\n else:\n response.set_cookie(\"token\", signed_token, httponly=True, path=\"/\")\n return redirect(\"/dashboard\")\n","sub_path":"api/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"569124027","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n1. 分词\n2. 词语 -> id\n3. matrix -> [|V|, embed_size]\n 词语A -> id(5)\n4. 词表\n\n5. label -> id\n\"\"\"\n\nimport sys\nimport os\nimport jieba\n\"\"\"pip install jieba\"\"\"\n\n#input files\ntrain_file = '../big_files/cnews/csv.cnews.train.txt'\nval_file = '../big_files/cnews/csv.cnews.val.txt'\ntest_file = '../big_files/cnews/csv.cnews.test.txt'\n\n#output files\nseg_train_file = '../big_files/cnews/cnews.train.seg.txt'\nseg_val_file = '../big_files/cnews/cnews.val.seg.txt'\nseg_test_file = '../big_files/cnews/cnews.test.seg.txt'\n\nvocab_file = '../big_files/cnews/cnews.vocab.txt'\ncategory_file = '../big_files/cnews/cnews.category.txt'\n\n\n\ndef generate_seg_file(input_file, output_seg_file):\n \"\"\"Segment the sentences in each line in input_file\"\"\"\n with open(input_file, 'r',encoding='UTF-8') as fr:\n lines = fr.readlines()\n with open(output_seg_file, 'w', encoding='UTF-8') as f:\n for line in lines:\n label ,content = line.strip('\\r\\n').split('\\t')\n\n word_iter = jieba.cut(content) \n word_content = ''\n for word in word_iter:\n word = word.strip(' ')\n if word != '':\n word_content += word + ' '\n out_line = '%s\\t%s\\n'%(label, word_content.strip(' '))\n\n f.write(out_line)\n \n\n#generate_seg_file(test_file, seg_test_file)\n#print('test file finished')\n#generate_seg_file(val_file, seg_val_file)\n#print('val file finished') \n#generate_seg_file(train_file, seg_train_file)\n#print('train file finished')\n\ndef generate_vocab_file(input_seg_file, output_vocab_file):\n with open(input_seg_file, 'r', encoding = 'utf-8') as f:\n lines = f.readlines()\n word_dict = {}\n for line in lines:\n label, content = line.strip('\\r\\n').split('\\t')\n for word in content.split():\n word_dict.setdefault(word, 0)\n word_dict[word] += 1\n #[(word, frequency),....()]\n sorted_word_dict = sorted(word_dict.items(), key = lambda d:d[1], reverse=True)\n with open(output_vocab_file, 'w', encoding = 'utf-8') as f:\n f.write('\\t1000000\\n')\n for item in sorted_word_dict:\n f.write('%s\\t%d\\n' % (item[0], item[1]))\n\n#generate_vocab_file(seg_train_file,vocab_file)\n \n \n \ndef generate_category_dict(input_file, category_file):\n with open(input_file, 'r', encoding = 'utf-8') as f:\n lines = f.readlines()\n category_dict = {}\n for line in lines:\n label, content = line.strip('\\r\\n').split('\\t')\n category_dict.setdefault(label, 0)\n category_dict[label] += 1\n category_number = len(category_dict)\n print(category_number)\n with open(category_file, 'w', encoding='utf-8') as f:\n for category in category_dict:\n line = '%s\\n' % category\n print ('%s\\t%d' % (category,category_dict[category]))\n f.write(line)\n \ngenerate_category_dict(train_file, category_file)\n \n \n \n \n \n\n \n \n \n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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":"deep_learn/RNN/pre-processing.py","file_name":"pre-processing.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"465951098","text":"from utils import get_page\nimport re\nfrom time import sleep\n\nclass Crawler(object):\n \"\"\"抓取代理\"\"\"\n BEGEN = 'crawl_'\n @staticmethod\n def get_proxies():\n proxies = []\n for key, value in Crawler.__dict__.items():\n if key.startswith(Crawler.BEGEN):\n res = getattr(Crawler, key)()\n try:\n proxies += res\n except Exception:\n pass\n return proxies\n @staticmethod\n def crawl_kuaidaili(page_count=4):\n \"\"\"快代理\"\"\"\n base_url = 'https://www.kuaidaili.com/free/inha/{}'\n urls = [base_url.format(page_number) for page_number in range(1, page_count + 1)]\n pattern = re.compile(r'(.*?)' +\n '.*?title=\"PORT\">(\\d+)' +\n '.*?title=\"类型\">([a-zA-Z]+)', re.S)\n result = []\n for url in urls:\n html = get_page(url)\n if html:\n match = re.findall(pattern, html)\n result += [':'.join(item[:-1]) for item in match]\n sleep(1)\n return result\n @staticmethod\n def crawl_xiladaili(page_count=4):\n \"\"\"西拉代理\"\"\"\n base_url = 'http://www.xiladaili.com/gaoni/{}'\n urls = [base_url.format(page_number) for page_number in range(1, page_count + 1)]\n pattern = re.compile(r'.*?(.*?).*?(.*?).*?', re.S)\n result = []\n for url in urls:\n html = get_page(url)\n if html:\n match = re.findall(pattern, html)\n result += [item[0] for item in match]\n sleep(1)\n return result\n @staticmethod\n def crawl_qiyundaili(page_count=4):\n \"\"\"旗云代理\"\"\"\n base_url = 'http://www.qydaili.com/free/?page={}'\n urls = [base_url.format(page_number) for page_number in range(1, page_count + 1)]\n pattern = re.compile(r'.*?title=\"IP\">(.*?).*?\"PORT\">(\\d+).*?', re.S)\n result = []\n for url in urls:\n html = get_page(url)\n if html:\n match = re.findall(pattern, html)\n result += [':'.join(item) for item in match]\n sleep(1)\n return result\n @staticmethod\n def crawl_xiaohuandaili(page_count=4):\n \"\"\"小幻代理\"\"\"\n pass\n # headers = {\n # 'authority': \"ip.ihuan.me\",\n # 'method': 'GET',\n # 'path': '/',\n # 'scheme': 'https',\n # 'cookie': '__cfduid=d963e2cf9ae530c8316df813a4c0937d61560778173; cf_clearance=04da4852d496dd2e0b8c1992f9a9e174ebf7635c-1560778173-1800-250',\n # 'upgrade-insecure-requests': '1'\n # }\n # base_url = 'https://ip.ihuan.me'\n # index_html = get_page(base_url, headers)\n # pattern_next_page = re.compile(r'
  • .*?
  • ', re.S)\n # pattern = re.compile(r'.*?(.*?).*?')\n # result = []\n # if index_html:\n # result = pattern.findall(pattern, index_html)\n # for _ in range(page_count):\n # res = re.match(pattern_next_page, html)\n # if res:\n # html = get_page(res[0])\n # if html:\n # result += re.findall(pattern, html)\n","sub_path":"pool/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598099417","text":"\nimport sys\nsys.path.insert(0, 'nTupleAnalysis/python/') #https://github.com/patrickbryant/nTupleAnalysis\nfrom commandLineHelpers import *\nimport math\n\nimport ROOT \nROOT.gROOT.SetBatch(True)\nROOT.gErrorIgnoreLevel = ROOT.kWarning\n\nROOT.gStyle.SetOptStat(0)\nROOT.gStyle.SetOptTitle(0)\n\n\nimport optparse\n\nparser = optparse.OptionParser()\nparser.add_option('-s', dest=\"subSamples\", default=\"0,1,2,3,4,5,6\", help=\"Year or comma separated list of subsamples\")\nparser.add_option('-o', dest=\"outDir\" )\nparser.add_option('-m', dest=\"mixedName\" )\n\n\no, a = parser.parse_args()\n\nsubSamples = o.subSamples.split(\",\")\nmixedName = o.mixedName\n\nmkdir(o.outDir)\n\n\n\n\ndef getBkgModel(hName,ttFile,d3File,rebin=1):\n ttHist = ttFile.Get(hName).Clone()\n ttHist.Rebin(rebin)\n d3Hist = d3File.Get(hName.replace(\"fourTag\",\"threeTag\")).Clone()\n d3Hist.Rebin(rebin)\n d3Hist.Add(ttHist)\n d3Hist.SetName(ttHist.GetName()+\"_bkg\")\n return d3Hist\n\n\n\ndef getPullNoTTBar(hName,d4File,d3File,ttFile,rebin=1):\n\n ttHist = ttFile.Get(hName).Clone()\n ttHist.Rebin(rebin)\n \n hDataNoTT = d4File.Get(hName).Clone()\n hDataNoTT.Rebin(rebin)\n hDataNoTT.Add(ttHist,-1)\n\n # Normalize\n hBkgNoTT = d3File.Get(hName.replace(\"fourTag\",\"threeTag\")).Clone()\n hBkgNoTT.Rebin(rebin)\n hBkgNoTT.Scale(hDataNoTT.Integral()/hBkgNoTT.Integral())\n\n pull = hDataNoTT.Clone()\n pull.SetMarkerStyle(20)\n pull.SetMarkerSize(0.7)\n pull.SetName(hDataNoTT.GetName()+\"_pull\") \n pull.GetYaxis().SetRangeUser(-5,5)\n pull.GetYaxis().SetTitle(\"Pull (Data-Bkg)/#sigma\")\n\n for iBin in range(pull.GetNbinsX()+1):\n \n dataNoTT = hDataNoTT.GetBinContent(iBin)\n bkgNoTT = hBkgNoTT .GetBinContent(iBin)\n bkgNoTTErr = hBkgNoTT .GetBinError (iBin)\n\n if (bkgNoTT + bkgNoTTErr*bkgNoTTErr) > 0:\n bkgNoTTErrTot = math.sqrt( bkgNoTT + bkgNoTTErr*bkgNoTTErr)\n else:\n bkgNoTTErrTot = 0\n #print \"D = \",dataNoTT, \"B = \", bkgNoTT, \" +/- \", math.sqrt(bkgNoTT),\" (stat) +/- \", bkgNoTTErr , \" (sys) \", bkgNoTTErrTot\n \n #cv = ratioIn.GetBinContent(iBin)\n #err = ratioIn.GetBinError(iBin)\n if bkgNoTTErrTot == 0:\n pull.SetBinContent(iBin,0)\n pull.SetBinError(iBin,0)\n else:\n pval = (dataNoTT-bkgNoTT)/bkgNoTTErrTot\n pull.SetBinContent(iBin,pval)\n pull.SetBinError(iBin,0)\n\n return pull\n\n\n\ndef getRatio(hName,d4Hist,d3Hist,ttHist,rebin=1):\n hBkg = getBkgModel(hName, ttHist, d3Hist,rebin=rebin)\n hData = d4Hist.Get(hName).Clone()\n hBkg.Scale(hData.Integral()/hBkg.Integral())\n hData.Rebin(rebin)\n hData.Divide(hBkg)\n hData.SetName(hData.GetName()+\"_ratio\")\n hData.SetMarkerStyle(20)\n hData.SetMarkerSize(0.7)\n hData.GetYaxis().SetRangeUser(0.7,1.3)\n hData.GetYaxis().SetTitle(\"Ratio (Data/Bkg)\")\n return hData\n\n\n\n\ndef getPullFromRatio(ratioIn):\n pull = ratioIn.Clone()\n pull.SetName(ratioIn.GetName()+\"_pullFromRatio\") \n pull.GetYaxis().SetRangeUser(-5,5)\n pull.GetYaxis().SetTitle(\"Pull (Data-Bkg)/#sigma\")\n for iBin in range(ratioIn.GetNbinsX()+1):\n cv = ratioIn.GetBinContent(iBin)\n err = ratioIn.GetBinError(iBin)\n if cv == 0.0 and err == 0.0:\n pull.SetBinContent(iBin,0)\n pull.SetBinError(iBin,0)\n else:\n pval = (cv-1.0)/err if err else 1.\n pull.SetBinContent(iBin,pval)\n pull.SetBinError(iBin,0)\n\n return pull\n\ndef getMeanStd(hists,nSigma):\n meanStd = hists[0].Clone()\n\n N = len(hists)\n\n for iBin in range(meanStd.GetNbinsX()+1):\n sumY = 0 \n sumY2 = 0\n\n for hItr, h in enumerate(hists):\n thisPull = h.GetBinContent(iBin)\n sumY += thisPull\n sumY2 += (thisPull*thisPull)\n \n\n mean = sumY / N\n var = sumY2 / N - mean*mean\n std = math.sqrt(var)\n\n meanStd.SetBinContent(iBin,mean)\n meanStd.SetBinError(iBin,nSigma*std)\n\n return meanStd\n\n\n\ndef lineAt(yVal,xMin, xMax):\n one = ROOT.TF1(\"one\",str(yVal),xMin,xMax)\n one.SetLineStyle(ROOT.kDashed)\n one.SetLineColor(ROOT.kBlack)\n return one\n\n\ndef drawAll(name,histList,yLine=None,drawOpts=\"\",underLays=None):\n for hItr, h in enumerate(histList):\n\n if hItr:\n h.Draw(drawOpts+\" same\")\n h.Draw(\"same AXIS\")\n else:\n h.Draw(drawOpts)\n \n if not underLays is None:\n for u in underLays:\n u.Draw(\"E2 same\")\n h.Draw(\"same AXIS\")\n\n if not yLine is None:\n one = lineAt(yLine,h.GetXaxis().GetXmin(),h.GetXaxis().GetXmax())\n one.Draw(\"same\")\n h.Draw(drawOpts+\" same\")\n h.Draw(\"same AXIS\")\n\n can.SaveAs(o.outDir+\"/\"+name+\".pdf\")\n\n \n\ncan = ROOT.TCanvas()\nttFiles = []\nd3Files = []\nd4Files = []\n\ncolors = [ROOT.kBlack,ROOT.kGray,ROOT.kBlue,ROOT.kRed,ROOT.kOrange,ROOT.kMagenta,ROOT.kCyan]\n\n\n#\n# Read Files\n#\nfor sItr, s in enumerate(subSamples):\n\n tt = \"/uscms/home/jda102/nobackup/HH4b/CMSSW_10_2_0/src/closureTests/3bMix4b/TTRunII/hists_4b_wFVT_\"+mixedName+\"_v\"+s+\"_comb_b0p6.root\"\n d3 = \"/uscms/home/jda102/nobackup/HH4b/CMSSW_10_2_0/src/closureTests/3bMix4b/dataRunII/hists_3b_wJCM_\"+mixedName+\"_v\"+s+\"_comb_wFVT_\"+mixedName+\"_v\"+s+\"_comb_b0p6.root \"\n d4 = \"/uscms/home/jda102/nobackup/HH4b/CMSSW_10_2_0/src/closureTests/3bMix4b/dataRunII/hists_4b_wFVT_\"+mixedName+\"_v\"+s+\"_comb_b0p6.root\"\n\n ttFiles.append(ROOT.TFile(tt,\"READ\"))\n d3Files.append(ROOT.TFile(d3,\"READ\"))\n d4Files.append(ROOT.TFile(d4,\"READ\"))\n\n\n\n\n\ndef makePlots(outDir, hName,outName,rebin):\n\n pullsNoTTbar = []\n ratios = []\n pullsFromRatio = []\n\n\n for sItr, s in enumerate(subSamples):\n\n pullsNoTTbar.append(getPullNoTTBar(hName, d4Files[sItr], d3Files[sItr], ttFiles[sItr], rebin=rebin))\n pullsNoTTbar[sItr].SetLineColor(colors[sItr])\n pullsNoTTbar[sItr].SetMarkerColor(colors[sItr])\n\n ratios.append(getRatio(hName, d4Files[sItr], d3Files[sItr], ttFiles[sItr], rebin=rebin))\n ratios[sItr].SetLineColor(colors[sItr])\n ratios[sItr].SetMarkerColor(colors[sItr])\n\n pullsFromRatio.append(getPullFromRatio(ratios[sItr]))\n\n\n can.cd()\n pullsNoTTbar[sItr].Draw(\"PE\")\n zero = lineAt(0,pullsNoTTbar[sItr].GetXaxis().GetXmin(),ratios[sItr].GetXaxis().GetXmax())\n zero.Draw(\"same\")\n can.SaveAs(o.outDir+\"/\"+outName+\"_pullNoTTbar_v\"+s+\".pdf\")\n\n\n can.cd()\n ratios[sItr].Draw(\"\")\n one = lineAt(1,ratios[sItr].GetXaxis().GetXmin(),ratios[sItr].GetXaxis().GetXmax())\n one.Draw(\"same\")\n can.SaveAs(o.outDir+\"/\"+outName+\"_ratio_v\"+s+\".pdf\")\n\n\n can.cd()\n pullsFromRatio[sItr].Draw(\"PE\")\n zero = lineAt(0,ratios[sItr].GetXaxis().GetXmin(),ratios[sItr].GetXaxis().GetXmax())\n zero.Draw(\"same\")\n can.SaveAs(o.outDir+\"/\"+outName+\"_pullFromRatio_v\"+s+\".pdf\")\n\n\n\n\n\n can.cd()\n\n pullNoTTbarMean1sigma = getMeanStd(pullsNoTTbar,1)\n pullNoTTbarMean1sigma.SetFillColor(ROOT.kGreen)\n pullNoTTbarMean1sigma.SetMarkerColor(ROOT.kGreen)\n\n pullNoTTbarMean2sigma = getMeanStd(pullsNoTTbar,2)\n pullNoTTbarMean2sigma.SetFillColor(ROOT.kYellow)\n pullNoTTbarMean2sigma.SetMarkerColor(ROOT.kYellow)\n\n drawAll(outName+\"_pullNoTTbar\", pullsNoTTbar ,yLine=0, drawOpts=\"PE\",underLays=[pullNoTTbarMean2sigma,pullNoTTbarMean1sigma])\n\n\n drawAll(outName+\"_ratio\",ratios,yLine=1)\n\n pullFromRatioMean1sigma = getMeanStd(pullsFromRatio,1)\n pullFromRatioMean1sigma.SetFillColor(ROOT.kGreen)\n\n pullFromRatioMean2sigma = getMeanStd(pullsFromRatio,2)\n pullFromRatioMean2sigma.SetFillColor(ROOT.kYellow)\n\n drawAll(outName+\"_pullFromRatio\", pullsFromRatio ,yLine=0, drawOpts=\"PE\",underLays=[pullFromRatioMean2sigma,pullFromRatioMean1sigma])\n\n outFile.cd()\n pullNoTTbarMean1sigma.SetName(outName)\n pullNoTTbarMean1sigma.Write()\n\n\n#hPath = \"passXWt/fourTag/mainView\"\nhPath = \"passMDRs/fourTag/mainView\"\n\noutFile = ROOT.TFile(o.outDir+\"/plotClosureTest_\"+o.mixedName+\"_b0p6_comb.root\",\"RECREATE\")\n\nfor r in [\"SR\",\"SB\",\"CR\"]:\n\n variables = [\n (\"SvB_ps_zz\", 2),\n (\"SvB_ps\", 2),\n (\"SvB_ps_zh\", 2),\n #(\"SvB_q_score\", 2),\n (\"FvT\", 2),\n ]\n\n for v in variables:\n makePlots(outFile, hName = hPath+\"/\"+r+\"/\"+v[0], outName=r+\"_\"+v[0] ,rebin=v[1])\n \n","sub_path":"nTupleAnalysis/scripts/plotClosureTest.py","file_name":"plotClosureTest.py","file_ext":"py","file_size_in_byte":8607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"464004121","text":"# -*-coding: utf-8\r\n\r\nimport pandas as pd\r\nimport openpyxl as px\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nimport seaborn as sns\r\nimport os\r\nimport shutil\r\nimport datetime\r\n \r\n\r\n#Font Setting\r\nfrom matplotlib.font_manager import FontProperties\r\nimport sys\r\nif sys.platform.startswith('win'):\r\n FontPath= 'C:\\\\Windows\\\\Fonts\\\\meiryo.ttc'\r\nelif sys.platform.startswith('darwin'):\r\n FontPath= '/System/Library/Fonts/ヒラノギ角ゴシック W4.ttc'\r\nelif sys.platform.startswith('linux'):\r\n FontPath= '/usr/share/fonts/truetype/takao-gothic/TakaoExGothic.ttc'\r\njpfont = FontProperties(fname = FontPath)\r\n\r\ndef fill_flag_area(ax, flags, label=None, freq=None, **kwargs):\r\n \"\"\" フラグが立っている領域を塗りつぶす\r\n params:\r\n ax: Matplotlib の Axes オブジェクト\r\n flags: index が DatetimeIndex で dtype が bool な pandas.Series オブジェクト\r\n freq: 時系列データの1単位時間, 指定しない場合は flags.index.freq が使われる\r\n flags.index.freq が None の場合には必ず指定しなければならない\r\n (例: 1日単位のデータの場合) pandas.tseries.frequencies.Day(1)\r\n return:\r\n Matplotlib の Axes オブジェクト\r\n \"\"\"\r\n assert flags.dtype == bool\r\n assert type(flags.index) == pd.DatetimeIndex\r\n freq = freq or flags.index.freq\r\n assert freq is not None\r\n diff = pd.Series([0] + list(flags.astype(int)) + [0]).diff().dropna()\r\n for start, end in zip(flags.index[diff.iloc[:-1] == 1], flags.index[diff.iloc[1:] == -1]):\r\n ax.axvspan(start, end + freq, label=label, **kwargs)\r\n label = None # 凡例が複数表示されないようにする\r\n return ax\r\n\r\ndef fill_area_BOJoperation_Date(ax,flags,label = False,stack=False,alpha=0.8,**kwargs):\r\n \"\"\" This def paint fill area during the BOJ Operation\r\n params:\r\n ax: Matplotlib の Axes オブジェクト\r\n flags: index が DatetimeIndex で dtype が bool な pandas.Series オブジェクト\r\n freq: 時系列データの1単位時間, 指定しない場合は flags.index.freq が使われる\r\n flags.index.freq が None の場合には必ず指定しなければならない\r\n (例: 1日単位のデータの場合) pandas.tseries.frequencies.Day(1)\r\n stack: 積み上げグラフに対して適応したい場合はTrueとする\r\n return:\r\n Matplotlib の Axes オブジェクト\r\n \"\"\"\r\n\r\n if stack:\r\n flags['Total']=flags.sum(axis=1)\r\n\r\n OpeData = [\r\n (datetime.datetime(2013,4,1),datetime.datetime(2016,2,1),'異次元緩和','#B0BEC5'),\r\n (datetime.datetime(2016,2,1),datetime.datetime(2016,9,1),'マイナス金利導入','#546E7A'),\r\n (datetime.datetime(2016,9,1), flags.index[len(flags)-1],'YCC','#455A64')\r\n ]\r\n bottom,top = ax.get_ylim()\r\n \r\n for Sdate,Edate,label,iro in OpeData:\r\n if not stack: \r\n ax.axvspan(Sdate,Edate,label=label,color=iro,alpha =alpha, **kwargs)\r\n else:\r\n ax.fill_between(flags.index,flags['Total'],top,where=flags.index>=Sdate,\r\n facecolor=iro, alpha=alpha,label =label)\r\n ax.annotate(label,xy=(Sdate + (Edate-Sdate)/2,top),size =10,color = \"black\",\r\n horizontalalignment='center') \r\n return ax\r\n\r\n\r\n# mpl_dirpath = os.path.dirname(mpl.__file__)\r\n# # デフォルトの設定ファイルのパス\r\n# default_config_path = os.path.join(mpl_dirpath, 'mpl-data', 'matplotlibrc')\r\n# # カスタム設定ファイルのパス\r\n# custom_config_path = os.path.join(mpl.get_configdir(), 'matplotlibrc')\r\n\r\n# os.makedirs(mpl.get_configdir(), exist_ok=True)\r\n# shutil.copyfile(default_config_path, custom_config_path)\r\n\r\nmpl.font_manager._rebuild() \r\nPath = os.getcwd()\r\n\r\n# ファイル読み込み\r\n\r\n\r\nGenTan_borrow = pd.read_excel(Path+'\\\\repo2.xlsx',sheet_name = 'borrow',header =8,date_parser=1,index_col=0)\r\nGenTan_loan = pd.read_excel(Path+'\\\\repo2.xlsx',sheet_name = 'loan',header =8,date_parser=1,index_col=0)\r\nGensaki_kai = pd.read_excel(Path+'\\\\repo2.xlsx',sheet_name = 'kaigensaki',header =8,date_parser=1,index_col=0)\r\nGensaki_uri = pd.read_excel(Path+'\\\\repo2.xlsx',sheet_name = 'urigensaki',header =8,date_parser=1,index_col=0)\r\n\r\n\r\ndf = pd.DataFrame({'現担レポ':GenTan_borrow['残高合計 Total']/10**12,\r\n '現先取引':Gensaki_kai['残高合計 Total']/10**12},\r\n index=GenTan_borrow.index)\r\ndf.dropna(axis=0,how='any',inplace=True)\r\nfig, ax = plt.subplots(figsize=(8, 4))\r\nax.stackplot(df.index,df['現担レポ'],df['現先取引'],labels =df.columns)\r\nfill_area_BOJoperation_Date(ax,df,label=True,stack=True)\r\n\r\nplt.legend(loc ='upper left',prop =jpfont )\r\nplt.title('レポ取引残高合計 【兆円】',FontProperties=jpfont)\r\nplt.show()\r\n","sub_path":"WTI/syukei.py","file_name":"syukei.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411725425","text":"import pyttsx\nimport time\nimport pyttsx\nimport re\n\nd = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot',\n 'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima',\n 'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo',\n 's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', \n 'x':'x-ray', 'y':'yankee', 'z':'zulu'}\n\ndef do_iaio(word):\n\tspelling = '%s. ' % word\n\tfor letter in word[:-1]:\n\t\tspelling += '%s for %s, ' % (letter, d[letter])\n\tspelling += '%s for %s.' % (word[-1], d[word[-1]])\n\treturn spelling\n\ndef make_msg(text):\n\tmsg = ''\n\tlow = text.lower() #lowecase the text\n\ttokenized = re.sub(r'\\W', ' ', low) #remove non-alphanumerics\n\twlist = low.split() #[, ]\n\tl = map(lambda x: do_iaio(x), wlist)\n\treturn l\n\n\n\n#def speak_ICAO(text, pause_letters, pause_words):\ndef speak_ICAO(text):\n\tt = make_msg(text)\n\tengine = pyttsx.init()\n\tengine.setProperty('rate', 120)\n\tfor i in t:\n\t\tengine.say(i)\n\tengine.runAndWait()\n\n\nname = \"Eleftheria Tsipidi\"\nspeak_ICAO(name)\n#print make_msg(name)","sub_path":"speak_ICAO.py","file_name":"speak_ICAO.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105691290","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nModule that contains custom Qt splitter widgets\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\nfrom Qt.QtCore import *\nfrom Qt.QtWidgets import *\nfrom Qt.QtGui import *\n\nfrom tpDcc.libs.qt.widgets import label\n\n\nclass Divider(QWidget, object):\n\n _ALIGN_MAP = {\n Qt.AlignCenter: 50,\n Qt.AlignLeft: 20,\n Qt.AlignRight: 80\n }\n\n def __init__(self, text=None, shadow=True, color=(150, 150, 150),\n orientation=Qt.Horizontal, alignment=Qt.AlignLeft, parent=None):\n \"\"\"\n Basic standard splitter with optional text\n :param str text: Optional text to include as title in the splitter\n :param bool shadow: True if you want a shadow above the splitter\n :param tuple(int) color: Color of the slitter's text\n :param Qt.Orientation orientation: Orientation of the splitter\n :param Qt.Align alignment: Alignment of the splitter\n :param QWidget parent: Parent of the splitter\n \"\"\"\n\n super(Divider, self).__init__(parent=parent)\n\n self._orient = orientation\n self._text = None\n\n main_color = 'rgba(%s, %s, %s, 255)' % color\n shadow_color = 'rgba(45, 45, 45, 255)'\n\n # bottom_border = ''\n # if shadow:\n # bottom_border = 'border-bottom:1px solid %s;' % shadow_color\n #\n # style_sheet = \"border:0px solid rgba(0,0,0,0); \\\n # background-color: %s; \\\n # line-height: 1px; \\\n # %s\" % (main_color, bottom_border)\n\n font = QFont()\n if shadow:\n font.setBold(True)\n self._text_width = QFontMetrics(font)\n width = self._text_width.width(text) + 6\n\n main_layout = QHBoxLayout()\n main_layout.setContentsMargins(0, 0, 0, 0)\n main_layout.setSpacing(0)\n self.setLayout(main_layout)\n\n self._label = label.BaseLabel().secondary()\n # self._label.setFont(font)\n # self._label.setMaximumWidth(width)\n\n first_line = QFrame()\n self._second_line = QFrame()\n # first_line.setStyleSheet(style_sheet)\n # self._second_line.setStyleSheet(style_sheet)\n\n main_layout.addWidget(first_line)\n main_layout.addWidget(self._label)\n main_layout.addWidget(self._second_line)\n\n if orientation == Qt.Horizontal:\n first_line.setFrameShape(QFrame.HLine)\n first_line.setFrameShadow(QFrame.Sunken)\n first_line.setFixedHeight(2) if shadow else first_line.setFixedHeight(1)\n self._second_line.setFrameShape(QFrame.HLine)\n self._second_line.setFrameShadow(QFrame.Sunken)\n self._second_line.setFixedHeight(2) if shadow else self._second_line.setFixedHeight(1)\n else:\n self._label.setVisible(False)\n self._second_line.setVisible(False)\n first_line.setFrameShape(QFrame.VLine)\n first_line.setFrameShadow(QFrame.Plain)\n self.setFixedWidth(2)\n first_line.setFixedWidth(2) if shadow else first_line.setFixedWidth(1)\n\n main_layout.setStretchFactor(first_line, self._ALIGN_MAP.get(alignment, 50))\n main_layout.setStretchFactor(self._second_line, 100 - self._ALIGN_MAP.get(alignment, 50))\n\n self.set_text(text)\n\n @classmethod\n def left(cls, text=''):\n \"\"\"\n Creates an horizontal splitter with text at left\n :param text:\n :return:\n \"\"\"\n\n return cls(text, alignment=Qt.AlignLeft)\n\n @classmethod\n def right(cls, text=''):\n \"\"\"\n Creates an horizontal splitter with text at right\n :param text:\n :return:\n \"\"\"\n\n return cls(text, alignment=Qt.AlignRight)\n\n @classmethod\n def center(cls, text=''):\n \"\"\"\n Creates an horizontal splitter with text at center\n :param text:\n :return:\n \"\"\"\n\n return cls(text, alignment=Qt.AlignCenter)\n\n @classmethod\n def vertical(cls):\n \"\"\"\n Creates a vertical splitter\n :return:\n \"\"\"\n\n return cls(orientation=Qt.Vertical)\n\n def get_text(self):\n \"\"\"\n Returns splitter text\n :return: str\n \"\"\"\n\n return self._label.text()\n\n def set_text(self, text):\n \"\"\"\n Sets splitter text\n :param str text:\n \"\"\"\n\n self._text = text\n self._label.setText(text)\n if self._orient == Qt.Horizontal:\n self._label.setVisible(bool(text))\n self._second_line.setVisible(bool(text))\n\n # width = self._text_width.width(text) + 6\n # self._label.setMaximumWidth(width)\n\n\nclass DividerLayout(QHBoxLayout, object):\n \"\"\"\n Basic splitter to separate layouts\n \"\"\"\n\n def __init__(self):\n super(DividerLayout, self).__init__()\n\n self.setContentsMargins(40, 2, 40, 2)\n\n splitter = Divider(shadow=False, color=(60, 60, 60))\n splitter.setFixedHeight(2)\n\n self.addWidget(splitter)\n\n\ndef get_horizontal_separator_widget(max_height=30):\n\n v_div_w = QWidget()\n v_div_l = QVBoxLayout()\n v_div_l.setAlignment(Qt.AlignLeft)\n v_div_l.setContentsMargins(5, 5, 5, 5)\n v_div_l.setSpacing(0)\n v_div_w.setLayout(v_div_l)\n v_div = QFrame()\n v_div.setMaximumHeight(max_height)\n v_div.setFrameShape(QFrame.VLine)\n v_div.setFrameShadow(QFrame.Sunken)\n v_div_l.addWidget(v_div)\n return v_div_w\n","sub_path":"tpDcc/libs/qt/widgets/dividers.py","file_name":"dividers.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"112646280","text":"import os\nimport cat_service\nimport subprocess\nimport platform\n\ndef main():\n print_header()\n folder = get_or_create_output_folder()\n print('Found or created folder: {}'.format(folder))\n download_cats(folder)\n display_cats(folder)\n \ndef print_header():\n print(\"---------------------------------\")\n print(\" Cat Factory\")\n print(\"---------------------------------\")\n print()\n\n\ndef get_or_create_output_folder(): \n base_folder = os.path.dirname(__file__)\n folder='cat_pictures'\n full_path = os.path.join(base_folder,folder)\n print(full_path)\n\n if not os.path.exists(full_path) or not os.path.isdir(full_path):\n print('Creating new directory at {}'.format(full_path))\n os.mkdir(full_path)\n\n return full_path\n\n\n\ndef download_cats(folder):\n print('Contacting server to download cats...')\n\n cat_count=3\n\n for i in range(1,cat_count+1): \n name = 'lolcat_{}'.format(i)\n print('Downloading cat {}'.format(name)) \n cat_service.get_cat(folder,name)\n\n print('Done\\n')\n\ndef display_cats(folder):\n #open folder\n print('Displaying cats')\n if platform.system() == 'Windows':\n subprocess.call(['start',folder],shell=True)\n else:\n print (\"I don't support your OS\")\n\nif __name__ == '__main__': \n main()\n\n","sub_path":"apps/06_lolcat_factory/you_try/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"134679416","text":"import os\nimport shutil\n\nimport pytest\n\nfrom jina.flow import Flow\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n\ndef rm_files(file_paths):\n for file_path in file_paths:\n if os.path.exists(file_path):\n if os.path.isfile(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path, ignore_errors=False, onerror=None)\n\n@pytest.mark.skip('based on discussion on Sept. 1, 2020, we will refactor it in another way')\ndef test_index_depth_0_search_depth_1():\n os.environ['CUR_DIR_GRANULARITY'] = cur_dir\n os.environ['TEST_WORKDIR'] = os.getcwd()\n index_data = [\n 'I am chunk 0 of doc 1, I am chunk 1 of doc 1, I am chunk 2 of doc 1',\n 'I am chunk 0 of doc 2, I am chunk 1 of doc 2',\n 'I am chunk 0 of doc 3, I am chunk 1 of doc 3, I am chunk 2 of doc 3, I am chunk 3 of doc 3',\n ]\n\n index_flow = Flow().load_config('flow-index.yml')\n with index_flow:\n index_flow.index(index_data)\n\n def validate_granularity_1(resp):\n assert len(resp.docs) == 3\n for doc in resp.docs:\n assert doc.granularity == 1\n assert len(doc.matches) == 1\n assert doc.matches[0].id == doc.id # done on purpose\n assert doc.matches[0].granularity == 0\n\n assert resp.docs[0].text == 'I am chunk 1 of doc 1,'\n assert resp.docs[0].matches[0].text == 'I am chunk 0 of doc 1, I am chunk 1 of doc 1, I am chunk 2 of doc 1'\n\n assert resp.docs[1].text == 'I am chunk 0 of doc 2,'\n assert resp.docs[1].matches[0].text == 'I am chunk 0 of doc 2, I am chunk 1 of doc 2'\n\n assert resp.docs[2].text == 'I am chunk 3 of doc 3'\n assert resp.docs[2].matches[\n 0].text == 'I am chunk 0 of doc 3, I am chunk 1 of doc 3, I am chunk 2 of doc 3, I am chunk 3 of doc 3'\n\n search_data = [\n 'I am chunk 1 of doc 1,',\n 'I am chunk 0 of doc 2,',\n 'I am chunk 3 of doc 3',\n ]\n\n search_flow = Flow().load_config('flow-query.yml')\n with search_flow:\n search_flow.search(input_fn=search_data, output_fn=validate_granularity_1, callback_on_body=True, granularity=1)\n\n rm_files([os.path.join(os.getenv('TEST_WORKDIR'), 'test_workspace')])\n del os.environ['CUR_DIR_GRANULARITY']\n del os.environ['TEST_WORKDIR']\n","sub_path":"tests/integration/level_depth/test_search_different_depths.py","file_name":"test_search_different_depths.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"256641176","text":"import pymongo\nimport unittest\n\nimport test_settings\nfrom shardmonster import api, connection as connection_module, metadata\n\n\ndef _is_same_mongo(conn1, conn2):\n uri_info1 = pymongo.uri_parser.parse_uri(conn1['uri'])\n uri_info2 = pymongo.uri_parser.parse_uri(conn2['uri'])\n return set(uri_info1['nodelist']) == set(uri_info2['nodelist'])\n\n\nclass MongoTestCase(unittest.TestCase):\n __connections = []\n\n def tearDown(self):\n for connection in self.__connections:\n connection.close()\n\n def _connect(self, uri, db_name):\n connection = pymongo.MongoClient(uri)\n db = connection[db_name]\n connection.drop_database(db.name)\n self.__connections.append(connection)\n return db\n\n\nclass ShardingTestCase(unittest.TestCase):\n def setUp(self):\n self._prepare_connections()\n self._clean_data_before_tests()\n self._prepare_clusters()\n self._prepare_realms()\n api.create_indices()\n\n def tearDown(self):\n self.conn1.close()\n self.conn2.close()\n\n def _create_connection(self, conn_settings):\n conn = connection_module._connect_to_mongo(conn_settings['uri'])\n db_name = conn_settings['db_name']\n db = conn[db_name]\n return conn, db\n\n def _prepare_connections(self):\n if _is_same_mongo(test_settings.CONN1, test_settings.CONN2):\n raise Exception('Must use two different Mongo servers for testing!')\n self.conn1, self.db1 = self._create_connection(\n test_settings.CONN1)\n self.conn2, self.db2 = self._create_connection(\n test_settings.CONN2)\n api.connect_to_controller(\n test_settings.CONTROLLER['uri'],\n test_settings.CONTROLLER['db_name'],\n )\n\n # Wipe the connections that are in the cache in shardmonster\n for connection in connection_module._connection_cache.values():\n connection.close()\n connection_module._connection_cache = {}\n connection_module._cluster_uri_cache = {}\n api._collection_cache = {}\n metadata._metadata_stores = {}\n\n def _clean_data_before_tests(self):\n self.db1.client.drop_database(self.db1.name)\n self.db2.client.drop_database(self.db2.name)\n api._reset_sharding_info()\n\n def _prepare_clusters(self):\n api.add_cluster('dest1', test_settings.CONN1['uri'])\n api.add_cluster('dest2', test_settings.CONN2['uri'])\n\n def _prepare_realms(self):\n api.create_realm(\n 'dummy', 'x', 'dummy',\n 'dest1/%s' % test_settings.CONN1['db_name'])\n","sub_path":"shardmonster/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592495509","text":"import os\nimport psycopg2\nfrom psycopg2 import extras\nimport json\nimport pandas as pd\nfrom dotenv import load_dotenv\n\n\n\ndef execute_values(conn, df, table):\n \"\"\"\n Using psycopg2.extras.execute_values() to insert the dataframe\n \"\"\"\n # Create a list of tupples from the dataframe values\n tuples = [tuple(x) for x in df.to_numpy()]\n # Comma-separated dataframe columns\n cols = ','.join(list(df.columns))\n # SQL quert to execute\n query = f\"INSERT INTO {table}({cols}) VALUES %s\"\n cursor = conn.cursor()\n try:\n extras.execute_values(cursor, query, tuples)\n conn.commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error: %s\" % error)\n conn.rollback()\n cursor.close()\n return 1\n print(\"execute_values() done\")\n cursor.close()\n\n\nload_dotenv()\n\nDB_NAME = os.getenv(\"DB_NAME\")\nDB_USER = os.getenv(\"DB_USER\")\nDB_PASSWORD = os.getenv(\"DB_PASSWORD\")\nDB_HOST = os.getenv(\"DB_HOST\")\n\nconnection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST)\nprint(\"CONNECTION\", type(connection))\n\ncursor = connection.cursor()\nprint(\"CURSOR\", type(cursor))\n\nprint(\"-------------------\")\nquery = \"SELECT usename, usecreatedb, usesuper, passwd FROM pg_user;\"\nprint(\"SQL:\", query)\ncursor.execute(query)\nfor row in cursor.fetchall()[0:10]:\n print(row)\n\n\ndf = pd.read_csv('titanic.csv')\n\nprint(df.columns)\n\ncols = {'Survived':'survived', 'Pclass':'pclass', 'Name':'name', 'Sex':'sex', 'Age':'age', 'Siblings/Spouses Aboard':'si_sp_aboard',\n 'Parents/Children Aboard':'pa_ch_aboard', 'Fare':'fare'}\n\ndf.rename(columns=cols, inplace=True)\n\nprint(df.columns)\n\ndf = df.astype({'survived':'bool'})\n#\n# CREATE THE TABLE\n#\n\ntable_name = \"titanic\"\n\nprint(\"-------------------\")\nquery = f\"\"\"\n-- CREATE TYPE gender AS ENUM ('male', 'female');\nCREATE TABLE IF NOT EXISTS {table_name} (\n id SERIAL PRIMARY KEY,\n survived BOOLEAN NOT NULL,\n pclass SMALLINT NOT NULL,\n name varchar NOT NULL,\n sex gender NOT NULL,\n age SMALLINT NOT NULL,\n si_sp_aboard SMALLINT NOT NULL,\n pa_ch_aboard SMALLINT NOT NULL,\n fare REAL NOT NULL\n);\n\"\"\"\nprint(\"SQL:\", query)\ncursor.execute(query)\nconnection.commit()\n\nexecute_values(connection, df, table_name)\n\ncursor.close()\nconnection.close()\n","sub_path":"module2-sql-for-analysis/insert_titanic.py","file_name":"insert_titanic.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"95937215","text":"from __future__ import print_function\nimport numpy as np\nimport cv2\n# from mpl_toolkits.mplot3d import axes3d, Axes3D\n# import pylab\n# from mayavi import mlab\nimport pylab\nimport copy\n\nimport spynnaker.pyNN as sim\nimport spynnaker_extra_pynn_models as q\nfrom setup_functions import *\nfrom pattern_generator import *\nimport os\nimport subprocess\n\n\n\ndef weights_to_img(ws):\n if isinstance(ws, list):\n ws = numpy.array(ws)\n \n width = int(numpy.ceil(numpy.sqrt(ws.size)))\n height = ws.size//width + 1\n\n w_img = numpy.zeros(width*height)\n w_img[:ws.size] = ws\n w_img = w_img.reshape((height, width))\n\n return w_img\n\ndef conns_to_weights(conns):\n return numpy.array([x[2] for x in conns])\n\n\n########################################################################\n\nVIS, RUN = 0, 1\nLINE, POLY = 0, 1\nIN2EXC, EXC2EXC, INH2EXC, EXC2INH = range(4)\nDOG = True\n\nvis_or_run = RUN\n\n\nmin_delay = 1.\nmax_delay = 16.\nnet_max_delay = 10.\nweight_min = 0.\nweight_max = 1.8\nweight_to_spike = 2.\n\ndesc = {\n 'conn_prob': 1., \n 'dist_func': \"exp(-d)\",# \"1.0/(1. + d**2)\",\n 'max_dist': 4.,\n 'inh_w': weight_max,\n 'exc_w': (weight_to_spike-weight_min)*0.25,\n 'inter_w':(weight_to_spike-weight_min)*0.25,# numpy.sqrt(weight_max),\n 'inter_conn_prob': 0.1,\n 'feedback_w': numpy.sqrt(weight_max),\n 'delay_scale': True,\n 'min_delay': min_delay,\n 'max_delay': net_max_delay,\n}\ninput_neurons = 8\nline_y0 = 0\nline_z0 = 0\nnet_filename = \"./line_small_network.pickle\"\n\nif os.path.isfile(net_filename):\n pops, conns = load_network(net_filename)\n line3d = pops[LINE]\n poly3d = pops[POLY]\nelse:\n line3d = line_pop3d(input_neurons, line_y0, line_z0)\n poly3d = setup_rand_layer(input_neurons, krnl_w=2, y0=2.,\n exc_height=3.,\n inh_height=3.)\n\n conns = connect_layers(line3d, poly3d, desc)\n \n pops = {LINE: line3d, POLY: poly3d}\n save_network(net_filename, pops, conns)\n\n\nmins = 0.\nsecs = 10.\nms = 0.\nsim_time = mins*60*1000 + secs*1000 + ms\n\nif vis_or_run == VIS:\n from mayavi import mlab\n from vis_tools import *\n scale_factor = 0.5\n in_color = (0., 0.5, 0.)\n inh_color = (0.5, 0., 0.)\n exc_color = (0., 0.5, 0.)\n\n fig = mlab.figure(bgcolor=(1., 1., 1.))\n\n plot_layer(line3d, scale_factor=scale_factor, exc_color=(0.1, 0.5, 0.5))\n plot_layer(poly3d, scale_factor=scale_factor)\n puc = 1.\n plot_connections(conns[IN2EXC][: int(len(conns[IN2EXC])*puc)], \n line3d['exc'], poly3d['exc'], color=in_color)\n \n #~ plot_connections(conns[INH2EXC][: int(len(conns[INH2EXC])*puc)], \n #~ poly3d['inh'], poly3d['exc'], color=inh_color)\n \n #~ plot_connections(conns[EXC2INH][: int(len(conns[EXC2INH])*puc)], \n #~ poly3d['exc'], poly3d['inh'], color=exc_color)\n #~ \n #~ plot_connections(conns[EXC2EXC][: int(len(conns[EXC2EXC])*puc)], \n #~ poly3d['exc'], poly3d['exc'], color=exc_color)\n\n mlab.show()\n\nelse: ### run simulation with the defined populations\n num_runs = 200\n MIN, MAX, AVG = range(3)\n start_stats = numpy.zeros((num_runs, 3))\n end_stats = numpy.zeros((num_runs, 3))\n diff_stats = numpy.zeros((num_runs, 3))\n out_dir = \"weight_change_comparison\"\n spike_times = []\n spike_ids = []\n projs = {}\n cell_params = {}\n spks = []\n in_spikes = []\n exc_spikes = []\n inh_spikes = []\n \n for rand_lif in [False, True]:\n for mySTDP in [False, True]:\n for run in range(0, num_runs, 5):\n # subprocess.call([\"../../../install_tools/setup_routes.sh\", ])\n sim.setup(timestep=1.0, min_delay=min_delay, max_delay=max_delay)\n #sim.set_number_of_neurons_per_core(\"IF_curr_exp\", 10)\n \n cell_params.clear()\n cell_params['cm'] = 0.25 # nF\n cell_params['i_offset'] = 0.0\n cell_params['tau_m'] = 10.0\n cell_params['tau_refrac'] = 2.0\n cell_params['tau_syn_E'] = 2.5\n cell_params['tau_syn_I'] = 2.5\n cell_params['v_reset'] = -70.0\n cell_params['v_rest'] = -65.0\n cell_params['v_thresh'] = -55.4\n\n\n if rand_lif:\n model = q.IF_curr_exp_stoc\n cell_params['spike_prob'] = 0.01\n cell_params['i_boost'] = 1\n else:\n model = sim.IF_curr_exp\n \n mad = True\n if mySTDP:\n additional_delta = 0.0#9\n else:\n additional_delta = 0.0\n dep_w_delta_std = 0.1#0.01\n dep_w_delta_max = dep_w_delta_std + additional_delta\n \n timing_dep = q.PiecewiseRule(depression_left_time_thresh = 10,\n depression_right_time_thresh = 20,\n potentiation_time_thresh = 10,\n depression_weight_delta_std = dep_w_delta_std,\n depression_weight_delta_max = dep_w_delta_max,\n potentiation_weight_delta = 0.5)\n # timing_dep = sim.SpikePairRule(tau_plus=20., tau_minus=20.0,\n # nearest=True)\n weight_dep = sim.AdditiveWeightDependence(w_min=weight_min, w_max=weight_max, \n A_plus=0.1, A_minus=0.1)\n\n stdp_model = sim.STDPMechanism(timing_dependence=timing_dep,\n weight_dependence=weight_dep,\n mad=mad)\n\n synapse_dynamics=sim.SynapseDynamics(slow=stdp_model)\n\n spks[:] = l2r(num_neurons=input_neurons, timestep=1, base_time=10)\n #spks[:] = merge_patterns(spks, l2r(input_neurons, 5, 20, rand_time_step=True))\n spks[:] = repeat_pattern(spks, run, 20)\n \n \n \n line_pop = sim.Population(input_neurons, sim.SpikeSourceArray,\n {'spike_times': spks})\n \n poly_exc_pop = sim.Population(poly3d['exc'].shape[0], model,\n cell_params, label=\"excitatory\")\n\n poly_inh_pop = sim.Population(poly3d['inh'].shape[0], model,\n cell_params, label=\"inhibitory\")\n \n projs.clear()\n projs[IN2EXC] = sim.Projection(line_pop, poly_exc_pop, \n sim.FromListConnector(conns[IN2EXC]),\n target='excitatory',\n synapse_dynamics=synapse_dynamics)\n \n projs[EXC2EXC] = sim.Projection(poly_exc_pop, poly_exc_pop, \n sim.FromListConnector(conns[EXC2EXC]),\n target='excitatory',\n # synapse_dynamics=synapse_dynamics\n )\n\n projs[EXC2INH] = sim.Projection(poly_exc_pop, poly_inh_pop, \n sim.FromListConnector(conns[EXC2INH]),\n target='excitatory',\n # synapse_dynamics=synapse_dynamics\n )\n \n projs[INH2EXC] = sim.Projection(poly_exc_pop, poly_inh_pop, \n sim.FromListConnector(conns[INH2EXC]),\n target='inhibitory',\n # synapse_dynamics=synapse_dynamics\n )\n\n poly_exc_pop.record()\n poly_inh_pop.record()\n line_pop.record()\n \n any_spikes_recorded = True\n sim.run(sim_time)\n \n try:\n in_spikes[:] = line_pop.getSpikes(compatible_output=True)\n exc_spikes[:] = poly_exc_pop.getSpikes(compatible_output=True)\n inh_spikes[:] = poly_inh_pop.getSpikes(compatible_output=True)\n except IndexError:\n print(\"No spikes?-----------------------------------\")\n any_spikes_recorded = False\n\n in2exc_w = numpy.array(projs[IN2EXC].getWeights())\n\n\n sim.end()\n\n \n\n if any_spikes_recorded:\n fig = pylab.figure()\n markersize=2\n marker='.'\n spike_times[:] = []\n spike_ids[:] = [] \n\n spike_times[:] = [spike_time for (neuron_id, spike_time) in in_spikes]\n spike_ids[:] = [neuron_id for (neuron_id, spike_time) in in_spikes]\n pylab.plot(spike_times, spike_ids, marker, markerfacecolor=\"None\",\n markeredgecolor='green', markersize=markersize)\n spike_times[:] = []\n spike_ids[:] = [] \n\n spike_times[:] = [spike_time for (neuron_id, spike_time) in exc_spikes]\n spike_ids[:] = [neuron_id + input_neurons for (neuron_id, spike_time) in exc_spikes]\n pylab.plot(spike_times, spike_ids, marker, markerfacecolor=\"None\",\n markeredgecolor='blue', markersize=markersize)\n\n num_exc = poly3d['exc'].shape[0] + input_neurons\n spike_times[:] = []\n spike_ids[:] = [] \n spike_times[:] = [spike_time for (neuron_id, spike_time) in inh_spikes]\n spike_ids[:] = [neuron_id + num_exc for (neuron_id, spike_time) in inh_spikes]\n\n pylab.plot(spike_times, spike_ids, marker, markerfacecolor=\"None\",\n markeredgecolor='red', markersize=markersize)\n pylab.savefig(\"%s/spikes_loop_%d_mySTDP_%s___randLIF_%s_.png\"%\\\n (out_dir, run, mySTDP, rand_lif), dpi=300)\n\n\n start_w = conns_to_weights(conns[IN2EXC])\n weight_diff = in2exc_w - start_w\n \n fig = pylab.figure()\n min_v = None#0.\n max_v = None#1.8\n ax = pylab.subplot(1, 3, 1)\n start_min = start_w.min()\n start_avg = start_w.mean()\n start_max = start_w.max()\n \n end_min = in2exc_w.min()\n end_avg = in2exc_w.mean()\n end_max = in2exc_w.max()\n\n diff_min = weight_diff.min()\n diff_avg = weight_diff.mean()\n diff_max = weight_diff.max()\n\n ax.set_title( \"Starting weights\\n(min, avg, max)\\n%s\\n%s\\n%s\"%\\\n (start_min, start_avg, start_max) )\n pylab.imshow(weights_to_img(start_w), \n cmap=\"Greys_r\", \n interpolation='none',\n vmin=min_v, vmax=max_v)\n\n ax = pylab.subplot(1, 3, 2)\n pylab.imshow(weights_to_img(in2exc_w),\n cmap=\"Greys_r\", \n interpolation='none',\n vmin=min_v, vmax=max_v)\n ax.set_title( \"End weights\\n(min, avg, max)\\n%s\\n%s\\n%s\"%\\\n (end_min, end_avg, end_max) )\n\n ax = pylab.subplot(1, 3, 3)\n ax.set_title( \"Weight difference\\n(min, avg, max)\\n%s\\n%s\\n%s\"%\\\n (diff_min, diff_avg, diff_max) )\n pylab.imshow(weights_to_img(numpy.abs(weight_diff)),\n cmap=\"Greys_r\", \n interpolation='none',\n vmin=min_v, vmax=max_v)\n pylab.savefig(\"%s/weights_loop_%d_mySTDP_%s___randLIF_%s_.png\"%\\\n (out_dir, run, mySTDP, rand_lif), dpi=300)\n # pylab.show()\n\n start_stats[run, MIN] = start_min\n start_stats[run, AVG] = start_avg\n start_stats[run, MAX] = start_max\n\n end_stats[run, MIN] = end_min\n end_stats[run, AVG] = end_avg\n end_stats[run, MAX] = end_max\n\n diff_stats[run, MIN] = diff_min\n diff_stats[run, AVG] = diff_avg\n diff_stats[run, MAX] = diff_max\n\n fig = pylab.figure()\n pylab.errorbar(range(num_runs), start_stats[:, AVG],\\\n yerr=start_stats[:, MAX] - start_stats[:, MIN], label=\"Start\")\n pylab.errorbar(range(num_runs), end_stats[:, AVG],\\\n yerr=end_stats[:, MAX] - end_stats[:, MIN], label=\"End\")\n # pylab.errorbar(range(num_runs), start_stats[:, AVG],\\\n # yerr=start_stats[:, MAX] - start_stats[:, MIN])\n pylab.savefig(\"%s/weight_change_mySTDP___%s_randLIF_%s_.png\"%\\\n (out_dir, mySTDP, rand_lif), dpi=300)\n \n np.save(\"%s/start_stats_mySTDP_%s___randLIF_%s_\"%\\\n (out_dir, mySTDP, rand_lif), start_stats)\n np.save(\"%s/start_stats_mySTDP_%s___randLIF_%s_\"%\\\n (out_dir, mySTDP, rand_lif), end_stats)\n np.save(\"%s/start_stats_mySTDP_%s___randLIF_%s_\"%\\\n (out_dir, mySTDP, rand_lif), diff_stats)\n\n\nprint(\"------------------------------------------------\")\nprint(\"------------------------------------------------\")\nprint(\"------------------------------------------------\")\n","sub_path":"spiking/piecewise/input_plus_one_layer/small_network_test.py","file_name":"small_network_test.py","file_ext":"py","file_size_in_byte":14471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"347379052","text":"from django import forms\r\nfrom django.conf import settings\r\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\r\nfrom django.core.urlresolvers import reverse\r\nfrom django.utils.translation import ugettext as _\r\n\r\nfrom .common import parse_name\r\n\r\nfrom string import lowercase\r\n\r\nclass TreeRootForm(forms.Form):\r\n\r\n PREFIX_CHOICES = zip(lowercase, lowercase)\r\n\r\n prefix = forms.ChoiceField(choices=PREFIX_CHOICES, )\r\n\r\n def __init__(self, request=None, *args, **kwargs):\r\n self.request = request\r\n super(TreeRootForm, self).__init__(*args, **kwargs)\r\n\r\n def get_result(self):\r\n prefix = self.cleaned_data['prefix']\r\n body = {\r\n 'query': {\r\n 'bool':{\r\n 'must': {'prefix': { 'name': prefix }},\r\n 'must_not': {'exists':{ 'field': 'parent_aphia_id' }}\r\n }\r\n },\r\n '_source': [ 'name', 'aphia_id', 'rank', 'parent_aphia_id', 'has_children' ],\r\n 'sort': {\r\n 'name': 'asc'\r\n },\r\n 'size': 10000\r\n }\r\n result = settings.ES.search(index=settings.ES_SETTINGS['index'], doc_type='nodes', body=body)\r\n if result.has_key('error') or (\r\n result.has_key('time_out') and result['time_out'] is True):\r\n return {'code': 2, 'error': _('Server error.'),} \r\n else:\r\n data = []\r\n for x in result['hits']['hits']:\r\n item = x['_source']\r\n item['iconSkin'] = item['rank']\r\n item['isParent'] = item['has_children']\r\n item['name'] = parse_name(item['name'], item['iconSkin'])\r\n del item['has_children']\r\n data.append(item)\r\n return {'code': 0, 'data': data, }\r\n\r\nclass TreeChildrenForm(forms.Form):\r\n\r\n aphia_id = forms.IntegerField()\r\n\r\n def __init__(self, request=None, *args, **kwargs):\r\n self.request = request\r\n super(TreeChildrenForm, self).__init__(*args, **kwargs)\r\n\r\n def get_result(self):\r\n aphia_id = self.cleaned_data['aphia_id']\r\n body = {\r\n 'query': {\r\n 'match': {\r\n 'parent_aphia_id': aphia_id\r\n }\r\n },\r\n '_source': [ 'name', 'aphia_id', 'rank', 'parent_aphia_id', 'has_children' ],\r\n 'sort': {\r\n 'name': 'asc'\r\n },\r\n 'size': 10000\r\n }\r\n result = settings.ES.search(index=settings.ES_SETTINGS['index'], doc_type='nodes', body=body)\r\n if result.has_key('error') or (\r\n result.has_key('time_out') and result['time_out'] is True):\r\n return {'code': 2, 'error': _('Server error.'),} \r\n else:\r\n data = []\r\n for x in result['hits']['hits']:\r\n item = x['_source']\r\n item['iconSkin'] = item['rank']\r\n item['isParent'] = item['has_children']\r\n item['name'] = parse_name(item['name'], item['iconSkin'])\r\n del item['has_children']\r\n data.append(item)\r\n return {'code': 0, 'data': data, }\r\n\r\nclass NodePathForm(forms.Form):\r\n\r\n aphia_id = forms.IntegerField()\r\n\r\n def __init__(self, request=None, *args, **kwargs):\r\n self.request = request\r\n super(NodePathForm, self).__init__(*args, **kwargs)\r\n\r\n def get_loop(self, primary, type_name):\r\n data = []\r\n result = {}\r\n while primary is not None:\r\n node = settings.ES.get(index=settings.ES_SETTINGS['index'], doc_type='nodes', id=primary)\r\n if node.has_key('error') or (\r\n node.has_key('found') and node['found'] is False):\r\n result = {'code': 2, 'error': _('Server error while getting path data of special node.'),}\r\n break\r\n else:\r\n primary = node['_source']['parent_aphia_id']\r\n if primary is not None:\r\n if type_name == 'list':\r\n data.append(primary)\r\n elif type_name == 'dict':\r\n data.append({\r\n 'aphia_id': node['_source']['aphia_id'],\r\n 'parent_aphia_id': primary,\r\n 'rank': node['_source']['rank'],\r\n 'name': node['_source']['name'],\r\n })\r\n else:\r\n if type_name == 'dict':\r\n data.append({\r\n 'aphia_id': node['_source']['aphia_id'],\r\n 'parent_aphia_id': primary,\r\n 'rank': node['_source']['rank'],\r\n 'name': parse_name(node['_source']['name'], node['_source']['rank']),\r\n })\r\n else:\r\n result = {'code': 0, 'data': {'leaf_to_root': data, }}\r\n return result\r\n\r\n def get_result(self, type_name='list'):\r\n aphia_id = self.cleaned_data['aphia_id']\r\n return self.get_loop(aphia_id, type_name)\r\n\r\nclass NodeDetailForm(forms.Form):\r\n\r\n aphia_id = forms.IntegerField()\r\n\r\n def __init__(self, request=None, *args, **kwargs):\r\n self.request = request\r\n super(NodeDetailForm, self).__init__(*args, **kwargs)\r\n\r\n def get_result(self):\r\n aphia_id = self.cleaned_data['aphia_id']\r\n node = settings.ES.get(index=settings.ES_SETTINGS['index'], doc_type='nodes', id=aphia_id)\r\n if node.has_key('error') or (\r\n node.has_key('found') and node['found'] is False):\r\n return {'code': 2, 'error': _('Server error.'),}\r\n else:\r\n result = {'code': 0, 'data': {'json': node['_source']},}\r\n result['data']['json']['name'] = parse_name(result['data']['json']['name'], result['data']['json']['rank'])\r\n images = []\r\n for i in result['data']['json']['images']:\r\n images.append(static(settings.IMAGE_DATA_DIR+i))\r\n result['data']['json']['images'] = images\r\n for k, v in result['data']['json']['data'].items():\r\n k_v = []\r\n for i in v:\r\n k_v.append({'name': i, 'url': reverse('download', kwargs={'filename': i})})\r\n result['data']['json']['data'][k] = k_v\r\n return result\r\n\r\nclass TreeVisualForm(forms.Form):\r\n\r\n TYPE_NAME_CHOICES = (('root', 'root',), ('child', 'child',),)\r\n PREFIX_CHOICES = zip(lowercase, lowercase)\r\n\r\n '''\r\n when type_name is root, aphia_id is useless, return the root with prefix and \r\n next two levels data for visualization.\r\n when type_name is child, prefix is useless, return the path to the aphia_id, \r\n all the same level nodes and next level nodes of aphia_id for visualization.\r\n '''\r\n type_name = forms.ChoiceField(choices=TYPE_NAME_CHOICES, )\r\n prefix = forms.ChoiceField(choices=PREFIX_CHOICES, )\r\n aphia_id = forms.IntegerField()\r\n\r\n def __init__(self, request=None, *args, **kwargs):\r\n self.request = request\r\n super(TreeVisualForm, self).__init__(*args, **kwargs)\r\n\r\n def get_path(self, aphia_id):\r\n form = NodePathForm(self.request, data=self.request.GET)\r\n if form.is_valid():\r\n return form.get_result(type_name='dict')\r\n else:\r\n return {'code': 2}\r\n\r\n def get_root(self, prefix):\r\n form = TreeRootForm(self.request, data=self.request.GET)\r\n if form.is_valid():\r\n return form.get_result()\r\n else:\r\n return {'code': 2}\r\n\r\n def get_next_level(self, aphia_id_list):\r\n body = {\r\n 'query': {\r\n 'terms' : {'parent_aphia_id' : aphia_id_list}\r\n },\r\n '_source': [ 'name', 'aphia_id', 'parent_aphia_id', 'rank', ],\r\n 'size': 10000\r\n }\r\n result = settings.ES.search(index=settings.ES_SETTINGS['index'], doc_type='nodes', body=body)\r\n if result.has_key('error') or (\r\n result.has_key('time_out') and result['time_out'] is True):\r\n return {'code': 2, 'error': _('Server error.'),}\r\n else:\r\n return {'code': 0, 'data': [x['_source'] for x in result['hits']['hits']]}\r\n\r\n def get_result(self):\r\n color_map = {\r\n 'class': 'rgba(255, 255, 0, 0.8)', \r\n 'family': 'rgba(0, 0, 255, 0.8)', \r\n 'forma': 'rgba(0, 0, 0, 1)', \r\n 'genus': 'rgba(62, 119, 148, 0.8)', \r\n 'infraclass': 'rgba(255, 255, 0, 0.4)', \r\n 'infraorder': 'rgba(0, 255, 255, 0.4)', \r\n 'infraphylum': 'rgba(255, 153, 0, 0.6)', \r\n 'kingdom': 'rgba(255, 0, 0, 0.8)', \r\n 'order': 'rgba(0, 255, 255, 0.8)', \r\n 'parvorder': 'rgba(0, 255, 255, 0.2)', \r\n 'phylum': 'rgba(255, 153, 0, 0.8)', \r\n 'section': 'rgba(0, 0, 0, 1)', \r\n 'species': 'rgba(160, 32, 240, 0.8)', \r\n 'subclass': 'rgba(255, 255, 0, 0.6)', \r\n 'subdivision': 'rgba(0, 0, 0, 1)', \r\n 'subfamily': 'rgba(0, 0, 255, 0.6)', \r\n 'subgenus': 'rgba(62, 119, 148, 0.6)', \r\n 'subkingdom': 'rgba(255, 0, 0, 0.6)', \r\n 'suborder': 'rgba(0, 255, 255, 0.6)', \r\n 'subsection': 'rgba(0, 0, 0, 1)', \r\n 'subspecies': 'rgba(160, 32, 240, 0.6)', \r\n 'superclass': 'rgba(255, 255, 0, 1)', \r\n 'superfamily': 'rgba(0, 0, 255, 1)', \r\n 'superorder': 'rgba(0, 255, 255, 1)', \r\n 'tribe': 'rgba(0, 0, 0, 1)', \r\n 'variety': 'rgba(0, 0, 0, 1)',\r\n }\r\n data = {}\r\n type_name = self.cleaned_data['type_name']\r\n prefix = self.cleaned_data['prefix']\r\n aphia_id = self.cleaned_data['aphia_id']\r\n if type_name == 'root':\r\n root_level = self.get_root(prefix)\r\n if root_level['code'] == 0:\r\n for i in root_level['data']:\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n del i['isParent'], i['iconSkin']\r\n root_list = [x['aphia_id'] for x in root_level['data']]\r\n second_level = self.get_next_level(root_list)\r\n if second_level['code'] == 0:\r\n nodes = []\r\n links = []\r\n for i in root_level['data']+second_level['data']:\r\n i['value'] = 1\r\n #i['label'] = parse_name(i['name'], i['rank'])\r\n i['label'] = i['name'].replace('', '').replace('', '')\r\n i['name'] = str(i['aphia_id'])\r\n i['id'] = i['aphia_id']\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n nodes.append(i)\r\n if i['parent_aphia_id'] != None:\r\n links.append({'target': str(i['parent_aphia_id']), 'source': str(i['aphia_id'])})\r\n del i['parent_aphia_id'], i['aphia_id'], i['rank']\r\n return {'code': 0, 'data': {'links': links, 'nodes': nodes}}\r\n elif type_name == 'child':\r\n path = self.get_path(aphia_id)\r\n if path['code'] == 0:\r\n if len(path['data']['leaf_to_root']) == 1:\r\n next_level = self.get_next_level([path['data']['leaf_to_root'][0]['aphia_id'],])\r\n if next_level['code'] == 0:\r\n next_list = [x['aphia_id'] for x in next_level['data']]\r\n next_next_level = self.get_next_level(next_list)\r\n if next_next_level['code'] == 0:\r\n result = path['data']['leaf_to_root'][0]\r\n result['itemStyle'] = {'normal': {'color': color_map[result['rank']]}}\r\n result['name'] = result['name'].replace('', '').replace('', '')\r\n result['id'] = result['aphia_id']\r\n del result['parent_aphia_id'], result['aphia_id']\r\n result['children'] = next_level['data']\r\n for i in next_next_level['data']:\r\n for j in next_level['data']:\r\n if i['parent_aphia_id'] == j['aphia_id']:\r\n if j.has_key('children'):\r\n j['children'].append(i)\r\n else:\r\n j['children'] = [i,]\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n #i['name'] = parse_name(i['name'], i['rank'])\r\n i['name'] = i['name'].replace('', '').replace('', '')\r\n i['id'] = i['aphia_id']\r\n del i['parent_aphia_id'], i['aphia_id']\r\n for i in next_level['data']:\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n #i['name'] = parse_name(i['name'], i['rank'])\r\n i['name'] = i['name'].replace('', '').replace('', '')\r\n i['id'] = i['aphia_id']\r\n del i['parent_aphia_id'], i['aphia_id']\r\n return {'code': 0, 'data': result}\r\n else:\r\n leaf_level = self.get_next_level([path['data']['leaf_to_root'][0]['aphia_id'],])\r\n same_level = self.get_next_level([path['data']['leaf_to_root'][0]['parent_aphia_id'],])\r\n if leaf_level['code'] == 0 and same_level['code'] == 0:\r\n for i in leaf_level['data']:\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n i['id'] = i['aphia_id']\r\n del i['parent_aphia_id'], i['aphia_id']\r\n if path['data']['leaf_to_root'][0].has_key('children'):\r\n path['data']['leaf_to_root'][0]['children'].append(i)\r\n else:\r\n path['data']['leaf_to_root'][0]['children'] = [i, ]\r\n path['data']['leaf_to_root'][1]['children'] = [path['data']['leaf_to_root'][0], ]\r\n for i in same_level['data']:\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n if i['aphia_id'] != path['data']['leaf_to_root'][0]['aphia_id']:\r\n path['data']['leaf_to_root'][1]['children'].append(i)\r\n i['id'] = i['aphia_id']\r\n del i['parent_aphia_id'], i['aphia_id']\r\n child_index = 1\r\n parent_index = 2\r\n while parent_index != len(path['data']['leaf_to_root']):\r\n path['data']['leaf_to_root'][parent_index]['children'] = [path['data']['leaf_to_root'][child_index], ]\r\n child_index += 1\r\n parent_index += 1\r\n for i in path['data']['leaf_to_root']:\r\n i['itemStyle'] = {'normal': {'color': color_map[i['rank']]}}\r\n i['name'] = i['name'].replace('', '').replace('', '')\r\n i['id'] = i['aphia_id']\r\n del i['parent_aphia_id'], i['aphia_id']\r\n return {'code': 0, 'data': path['data']['leaf_to_root'][-1]}\r\n return {'code': 2, 'error': _('Server error.'),}\r\n\r\nclass NodeForm(forms.Form):\r\n\r\n query = forms.CharField(required=False, )\r\n start = forms.IntegerField(min_value=0, required=False, )\r\n\r\n def __init__(self, request=None, *args, **kwargs):\r\n self.request = request\r\n super(NodeForm, self).__init__(*args, **kwargs)\r\n\r\n def get_filter_result(self):\r\n query = self.cleaned_data['query']\r\n body = {\r\n 'query': {\r\n 'match': {\r\n 'name.full_text': query\r\n }\r\n },\r\n '_source': [ 'name', 'aphia_id', 'rank' ]\r\n }\r\n result = settings.ES.search(index=settings.ES_SETTINGS['index'], doc_type='nodes', body=body)\r\n if result.has_key('error') or (\r\n result.has_key('time_out') and result['time_out'] is True):\r\n return {'code': 2, 'error': _('Server error.'),}\r\n else:\r\n result = {'code': 0, 'data': [x['_source'] for x in result['hits']['hits']]}\r\n for i in result['data']:\r\n i['name'] = parse_name(i['name'], i['rank'])\r\n del i['rank']\r\n return result\r\n\r\n def get_search_result(self):\r\n query = self.cleaned_data['query']\r\n start = self.cleaned_data['start']\r\n if query:\r\n body = {\r\n 'query': {\r\n 'multi_match': {\r\n 'query': query,\r\n 'fields': ['name.full_text', 'description', 'references',] \r\n }\r\n },\r\n 'size': 30,\r\n 'from': start\r\n }\r\n else:\r\n body = {\r\n 'query': {},\r\n 'size': 30,\r\n 'from': start\r\n }\r\n result = settings.ES.search(index=settings.ES_SETTINGS['index'], doc_type='nodes', body=body)\r\n if result.has_key('error') or (\r\n result.has_key('time_out') and result['time_out'] is True):\r\n return {'code': 2, 'error': _('Server error.'),}\r\n else:\r\n tmp_result = {'code': 0, 'data': [x['_source'] for x in result['hits']['hits']],}\r\n for i in tmp_result['data']:\r\n images = []\r\n for j in i['images']:\r\n images.append(static(settings.IMAGE_DATA_DIR+j))\r\n i['images'] = images\r\n data = 0\r\n for v in i['data'].values():\r\n data += len(v)\r\n i['data'] = data\r\n i['name'] = parse_name(i['name'], i['rank'])\r\n tmp_result = {\r\n 'code': 0, \r\n 'data': {\r\n 'total': result['hits']['total'],\r\n 'time': result['took'],\r\n 'json': tmp_result['data'],\r\n }\r\n }\r\n return tmp_result\r\n","sub_path":"website/main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":16042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83349656","text":"\nimport logging\nimport time\n\nlog = logging.getLogger(__name__)\n\ndef run(context):\n driver = context.get_driver()\n driver.switch_to_window_by_title(\"Transforming Testing: A Recipe for Quality Engineering\")\n context.get_all_elements()","sub_path":"lkg/scripts/switch_tab_transforming.py","file_name":"switch_tab_transforming.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"163666167","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 21 11:31:19 2020\r\n\r\n@author: mpkan\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n\r\ndata = np.loadtxt(\"bc.train.0\")\r\n#data = np.loadtxt(\"data.txt\")\r\ntrainlabels = data[:,0]\r\ntrain = data[:,1:]\r\n#norm = np.linalg.norm(train, axis = 0)\r\n#train = train/norm\r\ntrain = (train-np.amin(train,axis=0))/(np.amax(train,axis=0)-np.amin(train,axis=0))\r\n\r\ntest = np.loadtxt(\"bc.test.0\")\r\n#test = np.loadtxt(\"testdata.txt\")\r\ntestlabels = test[:,0]\r\ntest = test[:,1:]\r\ntest = (test-np.amin(test,axis=0))/(np.amax(test,axis=0)-np.amin(test,axis=0))\r\n\r\nn = len(train[:,0])\r\nm = len(train[0,:])\r\nw = np.random.rand(10,m)\r\nb = np.random.rand(10)\r\nC = 0.0000002\r\n\r\nfor i in range (10):\r\n \r\n print(w[i])\r\n \r\n h_loss = 1-(trainlabels*(train.dot(w[i])+b[i]))\r\n is_loss = np.greater(h_loss, 0)\r\n loss = np.sum(np.multiply(h_loss,is_loss))/n\r\n \r\n prev = loss + 10\r\n\r\n eta = 0.1\r\n print(prev,loss)\r\n \r\n while prev - loss > 0.0000001:\r\n grad = -trainlabels[:,np.newaxis] * train\r\n print(grad*(is_loss[:,np.newaxis]))\r\n grad = np.sum(grad * (is_loss[:,np.newaxis]), axis = 0)/n\r\n \r\n w[i] = w[i] - (C*np.linalg.norm(w[i])) - (eta*grad)\r\n b[i] = b[i] - (0.01*-np.sum(trainlabels*is_loss))/n\r\n \r\n h_loss = 1-(trainlabels*(train.dot(w[i])+b[i]))\r\n is_loss = np.greater(h_loss, 0)\r\n prev = loss \r\n loss = np.sum(np.multiply(h_loss,is_loss))/n \r\n print(\"prev-loss\",prev-loss)\r\n \r\n eta = eta \r\n y_pred = np.sign(train.dot(w[i])+b[i])\r\n print(accuracy_score(trainlabels,y_pred),np.sum(y_pred!=trainlabels))\r\n \r\n print(prev,loss)\r\nprint(\"w[i]\",w,\"b\",b)\r\nfor i in range(10):\r\n y_pred = np.sign(test.dot(w[i])+b[i])\r\n print(accuracy_score(testlabels,y_pred),np.sum(y_pred!=testlabels)) \r\n \r\n ","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"440004535","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\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-i686/egg/pytorrent/daemon.py\n# Compiled at: 2008-09-26 21:08:50\nimport subprocess, os, signal, time\n\nclass Daemon(object):\n term = signal.SIGTERM\n kill = signal.SIGKILL\n\n def __init__(self, executable):\n self.executable = executable\n self.pid = None\n self.process = None\n return\n\n def start(self):\n self.process = subprocess.Popen(self.executable)\n self.pid = self.process.pid\n\n def stop(self):\n if self.process:\n pid = self.process.pid\n for i in range(0, 10):\n if self.process.poll() is not None:\n return\n os.kill(pid, self.term)\n time.sleep(0.1)\n\n for i in range(0, 10):\n if self.process.poll() is not None:\n return\n os.kill(pid, self.kill)\n time.sleep(0.1)\n\n return","sub_path":"pycfiles/PyTorrent-0.1.1-py2.5/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"630857405","text":"#importing the required librabries\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\nimport cv2\nfrom PIL import Image\n#import queue\n\n\n\n'''function 'extract_feature' take three parameters pic and file and patch_size .pic is the one dimensional pexels value a cell image and\nfile is the a text file where the mean and variance of 7*7 patch of pixels to be written'''\n\ndef extract_feature(pic,file,patch_size):\n\theight=pic.shape[0]\n\twidth=pic.shape[1]\n\th=height%patch_size \n\tw=width%patch_size\n\tcond=0;cond1=0\n\t#patch=queue.Queue(maxsize=patch_size*patch_size)\n\ttemp=np.zeros(())\n\n\ti=0;j=0;\n\tf=open(file,\"a\") #open the file where mean and variance pair are to be stacked\n\twhile iwidth-w-1 and cond1==0 and width%patch_size!=0: #this loop ensures that no pixels is left even if there is not 32*32 patch we make we take some pixels from prev patch make 32*32 patch \n\t\t\t\tj=width-patch_size\n\t\t\t\tcond1=1\t\n\t\ti+=patch_size\n\t\tcond1=0\n\t\tif i>height-h-1 and cond==0 and height%patch_size!=0:\n\t\t\ti=height-patch_size\n\t\t\tcond=1\n\t\t\tcond1=0\t\n\n\n\tf.close()\t\n\n\n#source path and folder of the cell images\nsource_path=raw_input(\"enter the path to folder where trainig images are present:\")\n#output path and folder where the output to be stacked\ndestination=raw_input(\"enter the path to the file where feature vectors are to stored\")\n#patch size\npatch_size=7\n\nextract_feature(pic,destination,patch_size)\n\ni=1\nfor img in glob.glob(source_path+\"/*.png\"):\n\tpic= imageio.imread(img)\n\tprint(pic.shape[0])\n\tprint(pic.shape[1])\n\t#print('Shape of the image : {}'.format(pic.shape))\n\textract_feature(pic,destination,patch_size)\n\tprint (\"image completed\",i)\n\ti+=1\n\n\n\n","sub_path":"Assignment2/2.Cell_image_code/feature_extract.py","file_name":"feature_extract.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183292205","text":"from apply_defaults import apply_self\n\nclass MyClass:\n def __init__(self, ):\n self.option = True\n\n @apply_self\n def func(self, option=False):\n return option\n\n\nobj = MyClass()\n\n# Prints True\nprint(str(obj.func()))\n\n# Prints False\nprint(str(obj.func(option=False)))\n\n# If the attribute is not in the bound object, the default value from the parameter list is used.\ndel obj.option\n## Prints False now\nprint(str(obj.func()))\n","sub_path":"python_tutorial/basics/ex_apply_default/example_apply_self.py","file_name":"example_apply_self.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"328918566","text":"from django.forms import ModelForm, Textarea, RadioSelect\n\nfrom proposals.models import Proposal\n\nclass ProposalForm(ModelForm):\n class Meta:\n model = Proposal\n fields = ('type', 'name', 'desc', 'image')\n widgets = {\n 'type': RadioSelect(),\n 'desc': Textarea(attrs={'cols': 150, 'rows': 10}),\n }","sub_path":"apps/proposals/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644600864","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport time\nimport sys\nimport imageio\nimport math\nfrom scipy.ndimage import gaussian_filter1d\nimport os\nfrom tracking import rgb_to_gray, con_2d, con_1d, correlation_matrix, eigen_values, reduce_eig_values, get_points\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\n\n#from Left_overs import createJacobian, createHesian, createBArray, createAffine\n\n# Creating Delta Array using Source Corners and Target Corners\n\n\ndef createDelta(srcCorners, tgtCorners):\n deltaArray = []\n\n for i in range(0, len(srcCorners)):\n x = -(tgtCorners[i][0] - srcCorners[i][0])\n y = -(tgtCorners[i][1] - srcCorners[i][1])\n deltaArray.append([[x], [y]])\n\n return deltaArray\n\n\n# Creating Source corners array\n\n\ndef srcEdges(rows, columns):\n return [[0, 0], [0, columns], [rows, 0], [rows, columns]]\n\n\n# Reverse Assigning the pixels of source to target\n\n\ndef Homography(tgtCorners, srcCorners, affArray, changeElements, image,\n srcImage, final, poly):\n\n residual = 0\n newLocation = []\n for i in range(0, len(tgtCorners)):\n\n cordMat = [[srcCorners[i][0]], [srcCorners[i][1]], [1]]\n\n h20 = changeElements[6][0]\n h21 = changeElements[7][0]\n D = h20 * srcCorners[i][0] + h21 * srcCorners[i][1] + 1\n\n tgtCod = np.floor(np.matmul(affArray, cordMat))\n\n # print(tgtLoc)\n\n x = int(tgtCod[0][0] / D)\n y = int(tgtCod[1][0] / D)\n residual += np.linalg.norm([[tgtCorners[i][0] - x],\n [tgtCorners[i][1] - y]])\n newLocation.append([x, y])\n\n if final == True:\n #print(srcCorners)\n polygon = Polygon(poly)\n for i in range(0, len(image)):\n for j in range(0, len(image[0])):\n point = Point(i, j)\n if polygon.contains(point):\n cordMat = [[i], [j], [1]]\n\n tgtLoc = np.floor(np.matmul(affArray, cordMat))\n\n h20 = changeElements[6][0]\n h21 = changeElements[7][0]\n D = h20 * i + h21 * j + 1\n\n x = int(round(tgtLoc[0][0] / D))\n y = int(round(tgtLoc[1][0] / D))\n\n if x < len(srcImage) and y < len(\n srcImage[0]) and x >= 0 and y >= 0:\n image[i][j][0] = srcImage[x][y][0]\n image[i][j][1] = srcImage[x][y][1]\n image[i][j][2] = srcImage[x][y][2]\n\n return (residual, newLocation)\n\n\n# Finding Jacobian\n\n\ndef homoJacobian(points, tgtp, changeElements):\n jacArray = []\n\n h20 = changeElements[6][0]\n h21 = changeElements[7][0]\n\n # print(points)\n\n for i in range(0, len(tgtp)):\n D = h20 * points[i][0] + h21 * points[i][1] + 1\n\n # xc = ((1+h00)*points[i][0] + h01*points[i][1] + h02)/D\n # yc = (h10*points[i][0] + (h11+1)*points[i][1] + h12)/D\n\n jacArray.append(\n int(1 / D) * np.array([[\n points[i][0],\n points[i][1],\n 1,\n 0,\n 0,\n 0,\n -(points[i][0] * tgtp[i][0]),\n -(points[i][1] * tgtp[i][0]),\n ], [\n 0,\n 0,\n 0,\n points[i][0],\n points[i][1],\n 1,\n -(points[i][0] * tgtp[i][1]),\n -(points[i][1] * tgtp[i][1]),\n ]]))\n\n # print(jacArray)\n\n return jacArray\n\n\n# Creating Hesian Matrix\n\n\ndef homoHesian(jacArray):\n hesArray = np.zeros((8, 8))\n for i in range(0, len(jacArray)):\n jacArrayTrans = np.transpose(jacArray[i])\n\n # print(jacArrayTrans)\n # print(np.dot(jacArrayTrans,jacArray[i]))\n\n hesArray = np.add(hesArray, np.dot(jacArrayTrans, jacArray[i]))\n return hesArray.astype(int)\n\n\n# Creating b Array for Parameter Matrix calculation\n\n\ndef homoBArray(jacArray, deltaArray):\n BArray = np.zeros((8, 1))\n\n for i in range(0, len(jacArray)):\n jacArrayTrans = np.transpose(jacArray[i])\n BArray = np.add(BArray, np.matmul(jacArrayTrans, deltaArray[i]))\n\n return BArray.astype(int)\n\n\n# Find the parameter matrix\n\n\ndef changeEl(hesArray, BArray, esp):\n hessianInv = np.linalg.inv(\n hesArray + np.dot(esp, np.diag(np.diag(hesArray))))\n\n # print(hessianInv.astype(float))\n\n return np.matmul(hessianInv, BArray).astype(float)\n\n\n# Creating H Array\n\n\ndef createHomoArray(changeElements):\n homoArray = []\n\n h00 = changeElements[0][0]\n h01 = changeElements[1][0]\n h02 = changeElements[2][0]\n h10 = changeElements[3][0]\n h11 = changeElements[4][0]\n h12 = changeElements[5][0]\n h20 = changeElements[6][0]\n h21 = changeElements[7][0]\n\n homoArray = [[h00 + 1, h01, h02], [h10, h11 + 1, h12], [h20, h21, 1]]\n\n return homoArray\n\n\ndef main():\n with open('data.txt', 'r') as myfile:\n parameters = myfile.readlines()\n\n filename = \"\"\n for i in list(parameters[0]):\n if i != \"\\n\":\n filename = filename + i\n\n thresholdResidual = int(parameters[1])\n\n source = \"\"\n for i in list(parameters[2]):\n if i != \"\\n\":\n source = source + i\n\n output = \"\"\n for i in list(parameters[3]):\n if i != \"\\n\":\n output = output + i\n\n esp = float(parameters[4])\n image = imageio.imread(filename)\n\n # print(len(image),len(image[0]))\n\n srcImage = imageio.imread(source)\n srcCorners = []\n srcCorners = srcEdges(len(srcImage), len(srcImage[0]))\n if filename == 'target/pepsiTruck.png':\n tgtCorners = [[58, 1046], [283, 1569], [557, 1055], [519, 1578]]\n poly = [tgtCorners[0], tgtCorners[2], tgtCorners[3], tgtCorners[1]]\n\n elif filename == 'target/hallway.png':\n tgtCorners = [[492, 0], [54, 1100], [1225, 0], [1975, 1100]]\n poly = [tgtCorners[0], tgtCorners[2], tgtCorners[3], tgtCorners[1]]\n\n elif filename == 'target/hallway_30.png':\n tgtCorners = [[150, 0], [16, 330], [370, 0], [590, 330]]\n poly = [tgtCorners[0], tgtCorners[2], tgtCorners[3], tgtCorners[1]]\n\n elif filename == 'target/stopSign.jpg':\n tgtCorners = [[38, 82], [30, 139], [70, 182], [142, 181], [195, 136],\n [194, 76], [149, 38], [87, 40]]\n poly = [[38, 82], [30, 139], [70, 182], [142, 181], [195, 136],\n [194, 76], [149, 38], [87, 40]]\n if source == 'source/cokeBig.png':\n srcCorners = [[0, 427], [0, 854], [240, 1279], [480, 1279],\n [719, 854], [719, 427], [480, 0], [240, 0]]\n elif source == 'source/coke.png':\n srcCorners = [\n [0, 100],\n [0, 200],\n [56, 299],\n [112, 299],\n [168, 200],\n [168, 100],\n [112, 0],\n [56, 0],\n ]\n elif source == 'source/nerdy.png':\n srcCorners = [[0, 200], [0, 400], [117, 599], [234, 599],\n [349, 400], [349, 200], [234, 0], [117, 0]]\n if source == 'source/poca.jpg':\n srcCorners = [[0, 427], [0, 854], [240, 1279], [480, 1279],\n [719, 854], [719, 427], [480, 0], [240, 0]]\n\n else:\n gray_scale = rgb_to_gray(image)\n\n x_gradient = gaussian_filter1d(\n gaussian_filter1d(gray_scale, sigma=1, axis=0),\n sigma=1,\n order=1,\n axis=1)\n\n y_gradient = gaussian_filter1d(\n gaussian_filter1d(gray_scale, sigma=1, axis=1),\n sigma=1,\n order=1,\n axis=0)\n\n xy_gradient = con_2d(x_gradient, y_gradient)\n\n xx_gradient = con_1d(x_gradient)\n\n yy_gradient = con_1d(y_gradient)\n\n cor_mat = correlation_matrix(xx_gradient, yy_gradient, xy_gradient,\n gray_scale)\n\n eig_val_mat = eigen_values(cor_mat)\n\n reduce_eig_values(eig_val_mat)\n\n tgtCorners = get_points(eig_val_mat, 4)\n\n poly = [tgtCorners[0], tgtCorners[2], tgtCorners[3], tgtCorners[1]]\n\n print(\"Target corners and Source corners : Created!\")\n print(tgtCorners)\n\n print(\"Creating Homography matrix\",end=\"\")\n sys.stdout.flush()\n for i in range(5):\n time.sleep(1)\n print('.', end='', flush=True)\n print(\"\")\n \n\n p = [\n [0],\n [0],\n [0],\n [0],\n [0],\n [0],\n [0],\n [0],\n ]\n\n #jacArray = createJacobian(srcCorners)\n #deltaArray = createDelta(tgtCorners, srcCorners)\n #hesArray = createHesian(jacArray)\n #BArray = createBArray(jacArray, deltaArray)\n #p,AffineArray = createAffine(hesArray, BArray)\n\n # residual, newLocation = Homography(tgtCorners, srcCorners, AffineArray)\n H = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n (residual, newLocation) = Homography(srcCorners, tgtCorners, H, p, image,\n srcImage, False, tgtCorners)\n #print(srcCorners)\n # print(H)\n print(residual, newLocation)\n while residual > thresholdResidual:\n jacArray = homoJacobian(newLocation, srcCorners, p)\n\n #print(jacArray)\n\n deltaArray = createDelta(srcCorners, newLocation)\n\n #print(deltaArray)\n\n hesArray = homoHesian(jacArray)\n\n #print(hesArray)\n\n BArray = homoBArray(jacArray, deltaArray)\n\n # print(BArray)\n\n dp = changeEl(hesArray, BArray, esp)\n\n # print(dp)\n\n p = np.add(p, dp)\n\n # print(p)\n\n H = createHomoArray(p)\n\n #print(H)\n\n (residual, newLocation) = Homography(\n srcCorners, newLocation, H, p, image, srcImage, False, tgtCorners)\n\n print(residual, newLocation)\n # print(H)\n # mapPixel(image, srcImage, H,p)\n (residual, newLocation) = Homography(srcCorners, newLocation, H, p, image,\n srcImage, True, poly)\n \n\n\n print(\"Output Generating\",end='')\n sys.stdout.flush()\n for i in range(5):\n time.sleep(1)\n print('.', end='', flush=True)\n print(\"\")\n\n\n # Output\n imageio.imwrite(output, image)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"HomographyImplementation/Homography_final.py","file_name":"Homography_final.py","file_ext":"py","file_size_in_byte":10289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340691195","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n## 讀取資料檔\nf = file(\"./ch404.dat\", \"r\")\n\n## 逐步讀取資料檔\nfor line in f:\n\n ## 將資料進行分割並將分割後的資料寫入dats變數\n dats = line.split(\"||\")\n\n ## 輸入dats序列變數裡的項目\n print(dats[0], dats[2])\n\n## 關閉檔案\nf.close()\n","sub_path":"source code/code/ch404.py","file_name":"ch404.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"639229403","text":"# -*- coding: UTF-8 -*-\n\n# ------------------------(max to 80 columns)-----------------------------------\n# author by : (学员ID)\n# created: 2019.11\n\n# Description:\n# 初步学习 WinForm 编程 ( Window )\n# ------------------------(max to 80 columns)-----------------------------------\n\nimport tkinter as tk\nfrom tkinter import ttk\nimport tkinter.messagebox\n\n# create root window\ntop_win = tk.Tk()\n\n# naming root window\ntop_win.title('Hello World Window')\n\n# resize root window\nwin_size_pos = '800x600'\n#win_size_pos = '360x60'\ntop_win.geometry(win_size_pos)\n\n# ------------------------------\n\ndef create_subwin():\n sub_win = tk.Toplevel(top_win)\n sub_win.title('Python')\n #sub_win.attributes('-alpha',0.5)\n\n msg = tk.Message(sub_win, text='I love study')\n msg.pack()\n return\n\nbtn_create = tk.Button(top_win, text='Create a sub win', command=create_subwin)\nbtn_create.pack()\n# ------------------------------\n\n\n# show window and get into event loop\ntop_win.mainloop()\n","sub_path":"try_controls_1/try8_toplevel/try_toplevel1.py","file_name":"try_toplevel1.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"79872858","text":"\n\nfrom xai.brain.wordbase.verbs._convey import _CONVEY\n\n#calss header\nclass _CONVEYS(_CONVEY, ):\n\tdef __init__(self,): \n\t\t_CONVEY.__init__(self)\n\t\tself.name = \"CONVEYS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"convey\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_conveys.py","file_name":"_conveys.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115523317","text":"\nimport bpy.types as bpy_types\nimport math\nfrom . import space_rep_manager as sp_rep\nfrom . import mesh_manager as cv\nfrom .cell_type_manager import SQUARE, TRIANGLE, HEXAGON, OCTOGON\n\nM_WELD = 'MG_WELD'\nM_WELD_2 = 'MG_WELD_2'\nM_SCREW = 'MG_SCREW'\nM_SOLID = 'MG_SOLIDIFY'\nM_BEVEL = 'MG_BEVEL'\nM_THICKNESS_SOLID = 'MG_THICK_SOLID'\nM_WEAVE_MIX = 'MG_WEAVE_MIX'\nM_THICKNESS_DISP = 'MG_THICK_DISP'\nM_THICKNESS_SHRINKWRAP = 'MG_THICK_SHRINKWRAP'\nM_DECIMATE = 'MG_DECIMATE'\nM_DECIMATE_PLANAR = 'MG_DECIMATE_PLANAR'\nM_SUBDIV = 'MG_SUBSURF'\nM_WIREFRAME = 'MG_WIREFRAME'\nM_WEAVE_DISP = 'MG_WEAVE_DISPLACE'\nM_CYLINDER = 'MG_CYLINDER'\nM_CYLINDER_WELD = 'MG_CYLINDER_WELD'\nM_MOEBIUS = 'MG_MOEBIUS'\nM_TORUS = 'MG_TORUS'\nM_STAIRS = 'MG_STAIRS'\nM_TEXTURE_DISP = 'MG_TEX_DISP'\nM_MASK = 'MG_MASK_STAIRS'\nM_MASK_SPARSE = 'MG_MASK_SPARSE'\nM_MASK_LONGEST_PATH = 'MG_MASK_PATH'\nM_VERT_WEIGHT_PROX = 'MG_WEIGHT_PROX'\nM_SMOOTH_CENTER_NAME = 'MG_SMOOTH_CENTER'\nM_SMOOTH_BRIDGE_COL_X_NAME, M_SMOOTH_BRIDGE_COL_Y_NAME = 'MG_SMOOTH_BRIDGE_COL_X', 'MG_SMOOTH_BRIDGE_COL_Y'\nM_SMOOTH_BRIDGE_ROW_X_NAME, M_SMOOTH_BRIDGE_ROW_Y_NAME = 'MG_SMOOTH_BRIDGE_ROW_X', 'MG_SMOOTH_BRIDGE_ROW_Y'\nM_MASK_BRIDGE = 'MG_MASK_BRIDGE'\n\nVISIBILIY = 'VISIBILITY'\n\n\ndef setup_modifiers_and_drivers(MV, OM, TM) -> None:\n ow = MV.props.auto_overwrite or not any(ModifierManager.drivers)\n obj_walls = OM.obj_walls\n obj_cells = OM.obj_cells\n obj_cylinder = OM.obj_cylinder\n obj_torus = OM.obj_torus\n obj_thickness_shrinkwrap = OM.obj_thickness_shrinkwrap\n tex_disp = TM.tex_disp\n scene = MV.scene\n mod_dic = {\n obj_walls: (\n ('MASK', M_MASK_LONGEST_PATH, {\n VISIBILIY: (obj_cells, obj_walls, 'show_viewport', M_MASK_LONGEST_PATH, M_MASK_LONGEST_PATH, 'var'),\n 'vertex_group': cv.VG_LONGEST_PATH,\n 'invert_vertex_group': True,\n }),\n ('MASK', M_MASK_SPARSE, {\n 'vertex_group': cv.VG_STAIRS,\n 'threshold': 0\n }),\n ('MASK', M_MASK, {\n VISIBILIY: (obj_walls, obj_walls, 'threshold', M_MASK, M_MASK, 'var < 1'),\n 'vertex_group': cv.VG_STAIRS,\n 'invert_vertex_group': True,\n 'threshold': (obj_cells, obj_walls, 'threshold', M_MASK, M_MASK, 'var'),\n }),\n ('DISPLACE', M_STAIRS, {\n VISIBILIY: (obj_cells, obj_walls, 'strength', M_STAIRS, M_STAIRS, 'var != 0'),\n 'strength': (obj_cells, obj_walls, 'strength', M_STAIRS, M_STAIRS, 'var'),\n 'direction': 'Z',\n 'vertex_group': cv.VG_STAIRS,\n 'mid_level': 0,\n }),\n ('WELD', M_WELD, {\n }),\n ('SCREW', M_SCREW, {\n 'angle': 0,\n 'steps': 1,\n 'render_steps': 1,\n 'screw_offset': 0.3,\n 'use_smooth_shade': ('wall_bevel', 'var > 0.005'),\n }),\n ('VERTEX_WEIGHT_PROXIMITY', M_VERT_WEIGHT_PROX, {\n 'vertex_group': cv.VG_THICKNESS,\n 'target': obj_cells,\n 'proximity_mode': 'GEOMETRY',\n 'proximity_geometry': {'VERTEX'},\n 'falloff_type': 'STEP',\n 'min_dist': 0.001,\n 'max_dist': 0,\n }),\n ('SOLIDIFY', M_SOLID, {\n VISIBILIY: (obj_walls, obj_walls, 'thickness', M_SOLID, M_SOLID, 'var != 0'),\n 'solidify_mode': 'NON_MANIFOLD',\n 'thickness': 0.1,\n 'offset': 0,\n }),\n ('DISPLACE', M_THICKNESS_DISP, {\n VISIBILIY: ('maze_basement', 'not var'),\n 'direction': 'Z',\n 'vertex_group': cv.VG_THICKNESS,\n 'mid_level': 0,\n 'strength': (obj_cells, obj_walls, 'strength', M_THICKNESS_DISP, M_THICKNESS_DISP, 'var'),\n }),\n ('SHRINKWRAP', M_THICKNESS_SHRINKWRAP, {\n VISIBILIY: (obj_cells, obj_walls, 'show_viewport', M_THICKNESS_SHRINKWRAP, M_THICKNESS_SHRINKWRAP, 'var'),\n 'vertex_group': cv.VG_THICKNESS,\n 'wrap_method': 'PROJECT',\n 'use_project_x': False,\n 'use_project_y': False,\n 'use_project_z': True,\n 'use_negative_direction': True,\n 'use_positive_direction': True,\n 'target': obj_thickness_shrinkwrap\n }),\n ('BEVEL', M_BEVEL, {\n VISIBILIY: (obj_walls, obj_walls, 'width', M_BEVEL, M_BEVEL, 'var > 0'),\n 'segments': 4,\n 'limit_method': 'ANGLE',\n 'use_clamp_overlap': True,\n 'width': 0,\n 'harden_normals': ('cell_use_smooth', 'var'),\n }),\n ('DISPLACE', M_WEAVE_DISP, {\n VISIBILIY: ('maze_space_dimension', 'int(var) == ' + sp_rep.REP_CYLINDER + ' or int(var) == ' + sp_rep.REP_MEOBIUS),\n 'strength': ('wall_height', '-var'),\n 'direction': 'Z',\n 'mid_level': 0.5,\n }),\n ('SIMPLE_DEFORM', M_MOEBIUS, {\n VISIBILIY: ('maze_space_dimension', 'int(var) == ' + sp_rep.REP_MEOBIUS),\n 'angle': 2 * math.pi + (1 / 16 if MV.props.cell_type == TRIANGLE else 0),\n }),\n ('CURVE', M_CYLINDER, {\n VISIBILIY: ('maze_space_dimension', f'int(var) in ({sp_rep.REP_CYLINDER}, {sp_rep.REP_MEOBIUS}, {sp_rep.REP_TORUS})'),\n 'object': obj_cylinder,\n }),\n ('CURVE', M_TORUS, {\n VISIBILIY: ('maze_space_dimension', 'int(var) == ' + sp_rep.REP_TORUS),\n 'object': obj_torus,\n 'deform_axis': 'POS_Y',\n }),\n ('DISPLACE', M_TEXTURE_DISP, {\n VISIBILIY: (obj_cells, obj_walls, 'strength', M_TEXTURE_DISP, M_TEXTURE_DISP, 'var != 0'),\n 'strength': (obj_cells, obj_walls, 'strength', M_TEXTURE_DISP, M_TEXTURE_DISP, 'var'),\n 'texture': tex_disp,\n 'direction': 'Z',\n }),\n ),\n obj_cells: (\n ('MASK', M_MASK_LONGEST_PATH, {\n 'show_viewport': False,\n 'show_render': (obj_cells, obj_cells, 'show_viewport', M_MASK_LONGEST_PATH, M_MASK_LONGEST_PATH, 'var'),\n 'vertex_group': cv.VG_LONGEST_PATH,\n 'invert_vertex_group': True,\n }),\n ('MASK', M_MASK_SPARSE, {\n 'vertex_group': cv.VG_STAIRS,\n }), \n ('MASK', M_MASK, {\n VISIBILIY: (obj_cells, obj_cells, 'threshold', M_MASK, M_MASK, 'var < 1'),\n 'vertex_group': cv.VG_STAIRS,\n 'invert_vertex_group': True,\n 'threshold': 1,\n }),\n ('DISPLACE', M_STAIRS, {\n VISIBILIY: (obj_cells, obj_cells, 'strength', M_STAIRS, M_STAIRS, 'var != 0'),\n 'direction': 'Z',\n 'vertex_group': cv.VG_STAIRS,\n 'mid_level': 0, 'strength': 0,\n }),\n # ('WELD', M_WELD_2, {\n # VISIBILIY: ('maze_weave', 'var != 0'),\n # 'vertex_group': cv.VG_DISPLACE,\n # 'invert_vertex_group': False,\n # }),\n ('SOLIDIFY', M_THICKNESS_SOLID, {\n VISIBILIY:\n (\n obj_cells,\n M_THICKNESS_SOLID,\n (\n ('sw_visibility', 'OBJECT', obj_cells, 'modifiers[\"' + M_THICKNESS_DISP + '\"].show_viewport'),\n ('disp_visibility', 'OBJECT', obj_cells, 'modifiers[\"' + M_THICKNESS_SHRINKWRAP + '\"].show_viewport'),\n ),\n 'sw_visibility or disp_visibility',\n ),\n # VISIBILIY: (obj_cells, obj_cells, 'thickness', M_THICKNESS_SOLID, M_THICKNESS_SOLID, 'var != 0'),\n 'thickness': .000000001,\n 'shell_vertex_group': cv.VG_THICKNESS\n }),\n # ('VERTEX_WEIGHT_MIX', M_WEAVE_MIX, {\n # VISIBILIY: ('maze_weave', \"var\"),\n # 'vertex_group_a': cv.VG_THICKNESS,\n # 'vertex_group_b': cv.VG_DISPLACE,\n # 'mix_mode': 'ADD',\n # 'mix_set': 'B',\n # 'mask_constant': 0.97,\n # }),\n ('DISPLACE', M_THICKNESS_DISP, {\n VISIBILIY: ('maze_basement', 'not var'),\n 'direction': 'Z',\n 'vertex_group': cv.VG_THICKNESS,\n 'mid_level': 0,\n 'strength': 0,\n }),\n ('SHRINKWRAP', M_THICKNESS_SHRINKWRAP, {\n VISIBILIY:\n (\n obj_cells,\n M_THICKNESS_SHRINKWRAP,\n (\n ('maze_basement', 'SCENE', scene, 'mg_props.maze_basement'),\n ('stairs', 'OBJECT', obj_cells, 'modifiers[\"' + M_STAIRS + '\"].strength'),\n ),\n 'maze_basement and stairs != 0',\n ),\n # VISIBILIY: ('maze_basement', 'var'),\n 'vertex_group': cv.VG_THICKNESS,\n 'wrap_method': 'PROJECT',\n 'use_project_x': False,\n 'use_project_y': False,\n 'use_project_z': True,\n 'use_negative_direction': True,\n 'use_positive_direction': True,\n 'target': obj_thickness_shrinkwrap\n }),\n # ('DISPLACE', M_WEAVE_DISP, {\n # VISIBILIY: ('maze_weave', \"var\"),\n # 'direction': 'Z',\n # 'vertex_group': cv.VG_DISPLACE,\n # 'mid_level': 0,\n # 'strength': 0.2\n # }),\n ('SIMPLE_DEFORM', M_MOEBIUS, {\n VISIBILIY: ('maze_space_dimension', \"int(var) == \" + sp_rep.REP_MEOBIUS),\n 'angle': 2 * math.pi + (1 / 18 if MV.props.cell_type == TRIANGLE else 0),\n }),\n ('CURVE', M_CYLINDER, {\n VISIBILIY: ('maze_space_dimension', f'int(var) in ({sp_rep.REP_CYLINDER}, {sp_rep.REP_MEOBIUS}, {sp_rep.REP_TORUS})'),\n 'object': obj_cylinder,\n }),\n ('CURVE', M_TORUS, {\n VISIBILIY: ('maze_space_dimension', \"int(var) == \" + sp_rep.REP_TORUS),\n 'object': obj_torus,\n 'deform_axis': 'POS_Y',\n }),\n ('DISPLACE', M_TEXTURE_DISP, {\n VISIBILIY: (obj_cells, obj_cells, 'strength', M_TEXTURE_DISP, M_TEXTURE_DISP, 'var != 0'),\n 'texture': tex_disp,\n 'direction': 'Z',\n 'strength': 0,\n }),\n ('DECIMATE', M_DECIMATE, {\n VISIBILIY:\n (\n obj_cells,\n M_DECIMATE,\n (\n ('cell_deci', 'SCENE', scene, 'mg_props.cell_decimate'),\n ('cell_inset', 'SCENE', scene, 'mg_props.cell_inset'),\n ('stairs', 'OBJECT', obj_cells, 'modifiers[\"' + M_STAIRS + '\"].strength'),\n ),\n 'cell_deci > 0 and (cell_inset > 0 or stairs != 0)',\n ),\n 'ratio': ('cell_decimate', '1 - var / 100'),\n }),\n ('SUBSURF', M_SUBDIV, {\n VISIBILIY: (obj_cells, obj_cells, 'levels', M_SUBDIV, M_SUBDIV, 'var > 0'),\n 'render_levels': (obj_cells, obj_cells, 'levels', M_SUBDIV, M_SUBDIV, 'var'),\n 'levels': 0,\n }),\n ('BEVEL', M_BEVEL, {\n VISIBILIY:\n (\n obj_cells,\n M_BEVEL,\n (\n ('cell_bevel', 'OBJECT', obj_cells, 'modifiers[\"' + M_BEVEL + '\"].width'),\n ('cell_inset', 'SCENE', scene, 'mg_props.cell_inset'),\n ),\n 'cell_bevel != 0 and cell_inset > 0.1',\n ),\n 'segments': ('cell_contour_black', '2 if var else 4'),\n 'limit_method': 'ANGLE',\n 'material': ('cell_contour_black', '1 if var else 0'),\n 'profile': ('cell_contour_black', '1 if var else 0.5'),\n 'angle_limit': 0.75,\n 'width': 0,\n 'miter_inner': ('cell_contour_black', '2 if var else 0'),\n 'miter_outer': ('cell_contour_black', '2 if var else 0'),\n }),\n ('WIREFRAME', M_WIREFRAME, {\n VISIBILIY:\n (\n obj_cells,\n M_WIREFRAME,\n (\n ('cell_wireframe', 'OBJECT', obj_cells, 'modifiers[\"' + M_WIREFRAME + '\"].thickness'),\n ('cell_inset', 'SCENE', scene, 'mg_props.cell_inset'),\n ),\n 'cell_wireframe != 0 and cell_inset > 0.1',\n ),\n 'use_replace': False,\n 'material_offset': ('cell_contour_black', None),\n 'thickness': 0,\n }),\n )\n }\n\n for obj, mod_params in mod_dic.items():\n for params in mod_params:\n params[2]['show_expanded'] = False\n add_modifier(obj=obj, mod_type=params[0], mod_name=params[1], properties=params[2], overwrite_props=ow, scene=scene)\n\n if ow:\n add_driver_to_vars(\n obj_thickness_shrinkwrap,\n ('location', 2),\n (\n ('stairs', 'OBJECT', obj_cells, 'modifiers[\"' + M_STAIRS + '\"].strength'),\n ('thickness', 'OBJECT', obj_cells, 'modifiers[\"' + M_THICKNESS_DISP + '\"].strength'),\n ),\n expression='thickness if stairs > 0 else stairs + thickness',\n )\n\n # Scale the cylinder and torus objects when scaling the size of the maze\n for i, obj in enumerate((obj_cylinder, obj_torus)):\n drvList = obj.driver_add('scale')\n for fc in drvList:\n drv = fc.driver\n try:\n var = drv.variables[0]\n except IndexError:\n var = drv.variables.new()\n\n var.name = 'var'\n var.type = 'SINGLE_PROP'\n\n target = var.targets[0]\n target.id_type = 'SCENE'\n target.id = scene\n target.data_path = 'mg_props.maze_columns' if i == 0 else 'mg_props.maze_rows_or_radius'\n\n exp = 'var * 0.314'\n if MV.props.cell_type == SQUARE or MV.props.cell_type == OCTOGON:\n exp = 'var * 0.15915'\n elif MV.props.cell_type == TRIANGLE:\n if i == 0:\n exp = 'var * 0.07963'\n else:\n exp = 'var * 0.13791'\n elif MV.props.cell_type == HEXAGON:\n if i == 0:\n exp = 'var * 0.2388'\n else:\n exp = 'var * 0.2758'\n\n drv.expression = exp\n\n\ndef add_modifier(\n obj: bpy_types.Object, mod_type: str, mod_name: str,\n remove_if_already_exists: bool = False, remove_all_modifiers: bool = False,\n properties=None, overwrite_props: bool = True, scene: bpy_types.Scene = None) -> None:\n mod_name = mod_name if mod_name != \"\" else \"Fallback\"\n\n if obj is not None:\n mod = None\n if remove_all_modifiers:\n obj.modifiers.clear()\n\n if mod_name in obj.modifiers:\n if remove_if_already_exists:\n obj.modifiers.remove(obj.modifiers.get(mod_name))\n add_modifier(obj, mod_type, mod_name, remove_if_already_exists, remove_all_modifiers, properties)\n else:\n mod = obj.modifiers[mod_name]\n else:\n mod = obj.modifiers.new(mod_name, mod_type)\n if mod and type(properties) is dict and overwrite_props:\n for prop, value in properties.items():\n if type(value) is tuple:\n if type(value[0]) is not str:\n if type(value[2]) is tuple:\n if prop == VISIBILIY:\n add_driver_to_vars(value[0].modifiers[value[1]], 'show_render', value[2], value[3])\n add_driver_to_vars(value[0].modifiers[value[1]], 'show_viewport', value[2], value[3])\n else:\n add_driver_to_vars(value[0].modifiers[value[1]], prop, value[2], value[3])\n else:\n if prop == VISIBILIY:\n add_driver_to(value[1].modifiers[value[4]], 'show_render', 'var', 'OBJECT', value[0], 'modifiers[\"' + value[3] + '\"].' + value[2], value[5])\n add_driver_to(value[1].modifiers[value[4]], 'show_viewport', 'var', 'OBJECT', value[0], 'modifiers[\"' + value[3] + '\"].' + value[2], value[5])\n else:\n add_driver_to(value[1].modifiers[value[4]], prop, 'var', 'OBJECT', value[0], 'modifiers[\"' + value[3] + '\"].' + value[2], value[5])\n else:\n if prop == VISIBILIY:\n add_driver_to(obj.modifiers[mod_name], 'show_render', 'var', 'SCENE', scene, 'mg_props.' + value[0], expression=value[1])\n add_driver_to(obj.modifiers[mod_name], 'show_viewport', 'var', 'SCENE', scene, 'mg_props.' + value[0], expression=value[1])\n else:\n add_driver_to(obj.modifiers[mod_name], prop, 'var', 'SCENE', scene, 'mg_props.' + value[0], expression=value[1])\n elif hasattr(mod, prop):\n setattr(mod, prop, value)\n\n\ndef add_driver_to(obj: bpy_types.Object, prop_to, var_name: str, id_type: str, _id, prop_from, expression: str = None) -> None:\n add_driver_to_vars(obj, prop_to, ((var_name, id_type, _id, prop_from),), expression)\n\n\ndef add_driver_to_vars(obj: bpy_types.Object, prop_to, variables, expression: str = None) -> None:\n \"\"\"\n Add a driver to obj's prop_to property\n\n Each var must be under the form : (var_name, id_type, _id, prop_from)\"\"\"\n if obj:\n if type(prop_to) is tuple:\n driver = obj.driver_add(prop_to[0], prop_to[1]).driver\n else:\n driver = obj.driver_add(prop_to).driver\n ModifierManager.drivers.append((obj, prop_to))\n for i, var_prop in enumerate(variables):\n try:\n var = driver.variables[i]\n except IndexError:\n var = driver.variables.new()\n var.name = var_prop[0]\n var.type = 'SINGLE_PROP'\n\n target = var.targets[0]\n target.id_type = var_prop[1]\n target.id = var_prop[2]\n target.data_path = str(var_prop[3])\n\n if expression:\n driver.expression = expression\n else:\n driver.expression = variables[0][0]\n\n\nclass ModifierManager:\n drivers = []\n\n def delete_all_drivers():\n for driver_settings in ModifierManager.drivers:\n try:\n driver_settings[0].driver_remove(driver_settings[1])\n except TypeError:\n pass\n ModifierManager.drivers = []\n","sub_path":"Maze Generator/managers/modifier_manager.py","file_name":"modifier_manager.py","file_ext":"py","file_size_in_byte":19542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"71508903","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport copy\n\n# sys imports\n\n# python imports\nimport re\nimport logging\nimport configparser\n\n\n# numpy imports\nimport numpy as np\nimport numpy.ma as ma\n\n# astropy imports\nfrom astropy.io import fits\nfrom astropy.stats import sigma_clip\nfrom astropy.visualization import ZScaleInterval\n\n# scipy imports\nimport scipy as sp\nfrom scipy.signal import savgol_filter\nfrom scipy.signal import find_peaks_cwt\n# Problems when the boundary order has some intense line, like order 65 and Hα.\nfrom scipy.signal import butter, filtfilt\nfrom statsmodels.api import nonparametric\n\n# pandas imports\nimport pandas as pd\n\n# matplotlib imports\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.colorbar as cb\n\n# Using the logger created in the main script\n\nlogger = logging.getLogger('HRSP')\n\n\ndef getshape(orderinf, ordersup):\n \"\"\"\n In order to derive the shape of a given order, we use one order after and one order before\n We suppose that the variations are continuous.\n Thus approximating order n using orders n+1 and n-1 is close enough from reality\n \"\"\"\n # Now we find the shape, it needs several steps and various fitting/smoothing\n b, a = butter(10, 0.025)\n # the shape of the orders does not vary much between orders, but there can be cosmic rays or emission lines\n # Since it's unlikely that the same pixel is affected on two non contiguous orders, we pick the minimum of the\n # two orders, and we create an artificial order between them and it's the one that we'll fit.\n shape = np.minimum(orderinf, ordersup)\n ysh2 = filtfilt(b, a, shape)\n x = np.arange(ysh2.shape[0])\n ysh3 = np.poly1d(np.polyfit(x, ysh2, 11))(x)\n ysh4 = np.minimum(ysh2, ysh3)\n ysh5 = np.poly1d(np.polyfit(x, ysh4, 11))(x)\n # ysh5 fits now the shape of the ThAr order quite well, and we can start from there to identify the lines.\n return ysh5\n\n\nclass FITS(object):\n\n def __add__(self, other):\n \"\"\"\n Defining what it is to add two HRS objects\n \"\"\"\n new = copy.copy(self)\n dt = new.data.dtype\n\n if isinstance(other, HRS):\n new.data = np.asarray(self.data + other.data, dtype=np.float64)\n elif isinstance(other, np.int):\n new.data = np.asarray(self.data + other, dtype=np.float64)\n elif isinstance(other, np.float):\n new.data = np.asarray(self.data + other, dtype=np.float64)\n else:\n logger.error('Trying to add two incompatible types: %s and %s', type(self), type(other))\n return NotImplemented\n new.data[new.data <= 0] = 0\n (new.dataminzs, new.datamaxzs) = ZScaleInterval().get_limits(new.data)\n logger.info('Updating the ZScale range of %s after addition to %s and %s',\n self.file.name,\n new.dataminzs,\n new.datamaxzs)\n new.data = np.asarray(new.data, dtype=dt)\n return new\n\n def __sub__(self, other):\n \"\"\"\n Defining what substracting two HRS object is.\n\n \"\"\"\n new = copy.copy(self)\n dt = new.data.dtype\n\n if not isinstance(other, HRS):\n if isinstance(other, (np.int, np.float)):\n new.data = np.asarray(self.data, dtype=np.float64) - other\n logger.info('Not an HRS object')\n else:\n logger.error('Trying to substract two incompatible types : %s and %s',\n type(self),\n type(other))\n return NotImplemented\n else:\n new.data = np.asarray(self.data, dtype=np.float64) - np.asarray(other.data, dtype=np.float64)\n# updating the datamin and datamax attributes after the substraction.\n new.data[new.data <= 0] = 0\n (new.dataminzs, new.datamaxzs) = ZScaleInterval().get_limits(new.data)\n logger.info('Updating the ZScale range after substraction to %s and %s',\n new.dataminzs,\n new.datamaxzs)\n new.data = np.asarray(new.data, dtype=dt)\n\n return new\n\n def __truediv__(self, other):\n \"\"\"\n Define what it is to divide a HRS object\n \"\"\"\n new = copy.copy(self)\n\n if not isinstance(other, HRS):\n if isinstance(other, np.int) or isinstance(other, np.float):\n new.data = self.data / other\n else:\n return NotImplemented\n else:\n new.data = self.data / other.data\n# updating the datamin and datamax attributes after the substraction.\n (new.dataminzs, new.datamaxzs) = ZScaleInterval().get_limits(new.data)\n\n return new\n\n\nclass Order(object):\n \"\"\"\n Creates an object that defines the position of the orders.\n \"\"\"\n def __init__(self,\n hrs='',\n sigma=3.0):\n self.hrs = hrs\n self.step = 50\n self.sigma = sigma\n self.spversion = sp.__version__\n self.got_flat = self.check_type(self.hrs)\n self.orderguess = self.find_peaks(self.hrs)\n self.order = self.identify_orders(self.orderguess)\n self.extracted, self.order_fit = self.find_orders(self.order)\n\n def __repr__(self):\n description = \"Location of the orders for file {file}\".format(\n file=self.hrs.file.name)\n logger.info('%s', description)\n return description\n\n def check_type(self, frame):\n if 'Flat field' not in frame.name:\n logger.error('The frame %s is not a flat-field', frame.file.name)\n return False\n return True\n\n def save(self):\n \"\"\" Save the Order object in a csv file\n \"\"\"\n\n def find_peaks(self, frame):\n \"\"\"\n Identifies in a Flat-Field frame where the orders are located\n The procedure is as follows:\n 1 -\n \"\"\"\n splitscipyversion = self.spversion.split('.')\n# To avoid weird detection, we set any value below zero to zero.\n data = frame.data.copy()\n if not self.got_flat:\n logger.info(\"The file chosen is not a flat, it's not possible to determine the position of the orders.\")\n return None\n else:\n logger.info('Starting the order identification process.')\n pixelstart = self.step\n pixelstop = frame.data.shape[1]\n # step = 20\n xb = np.arange(pixelstart, pixelstop, self.step)\n temp = []\n if 'LOW' in frame.mode:\n window = 31\n polyorder = 5\n f = 15\n else:\n window = 37\n polyorder = 3\n f = 1\n logger.info('Savitzky-Golay filter parameters: Window width: %s, polynomial order: %s, histogram adhoc parmeter: %s', window, polyorder, f) # noqa\n for pixel in xb:\n test = data[:, pixel]\n b, c = np.histogram(np.abs(test))\n mask = test < c[1] / f\n t = ma.array(test, mask=mask)\n if pixel > frame.xpix:\n break\n filtereddata = savgol_filter(t, window, polyorder)\n xp = find_peaks_cwt(filtereddata, widths=np.arange(1, 20))\n# TODO : Older version of scipy output a list and not a numpy array. Test it. Change occurred in version 0.19\n if splitscipyversion[0] == '0' and np.int(splitscipyversion[1]) < 19:\n xp = np.array(xp)\n# We now extract the valid entries from the peaks_cwt()\n x = xp[~t[xp].mask].copy()\n temp.append(x)\n # Storing the location of the peaks in a numpy array\n size = max([len(i) for i in temp])\n peaks = np.ones((size, len(temp)), dtype=np.int)\n for index in range(len(temp)):\n temp[index].resize(size, refcheck=False)\n peaks[:, index] = temp[index]\n\n return peaks\n\n def identify_orders(self, pts):\n \"\"\"\n This function extracts the real location of the orders\n The input parameter is a numpy array containing the probable location of the orders.\n It has been filtered to remove the false detection of the algorithm.\n\n \"\"\"\n o = np.zeros_like(pts)\n # Detection of the first order shifts.\n p = np.where((pts[2, 1:] - pts[2, :-1]) > 10)[0]\n logger.info('Orders jumps at pixels %s', 50 * p)\n# The indices will allow us to know when to switch row in order to follow the orders.\n# The first one has to be zero and the last one the size of the orders.\n# This is so that the automatic procedure picks them properly\n indices = [0] + list(p + 1) + [pts.shape[1]]\n for i in range(pts.shape[0]):\n # The orders come in three section, so we coalesce them\n logger.info('Locating position of order %i', i)\n ind = np.arange(i, i - (len(p) + 1), -1) + 1\n ind[np.where(ind <= 0)] = 0\n a = ind > 0\n a = a * 1\n for j in range(len(a)):\n arr1 = pts[i - j, indices[j]:indices[j + 1]] * a[j]\n o[i, indices[j]:indices[j + 1]] = arr1\n return o\n\n def _gaussian_fit(self, a, k):\n from astropy.modeling import fitting, models\n fitter = fitting.SLSQPLSQFitter()\n gaus = models.Gaussian1D(amplitude=1., mean=a, stddev=5.)\n y1 = a - 25\n y2 = a + 25\n y = np.arange(y1, y2)\n try:\n gfit = fitter(gaus,\n y,\n self.hrs.data[y, self.step * (k + 1)] / self.hrs.data[y, self.step * (k + 1)].max(),\n verblevel=0)\n except IndexError:\n logger.error('Index %s outside range', a)\n return\n return gfit\n\n def _add_gaussian(self, a):\n \"\"\" Computes the size of the orders by adding/substracting 2.7 times the standard dev of the gaussian\n fit to the mean of the same fit.\n Returns the lower limit, the center and the upper limit.\n \"\"\"\n try:\n return(a.mean.value - self.sigma * a.stddev.value, a.mean.value, a.mean.value + self.sigma * a.stddev.value)\n except AttributeError:\n logger.error(\"Can't compute mean and std. Returning NaN instead\")\n return(np.nan, np.nan, np.nan)\n\n def find_orders(self, op):\n \"\"\" Computes the location of the orders\n Returns a 3D numpy array\n \"\"\"\n vgf = np.vectorize(self._gaussian_fit)\n vadd = np.vectorize(self._add_gaussian)\n fit = np.zeros_like(op, dtype=object)\n positions = np.zeros((op.shape[0], op.shape[1], 3))\n for i in range(op.shape[1]):\n logger.info('Computing the extend of order number %i', i + 1)\n tt = vgf(op[:, i], i)\n fit[:, i] = tt\n positions[:, :, 0], positions[:, :, 1], positions[:, :, 2] = vadd(fit)\n return positions, fit\n\n\nclass HRS(FITS):\n \"\"\"\n Class that allows to set the parameters of each files\n the data attribute is such that all frames have the same orientation\n \"\"\"\n def __init__(self,\n hrsfile=''):\n HRSConfig = configparser.ConfigParser()\n HRSConfig.read('./pipeline/HRS.ini')\n self.file = hrsfile\n self.hdulist = fits.open(self.file)\n self.header = self.hdulist[0].header\n self.dataX1 = int(self.header['DATASEC'][1:8].split(':')[0])\n self.dataX2 = int(self.header['DATASEC'][1:8].split(':')[1])\n self.dataY1 = int(self.header['DATASEC'][9:15].split(':')[0])\n self.dataY2 = int(self.header['DATASEC'][9:15].split(':')[1])\n self.mode = self.header['OBSMODE']\n self.type = self.header['OBSTYPE']\n self.name = self.header['OBJECT']\n self.chip = self.header['DETNAM']\n self.data = self.prepare_data()\n self.shape = self.data.shape\n (self.dataminzs, self.datamaxzs) = ZScaleInterval().get_limits(self.data)\n # parameters = {'HBDET': {'OrderShift': 83,\n # 'XPix': 2048,\n # 'BiasLevel': 690},\n # 'HRDET': {'OrderShift': 52,\n # 'XPix': 4096,\n # 'BiasLevel': 920}}\n self.biaslevel = HRSConfig[self.chip]['XPix']\n # self.biaslevel = parameters[self.chip]['BiasLevel']\n self.ordershift = np.int(HRSConfig[self.chip]['OrderShift'])\n # self.ordershift = parameters[self.chip]['OrderShift']\n self.xpix = np.int(HRSConfig[self.chip]['XPix'])\n # self.xpix = parameters[self.chip]['XPix']\n # print('xpix: {xpix}'.format(xpix=self.xpix))\n self.mean = self.data.mean()\n self.std = self.data.std()\n self.counter = 0\n self._zoom1 = 100\n\n def __repr__(self):\n color = 'blue'\n if 'HR' in self.chip:\n color = 'red'\n description = 'HRS {color} Frame\\nSize : {x}x{y}\\nObject : {target}\\nMode: {mode}'.format(\n target=self.name,\n color=color,\n x=self.data.shape[0],\n y=self.data.shape[1],\n mode=self.mode)\n return description\n\n def prepare_data(self):\n \"\"\"\n This method sets the orientation of both the red and the blue files to be the same, which is red is up and right\n \"\"\"\n d = self.hdulist[0].data\n logger.info('Preparing the format of the data, so the orientation of the blue and the red is identical: Red is up and right') # noqa\n if self.chip == 'HRDET':\n d = d[:, self.dataX1 - 1:self.dataX2]\n else:\n d = d[::-1, self.dataX1 - 1:self.dataX2]\n#\n return d\n\n def _zoom(self, event):\n self.counter += 1\n if self.counter % 4: # Limiting the frequency of the update to every 4 moves.\n return\n if event.inaxes is self.ax1:\n # Mouse is in subplot 1.\n xinf2 = np.int(event.xdata - self._zoom1)\n xsup2 = np.int(event.xdata + self._zoom1)\n yinf2 = np.int(event.ydata - self._zoom1)\n ysup2 = np.int(event.ydata + self._zoom1)\n ax2data = self.data[yinf2:ysup2, xinf2:xsup2]\n self.plot2.set_data(ax2data)\n self.ax2.figure.canvas.draw()\n self.fig.canvas.blit(self.ax2.bbox)\n self.counter = 0\n\n def _plot(self, event):\n if event.inaxes is self.ax1:\n ax3ydata = self.data[:, np.int(event.xdata)]\n ax3xdata = self.data[np.int(event.ydata), :]\n if event.button == 1: # Left button\n self.ax3.cla()\n self.ax3.yaxis.tick_left()\n self.ax3.set_xlabel('Pixel', color=self.ax3.color)\n self.ax3.set_ylabel('Intensity', color=self.ax3.color)\n self.ax3.xaxis.set_label_position('bottom')\n self.ax3.yaxis.set_label_position('left')\n self.ax3.tick_params(axis='y', colors=self.ax3.color)\n self.ax3.plot(ax3ydata, color=self.ax3.color)\n self.ax3.figure.canvas.draw()\n elif event.button == 3: # Right button\n self.ax4.cla()\n self.ax4.xaxis.tick_top()\n self.ax4.yaxis.tick_right()\n self.ax4.set_xlabel('Pixel', color=self.ax4.color)\n self.ax4.set_ylabel('Intensity', color=self.ax4.color)\n self.ax4.xaxis.set_label_position('top')\n self.ax4.yaxis.set_label_position('right')\n self.ax4.tick_params(axis='y', colors=self.ax4.color)\n self.ax4.plot(ax3xdata, color=self.ax4.color)\n self.ax4.figure.canvas.draw()\n\n def plot(self, fig=None):\n \"\"\"\n Creates a matplotlib window to display the frame\n Adds a small window which is a zoom on where the cursor is\n \"\"\"\n # Peut-être faire une classe Plot() qui se chargera de tout, et faire que plot() appelle Plot().\n # https://matplotlib.org/examples/animation/subplots.html\n # Defining the grid on which the plot will be shown\n grid = gridspec.GridSpec(6, 2)\n if fig is None:\n fig = plt.figure(num=\"HRS Frame visualisation\",\n figsize=(9.6, 6.4), clear=True)\n self.fig = fig\n self.ax1 = fig.add_subplot(grid[:-1, 0])\n self.ax2 = fig.add_subplot(grid[0:3, 1])\n self.ax3 = fig.add_subplot(grid[3:, 1], label='x')\n self.ax4 = fig.add_subplot(grid[3:, 1], label='y', frameon=False)\n cbax1 = fig.add_subplot(grid[-1, 0])\n fig.subplots_adjust(wspace=0.3, hspace=2.2)\n\n # Convenience names\n ax1 = self.ax1\n ax2 = self.ax2\n ax3 = self.ax3\n ax3.color = 'xkcd:cerulean'\n ax4 = self.ax4\n ax4.color = 'xkcd:tangerine'\n data = self.data\n zoom = self._zoom1\n\n # Adding the plots\n self.plot1 = ax1.imshow(data, vmin=self.dataminzs, vmax=self.datamaxzs)\n ax1.title.set_text('CCD')\n cb.Colorbar(ax=cbax1, mappable=self.plot1, orientation='horizontal', ticklocation='bottom')\n zoomeddata = self.data[\n np.int(self.data.shape[0] // 2) - zoom:np.int(self.data.shape[0] // 2) + zoom,\n np.int(self.data.shape[1] // 2) - zoom:np.int(self.data.shape[1] // 2) + zoom]\n self.plot2 = ax2.imshow(zoomeddata, vmin=self.dataminzs, vmax=self.datamaxzs)\n # We need to tidy the bottom right plot a little bit first\n # Ax3 first\n self.ax3.tick_params(axis='x', colors=ax3.color)\n self.ax3.tick_params(axis='y', colors=ax3.color)\n self.ax3.xaxis.tick_bottom()\n self.ax3.yaxis.tick_left()\n self.ax3.set_xlabel('Pixel', color=ax3.color)\n self.ax3.set_ylabel('Intensity', color=ax3.color)\n self.ax3.xaxis.set_label_position('bottom')\n self.ax3.yaxis.set_label_position('left')\n # Ax4\n self.ax4.tick_params(axis='x', colors=ax4.color)\n self.ax4.tick_params(axis='y', colors=ax4.color)\n self.ax4.xaxis.tick_top()\n self.ax4.yaxis.tick_right()\n self.ax4.set_xlabel('Pixel', color=ax4.color)\n self.ax4.set_ylabel('Intensity', color=ax4.color)\n self.ax4.xaxis.set_label_position('top')\n self.ax4.yaxis.set_label_position('right')\n\n self.ax3.plot(self.data[:, np.int(self.data.shape[1] / 2)], color=ax3.color)\n self.ax4.plot(self.data[np.int(self.data.shape[0] / 2), :], color=ax4.color)\n ax1.figure.canvas.mpl_connect('motion_notify_event', self._zoom)\n ax1.figure.canvas.mpl_connect('button_press_event', self._plot)\n plt.show()\n\n\nclass Master(object):\n \"\"\"\n\n\n Parameters:\n -----------\n masterflat = median( (flat_i - masterbias)/exptime_i ) - masterdark/exptime\\n\"\n\" - background.\\n\"\n\n flat : orders\n \"\"\"\n\n def makemasterbias(self, lof):\n blue = []\n red = []\n for b in lof.bias:\n if b.name.startswith('H'):\n blue.append(HRS(b).data)\n blueheader = HRS(b).header\n elif b.name.startswith('R'):\n red.append(HRS(b).data)\n redheader = HRS(b).header\n else:\n continue\n bshape = list(blue[0].shape)\n bshape[:0] = [len(blue)]\n ba = np.concatenate(blue).reshape(bshape)\n mbdata = np.int16(np.average(ba, axis=0))\n mbfile = b.parent / 'bluemasterbias.fits'\n rshape = list(red[0].shape)\n rshape[:0] = [len(red)]\n ra = np.concatenate(red).reshape(rshape)\n mrdata = np.int16(np.average(ra, axis=0))\n mrfile = b.parent / 'redmasterbias.fits'\n\n try:\n fits.writeto(mbfile, mbdata, blueheader, overwrite=True)\n fits.writeto(mrfile, mrdata, redheader, overwrite=True)\n except FileNotFoundError:\n fits.writeto(mrfile, mrdata, redheader, overwrite=False)\n fits.writeto(mbfile, mbdata, blueheader, overwrite=False)\n ListOfFiles.update(lof, mbfile)\n ListOfFiles.update(lof, mrfile)\n\n def makemasterflat(self, lof):\n blue = []\n red = []\n for b in lof.flat:\n if b.name.startswith('H'):\n blue.append(b.parent / b.name)\n if b.name.startswith('R'):\n red.append(b.parent / b.name)\n else:\n continue\n t = []\n\n\nclass Normalise(object):\n \"\"\"\n Normalise each order\n \"\"\"\n def __init__(self,\n science,\n specphot):\n self.science = science\n self.specphot = specphot\n self.exptime = specphot.hrsfile.header['exptime']\n # self.select_source(self.specphot)\n self.flatfielded = self.deflat(self.science)\n self.normalised = self.deblaze(self.science)\n\n def _shape_2(self, x, y, frac=0.05):\n \"\"\"\n Determine the shape of an order\n \"\"\"\n lowess = nonparametric.lowess\n return (lowess(x, y, frac=frac))\n\n def _shape(self, source, field, o, frac=0.05):\n \"\"\"\n Determine the shape of an order, by using a Locally Weighted Scatterplot Smoothing method\n One could use a polynomial fitting too\n \"\"\"\n lowess = nonparametric.lowess\n order = source.wlcrorders.Order == o\n # Because of the weird shape of the orders, we need to split the fit into two separate fits\n # The break is at pixel 1650 Nope. It varies along the chip.\n bk = 1650\n ya = source.wlcrorders.loc[order, [field]].values.flatten()[:bk]\n xa = source.wlcrorders.loc[order, ['Wavelength']].values.flatten()[:bk]\n yb = source.wlcrorders.loc[order, [field]].values.flatten()[bk:]\n xb = source.wlcrorders.loc[order, ['Wavelength']].values.flatten()[bk:]\n # print('Max : ', self._maxorder(ya), self._maxorder(yb), \"\\n\")\n lowessfita = lowess(ya, xa, frac=frac)\n lowessfitb = lowess(yb, xb, frac=frac)\n # lowessfit = lowess(source.wlcrorders.Object[order], source.wlcrorders.Wavelength[order], frac=frac)\n return np.concatenate((lowessfita, lowessfitb))\n\n def _maxorder(self, y):\n if y.max() == 0:\n return 1\n return np.nanmax(y)\n\n def deflat(self, science):\n \"\"\"\n Correction of the pixel-pixel variations\n \"\"\"\n # fshape = self._shape(self.specphot, 'Object')\n # We add one column that will hold the normalisez flux\n science.wlcrorders = science.wlcrorders.assign(FlatField=science.wlcrorders.CosmicRaysObject)\n for order in science.wlcrorders.Order.unique():\n o = science.wlcrorders.Order == order\n fshape = self._shape(self.specphot, 'Object', order)\n print(fshape.max())\n fshapen = fshape[:, 1] / np.nanmax(fshape[:, 1])\n science.wlcrorders.loc[science.wlcrorders.Order == order,\n ['FlatField']] = science.wlcrorders.CosmicRaysObject[o] / fshape[:, 1]\n return science\n\n def deblaze(self, science):\n \"\"\"\n Deblaze the orders to have their flux set to unity\n \"\"\"\n # oshape = self._shape(self.science, 'FlatField')\n # Two new columns needed, one to store the shape of the orders\n # one to stor the deblazed orders.\n logger.info('Creating two new attributes that will store the cosmic ray corrected object and sky')\n science.wlcrorders = science.wlcrorders.assign(Normalised=science.wlcrorders.CosmicRaysObject)\n science.wlcrorders = science.wlcrorders.assign(oshape=science.wlcrorders.CosmicRaysObject)\n for order in science.wlcrorders.Order.unique()[2:-1]:\n o = science.wlcrorders.Order == order\n oshape = self._shape(self.science, 'FlatField', order)\n # print(oshape.shape)\n orderlength = science.hrsfile.data.shape[1]\n if orderlength > 4000:\n logger.info('Only 4040 pixels are used for the red file.')\n orderlength = 4040\n if len(oshape) != orderlength:\n logger.info('The shape of the order does not have the right length. Padding it with edges values.')\n os = np.pad(oshape[:, 1], (0, orderlength - len(oshape[:, 1]) % orderlength), 'edge')\n else:\n logger.info('The shape of the order has the proper length')\n os = oshape[:, 1]\n # print(os.shape)\n # print(os.max())\n science.wlcrorders.loc[science.wlcrorders.Order == order,\n ['oshape']] = os\n # print('apres', order, os.shape)\n science.wlcrorders.loc[science.wlcrorders.Order == order,\n ['Normalised']] = science.wlcrorders.FlatField[o] / os\n return science\n\n def order_merge(self, science):\n \"\"\"\n Merge the orders\n \"\"\"\n normalised_orders = science.wlcrorders.Order.unique()[::-1]\n for (blue, red) in zip(normalised_orders[:-1], normalised_orders[1:]):\n # We find the overlapping region in pixel space.\n print(blue, red)\n lower = science.wlcrorders.Wavelength[science.wlcrorders.Order == blue]\n upper = science.wlcrorders.Wavelength[science.wlcrorders.Order == red]\n xlower = np.where(upper.values > lower.values.min())\n xupper = np.where(lower.values < lower.values.max())\n\n\nclass Extract(object):\n \"\"\"\n With the location of the orders defined, we can now extract the orders from the science frame\n and perform a wavelength calibration\n\n Parameters:\n -----------\n orderposition : location of the orders.\n\n sciencedata : HRS Science frame that will be extracted. FITS file.\n\n save: if set to True, a file with the extracted content will be created. False (default) prevents saving.\n Anything else is considered False.\n\n Output:\n -------\n\n .orders : Numpy array containing the extracted orders\n .worders : Numpy array containing the wavelength calibrated extracted orders\n .wlcrorders : Numpy array containing the wavelength calibrated, cosmic rays corrected orders.\n \"\"\"\n def __init__(self,\n orderposition='',\n hrsscience='',\n extract=False,\n save=False,\n savedir=''):\n # self.orderposition = orderposition\n self.hrsfile = hrsscience\n self.step = orderposition.step\n self.extract = extract\n self.savedir = savedir\n\n self.orders, self.widths = self._extract_orders(\n orderposition.extracted,\n self.hrsfile.data)\n if self.extract:\n self.extraction()\n if self.checksave(save):\n self.save()\n\n def extraction(self):\n self.worders = self._wavelength(\n self.orders,\n self.widths) # , pyhrsfile, name)\n self.wlcrorders = self._cosmicrays(\n self.worders)\n\n def checksave(self, save):\n if not isinstance(save, bool):\n logger.info('Save option must be True or False, not %s. Saving disabled', type(save))\n return False\n return save\n\n def _cosmicrays(self, orders):\n orders = orders.assign(\n CosmicRaysSky=orders['Sky'])\n orders = orders.assign(\n CosmicRaysObject=orders['Object'])\n for o in orders.Order.unique():\n filt = orders.Order == o\n crs = sigma_clip(orders.Sky[filt])\n cro = sigma_clip(orders.Object[filt])\n orders.loc[orders.Order == o, ['CosmicRaysSky']] = orders.Sky[filt][~crs.mask]\n orders.loc[orders.Order == o, ['CosmicRaysObject']] = orders.Object[filt][~cro.mask]\n return orders\n\n def _extract_orders(self, positions, data):\n \"\"\" positions est un array à 3 dimensions représentant pour chaque point des ordres detectes :\n la limite inférieure,\n le centre,\n la limite supérieure des ordres.\n [:,:,0] est la limite inférieure\n [:,:,1] le centre,\n [:,:,2] la limite supérieure\n \"\"\"\n# TODO penser à mettre l'array en fortran, vu qu'on travaille par colonnes, ça ira plus vite.\n\n # data = parameters['data']\n orders = np.zeros((positions.shape[0], data.shape[1]))\n widths = np.zeros((positions.shape[0]))\n npixels = orders.shape[1]\n x = [i for i in range(npixels)]\n # Sliced orders are not located at the same place as non sliced orders.\n # This is a crude way of correcting that effect.\n # It works, so let's do it that way for now.\n if 'MEDIUM' in self.hrsfile.mode:\n xshift = 6\n logger.info('Extracting a Medium Resolution file. Shifting the location of the orders by %d pixels', xshift)\n elif 'LOW' in self.hrsfile.mode:\n xshift = 0\n for o in range(2, orders.shape[0]):\n logger.info('Extracting order number %s', o)\n X = [self.step * (i + 1) for i in range(positions[o, :, 0].shape[0])]\n try:\n foinf = np.poly1d(np.polyfit(X, positions[o, :, 0], 7))\n fosup = np.poly1d(np.polyfit(X, positions[o, :, 2], 7))\n orderwidth = np.floor(np.mean(fosup(x) - foinf(x))).astype(int)\n logger.info('Orderwidth : %s pixels', orderwidth)\n except ValueError:\n continue\n for i in x:\n try:\n orders[o, i] = data[np.int(foinf(i)) + xshift: np.int(foinf(i)) + orderwidth + xshift, i].sum()\n widths[o] = orderwidth\n except ValueError:\n continue\n# TODO:\n# avant de sommer les pixels, tout mettre dans un np.array, pour pouvoir tenir compte de la rotation de la fente.\n# Normaliser au nombre de pixels, peut-être.\n return orders, widths\n\n def _ordersums():\n \"\"\"\n Do the summation over the order width to obtain the signal\n \"\"\"\n pass\n\n def _wavelength(self, extracted_data, order_width):\n '''\n In order to get the wavelength solution, we will merge the wavelength solution\n obtained from the pyhrs reduced spectra, with our extracted data\n This is a temporary solution until we have a working wavelength solution.\n '''\n pyhrsfile = 'p' + self.hrsfile.file.stem + '_obj' + self.hrsfile.file.suffix\n try:\n pyhrs_data = fits.open(self.hrsfile.file.parent / pyhrsfile)\n except FileNotFoundError:\n logger.error('Wavelength calibration file %s not found. Cannot do the wavelength calibration', self.hrsfile.file.parent / pyhrsfile)\n return None\n logger.info('Using %s to derive the wavelength solution', pyhrsfile)\n list_orders = np.unique(pyhrs_data[1].data['Order'])\n dex = pd.DataFrame()\n\n for o in list_orders[::-1]:\n logger.info('Calibrating order %d', o)\n a = pyhrs_data[1].data[np.where(pyhrs_data[1].data['Order'] == o)[0]]\n line = 2 * (int(o) - self.hrsfile.ordershift)\n orderlength = 2048\n if 'HR' in self.hrsfile.chip:\n if o == 53:\n orderlength = 3269\n else:\n orderlength = 4040\n try:\n dex = dex.append(pd.DataFrame(\n {\n 'Wavelength': a['Wavelength'],\n # We compute the value of the sky per pixel, by dividing each sky order by its computed width.\n 'Sky': extracted_data[line, :orderlength] / order_width[line],\n 'Object': extracted_data[line - 1, :orderlength],\n 'OrderWidth': [order_width[line-1] for i in range(orderlength)],\n 'Order': [o for i in range(orderlength)]}))\n except (IndexError, ValueError):\n logger.error(\"Mismatch between the wavelength file at order %d and the raw data at order %d, can't extract wavelength solution for this order.\", line, o)\n continue\n dex = dex.reset_index()\n # Reordering the columns\n dex = dex[['Wavelength', 'Object', 'Sky', 'Order', 'OrderWidth']]\n return dex\n\n def save(self):\n \"\"\"\n Saving the DataFrame to disk.\n \"\"\"\n if 'HBDET' in self.hrsfile.chip:\n ext = 'B'\n else:\n ext = 'R'\n name = self.hrsfile.name + '_' + ext + '.csv.gz'\n filename = self.savedir.absolute() / name\n # print(filename)\n logger.info('Saving extracted data as %s', filename)\n self.wlcrorders.to_csv(filename, compression='gzip', index=False)\n\n\nclass ListOfFiles(object):\n \"\"\"\n List all the HRS raw files in the directory\n Returns the description of the files\n \"\"\"\n def __init__(self, datadir):\n self.path = datadir\n self.thar = []\n self.bias = []\n self.flat = []\n self.science = []\n self.object = []\n self.sky = []\n self.specphot = []\n self.crawl(self.path)\n # self.calibrations_check()\n\n def update(self, file):\n \"\"\"\n This function updates the bias and flat attributes of the listoffile\n in order to take into account the master bias/flats that have been created after\n the datadir has been parsed\n \"\"\"\n logger.info('Updating the list of files with new entries')\n with fits.open(self.path / file) as fh:\n propid = fh[0].header['propid']\n print(propid)\n print(self.path / file)\n if 'BIAS' in propid and self.path / file not in self.bias:\n self.bias.append(self.path / file)\n else:\n logger.info('No need to update the file list, the file %s is already included', self.path / file)\n\n def calibrations_check(self):\n if not self.flat and not self.bias:\n logger.error(\"No Flats found in %s, can't continue\", self.path)\n return False\n return\n\n def crawl(self, path):\n thar = []\n bias = []\n flat = []\n science = []\n objet = []\n sky = []\n specphot = []\n filelist = []\n # We build the list of files in the directories\n if not isinstance(path, list):\n path = [path]\n for p in path:\n for f in p.glob('*.fits'):\n # if f.name.startswith('H') or f.name.startswith('R'):\n if re.match(r'^p?(H|R)', f.name):\n # We have a HRS raw file\n filelist.append(p / f.name)\n # we now extract the information\n logger.info('Sorting files according to their type.')\n for file in filelist:\n if 'obj' in file.name:\n logger.info('%s is a reduced object file', file.name)\n objet.append(file)\n continue\n if 'sky' in file.name:\n logger.info('%s is a reduced sky file', file.name)\n sky.append(file)\n continue\n if 'spec' in file.name:\n continue\n with fits.open(file) as fh:\n h = fh[0].header['propid']\n if 'STABLE' in h:\n logger.info('%s is a Thorium-Argon calibration', file.name)\n thar.append(file)\n if 'CAL_FLAT' in h:\n logger.info('%s is a Flat Field calibration', file.name)\n flat.append(file)\n if 'BIAS' in h:\n logger.info('%s is a Bias calibration', file.name)\n bias.append(file)\n if 'SCI' in h or 'MLT' in h or 'LSP' in h:\n logger.info('%s is a Science frame', file.name)\n science.append(file)\n if 'SPST' in h:\n logger.info('%s is a Spectrophotmetric frame', file.name)\n specphot.append(file)\n# We sort the lists to avoid any side effects\n science.sort()\n bias.sort()\n flat.sort()\n thar.sort()\n objet.sort()\n sky.sort()\n specphot.sort()\n\n self.science = science\n self.bias = bias\n self.thar = thar\n self.flat = flat\n self.object = objet\n self.sky = sky\n self.specphot = specphot\n","sub_path":"pipeline/hrspy.py","file_name":"hrspy.py","file_ext":"py","file_size_in_byte":36561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"144587129","text":"# -*- coding: utf-8 -*-\nimport keyword\n\nprint('dir(keyword) = {0}'.format(dir(keyword)))\n\nmethod_type = type(keyword.iskeyword)\n\nfor m in dir(keyword):\n if hasattr(keyword, m):\n attr = getattr(keyword, m)\n if type(attr) != method_type:\n print('keyword[{0}] = {1}'.format(m, attr))\n else:\n if m.startswith('get') or m.startswith('is'):\n try:\n # print('keyword.{0}() = {1}\\n'.format(m, apply(attr))) # python3 not support apply\n print('keyword.{0}() = {1}'.format(m, attr()))\n except TypeError:\n print('ignore keyword.{0}()'.format(m))\n else:\n print('ignore keyword.{0}()'.format(m))\n\n","sub_path":"06-programing-languages/01-pythons/02-boilerplate-codes/01-builtin-api/04_keyword.py","file_name":"04_keyword.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"152394544","text":"from django.db import models\nfrom ..models import IdProduct\n\n\nclass ProductUnitConvManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().select_related('productid')\n\n # def product_conv_factor(self, productid, unitid, convunitid, convqty):\n # self.productid = productid\n # self.unitid = fromunit\n # self.convunitid = tounit\n # self.convqty = convqty\n\n\nclass IdProductUnitConv(models.Model):\n productid = models.ForeignKey(IdProduct, db_column='ProductID', related_name='puc', to_field='productid', max_length=60, on_delete=models.CASCADE)\n unitid = models.CharField(db_column='UnitID', max_length=60)\n convqty = models.DecimalField(db_column='ConvQty', max_digits=20, decimal_places=8)\n convunitid = models.CharField(db_column='ConvUnitID', max_length=12)\n\n class Meta:\n db_table = 'id_product_unit_conv'\n\n # @property\n # def conv(self):\n # return \n","sub_path":"backend/source/Products/models/ProductConv.py","file_name":"ProductConv.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451240010","text":"import os\nimport subprocess as sp\nimport logging\nfrom . import utils\nlogger = logging.getLogger(__name__)\n\ndef upload(package, token=None, label=None):\n \"\"\"\n Upload a package to anaconda.\n\n Parameters\n ----------\n package : str\n Filename to built package\n\n token : str\n If None, use the environment variable ANACONDA_TOKEN, otherwise, use\n this as the token for authenticating the anaconda client.\n\n label : str\n Optional label to add, see\n https://docs.continuum.io/anaconda-cloud/using#Uploading. Mostly useful\n for testing.\n \"\"\"\n label_arg = []\n if label is not None:\n label_arg = ['--label', label]\n\n if not os.path.exists(package):\n logger.error(\"BIOCONDA UPLOAD ERROR: package %s cannot be found.\",\n package)\n return False\n\n if token is None:\n token = os.environ.get('ANACONDA_TOKEN')\n if token is None:\n raise ValueError(\"Env var ANACONDA_TOKEN not found\")\n\n logger.info(\"BIOCONDA UPLOAD uploading package %s\", package)\n try:\n cmds = [\"anaconda\", \"-t\", token, 'upload', package] + label_arg\n p = utils.run(cmds)\n logger.info(\"BIOCONDA UPLOAD SUCCESS: uploaded package %s\", package)\n return True\n\n except sp.CalledProcessError as e:\n if \"already exists\" in e.stdout:\n # ignore error assuming that it is caused by\n # existing package\n logger.warning(\n \"BIOCONDA UPLOAD WARNING: tried to upload package, got: \"\n \"%s\", e.stdout)\n return True\n else:\n # to avoid broadcasting the token in logs\n e.cmd = ' '.join(cmds).replace(token, '')\n logger.error('BIOCONDA UPLOAD ERROR: command: %s', e.cmd)\n logger.error('BIOCONDA UPLOAD ERROR: stdout+stderr: %s', e.stdout)\n raise e\n\n","sub_path":"bioconda_utils/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"89129588","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Python curses template.\n\nUSAGE:\n=====\n- `$ python %.py`\n\nWARNING:\n=======\n- N/a.\n\nNOTE:\n====\n- Dev's: run all modules through pyflakes, pylint, & pydoc.\n\n\"\"\"\nfrom __future__ import print_function\n\n## METADATA\n#\n__creator__ = \"Matt Busby\"\n__email__ = \"@MrMattBusby\"\n__program__ = \"Curses Template\"\n__date__ = \"1 Oct, 2015\" # Created\n__version__ = \"0.1.0\" # Release\n__project__ = \"https://github.com/MrMattBusby/\"\n__author__ = \"{0} {1}\".format(__creator__, __email__)\n__credits__ = \"N/a\" # References\n__contributors__ = \"N/a\"\n__compiler__ = \"N/a\" # Designed with\n__os__ = \"N/a\" # Designed on\n__copyright__ = \"Copyright (c) {year}, {owner}. \".format(\n owner=__author__,\n year=__date__.replace(',', '').split()[-1]) + \\\n \"All rights reserved.\"\n__licence__ = \"\"\"BSD-3:\n\n {copyright}\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the\n distribution.\n\n 3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n \"\"\".format(copyright=__copyright__)\n\n## IMPORTS\n#\nIMPORT_ERRORS = [] # Import errors to log after opt parsing for a logger level\n\n# BUILT-IN/SYSTEM\nfrom datetime import datetime\nfrom functools import wraps\nimport argparse\nimport curses\nimport curses.ascii\nimport curses.textpad\nimport logging\nimport nose\nimport nose.tools\nimport os\nimport platform\nimport sys\nimport time\ntry:\n import _curses\nexcept ImportError:\n _curses = curses\n\n# EXTERNAL\ntry:\n import pudb as pdb\nexcept ImportError:\n IMPORT_ERRORS.append(\"Can't import 'pudb', using 'pdb'!\")\n import pdb\n\n## GLOBALS\n#\nOPT = None # Options populated below\nNONBLOCKING = True # Getch blocking\nNONBLOCKING_TIMEOUT = 5 # 0 # Getch ms\nSLEEPTIME = .002 # Sleep time after update\n\n# Left mouse click events\nSGL_CLICKS = (curses.BUTTON1_CLICKED, curses.BUTTON1_RELEASED)\nDBL_CLICKS = (curses.BUTTON1_DOUBLE_CLICKED, curses.BUTTON1_TRIPLE_CLICKED)\n\n# Text colors\n# 16 colors can be active at once\nCLRS = {'default' : -0x01,\n 'red' : 0x01,\n 'green' : 0x02,\n 'cyan' : 0x0e,\n 'black' : 0x10,\n 'blue' : 0x15,\n 'lime' : 0x52,\n 'brown' : 0x5e,\n 'violet' : 0x81,\n 'orange' : 0xca,\n 'pink' : 0xd5,\n 'yellow' : 0xe2,\n 'cream' : 0xe5,\n 'white' : 0xe7,\n 'gray' : 0xf1,\n 'lgray' : 0xfa\n # 'dgray' : 0x00,\n # 'magenta' : 0x0d,\n # 'navy' : 0x13,\n # 'indigo' : 0x36,\n # 'sage' : 0x41,\n # 'sky' : 0x9f,\n # 'dorange' : 0xc4,\n # 'dpink' : 0xc8\n }\n\n# Text attributes\nATTRS = {'bold' : curses.A_BOLD,\n 'dim' : curses.A_DIM,\n 'invis' : curses.A_INVIS,\n 'norm' : curses.A_NORMAL,\n 'rev' : curses.A_REVERSE,\n 'uline' : curses.A_UNDERLINE\n }\n\n# Color pair attributes, e.g. PAIRS[(fg,bg)]\nPAIRS = {}\n\n## DECORATORS\n#\ndef entry_exit(func):\n \"\"\"Decorator.\"\"\"\n def log_final_time(func, t_i):\n \"\"\"Log final function execution time.\"\"\"\n t_f = time.time()\n logging.info(\"Exiting {}() after {:.3f} sec.\".format(func, t_f - t_i))\n @wraps(func)\n def wrapper(*args, **kwargs):\n \"\"\"Replacement.\"\"\"\n logging.info(\"Entering {}()..\".format(func.__name__))\n t_i = time.time()\n try:\n rtn = func(*args, **kwargs)\n except:\n log_final_time(func.__name__, t_i)\n raise\n else:\n log_final_time(func.__name__, t_i)\n return rtn\n return wrapper\n\n## CLASSES\n#\nclass TestModule(object):\n \"\"\"Nose test class.\"\"\"\n def __init__(self, *args, **kwargs):\n pass\n\n @classmethod\n def setup_class(cls):\n \"\"\"Sets up the test.\"\"\"\n\n @classmethod\n def teardown_class(cls):\n \"\"\"Tears down the test.\"\"\"\n pass\n\n def test_main(self):\n \"\"\"Test call to _main.\"\"\"\n nose.tools.eq_(_main(), None)\n\n## FUNCTIONS\n#\ndef parse_argv():\n \"Parse input arguments.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--debug', action='store_true',\n default=False, help='debug')\n parser.add_argument('-m', '--post_mortem', action='store_true',\n default=False, help='enter post mortem on exception')\n parser.add_argument('arg', metavar='A', type=str, nargs='?',\n default='', help='optional arg')\n opts = parser.parse_args() # OR opts, _ = parser.parse_known_args()\n return {'arg': opts.arg,\n 'debug': opts.debug,\n 'post_mortem': opts.post_mortem}\n\nclass Desktop(object):\n def __init__(self, stdscr, fg='white', bg='blue'):\n\n # Desktop parameters\n self.desktop = stdscr\n self.windows = [] # All subwindows\n self.fg = fg\n self.bg = bg\n self.ymax = 0\n self.xmax = 0\n self.shadow = True\n self.initted = False\n self.ended = False\n self.getch = None\n self.my = None\n self.mx = None\n self.click = None\n self.tmp = 0\n\n self.init_curses()\n self.init_window()\n self.build()\n\n self.mainloop()\n\n def __del__(self):\n \"\"\"Del method, should all be handled fine by the curses wrapper.\"\"\"\n if not self.ended:\n if self.desktop:\n self.desktop.leaveok(0)\n self.desktop.scrollok(1)\n self.desktop.keypad(0)\n curses.echo()\n curses.nocbreak()\n curses.endwin()\n self.ended = True\n\n def init_curses(self):\n # Constants\n self.ymax, self.xmax = self.desktop.getmaxyx()\n\n # Colors\n terminfo = curses.longname()\n assert '256' in terminfo # Your env TERM must be xterm-256color!\n assert curses.has_colors()\n curses.start_color()\n curses.use_default_colors()\n ctr = 1\n for fg in CLRS:\n for bg in CLRS:\n if ctr <= curses.COLORS-1 and fg != bg:\n curses.init_pair(ctr, CLRS[fg], CLRS[bg])\n PAIRS[(fg,bg)] = curses.color_pair(ctr)\n ctr += 1\n\n # I/O\n availmask, _ = curses.mousemask(curses.ALL_MOUSE_EVENTS)\n assert availmask != 0 # mouse must be available!\n curses.meta(1) # 8b chars\n curses.noecho() # No auto echo keys to window\n curses.cbreak() # Don't wait for \n curses.curs_set(0) # Invisible cursor\n curses.delay_output(0)\n curses.mouseinterval(150)\n\n def init_window(self):\n # I/O\n window.border() # Or box on edges\n self.desktop.leaveok(1) # Virtual screen cursor after update\n self.desktop.scrollok(0) # Cursor moves off page don't scroll\n self.desktop.keypad(1) # Use special char values\n\n # User input\n if NONBLOCKING:\n self.desktop.nodelay(1) # Nonblocking getch/str\n self.desktop.timeout(NONBLOCKING_TIMEOUT) # Nonblocking gets, ms\n else:\n self.desktop.nodelay(0)\n self.desktop.timeout(-1)\n self.desktop.refresh()\n\n def add_win(self, window):\n ysize = min(window.ysize, self.ymax - window.y)\n xsize = min(window.xsize, self.xmax - window.x)\n y = min(window.y, self.ymax)\n x = min(window.x, self.xmax)\n newwin = self.desktop.subwin(ysize, xsize, y, x)\n window.init(newwin, ysize, xsize, y, x)\n # for each in self.windows:\n # each.z += 1\n # window.z = 0\n self.windows.append(window)\n\n def redraw(self):\n self.desktop.bkgd(' ', PAIRS[(self.fg, self.bg)]) # Background\n self.desktop.addstr(0, 0, str(self.tmp))\n self.tmp += 1\n self.desktop.noutrefresh()\n for each in self.windows:\n if self.shadow:\n self.draw_shadow(each)\n self.desktop.noutrefresh()\n for each in self.windows:\n each.redraw()\n curses.doupdate()\n\n def draw_shadow(self, window):\n # self.window.hline(window.y+window.ymax, window.x+1, ' ', window.xsize, PAIRS['white', 'black'])\n # self.window.vline(window.y+1, window.x+window.xmax, ' ', window.ysize, PAIRS['white', 'black'])\n pass\n\n def build(self):\n \"\"\"Override this method in a subclass, use to compose subwindows.\"\"\"\n pass\n\n def mainloop(self):\n \"\"\"Main update loop.\"\"\"\n while True:\n # Redraw\n self.redraw()\n self.getch = self.desktop.getch()\n\n # Input\n self.mx, self.my, self.click = None, None, None\n if self.getch != -1:\n if self.getch == ord('q'):\n self.desktop.addstr(2, 2, 'q')\n self.desktop.noutrefresh()\n elif self.getch in (curses.KEY_MOUSE,):\n _, self.mx, self.my, _, self.click = curses.getmouse()\n self.desktop.addstr(3, 3, str(self.mx))\n self.desktop.addstr(4, 4, str(self.my))\n self.desktop.addstr(5, 5, str(self.click))\n self.desktop.noutrefresh()\n for each in self.windows:\n if each.window.enclose(self.my, self.mx):\n each._on_click(self.my, self.mx, self.click)\n\n # Sleep\n if SLEEPTIME:\n time.sleep(SLEEPTIME)\n # curses.napms()\n\nclass Window(object):\n def __init__(self, y=1, x=1, ysize=10, xsize=20, fg='black', bg='cream', has_border=True, has_titlebar=True, has_menubar=True):\n self.window = None\n self.has_titlebar = has_titlebar\n self.titlebar = None\n self.has_menubar = has_menubar\n self.menubar = None\n self.fg = fg\n self.bg = bg\n self.y = y\n self.x = x\n self.ysize = ysize\n self.xsize = xsize\n self.ymax = 0\n self.xmax = 0\n\n def init(self, window, ysize, xsize, y, x):\n self.window = window\n self.ysize = ysize\n self.xsize = xsize\n self.y = y\n self.x = x\n self.ymax, self.xmax = self.window.getmaxyx()\n # if self.has_titlebar:\n # self.titlebar = self.window.derwin(1, self.xmax, 0, 0)\n # if self.has_menubar:\n # self.menubar = self.window.derwin(1, self.xmax, 1, 0)\n self.window.refresh()\n\n def redraw(self):\n self.window.bkgd(' ', PAIRS[(self.fg, self.bg)])\n # Do stuff\n self.window.noutrefresh()\n # if self.has_titlebar:\n # if self.z == 0:\n # self.titlebar.bkgd(' ', PAIRS[('white', 'cyan')])\n # else:\n # self.titlebar.bkgd(' ', PAIRS[('gray', 'green')])\n # self.titlebar.noutrefresh()\n # if self.has_menubar:\n # self.menubar.bkgd(' ', PAIRS[('black', 'lgray')])\n # self.menubar.noutrefresh()\n\n def _on_click(self, my, mx, click):\n # func = getattr(self, on_click) TODO YOU ARE HERE\n pass\n\nclass MyWin(Window):\n def __init__(self, *args, **kwargs):\n super(MyWin, self).__init__(*args, **kwargs)\n def on_click(self, my, mx, click):\n self.window.addch(my, mx, 'X')\n self.window.noutrefresh()\n\nclass MyDesktop(Desktop):\n \"\"\"Create a custom desktop.\"\"\"\n def __init__(self, stdscr):\n \"\"\"Init.\"\"\"\n super(MyDesktop, self).__init__(stdscr, fg='white', bg='blue')\n\n def build(self):\n \"\"\"Build subwindows.\"\"\"\n myWin = MyWin()\n self.add_win(myWin)\n\n## MAIN\n#\n@entry_exit\ndef _main():\n \"\"\"...\"\"\"\n curses.wrapper(MyDesktop)\n\n## EXECUTION\n#\nif __name__ == '__main__':\n # Global options\n OPT = parse_argv()\n if OPT.get('debug'):\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.WARN)\n\n # Print any import issues.\"\"\"\n for each in IMPORT_ERRORS:\n logging.warn(each)\n del IMPORT_ERRORS\n\n # Clear screen on start\n try:\n _main()\n except KeyboardInterrupt:\n sys.stdout.flush()\n sys.stderr.flush()\n except (Exception, curses.error) as err:\n # Unhandeld exception\n if OPT.get('post_mortem'):\n logging.exception(err)\n pdb.post_mortem() # 'e' to view\n else:\n raise\n except: # SystemExit, KeyboardInterrupt, GeneratorExit\n raise\nelse:\n # If imported\n pass\n\n","sub_path":"template_curses.py","file_name":"template_curses.py","file_ext":"py","file_size_in_byte":14080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"147767751","text":"import pandas as pd\nimport numpy as np\nimport os\nimport jieba.analyse\nfrom wordcloud import WordCloud, ImageColorGenerator\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n# import PIL # Python 中的图像处理模块,在本文中用以对图片进行处理。\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\nSTOPWORDS=['to','the','is','in','be']\ndef Gender_status(friends):\n df=pd.DataFrame(friends)\n #print(df.columns)\n sex_group=df.groupby(['sex'],as_index=True)['sex'].count()\n # print(sex_group.index)\n sex_group1=pd.Series(list(sex_group),index=['Unknow','Man','Female'])\n sex_group1.plot(kind='pie')\n plt.show()\n\ndef Places_stats(users):\n place = pd.DataFrame(users)\n place_group = place.groupby('province', as_index=True)['province'].count().sort_values(ascending=False)\n print(type(place_group)) #Series\n print(place_group)\n place_group.head(15).plot(kind='bar')\n plt.show()\n\ndef Signature_data(users):\n signature = users['signature']\n words = ''.join(signature)\n res_list = jieba.cut(words, cut_all=True)\n return res_list\n\ndef Create_wc(words_list):\n res_path = os.path.abspath('./static')\n words = ' '.join(words_list)\n back_pic = np.array(Image.open(\"%s/images/images.png\" % res_path))\n stopwords = set(STOPWORDS)\n stopwords = stopwords.union(set(['class','span','emoji','emoji','emoji1f388','emoji1f604']))\n result = jieba.analyse.textrank(words, topK=1000, withWeight=True)\n # generate weight dictionary:\n keywords = dict()\n for i in result:\n keywords[i[0]] = i[1]\n wc = WordCloud(background_color=\"white\", margin=0,\n font_path='%s/fronts/simhei.ttf' % res_path,\n mask=back_pic,\n max_font_size=70,\n stopwords=stopwords\n ).generate(words)\n # back_color = imread('./static/images/images.png')\n # image_colors = ImageColorGenerator(back_color)\n plt.imshow(wc)\n # plt.imshow(wc.recolor(color_func=image_colors))\n plt.axis('off')\n plt.title(u'My Weichat Key Words')\n plt.show()\n wc.to_file('%s/images/signatures.jpg' % res_path)\n\n\n","sub_path":"Data_analysis.py","file_name":"Data_analysis.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"279213953","text":"class Bob:\n\n def hey(self, msg):\n self.inquiry = msg\n return self.resolve()\n\n def resolve(self):\n if not self.test_blank():\n response = 'Whatever.'\n if self.test_question():\n response = 'Sure.'\n\n if self.test_caps():\n response = 'Woah, chill out!'\n else:\n response = \"Fine. Be that way.\"\n\n return response\n\n def test_blank(self):\n if not self.inquiry or \\\n self.inquiry.isspace():\n return True\n else:\n return False\n\n def test_question(self):\n if self.inquiry.endswith('?'):\n return True\n else:\n return False\n\n def test_caps(self):\n if self.inquiry.isupper():\n return True\n else:\n return False\n","sub_path":"all_data/exercism_data/python/bob/9a5c08e386564bd0b97b28289b585da5.py","file_name":"9a5c08e386564bd0b97b28289b585da5.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"136681430","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\n\nCreated on Tue Apr 21 17:26:40 2020\n\n@author: Felipe\n\nApproximations of Aki and Richard and Shuey\n\"\"\"\n\nimport numpy as np\n\ndef snell(vp1, vp2, theta1):\n \"\"\"\n Computes the angles of refraction for an incident P-wave in a two-layered\n model. AVO - Chopra and Castagna, 2014, Page 6.\n\n Parameters\n ----------\n vp1 : array\n P-wave in the upper layer.\n vp2 : array\n P-wave in the lower layer.\n theta1 : array\n Angles of incidence.\n\n Returns\n -------\n theta2 : array\n Angles of refraction.\n p : array\n Ray parameter.\n \"\"\"\n p = np.sin(theta1)/vp1 \n theta2 = np.arcsin(p*vp2)\n\n return(theta2, p)\n\ndef akirichards(vp1, vs1, rho1, vp2, vs2, rho2, theta1):\n \"\"\"\n Computes the P-wave reflectivity with Aki and Richard's (1980) equation for\n a two-layered model.\n AVO - Chopra and Castagna, 2014, Page 62.\n \n Parameters\n ----------\n vp1 : array\n P-wave in the upper layer.\n vs1 : array\n S-wave in the upper layer.\n rho1 : array\n Density in the upper layer. \n vp2 : array\n P-wave in the lower layer. \n vs2 : array\n S-wave in the lower layer. \n rho2 : array\n Density in the lower layer. \n theta1 : array\n Angles of incidence.\n\n Returns\n -------\n R : array\n Reflection coefficient.\n \"\"\" \n \n theta1 = np.radians(theta1) \n theta2, p = snell(vp1, vp2, theta1)\n theta = (theta1 + theta2) / 2.\n\n dvp = vp2-vp1\n dvs = vs2-vs1\n drho = rho2-rho1\n vp = (vp1+vp2)/2\n vs = (vs1+vs2)/2\n rho = (rho1+rho2)/2 \n \n R1 = 0.5*(1-4*p**2*vs**2)*drho/rho\n R2 = 0.5/(np.cos(theta)**2)*dvp/vp\n R3 = 4*p**2*vs**2*dvs/vs\n \n R = R1+R2-R3\n \n return (R)\n\ndef shuey(vp1, vs1, rho1, vp2, vs2, rho2, theta1):\n \"\"\"\n Computes the P-wave reflectivity with Shuey (1985) 2 and 3 terms for a \n two-layerd model.\n Avseth et al., Quantitative seismic interpretation, 2006, Page 182.\n \n Parameters\n ----------\n vp1 : array\n P-wave in the upper layer.\n vs1 : array\n S-wave in the upper layer.\n rho1 : array\n Density in the upper layer. \n vp2 : array\n P-wave in the lower layer. \n vs2 : array\n S-wave in the lower layer. \n rho2 : array\n Density in the lower layer. \n theta1 : array\n Angles of incidence.\n\n Returns\n -------\n R0 : array\n Intercept.\n G : array\n Gradient. \n R2 : array\n Reflection coefficient for the 2-term approximation.\n R3 : array\n Reflection coefficient for the 3-term approximation. \n \"\"\" \n \n theta1 = np.radians(theta1) \n \n dvp = vp2-vp1\n dvs = vs2-vs1\n drho = rho2-rho1\n vp = (vp1+vp2)/2\n vs = (vs1+vs2)/2\n rho = (rho1+rho2)/2 \n \n R0 = 0.5*(dvp/vp + drho/rho)\n G = 0.5*(dvp/vp) - 2*(vs**2/vp**2)*(drho/rho+2*(dvs/vs))\n F = 0.5*(dvp/vp)\n \n R2 = R0 + G*np.sin(theta1)**2\n R3 = R0 + G*np.sin(theta1)**2 + F*(np.tan(theta1)**2-np.sin(theta1)**2)\n \n return (R0,G,R2, R3)\n\ndef shueyrc(vp0, vs0, rho0, theta1):\n \"\"\"\n Computes the P-wave reflectivity with Shuey (1985) 2 terms for a \n log.\n Avseth et al., Quantitative seismic interpretation, 2006, Page 182.\n \n Parameters\n ----------\n vp0 : array\n P-wave.\n vs0 : array\n S-wave.\n rho0 : array\n Density. \n theta1 : array\n Angles of incidence.\n\n Returns\n -------\n R : array\n Reflection coefficient for the 2-term approximation. \n R0 : array\n Intercept.\n G : array\n Gradient. \n \"\"\" \n \n theta1 = np.radians(theta1)\n \n dvp=vp0[1:]-vp0[:-1]\n dvs=vs0[1:]-vs0[:-1]\n drho=rho0[1:]-rho0[:-1]\n #insert in the first position \n drho=np.insert(drho,0,drho[0]) \n dvp=np.insert(dvp,0,dvp[0]) \n dvs=np.insert(dvs,0,dvs[0]) \n\n vp=(vp0[1:]+vp0[:-1])/2.0\n vs=(vs0[1:]+vs0[:-1])/2.0 \n rho=(rho0[1:]+rho0[:-1])/2.0\n\n vp=np.insert(vp,0,vp[0])\n vs=np.insert(vs,0,vs[0]) \n rho=np.insert(rho,0,rho[0])\n\n # Compute two-term reflectivity\n R0 = 0.5 * (dvp/vp + drho/rho)\n G = 0.5 * dvp/vp - 2 * (vs**2/vp**2) * (drho/rho + 2 * dvs/vs)\n\n term1 = np.outer(R0,1)\n term2 = np.outer(G, np.sin(theta1)**2)\n \n R = term1 + term2 \n return (R,R0,G)\n\ndef rickerwave(f = 25, length = 0.512, dt = 0.004):\n \"\"\"\n Computes the ricker wavelet.\n \n Parameters\n ----------\n f : float\n Central frequency.\n length : float\n Length of the wavelet.\n dt : float\n Sample rate. \n\n Returns\n -------\n time : array\n Time. \n Amplitude : array\n Amplitude of the wavelet.\n \"\"\" \n time = np.arange(-length/2, (length-dt)/2, dt)\n amplitude = (1.0 - 2.0*(np.pi**2)*(f**2)*(time**2))* \\\n np.exp(-(np.pi**2)*(f**2)*(time**2))\n return (time, amplitude)\n\ndef reflect_coef(ip):\n \"\"\"\n Computes the reflection coefficient for a plane incident P-wave.\n \n Parameters\n ----------\n ip : array\n P-impedance.\n\n Returns\n -------\n rc : array\n The reflection coefficient\n \"\"\" \n rc=(ip[1:]-ip[:-1])/(ip[1:]+ip[:-1])\n rc=np.append(rc,rc[-1])\n \n return(rc)\n","sub_path":"2_real_well_avseth/avo_func.py","file_name":"avo_func.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"466520744","text":"import numpy as np\nfrom utils import mnist_reader\nfrom utils import plot_utils\nfrom matplotlib import pyplot as plt\n\nfrom keras.utils import np_utils\nfrom models.cnnmodel import CNNModel\nfrom models.vggnetmodel import VGGNet\nfrom models.testmodel import TESTmodel\nfrom models.fcmodel import FCModel\n\n# loading the data set and convert to correct format and scale\nX_train, y_train = mnist_reader.load_mnist('data/fashion', kind='train')\nX_test, y_test = mnist_reader.load_mnist('data/fashion', kind='t10k')\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255\nprint(\"Training matrix shape\", X_train.shape)\nprint(\"Testing matrix shape\", X_test.shape)\n\n# some more details: https://github.com/zalandoresearch/fashion-mnist\n\n# image size\nimg_rows, img_cols = 28, 28\n\nnb_classes = 10\n# 0\tT-shirt/top\n# 1\tTrouser\n# 2\tPullover\n# 3\tDress\n# 4\tCoat\n# 5\tSandal\n# 6\tShirt\n# 7\tSneaker\n# 8\tBag\n# 9\tAnkle boot\n\n# uncomment for debugging\n# show 9 grayscale images as examples of the data set\n# ------- start show images ----------\n# import sys\n# for i in range(9):\n# plt.subplot(3,3,i+1)\n# plt.imshow(X_train[i].reshape(28,28), cmap='gray', interpolation='none')\n# plt.title(\"Class {}\".format(y_train[i]))\n#\n# plt.show()\n# sys.exit()\n# ------- end show images ----------\n\n\n# converts a class vector (list of labels in one vector (as for SVM)\n# to binary class matrix (one-n-encoding)\nY_train = np_utils.to_categorical(y_train, nb_classes)\nY_test = np_utils.to_categorical(y_test, nb_classes)\n\n# we need to reshape the input data to fit keras.io input matrix format\nX_train, X_test = CNNModel.reshape_input_data(X_train, X_test)\n# X_train, X_test = FCModel.reshape_input_data(X_train, X_test)\n# X_train, X_test = VGGNet.reshape_input_data(X_train, X_test)\n# X_train, X_test = TESTmodel.reshape_input_data(X_train, X_test)\n\n# hyperparameter\nnb_epoch = 10\nbatch_size = 128\n\nmodel = CNNModel.load_model(nb_classes)\n# model = FCModel.load_model(nb_classes)\n# model = VGGNet.load_model(nb_classes)\n# model = TESTmodel.load_model(nb_classes)\n\nhistory = model.fit(X_train, Y_train, batch_size=batch_size, epochs=nb_epoch, verbose=1, validation_data=(X_test, Y_test))\n\n\nscore = model.evaluate(X_test, Y_test, verbose=0)\nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])\n\nplot_utils.plot_model_history(history)\nplot_utils.plot_result_examples(model, X_test, y_test, img_rows, img_cols)\n","sub_path":"Aufgabe4/04_cnn.py","file_name":"04_cnn.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"625956181","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 25 13:05:22 2020\n\n@author: loris\n\nFaça um programa que leia 5 números e informe a soma e a média dos números.\n\n\n\"\"\"\n\ncount = 0 \nlista = []\n\nwhile count != 5:\n numero = int(input(\"Insira um numero: \"))\n lista.append(numero)\n count += 1 \n\nsoma = sum(lista)\nmedia = soma / len(lista)\n\nprint(\"O tamanho da lista é: \"+str(len(lista)))\nprint(\"A soma dos números é: \"+str(soma))\nprint(\"A média dos números é: \"+str(media)) ","sub_path":"3 - Estrutura de Repetição/8nv.py","file_name":"8nv.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"27646769","text":"import numpy as np\r\nimport pickle\r\nimport os\r\nfrom time import time\r\nfrom bpe_encoder import TextEncoder\r\n\r\nsst_pkl = './data/sst_encoded.pkl'\r\nsst_label_pkl = './data/sst_label.pkl'\r\nsst_mask_pkl = './data/sst_mask.pkl'\r\nencoder_path = './pretrain/encoder_bpe_40000.json'\r\nbpe_path = './pretrain/vocab_40000.bpe'\r\n\r\ndef array(x, dtype=np.int32):\r\n return np.array(x, dtype=dtype)\r\n\r\n\r\ndef load_pkl(file):\r\n # load pickle file\r\n f = open(file, 'rb')\r\n data = pickle.load(f)\r\n f.close()\r\n\r\n return data\r\n\r\n\r\nclass DataLoader:\r\n\r\n def __init__(self, max_word=100):\r\n # read label: list of tuple (date, 0/1)\r\n # news: list of np tuple (date, news array with encoding)\r\n # news array: (n_news, 30(max_word), 2)\r\n # n_lag1, n_lag2: scope of mid turn and long turn range\r\n # max_news maximun number of news\r\n\r\n self.sst = load_pkl(sst_pkl)\r\n self.mask = load_pkl(sst_mask_pkl)\r\n self.label = load_pkl(sst_label_pkl)\r\n\r\n # bpe encoder\r\n self.text_encoder = TextEncoder(encoder_path, bpe_path)\r\n self.encoder = self.text_encoder.encoder\r\n self.n_vocab = len(self.encoder)\r\n\r\n self.n_special = 3\r\n self.max_word = max_word\r\n\r\n self.pos = 0\r\n self.train_index = np.arange(0, 6920)\r\n self.val_index = np.arange(6920, 6920+872)\r\n self.test_index = np.arange(6920+872, 6920+872+1821)\r\n\r\n self.build_extra_embedding()\r\n\r\n def build_extra_embedding(self):\r\n self.encoder['_start_'] = len(self.encoder)\r\n self.encoder['_delimiter_'] = len(self.encoder)\r\n self.encoder['_classify_'] = len(self.encoder)\r\n\r\n def iter_reset(self, shuffle=True):\r\n self.pos = 0\r\n if shuffle:\r\n np.random.shuffle(self.train_index)\r\n\r\n def sampled_batch(self, batch_size, phase='train'):\r\n\r\n # batch iterator, shuffle if train\r\n if phase == 'train':\r\n n = len(self.train_index)\r\n self.iter_reset(shuffle=True)\r\n index = self.train_index\r\n elif phase == 'validation':\r\n n = len(self.val_index)\r\n self.iter_reset(shuffle=False)\r\n index = self.val_index\r\n else:\r\n n = len(self.test_index)\r\n self.iter_reset(shuffle=False)\r\n index = self.test_index\r\n\r\n\r\n\r\n while self.pos < n:\r\n\r\n X_batch = []\r\n y_batch = []\r\n M_batch = []\r\n\r\n for i in range(batch_size):\r\n X_batch.append(self.sst[index[self.pos]])\r\n y_batch.append(self.label[index[self.pos]])\r\n M_batch.append(self.mask[index[self.pos]])\r\n\r\n self.pos += 1\r\n if self.pos >= n:\r\n break\r\n # all return news array are: [batch_size, max_news, max_words, 2]\r\n # all masks are [batch_size, max_news, max_word]\r\n\r\n yield array(X_batch), array(y_batch), array(M_batch)\r\n\r\n\r\n def get_data(self, phase='train'):\r\n if phase == 'train':\r\n return self.sst[self.train_index], self.label[self.train_index], self.mask[self.train_index]\r\n elif phase == 'validation':\r\n return self.sst[self.val_index], self.label[self.val_index], self.mask[self.val_index]\r\n elif phase == 'test':\r\n return self.sst[self.test_index], self.label[self.test_index], self.mask[self.test_index]\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n # text_encoder = TextEncoder(encoder_path, bpe_path)\r\n # encoder = text_encoder.encoder\r\n # for key,val in encoder.items():\r\n # if key == '\\251' or key == '\\251':\r\n # print(key, val)\r\n # exit(0)\r\n # Testing\r\n iterator = DataLoader()\r\n # for sample in iterator.sampled_batch(1, phase='test'):\r\n # print(sample[0], sample[1], sample[2])\r\n # print(sample[3].shape)\r\n # print(sample[4].shape)\r\n # print(sample[5].shape)\r\n # print(sample[6].shape)\r\n # print(sample[7].shape)\r\n # print('\\n')\r\n\r\n decoder = iterator.text_encoder.decoder\r\n for x, y, m in iterator.sampled_batch(batch_size=1):\r\n print(x.shape)\r\n print(y.shape)\r\n print(m.shape)","sub_path":"load_sst.py","file_name":"load_sst.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183764428","text":"# File_name: simple_notification.py\n# Purpose: Send list of instances/jobs that were running and are now stopped\n# Problem: \n# Author: Søren Wandrup-Bendixen\n# Email: soren.wandrup-Bendixen@cybercom.com\n# Created: 2019-07-01\n# Called from lambda_handler.py\n\nimport os\nimport boto3\n \ndef send_info ( message = 'test'):\n\t# Create an SNS client\n\tsns = boto3.client('sns')\n\ttopic_arn = os.environ['TOPIC_ARN']\n# 'arn:aws:sns:us-east-1:015670528421:auto_stop_all'\n\t# Publish a simple message to the specified SNS topic\n\tresponse = sns.publish(\n\t\tTopicArn=topic_arn, \n\t\tMessage=message \n\t)\n\n\treturn response\n","sub_path":"cost-explorer-reporting/simple_notification.py","file_name":"simple_notification.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"129371696","text":"from lxml import etree\n\nimport requests\n\nfor page in range(10):\n resp = requests.get(\n url=f'https://movie.douban.com/top250?start={page * 25}',\n headers={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/83.0.4103.97 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;'\n 'q=0.9,image/webp,image/apng,*/*;'\n 'q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',\n }\n )\n html = etree.HTML(resp.text)\n spans = html.xpath('/html/body/div[3]/div[1]/div/div[1]/ol/li/div/div[2]/div[1]/a/span[1]')\n for span in spans:\n print(span.text)\n","sub_path":"douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534056749","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom gremlin_python.process.anonymous_traversal import traversal\nfrom gremlin_python.driver.driver_remote_connection import DriverRemoteConnection\nimport json\n\n\nto_string = json.dumps\n\n\ndef main():\n\n # connect to a remote server that is compatible with the Gremlin Server protocol. for those who\n # downloaded and are using Gremlin Server directly be sure that it is running locally with:\n #\n # bin/gremlin-server.sh console\n #\n # which starts it in \"console\" mode with an empty in-memory TinkerGraph ready to go bound to a\n # variable named \"g\" as referenced in the following line.\n g = traversal().with_remote(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g'))\n\n # add some data - be sure to use a terminating step like iterate() so that the traversal\n # \"executes\". iterate() does not return any data and is used to just generate side-effects\n # (i.e. write data to the database)\n g.add_v('person').property('name', 'marko').as_('m'). \\\n add_v('person').property('name', 'vadas').as_('v'). \\\n add_e('knows').from_('m').to('v').iterate()\n\n # retrieve the data from the \"marko\" vertex\n print(\"marko: \" + to_string(g.V().has('person', 'name', 'marko').value_map().next()))\n\n # find the \"marko\" vertex and then traverse to the people he \"knows\" and return their data\n print(\"who marko knows: \" + to_string(g.V().has('person', 'name', 'marko').out('knows').value_map().next()))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gremlin-python/src/main/python/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52048418","text":"from bokeh.plotting import figure\nfrom bokeh.io import output_file, show\nimport pandas\n\nweather=pandas.read_excel(\"verlegenhuken.xlsx\")\nx=weather[\"Temperature\"] / 10\ny=weather[\"Pressure\"] / 10\n\noutput_file(\"weather.html\")\n\nf=figure(plot_width=500,plot_height=400,tools='pan')\n\nf.title.text=\"Temperature and Air Pressure\"\nf.title.text_color=\"Gray\"\nf.title.text_font=\"times\"\nf.title.text_font_style=\"bold\"\nf.xaxis.axis_label=\"Temperature\"\nf.yaxis.axis_label=\"Pressure (hPA)\"\n\nf.scatter(x,y, size=0.5)\n\nshow(f)","sub_path":"sec27-bokeh/bokeh_plot_weather.py","file_name":"bokeh_plot_weather.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313795257","text":"# In[0]:\n\nfrom pathlib import Path\nfrom Train_Generator import *\nfrom OrganizeData import *\nimport matplotlib.pyplot as plt\nfrom keras import optimizers, losses, activations, models\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\nimport keras.backend as K\nimport tensorflow as tf\nimport Resnet18\nimport argparse\nimport math\n\nap = argparse.ArgumentParser()\n\nap.add_argument(\"--n-threads\", type=int, default=4, help=\"number of working threads\")\n\nap.add_argument(\"--data-dir\", type=str,\n help=\"path for training and val files\")\n\nap.add_argument(\"--freq-compress\", type=str, default='linear', help=\"define compression type\")\n\nap.add_argument(\"-m\", \"--model\", type=str, default=None,\n help=\"path to model checkpoint to load in case you want to resume a model training from where you left of\")\n\nap.add_argument(\"--res-dir\", type=str, help=\"path to model results plot,weights,checkpoints etc.\")\n\nap.add_argument(\"-ie\", \"--initial-epoch\", type=int, default=0,\n help=\"epoch to restart training at\")\n\nap.add_argument(\"--batch\", type=int, default=32, help=\"choose batch size\")\n\nap.add_argument(\"--n-epochs\", type=int, default=100, help=\"number of epochs\")\n\nap.add_argument(\n \"--lr\",\n \"--learning_rate\",\n type=float,\n default=1e-5,\n help=\"Initial learning rate. Will get multiplied by the batch size.\",\n)\n\nap.add_argument(\n \"--beta1\", type=float, default=0.5, help=\"beta1 for the adam optimizer.\"\n)\n\nap.add_argument(\n \"--lr_patience_epochs\",\n type=int,\n default=8,\n help=\"Decay the learning rate after N/epochs_per_eval epochs without any improvements on the validation set.\",\n)\n\nap.add_argument(\n \"--lr_decay_factor\",\n type=float,\n default=0.5,\n help=\"Decay factor to apply to the learning rate.\",\n)\n\nap.add_argument(\n \"--early_stopping_patience_epochs\",\n metavar=\"N\",\n type=int,\n default=20,\n help=\"Early stopping (stop training) after N/epochs_per_eval epochs without any improvements on the validation set.\",\n)\n\nap.add_argument(\n \"--epochs_per_eval\",\n type=int,\n default=2,\n help=\"The number of batches to run in between evaluations.\",\n)\n\nARGS = ap.parse_args()\n\n# In[2]:\nif __name__ == '__main__':\n\n # In[2]:\n\n dir = ARGS.res_dir\n\n HISTORY_CSV = \"{}\".format(dir) + \"history.csv\"\n TEST_FILES_CSV = \"{}\".format(dir) + \"test_files.csv\"\n MODEL_STRUCTURE_JSON = \"{}\".format(dir) + \"model_structure.json\"\n WEIGHTS_CNN = \"{}\".format(dir) + \"weights.h5\"\n BEST_MODEL = \"{}\".format(dir) + \"best_model.h5\"\n PLOT = \"{}\".format(dir) + \"plot.png\"\n RESULTS_CSV = \"{}\".format(dir) + \"results.csv\"\n WEIGHTS_CSV = \"{}\".format(dir) + \"weights.csv\"\n LOG = \"{}\".format(dir) + \"log/\"\n\n # In[]:\n print(\"{} compression\".format(ARGS.freq_compress))\n data_dir = ARGS.data_dir\n tr_files, file_to_label_train = findcsv(\"train\", data_dir)\n print(\"len train\", len(tr_files))\n val_files, file_to_label_val = findcsv(\"val\", data_dir)\n print(\"len val \", len(val_files))\n\n list_labels = getUniqueLabels(data_dir)\n print(\"Unique Values: \",list_labels)\n\n n_output = len(list_labels)\n print(\"n output \", n_output)\n\n label_to_int = {k: v for v, k in enumerate(list_labels)}\n\n file_to_int_train = {k: label_to_int[v] for k, v in file_to_label_train.items()}\n file_to_int_val = {k: label_to_int[v] for k, v in file_to_label_val.items()}\n\n training_generator = Train_Generator(\"train\", tr_files, file_to_int_train, freq_compress=ARGS.freq_compress,\n augment=True,\n batch_size=ARGS.batch)\n validation_generator = Train_Generator(\"val\", val_files, file_to_int_val, freq_compress=ARGS.freq_compress,\n augment=False,\n batch_size=ARGS.batch)\n\n # In[15]:\n ARGS.lr *= ARGS.batch\n print(\"learning rate \", ARGS.lr)\n\n patience_lr = math.ceil(ARGS.lr_patience_epochs / ARGS.epochs_per_eval)\n patience_lr = int(max(1, patience_lr))\n print(\"patience lr \", patience_lr)\n\n reduce_lr = ReduceLROnPlateau(monitor='val_acc', factor=0.5, mode='max',\n patience=patience_lr, min_delta=1e-3, cooldown=1, verbose=1)\n\n earlystop = EarlyStopping(monitor='val_acc', patience=ARGS.early_stopping_patience_epochs, mode='max')\n #tensorboard = keras.callbacks.TensorBoard(log_dir=LOG, histogram_freq=1)\n\n if ARGS.model is None:\n check = BEST_MODEL\n else:\n check = ARGS.model\n\n mcheckpoint = ModelCheckpoint(check, monitor='val_acc', save_best_only=True, mode='max')\n logger = keras.callbacks.CSVLogger(HISTORY_CSV,separator=\",\",append=True)\n\n if ARGS.model is None:\n print(\"[INFO] compiling model...\")\n model = Resnet18.ResnetBuilder.build_resnet_18((128, 256, 1), n_output)\n opt = optimizers.Adam(lr=ARGS.lr, beta_1=0.5, beta_2=0.999, amsgrad=False)\n model.compile(optimizer=opt, loss=\"sparse_categorical_crossentropy\", metrics=[\"acc\"])\n model.summary()\n # otherwise, we're using a checkpoint model\n else:\n # load the checkpoint from disk\n print(\"[INFO] loading {}...\".format(ARGS.model))\n model = models.load_model(ARGS.model)\n print(\"[INFO] current learning rate: {}\".format(\n K.get_value(model.optimizer.lr)))\n\n H = model.fit_generator(generator=training_generator, epochs=ARGS.n_epochs, initial_epoch=ARGS.initial_epoch,\n steps_per_epoch=math.floor(len(tr_files) // ARGS.batch),\n validation_data=validation_generator,\n validation_steps=math.ceil(len(val_files) // ARGS.batch),\n use_multiprocessing=False,\n workers=ARGS.n_threads, verbose=1,\n callbacks=[mcheckpoint, reduce_lr, earlystop,logger])\n\n # In[]:\n\n model_structure = model.to_json() # convert the NN into JSON\n f = Path(MODEL_STRUCTURE_JSON) # write the JSON data into a text file\n f.write_text(model_structure) # Pass in the data that we want to write into the file.\n\n model.save_weights(BEST_MODEL)\n #pd.DataFrame.from_dict(H.history).to_csv(HISTORY_CSV, index=False)\n\n # In[19]:\n\n # plot the training loss and accuracy\n N = len(H.history['loss'])\n plt.style.use(\"ggplot\")\n plt.figure()\n plt.plot(np.arange(0, N), H.history[\"loss\"], label=\"train_loss\")\n plt.plot(np.arange(0, N), H.history[\"val_loss\"], label=\"val_loss\")\n plt.plot(np.arange(0, N), H.history[\"acc\"], label=\"train_acc\")\n plt.plot(np.arange(0, N), H.history[\"val_acc\"], label=\"val_acc\")\n plt.title(\"Training Loss and Accuracy on Dataset\")\n plt.xlabel(\"Epoch #\")\n plt.ylabel(\"Loss/Accuracy\")\n plt.legend(loc=\"lower left\")\n plt.savefig(PLOT)\n","sub_path":"Multi_classification/Pipeline.py","file_name":"Pipeline.py","file_ext":"py","file_size_in_byte":6878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"560705617","text":"import tensorflow as tf\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport random\n\nLONGITUDE=24\nWIDTH=24\nPIXEL=LONGITUDE*WIDTH\nBATCHSIZE=10\nCONV_FRAME=1\nTIMESTEP=10\nframe_size = 3\n\nn_inputs = PIXEL\nn_hidden_units = 2048\nn_outputs = PIXEL\nn_steps = 10\nbatch_size = 10\nlr = 0.001\ntraining_iters = 10000\ndata_size = 6000\n\ndef gray2binary(a):\n for i in range(len(a)):\n if a[i]>127:\n a[i]=1\n elif a[i]<=127:\n a[i]=0\n return a\n\ndef get_batch():\n ran = random.randint(1, data_size)\n #print(ran)\n image = []\n label = []\n label_0 = []\n n_pic = ran\n # print(n_pic)\n for i in range(batch_size * n_steps):\n frame_0 = cv2.imread('./hardPixelImage/%d.jpg' % (n_pic+i), 0)\n frame_0 = cv2.resize(frame_0, (24, 24))\n frame_0 = np.array(frame_0).reshape(-1)\n image.append(frame_0)\n #print(np.shape(image))\n for i in range(batch_size):\n frame_1 = cv2.imread('./easyPixelImage2/%d.jpg' % (n_pic + batch_size * (i+1) ), 0)\n frame_1 = cv2.resize(frame_1, (24, 24))\n frame_1 = np.array(frame_1).reshape(-1)\n frame_1 = gray2binary(frame_1)\n label.append(frame_1)\n for i in range(batch_size):\n frame_2 = cv2.imread('./hardPixelImage/%d.jpg' % (n_pic + batch_size * (i+1) ), 0)\n frame_2 = cv2.resize(frame_2, (24, 24))\n frame_2 = np.array(frame_2).reshape(-1)\n label_0.append(frame_2)\n return image , label , label_0\n\nx = tf.placeholder(tf.float32, [None, n_steps, n_inputs])\ny = tf.placeholder(tf.float32, [None, n_outputs])\n\nweights = {\n # (576, 1024)\n 'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),\n # (1024, 576)\n 'out': tf.Variable(tf.random_normal([n_hidden_units, n_outputs]))\n}\nbiases = {\n # (1024, )\n 'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),\n # (576, )\n 'out': tf.Variable(tf.constant(0.1, shape=[n_outputs, ]))\n}\n\n# transpose the inputs shape from\n# X ==> ( batchsize * 10 steps, 576 inputs)\nX_in = tf.reshape(x, [-1, n_inputs])\n# into hidden\n# X_in ==> ( batchsize * 10 steps, 1024 hidden)\nX_in = tf.matmul(X_in, weights['in']) + biases['in']\n# X_in ==> ( batchsize , 10 steps, 1024 hidden)\nX_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])\n\ncell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True)\ninit_state = cell.zero_state(batch_size, dtype=tf.float32)\noutputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False)\n\noutputs = tf.unstack(tf.transpose(outputs, [1, 0, 2]))\npred_0 = tf.matmul(outputs[-1], weights['out']) + biases['out']\noutputs = tf.reshape(pred_0,[-1,24,24,1])\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\ndef bias_variable(shape):\n initial = tf.constant(0.01, shape=shape)\n return tf.Variable(initial)\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\nW_conv=weight_variable([frame_size,frame_size,1,2])\nb_conv=bias_variable([2])\nx_image=tf.reshape(outputs,[-1,LONGITUDE,WIDTH,1])\nh_conv= tf.nn.relu(conv2d(x_image, W_conv) + b_conv) #shape=[-1,24,24,2]\n\npred = tf.nn.softmax(tf.reshape(h_conv,[-1,2]))\npred = tf.unstack(pred,axis=1)\npred = tf.reshape(pred[0],[-1,24,24,1])\npred_255 = pred * 255\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=tf.reshape(pred,[-1,n_outputs]), labels=y))\n\n#pred = tf.matmul(outputs[-1], weights['out']) + biases['out'] # shape = (batchsize, 576)\n# pred = tf.nn.softmax(pred)\n# cost = tf.reduce_mean(tf.pow(pred - y, 2))\n\ntrain_op = tf.train.AdamOptimizer(lr).minimize(cross_entropy)\n\n#loss_history=[]\n\n\nwith tf.Session() as sess:\n init = tf.global_variables_initializer()\n sess.run(init)\n step = 0\n while step * batch_size < training_iters:\n batch_xs, batch_ys ,_ = get_batch()\n batch_xs = np.reshape(batch_xs,[batch_size, n_steps, n_inputs])\n sess.run(train_op , feed_dict = { x: batch_xs ,y: batch_ys })\n # plt.ion()\n # plt.show()\n if step % 20 == 0:\n loss = sess.run(cross_entropy, feed_dict={x: batch_xs ,y: batch_ys })\n print('step ',step,' cost = ',loss )\n #loss_history.append(loss)\n # plt.plot(loss_history, '-b')\n # plt.draw()\n # plt.pause(0.01)\n # image_p = sess.run(pred[-1], feed_dict={x: batch_xs ,y: batch_ys,})\n # image_p = tf.reshape(image_p, [LONGITUDE, WIDTH])\n # image_p = np.array( image_p , dtype = int)\n # cv2.imwrite('image_predict/' + str(step) + '.jpg', image_p)\n step += 1\n print(\"Optimization Finishes!\")\n\n batch_xs, batch_ys ,ys_0= get_batch()\n batch_xs = np.reshape(batch_xs, [batch_size, n_steps, n_inputs])\n #batch_ys = np.reshape(batch_ys, [batch_size, n_steps, n_inputs])\n image_p = sess.run(pred_255, feed_dict={x: batch_xs, y: batch_ys })\n batch_ys = batch_ys * 255\n f, a = plt.subplots(3, 10, figsize=(10, 3))\n for i in range(10):\n a[0][i].imshow(np.reshape(ys_0[i], (24, 24)))\n a[1][i].imshow(np.reshape(batch_ys[i], (24, 24)))\n a[2][i].imshow(np.reshape(image_p[i], (24, 24)))\n #a[3][i].imshow(np.reshape(image_p[i], (24, 24)))\n plt.show()\n","sub_path":"1.3.1-1 RNN_softmax.py","file_name":"1.3.1-1 RNN_softmax.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"524560718","text":"# coding=utf-8\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\n\nimport numpy as np\n\nclass ResidualBlock(nn.Module):\n\n\tdef __init__(self, in_channels, d1, d2, stride = 1):\n\t\tsuper(ResidualBlock, self).__init__()\n\n\t\t# leading into d1\n\t\tself.conv1 = nn.Conv2d(in_channels, d1, 1, stride = stride, bias = False)\n\t\tself.bn1 = nn.BatchNorm2d(d1)\n\t\tself.relu1 = nn.ReLU(inplace = True)\n\n\t\t# leading into d1-2\n\t\tself.conv2 = nn.Conv2d(d1, d1, 3, padding = 1, bias = False)\n\t\tself.bn2 = nn.BatchNorm2d(d1)\n\t\tself.relu2 = nn.ReLU(inplace = True)\n\n\t\t# leading into d2\n\t\tself.conv3 = nn.Conv2d(d1, d2, 1, bias = False)\n\t\tself.bn3 = nn.BatchNorm2d(d2)\n\t\tself.relu3 = nn.ReLU(inplace = True)\n\n\n\tdef forward(self, x):\n\n\t\tout = self.conv1(x)\n\t\tout = self.bn1(out)\n\t\tout = self.relu1(out)\n\n\n\t\tout = self.conv2(out)\n\t\tout = self.bn2(out)\n\t\tout = self.relu2(out)\n\n\t\tout = self.conv3(out)\n\t\tout = self.bn3(out)\n\n\t\tout += x\n\n\t\tout = self.relu3(out)\n\n\t\treturn out\n\nclass ProjectionBlock(nn.Module):\n\n\tdef __init__(self, in_channels, d1, d2, stride = 1):\n\t\tsuper(ProjectionBlock, self).__init__()\n\n\t\t# feeding into first d1 block\n\t\tself.conv1 = nn.Conv2d(in_channels, d1, 1, stride = stride, bias = False)\n\t\tself.bn1 = nn.BatchNorm2d(d1)\n\t\tself.relu1 = nn.ReLU(inplace = True)\n\n\t\t# feeding into second d1 block\n\t\tself.conv2 = nn.Conv2d(d1, d1, 3, padding = 1, bias = False)\n\t\tself.bn2 = nn.BatchNorm2d(d1)\n\t\tself.relu2 = nn.ReLU(inplace = True)\n\n\t\t# feeding into first d2 block\n\t\tself.conv3 = nn.Conv2d(d1, d2, 1, bias = False)\n\t\tself.bn3 = nn.BatchNorm2d(d2)\n\n\t\t# feeding into second d2 block\n\t\tself.conv4 = nn.Conv2d(in_channels, d2, 1, stride = stride, bias = False)\n\t\tself.bn4 = nn.BatchNorm2d(d2)\n\n\t\tself.relu3 = nn.ReLU(inplace = True)\n\n\n\tdef forward(self, x):\n\t\tout = self.conv1(x)\n\t\tout = self.bn1(out)\n\t\tout = self.relu1(out)\n\n\t\tout = self.conv2(out)\n\t\tout = self.bn2(out)\n\t\tout = self.relu2(out)\n\n\t\tout = self.conv3(out)\n\t\tout = self.bn3(out)\n\n\t\t# do residual branch\n\t\tresidual = x\n\t\tresidual = self.conv4(residual)\n\t\tresidual = self.bn4(residual)\n\n\t\tout += residual\n\n\t\tout = self.relu3(out)\n\n\t\treturn out\n\n# Fast Up Convolution from the paper, including the interleaving step\nclass UpConvolution(nn.Module):\n\tdef __init__(self, in_channels, out_channels, batch_size):\n\t\tsuper(UpConvolution, self).__init__()\n\n\t\tself.batch_size = batch_size\n\n\t\t# do 4 convolutions on the same output with different kernels\n\t\tself.conv1 = nn.Conv2d(in_channels, out_channels, (3,3))\n\t\tself.conv2 = nn.Conv2d(in_channels, out_channels, (2,3))\n\t\tself.conv3 = nn.Conv2d(in_channels, out_channels, (3,2))\n\t\tself.conv4 = nn.Conv2d(in_channels, out_channels, (2,2))\n\n\t\tself.bn = nn.BatchNorm2d(out_channels)\n\n\tdef prepare_indices(self, before, row, col, after, dims):\n\n\t\tx0, x1, x2, x3 = np.meshgrid(before, row, col, after)\n\t\tx_0 = torch.from_numpy(x0.reshape([-1]))\n\t\tx_1 = torch.from_numpy(x1.reshape([-1]))\n\t\tx_2 = torch.from_numpy(x2.reshape([-1]))\n\t\tx_3 = torch.from_numpy(x3.reshape([-1]))\n\n\t\tlinear_indices = x_3 + dims[3] * x_2 + 2 * dims[2] * dims[3] * x_0 * 2 * dims[1] + 2 * dims[2] * dims[3] * x_1\n\t\treturn linear_indices\n\n\n\tdef interleave(self, out1, out2, out3, out4):\n\n\t\tout1 = out1.permute(0, 2, 3, 1)\n\t\tout2 = out2.permute(0, 2, 3, 1)\n\t\tout3 = out3.permute(0, 2, 3, 1)\n\t\tout4 = out4.permute(0, 2, 3, 1)\n\n\t\tdims = out1.size()\n\t\tdim1 = dims[1] * 2\n\t\tdim2 = dims[2] * 2\n\n\t\tA_row_indices = range(0, dim1, 2)\n\n\t\tA_col_indices = range(0, dim2, 2)\n\t\tB_row_indices = range(1, dim1, 2)\n\t\tB_col_indices = range(0, dim2, 2)\n\t\tC_row_indices = range(0, dim1, 2)\n\t\tC_col_indices = range(1, dim2, 2)\n\t\tD_row_indices = range(1, dim1, 2)\n\t\tD_col_indices = range(1, dim2, 2)\n\n\t\tall_indices_before = range(int(self.batch_size))\n\t\tall_indices_after = range(dims[3])\n\n\t\tA_linear_indices = self.prepare_indices(all_indices_before, A_row_indices, A_col_indices, all_indices_after, dims).cuda()\n\t\tB_linear_indices = self.prepare_indices(all_indices_before, B_row_indices, B_col_indices, all_indices_after, dims).cuda()\n\t\tC_linear_indices = self.prepare_indices(all_indices_before, C_row_indices, C_col_indices, all_indices_after, dims).cuda()\n\t\tD_linear_indices = self.prepare_indices(all_indices_before, D_row_indices, D_col_indices, all_indices_after, dims).cuda()\n\n\t\tA_flat = (out1.permute(1, 0, 2, 3)).contiguous().view(-1)\n\t\tB_flat = (out2.permute(1, 0, 2, 3)).contiguous().view(-1)\n\t\tC_flat = (out3.permute(1, 0, 2, 3)).contiguous().view(-1)\n\t\tD_flat = (out4.permute(1, 0, 2, 3)).contiguous().view(-1)\n\n\t\tsize_ = A_linear_indices.size()[0] + B_linear_indices.size()[0]+C_linear_indices.size()[0]+D_linear_indices.size()[0]\n\n\t\tY_flat = torch.cuda.FloatTensor(size_).zero_()\n\t\t#print('a_float', A_linear_indices.squeeze().type())\n\t\tY_flat.scatter_(0, A_linear_indices.squeeze().long(),A_flat.data.float())\n\t\tY_flat.scatter_(0, B_linear_indices.squeeze().long(),B_flat.data.float())\n\t\tY_flat.scatter_(0, C_linear_indices.squeeze().long(),C_flat.data.float())\n\t\tY_flat.scatter_(0, D_linear_indices.squeeze().long(),D_flat.data.float())\n\n\n\t\tY = Y_flat.view(-1, dim1, dim2, dims[3])\n\t\tY=Variable(Y.permute(0,3,1,2)).contiguous()\n\n\t\treturn Y\n\n\tdef forward(self, x):\n\n\t\tout1 = self.conv1(nn.functional.pad(x, (1,1,1,1)))\n\t\tout2 = self.conv2(nn.functional.pad(x, (1,1,1,0)))\n\t\tout3 = self.conv3(nn.functional.pad(x, (1,0,1,1)))\n\t\tout4 = self.conv4(nn.functional.pad(x, (1,0,1,0)))\n\t\t#print('out1', out1.type())\n\t\tout = self.interleave(out1, out2, out3, out4)\n\t\t#print('cout1', out.type())\n\n\t\tout = self.bn(out)\n\t\tout = out.cuda()\n\n\t\treturn out\n\nclass UpProjection(nn.Module):\n\n\tdef __init__(self, in_channels, out_channels, batch_size):\n\t\tsuper(UpProjection, self).__init__()\n\n\t\tself.UpConv1 = UpConvolution(in_channels, out_channels, batch_size)\n\t\tself.relu1 = nn.ReLU(inplace = True)\n\t\tself.bn = nn.BatchNorm2d(out_channels)\n\n\t\tself.UpConv2 = UpConvolution(in_channels, out_channels, batch_size)\n\n\t\tself.conv1 = nn.Conv2d(out_channels, out_channels, 3, padding = 1)\n\t\tself.relu2 = nn.ReLU(inplace = True)\n\n\tdef forward(self, x):\n\n\t\tout1 = self.UpConv1(x)\n\t\tout2 = self.UpConv2(x)\n\n\t\tout1 = self.relu1(out1)\n\t\tout1 = self.conv1(out1)\n\t\tout1 = self.bn(out1)\n\n\t\tout = out1 + out2\n\t\tout = self.relu2(out)\n\n\t\treturn out\n\nclass FCRN(nn.Module):\n\n\tdef __init__(self, batch_size = 1):\n\t\tsuper(FCRN, self).__init__()\n\t\tself.batch_size = batch_size\n\n\t\tself.conv1 = nn.Conv2d(3, 64, kernel_size = 7, stride = 2, padding = 4)\n\t\tself.bn1 = nn.BatchNorm2d(64)\n\t\tself.relu1 = nn.ReLU(inplace = True)\n\t\tself.max_pool1 = nn.MaxPool2d(3, stride = 2)\n\n\t\tself.proj1 = ProjectionBlock(64, d1 = 64, d2 = 256, stride = 1)\n\t\tself.res1_1 = ResidualBlock(256, d1 = 64, d2 = 256, stride = 1)\n\t\tself.res1_2 = ResidualBlock(256, d1 = 64, d2 = 256, stride = 1)\n\n\t\tself.proj2 = ProjectionBlock(256, d1 = 128, d2 = 512, stride = 2)\n\t\tself.res2_1 = ResidualBlock(512, d1 = 128, d2 = 512, stride = 1)\n\t\tself.res2_2 = ResidualBlock(512, d1 = 128, d2 = 512, stride = 1)\n\t\tself.res2_3 = ResidualBlock(512, d1 = 128, d2 = 512, stride = 1)\n\n\t\tself.proj3 = ProjectionBlock(512, d1 = 256, d2 = 1024, stride = 2)\n\t\tself.res3_1 = ResidualBlock(1024, d1 = 256, d2 = 1024)\n\t\tself.res3_2 = ResidualBlock(1024, d1 = 256, d2 = 1024)\n\t\tself.res3_3 = ResidualBlock(1024, d1 = 256, d2 = 1024)\n\t\tself.res3_4 = ResidualBlock(1024, d1 = 256, d2 = 1024)\n\t\tself.res3_5 = ResidualBlock(1024, d1 = 256, d2 = 1024)\n\n\t\tself.proj4 = ProjectionBlock(1024, d1 = 512, d2 = 2048, stride = 2)\n\t\tself.res4_1 = ResidualBlock(2048, d1 = 512, d2 = 2048)\n\t\tself.res4_2 = ResidualBlock(2048, d1 = 512, d2 = 2048)\n\n\t\tself.conv2 = nn.Conv2d(2048, 1024, kernel_size = 1)\n\t\tself.bn2 = nn.BatchNorm2d(1024)\n\n\t\tself.UpProj1 = UpProjection(1024, 512, self.batch_size)\n\t\tself.UpProj2 = UpProjection(512, 256, self.batch_size)\n\t\tself.UpProj3 = UpProjection(256, 128, self.batch_size)\n\t\tself.UpProj4 = UpProjection(128, 64, self.batch_size)\n\n\t\tself.conv3 = nn.Conv2d(64, 1, kernel_size = 3, padding = 1)\n\t\tself.relu2 = nn.ReLU(inplace = True)\n\n\n\tdef forward(self, x):\n\n\t\tout = self.conv1(x)\n\t\tout = self.bn1(out)\n\t\tout = self.relu1(out)\n\t\tout = self.max_pool1(out)\n\n\t\tout = self.proj1(out)\n\t\tout = self.res1_1(out)\n\t\tout = self.res1_2(out)\n\t\tprint(out.type())\n\t\tout = self.proj2(out)\n\t\tout = self.res2_1(out)\n\t\tout = self.res2_2(out)\n\t\tout = self.res2_3(out)\n\n\t\tout = self.proj3(out)\n\t\tout = self.res3_1(out)\n\t\tout = self.res3_2(out)\n\t\tout = self.res3_3(out)\n\t\tout = self.res3_4(out)\n\t\tout = self.res3_5(out)\n\n\t\tout = self.proj4(out)\n\t\tout = self.res4_1(out)\n\t\tout = self.res4_2(out)\n\n\n\t\tout = self.conv2(out)\n\t\tout = self.bn2(out)\n\t\tprint(out.type())\n\t\tout = self.UpProj1(out)\n\t\tprint(out.type())\n\t\tout = self.UpProj2(out)\n\n\t\tout = self.UpProj3(out)\n\n\t\tout = self.UpProj4(out)\n\n\t\tout = self.conv3(out)\n\t\tout = self.relu2(out)\n\n\t\treturn out\n","sub_path":"python_code/FCRN_Accelerate/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"414293924","text":"# -*- coding: utf-8 -*-\nimport re\nimport jieba\n\n\n\ndef segment_with_jieba(inp_, out_):\n with open(inp_, 'r') as file:\n # read in the unsegmented lines\n result = re.sub(r' \\—\\\"\\—|世 界 文 学 名 著 百 部|红 与 黑|\\,|\\—\\!\\—|\\—\\!\\\"\\—|\\—\\!(.)\\!\\—| \\—\\!\\\"\\#\\—|\\—\\!\\\"\\#\\—| \\—\\\"\\#\\$\\—| \\—\\!\\!\\\"\\—|\\—\\\"\\#\\\"\\—|\\—\\%\\&\\’\\—|\" \"|\\—.*\\—', ' ', file.read())\n result = re.sub(r'\\n\\n*','', result)\n verses = re.sub(r'[?。! ; ,]','\\n',result)\n segmented_verses = jieba.cut(verses, cut_all=False)\n\n # write out segmented results\n with open(out_, 'w') as f:\n f.write(\"{}\\n\".format(' '.join(segmented_verses)))\n print('Segmented file written to {}'.format(out_))\n\n\nif __name__ == '__main__':\n \n segment_with_jieba(\n inp_='../data/test/01.txt',\n out_='../data/result/segmented_01_jieba.txt'\n )\n\n\n '''\n \n\n segment_with_jieba(\n inp_='../data/test/02.txt',\n out_='../data/result/segmented_02_jieba.txt'\n )\n '''\n","sub_path":"Segmentations/jb_tok.py","file_name":"jb_tok.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"51530199","text":"from config.config import DefaultConfig\n\n\nclass AlgoConfig(DefaultConfig):\n def __init__(self) -> None:\n # set epsilon_start=epsilon_end can obtain fixed epsilon=epsilon_end\n self.epsilon_start = 0.95 # epsilon start value\n self.epsilon_end = 0.01 # epsilon end value\n self.epsilon_decay = 500 # epsilon decay rate\n self.gamma = 0.95 # discount factor\n self.lr = 0.0001 # learning rate\n self.buffer_size = 100000 # size of replay buffer\n self.batch_size = 64 # batch size\n self.target_update = 4 # target network update frequency\n # self.value_layers = [\n # {'layer_type': 'linear', 'layer_dim': ['n_states', 256],\n # 'activation': 'relu'},\n # {'layer_type': 'linear', 'layer_dim': [256, 256],\n # 'activation': 'relu'},\n # {'layer_type': 'linear', 'layer_dim': [256, 'n_actions'],\n # 'activation': 'none'}]\n","sub_path":"joyrl/algos/DQN_CNN/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599529343","text":"# coding:utf-8\n\nimport requests\n\nclass SpiderDownloader(object):\n def download(self, url):\n if url is None:\n return None\n user_agent = 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; vivo y31 Build/LMY48Z)'\n headers = {'User-Agent': user_agent}\n r = requests.get(url, headers = headers)\n if r.status_code == 200:\n r.encoding = 'utf-8'\n return r.text\n return None","sub_path":"kuwospider/spiderdownloader.py","file_name":"spiderdownloader.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294650441","text":"\"\"\"\nSolutions to string manipulation problems\n\"\"\"\n\nimport string\nimport functools\nimport itertools\n\ndef is_palindromic(s):\n return all(s[i] == s[~i] for i in range(len(s)//2))\n\ndef int_to_string(x):\n is_negative = False\n if x < 0:\n x, is_negative = -x, True\n \n s = []\n while True:\n s.append(chr(ord('0') + x % 10))\n x //= 10\n if x == 0:\n break\n\n # adds negative sign back if is_negative\n return ('-' if is_negative else '') + ''.join(reversed(s))\n\ndef string_to_int(s):\n return functools.reduce(lambda running_sum, c :running_sum * 10 + string.digits.index(c),\n s[s[0] == '-':],0) * (-1 if s[0] == '-' else 1)\n\n\ndef convert_base(num_as_string, b1, b2):\n \"\"\"\n Covert a number given as a string from one base (b1) to another (b2)\n \"\"\"\n def construct_from_base(num_as_int, base):\n return ('' if num_as_int == 0 else\n construct_from_base(num_as_int // base, base) + \n string.hexdigits[num_as_int % base].upper())\n\n is_negative = num_as_string[0] == '-'\n num_as_int = functools.reduce(lambda x, c: x * b1 + string.hexdigits.index(c.lower()),\n num_as_string[is_negative:], 0)\n return ('-' if is_negative else '') + ('0' if num_as_int == 0 else \n construct_from_base(num_as_int, b2))\n\ndef look_and_say_pythonic(n):\n \"\"\"\n n is a number from 1 to max Integer\n \"\"\"\n s = '1'\n for _ in range(n - 1):\n s = ''.join(str(len(list(group))) + key for key, group in itertools.groupby(s))\n return s \n\ndef roman_to_integer(s):\n \"\"\"\n s is a string made up of roman numerals\n \"\"\"\n T = {'I' : 1, 'V' : 5, 'X': 10, 'L':50, 'C': 100, 'D': 500, 'M': 1000}\n\n return functools.reduce(\n lambda val, i: val + (-T[s[i]] if T[s[i]] < T[s[i + 1]] else T[s[i]]),\n reversed(range(len(s) - 1)), T[s[-1]])\n\ndef get_valid_ip_address(s):\n \"\"\"\n s is a string of integer digits from which all\n valid ip addresses will be generated\n \n e.g. 19216811 -> 192.168.1.1\n \"\"\"\n def is_valid_part(s):\n # '00', '000', '01', etc. are not valid, but '0' is valid.\n return len(s) == 1 or (s[0] != '0' and int(s) <= 255)\n result, parts = [], [None] * 4\n for i in range(1, min(4, len(s))):\n parts[0] = s[:i]\n if is_valid_part(parts[0]):\n for j in range(1, min(len(s) - i, 4)):\n parts[1] = s[i:i+j]\n if is_valid_part(parts[1]):\n for k in range(1, min(len(s) - i - j, 4)):\n parts[2], parts[3] = s[i + j:i + j + k],s[i + j + k:]\n if is_valid_part(parts[2]) and is_valid_part(parts[3]):\n result.append('.'.join(parts))\n return result\n\ndef rle_encoding(s):\n \"\"\"\n use run length encoding to compress string s\n \"\"\"\n return ''.join([str(len(list(g))) + str(e) for e, g in itertools.groupby(s)])\n\ndef rle_decoding(s):\n \"\"\"\n decode a string s encoded by rle_encoding(s)\n \"\"\"\n return ''.join([j*int(i) for i, j in zip(s[::2],s[1::2])]) \n\n\ndef rabin_karp(t, s):\n \"\"\"Rabin karp substring search\n \"\"\"\n\n if len(s) > len(t):\n return -1 # s is not a substring of t\n BASE = 26\n # Hash codes for the substring of t and s\n t_hash = functools.reduce(lambda h, c: h * BASE + ord(c), t[:len(s)], 0)\n s_hash = functools.reduce(lambda h, c: h * BASE + ord(c), s, 0)\n power_s = BASE**max(len(s)-1, 0)\n counter = 0\n\n for i in range(len(s), len(t)):\n # checks the two substrings are actually equal or not to protect\n # against hash collision\n if t_hash == s_hash and t[i - len(s):i] == s:\n return i - len(s) # found a match\n\n # uses rolling hash to compute the hash code\n t_hash -= ord(t[i - len(s)]) * power_s\n t_hash = t_hash * BASE + ord(t[i])\n counter += 1\n print(counter)\n \n # Tries to match s and t[-len(s):]\n if t_hash == s_hash and t[-len(s):] == s:\n return len(t) - len(s)\n counter += 1\n print(counter)\n return -1 # s is not a substring of t\n\nif __name__ == \"__main__\":\n t = 'aaaaaaaaaa'\n s = 'aaaaab'\n print(rabin_karp(t,s))\n","sub_path":"stringManipulation.py","file_name":"stringManipulation.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"407138275","text":"import sys\nimport pathlib\nimport argparse\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import describe\n\nfrom cmapPy.math import fast_corr\nfrom pycytominer.cyto_utils import infer_cp_features\n\nfrom util import diffuse_wells, load_args\n\n# Define command arguments\nargs = load_args()\n\ndata_dir = args.data_dir\noutput_dir = args.output_dir\nprofile_file = args.profile_file\ndiffusion = args.diffusion\nmirror = args.mirror\ndrop_same_position = args.drop_same_position\nl1000 = args.l1000\n\n# Load common compounds\ncommon_file = pathlib.Path(\n \"..\",\n \"..\",\n \"..\",\n \"6.paper_figures\",\n \"data\",\n \"significant_compounds_by_threshold_both_assays.tsv.gz\",\n)\ncommon_df = pd.read_csv(common_file, sep=\"\\t\")\n\ncommon_compounds = common_df.compound.unique()\n\n# Load profiles\nfull_profile_file = pathlib.Path(data_dir, profile_file)\nprofile_df = pd.read_csv(full_profile_file, compression=\"gzip\", low_memory=False)\n\n# Wrangle data differently depending on modality\nif l1000:\n assay = \"L1000\"\n features = profile_df.columns[profile_df.columns.str.contains(\"_at\")]\n\n # Extract out metadata information necessary for analysis\n metadata_plate_df = pd.DataFrame(\n [pd.Series(x) for x in profile_df.replicate_id.str.split(\":\")],\n )\n\n metadata_plate_df.columns = [\"plate\", \"well_position\"]\n metadata_plate_df = metadata_plate_df.assign(\n plate_map=metadata_plate_df.plate.str[:17]\n )\n\n # Make sure each plate only has one of the same well (no duplicates)\n assert (\n metadata_plate_df.drop_duplicates(subset=[\"plate\", \"well_position\"]).shape\n == metadata_plate_df.shape\n )\n\n profile_df = pd.concat([metadata_plate_df, profile_df], axis=\"columns\")\n\n all_well_positions = profile_df.well_position.unique()\n platemap_col_id = \"plate_map\"\n well_position_col_id = \"well_position\"\n\nelse:\n assay = \"CellPainting\"\n features = infer_cp_features(profile_df)\n all_well_positions = profile_df.Metadata_Well.unique()\n\n cp_platemap_file = \"https://github.com/broadinstitute/lincs-cell-painting/raw/e9737c3e4e4443eb03c2c278a145f12efe255756/metadata/platemaps/2016_04_01_a549_48hr_batch1/barcode_platemap.csv\"\n cp_meta_df = pd.read_csv(cp_platemap_file, sep=\",\")\n\n cp_meta_df.columns = [f\"Metadata_{x}\" for x in cp_meta_df.columns]\n\n profile_df = cp_meta_df.merge(\n profile_df,\n left_on=[\"Metadata_Assay_Plate_Barcode\"],\n right_on=\"Metadata_Plate\",\n how=\"right\",\n )\n\n platemap_col_id = \"Metadata_Plate_Map_Name\"\n well_position_col_id = \"Metadata_Well\"\n\n# Define diffusion sets, which inform which wells to use as non-replicates\ndiffusion_sets = diffuse_wells(\n all_well_positions,\n diffusion=diffusion,\n mirror=mirror,\n keep_same_position=~drop_same_position,\n)\n\n# Define output file\nprofile_file_id = profile_file.split(\".csv.gz\")[0]\noutput_summary_file = pathlib.Path(\n f\"{output_dir}/{profile_file_id}__non_replicate_correlation_diffusion{diffusion}_mirror{mirror}_dropsameposition{drop_same_position}_assay{assay}.tsv.gz\"\n)\n\n# Perform the full analysis and save summary statistics\nall_results = []\nfor well in profile_df.loc[:, well_position_col_id].unique():\n print(\n f\"Now analyzing well {well} with diffusion {diffusion} for file {profile_file_id}\"\n )\n subset_diffusion = diffusion_sets[well]\n\n for plate_map in profile_df.loc[:, platemap_col_id].unique():\n # Define the two matrices to calculate pairwise correlations between\n focus_df = profile_df.query(f\"{well_position_col_id} == @well\").query(\n f\"{platemap_col_id} == @plate_map\"\n )\n compare_df = profile_df.query(\n f\"{well_position_col_id} in @subset_diffusion\"\n ).query(f\"{platemap_col_id} != @plate_map\")\n\n # Get all non-replicate pairwise correlations\n distrib = fast_corr.fast_corr(\n focus_df.loc[:, features].transpose().values,\n compare_df.loc[:, features].transpose().values,\n ).flatten()\n\n if len(distrib) == 0:\n print(f\"well {well} on {plate_map} skipped. Missing data.\")\n continue\n\n med = np.median(distrib)\n\n result = (\n pd.DataFrame(describe(distrib))\n .transpose()\n .assign(\n median=med, cor_category=\"nonreplicate\", well=well, plate_map=plate_map\n )\n )\n\n all_results.append(result)\n\n # Get all replicate pairwise correlations\n pairwise_cor = fast_corr.fast_corr(focus_df.loc[:, features].transpose().values)\n\n pairwise_cor[np.tril_indices(pairwise_cor.shape[0])] = np.nan\n\n pairwise_cor = pairwise_cor.flatten()\n pairwise_cor = pairwise_cor[~np.isnan(pairwise_cor)]\n\n if len(pairwise_cor) == 0:\n print(f\"Replicates in {well} on {plate_map} skipped. Missing data.\")\n continue\n med = np.median(pairwise_cor)\n\n result = (\n pd.DataFrame(describe(pairwise_cor))\n .transpose()\n .assign(\n median=med, cor_category=\"replicate\", well=well, plate_map=plate_map\n )\n )\n\n all_results.append(result)\n\n# Compile and output results\nall_results_df = pd.concat(all_results).assign(assay=assay)\nall_results_df.columns = [\n \"num_observations\",\n \"min_max\",\n \"mean\",\n \"variance\",\n \"skewness\",\n \"kurtosis\",\n \"median\",\n \"cor_category\",\n \"well\",\n \"plate_map\",\n \"assay\",\n]\nall_results_df.to_csv(output_summary_file, index=False, sep=\"\\t\")\nprint(\"done.\\n\")\n","sub_path":"1.Data-exploration/Profiles_level4/plate_position_effects/characterize_plate_position.py","file_name":"characterize_plate_position.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119353183","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Bool\nfrom PID.msg import IntArr\nimport numpy as np #pylint ignore\nimport time\nimport signal\nimport sys\n\ndef target_callback(msg):\n global dtarget,dcycles\n dtarget = msg.ticks\n dcycles = msg.cycles\n rospy.loginfo(\"-_-_-_-_-_-_-_-_-_-_-_-_-_-\")\n\ndef break_callback(msg):\n global breakstate\n breakstate = msg.data\n\ndef p(x):\n A=0.6093\n B = 2.794\n C = 99.69\n a = 1\n b = 30.04\n c = 390\n d = 2080\n return ((A*x*x)+(B*x)+C)/((a*x*x*x)+(b*x*x)+(c*x)+d)\n\ndef setup():\n global dtarget,dval,dcycles,breakstate\n running = True\n dval =0\n dtarget=5\n dcycles=10000\n breakstate = False\n global realitypub,targetsub,breaksub\n realitypub = rospy.Publisher(\"/N1/reality\",IntArr)\n targetsub = rospy.Subscriber(\"/N1/target\",IntArr,target_callback)\n breaksub = rospy.Subscriber(\"/breakServo\",Bool,break_callback)\n rospy.init_node(\"dummy_leftteensy\",anonymous=False)\n rospy.loginfo(\"> succesfully initialised\")\n while running:\n if(not breakstate):\n if dcycles>0:\n dcycles-=1\n noise = np.random.randint(-2,2)\n dval = (8*dval+2*dtarget+noise)/10\n msg = IntArr()\n msg.ticks = dval\n msg.cycles = dcycles\n realitypub.publish(msg)\n rospy.loginfo(\"ticks: \"+str(msg.ticks)+ \" || cycles: \"+str(msg.cycles))\n else:\n rospy.loginfo(\"cycles empty\")\n else:\n rospy.loginfo(\"____breaking____\")\n time.sleep(0.01)\n\ndef signal_handler(signal, frame):\n sys.exit(0)\n\nsignal.signal(signal.SIGINT, signal_handler)\n\nif __name__ == \"__main__\":\n setup()","sub_path":"cdr_robot_ws/src/dummy_teensy/src/lapp.py","file_name":"lapp.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"178666834","text":"\r\n# CSC 475 Assignment 1\r\n# Written By: John Hawkins\r\n# Date: 10/2/14\r\n\r\nimport math\r\nimport random\r\nfrom NeuralNet import *\r\n\r\n# Define Global Constants & Functions here\r\n\r\nLEARNING_RATE = 0.5;\r\n\t\t\r\n# Start of Program\r\n\r\nrandom.seed();\r\n\r\n# Create the neural network input edges\r\nrw_edge = Edge(\"RW Edge\");\r\ncl_edge = Edge(\"CL Edge\");\r\nout_edge = Edge(\"Output Edge\");\r\n\r\n# Set up the neural network\r\nrw_edge.weight = 1.0;\r\ncl_edge.weight = 1.0;\r\n\r\np = Perceptron(\"Main Perceptron\");\r\np.addInput(rw_edge);\r\np.addInput(cl_edge);\r\np.addOutput(out_edge);\r\np.threshold = 0.0;\r\n\r\nfile = open(\"crabs.csv\", \"r\");\r\n\r\n# Skip header information in CSV file\r\nfile.readline();\r\n\r\n# Initialize Data lists\r\n# The attributes RW and CL were chosen based on the distance between genders when plotted\r\nrw_values = [];\r\ncl_values = [];\r\n\r\n# Gender is stored as 1.0 is male, 0.0 is female\r\ngenders = [];\r\n\r\n# Iterate over all lines the CSV file\r\n# Extract relevant attributes from the data\r\n# and the gender of the crabs for training\r\n\r\n# Statistics to compute mean and stdev\r\n# for input normalization\r\ncount = 0;\r\n\r\nrw_sum = 0.0;\r\ncl_sum = 0.0;\r\n\r\nrw_sum2 = 0.0;\r\ncl_sum2 = 0.0;\r\n\r\nwhile 1:\r\n\tline = file.readline();\r\n\tif not line:\r\n\t\tbreak;\r\n\tsplits = line.split(\",\");\r\n\t\r\n\trw = float(splits[5]);\r\n\tcl = float(splits[6]);\r\n\t\r\n\trw_values.append(rw);\r\n\tcl_values.append(cl);\r\n\tgenders.append(1.0 if \"M\" in splits[2] else 0.0);\r\n\t\t\r\n\tcount += 1.0;\r\n\trw_sum += rw;\r\n\tcl_sum += cl;\r\n\trw_sum2 += rw * rw;\r\n\tcl_sum2 += cl * cl;\r\n\t\r\nfile.close();\r\n\r\n#Compute means and stdevs\r\n\r\nrw_mean = rw_sum / count;\r\ncl_mean = cl_sum / count;\r\n\r\nrw_stdev = math.sqrt((count * rw_sum2 - rw_sum) / (count * (count - 1)));\r\ncl_stdev = math.sqrt((count * cl_sum2 - cl_sum) / (count * (count - 1)));\r\n\r\n# Normalize inputs\r\nfor i in range(0, len(rw_values)):\r\n\trw_values[i] -= rw_mean;\r\n\trw_values[i] /= rw_stdev;\r\n\tcl_values[i] -= cl_mean;\r\n\tcl_values[i] /= cl_stdev;\r\n\r\n# Iterate 10,000 (that's right, ten thousand times)\r\n# We gotta make this bad boy as accurate as possible\r\nfor num in range(0, 10000):\r\n\r\n\ti = random.randint(0,len(rw_values) - 1);\r\n\t\r\n\t# Feed the neural network the sample input values\r\n\trw_edge.setValue(rw_values[i]);\r\n\tcl_edge.setValue(cl_values[i]);\r\n\t\r\n\t# Read the output\r\n\tresult = out_edge.value;\r\n\t\r\n\t# Flip this flag or else the output of the neural network gets stuck\r\n\tout_edge.has_fired = False;\r\n\t\r\n\t# Update the weights of the neural network using error calculation\r\n\tp.updateWeights(genders[i], LEARNING_RATE);\r\n\r\n# For some unknown reason, the neural network gets trained backwards\r\n# e.g. it learns to guess wrong. Flipping the weights after training\r\n# resolves this issue\r\nrw_edge.weight *= -1.0;\r\ncl_edge.weight *= -1.0;\r\n\t\r\n# Initialize Confusion Matrix Variables\r\ntrue_pos = 0.0;\r\ntrue_neg = 0.0;\r\nfalse_pos = 0.0;\r\nfalse_neg = 0.0;\r\n\r\npositives = 0.0;\r\nnegatives = 0.0;\r\n\r\n# Gather Neural Net Confusion Matrix\r\nfor i in range(0, len(rw_values)):\r\n\r\n\t# Feed the neural network the sample input values\r\n\trw_edge.setValue(rw_values[i]);\r\n\tcl_edge.setValue(cl_values[i]);\r\n\t\r\n\t# Read the output\r\n\tresult = out_edge.value;\r\n\t\r\n\t# Flip this flag or else the output of the neural network gets stuck\r\n\tout_edge.has_fired = False;\r\n\t\r\n\tif genders[i] == 1.0:\r\n\t\tpositives += 1.0;\r\n\t\tif result == 1.0:\r\n\t\t\ttrue_pos += 1.0;\r\n\t\telse:\r\n\t\t\tfalse_neg += 1.0;\r\n\telse:\r\n\t\tnegatives += 1.0;\r\n\t\tif result == 1.0:\r\n\t\t\tfalse_pos += 1.0;\r\n\t\telse:\r\n\t\t\ttrue_neg += 1.0;\r\n\r\nprint(\"RW Weight: \" + str(rw_edge.weight));\r\nprint(\"CL Weight: \" + str(cl_edge.weight));\r\n\t\t\t\r\nprint(\"True Positive Rate: \" + str(true_pos / positives));\r\nprint(\"True Negative Rate: \" + str(true_neg / negatives));\r\nprint(\"False Positive Rate: \" + str(false_pos / negatives));\r\nprint(\"False Negative Rate: \" + str(false_neg / positives));\r\n\r\nprint(\"System Accuracy: \" + str((true_pos + true_neg) / (positives + negatives)));","sub_path":"Assignment1.py","file_name":"Assignment1.py","file_ext":"py","file_size_in_byte":3874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"591772775","text":"import sqlite3, uuid, sys, logging, time, os, json, zlib, hashlib, tempfile\n\nfrom util import mbtiles_connect, prettify_connect_string\n\nlogger = logging.getLogger(__name__)\n\n\ndef clean_mbtiles(mbtiles_file, **kwargs):\n\n result = True\n\n auto_commit = kwargs.get('auto_commit', False)\n journal_mode = kwargs.get('journal_mode', 'wal')\n synchronous_off = kwargs.get('synchronous_off', False)\n\n\n con = mbtiles_connect(mbtiles_file, auto_commit, journal_mode, synchronous_off, False, True)\n\n\n logger.info(\"Cleaning %s\" % (prettify_connect_string(con.connect_string)))\n\n con.delete_orphaned_images()\n\n con.close()\n\n return result\n","sub_path":"mbutil/util_clean.py","file_name":"util_clean.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"415721054","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport real_genetic_algorithm as realga\n\n\ndef fitnessfunction(ind):\n\n r = 10. # reference of 10 m/s\n m = 1000. # mass\n b = 50. # fricion coeff (depends on v)\n yp = 0. # initial reponse\n kp = ind[0] # 790 # proportional constant\n ki = ind[1] # 40 # integral constant\n kd = ind[2] # 0 # derivative term\n\n previous_error = 0.\n integral = 0.\n dt = 0.001\n\n yp_list = []\n time = []\n error = 0\n\n # control loop\n for i in range(20000):\n error = r - yp\n integral = integral + error*dt\n derivate = (error - previous_error)/dt\n u = kp*error + ki*integral + kd*derivate\n yp = yp + (-b*yp/m + u/m)*dt\n previous_error = error\n yp_list.append(yp)\n time.append(i)\n\n r_list = [r for x in range(len(yp_list))]\n\n plt.plot(time, r_list)\n plt.plot(time, yp_list)\n plt.show()\n\n return 1/(np.fabs(error)+1)\n\n\nif __name__ == '__main__':\n\n rga = realga.RealGA(100, 0.9, 0.1, fitnessfunction, 3, np.array([[700, 800], [0, 100], [0, 10]]), 123456789)\n # rga = realga.RealGA(100, 0.9, 0.1, fitnessfunction, 3, np.array([[0, 1000], [0, 1000], [0, 1000]]), 123456789)\n rga.run(generations=1000)\n\n #sol = np.array([980.25860368, 542.0651799, 242.29461194])\n #sol = [ 7.96449945e+02, 3.98253859e+01, 4.66307377e-01]\n #fitnessfunction(sol)\n","sub_path":"Aplicaciones/pid_controller.py","file_name":"pid_controller.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452464973","text":"#Draw 3 triangles\n #Draw 1 triangle\n #Print two spaces then *\n #Print one space then ***\n #Print *****\n #Repeat 2x\n\ndef drawTriangles():\n numberToDraw = int(input(\"Enter number of triangles: \"))\n for i in range (numberToDraw):\n print(\" *\\n\", \" ***\\n\", \"*****\")\n \ndrawTriangles()\n","sub_path":"print_triangles.py","file_name":"print_triangles.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"354604268","text":"import os\nimport time\nimport imp\nimport logging\nfrom flask import send_from_directory, abort, Response, request\nfrom emonitor.sockethandler import SocketHandler\nfrom emonitor.utils import Module\nfrom emonitor.extensions import classes, db, events, scheduler, babel, signal\nfrom emonitor.modules.settings.settings import Settings\nfrom .content_admin import getAdminContent, getAdminData\nfrom .content_frontend import getFrontendContent, getFrontendData\nfrom .alarmutils import AlarmFaxChecker, AlarmRemarkWidget, AlarmWidget, AlarmIncomeWidget, AlarmTimerWidget\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.ERROR)\n\n\nclass AlarmsModule(Module):\n \"\"\"\n Definition of alarms module with frontend, admin and widget area\n \"\"\"\n info = dict(area=['admin', 'frontend', 'widget'], messages=['add', 'info', 'activate', 'close'], name='alarms', path='alarms', icon='fa-fire', version='0.2')\n \n def __repr__(self):\n return \"alarms\"\n\n def __init__(self, app):\n \"\"\"\n Add specific parameters and configuration to app object\n\n :param app: flask wsgi application\n \"\"\"\n Module.__init__(self, app)\n # add template path\n app.jinja_loader.searchpath.append(\"%s/emonitor/modules/alarms/templates\" % app.config.get('PROJECT_ROOT'))\n\n # subnavigation\n self.adminsubnavigation = [('/admin/alarms', 'alarms.base'), ('/admin/alarms/types', 'module.alarms.types'), ('/admin/alarms/test', 'module.alarms.test')]\n \n # create database tables\n from .alarm import Alarm\n from .alarmhistory import AlarmHistory \n from .alarmattribute import AlarmAttribute\n from .alarmsection import AlarmSection\n from .alarmtype import AlarmType\n classes.add('alarm', Alarm)\n classes.add('alarmattribute', AlarmAttribute)\n classes.add('alarmhistory', AlarmHistory)\n classes.add('alarmsection', AlarmSection)\n classes.add('alarmtype', AlarmType)\n db.create_all()\n\n self.widgets = [AlarmIncomeWidget('alarms_income'), AlarmWidget('alarms'), AlarmTimerWidget('alarms_timer'), AlarmRemarkWidget('alarms_remark')]\n \n # eventhandlers\n for f in [f for f in os.listdir('%s/emonitor/modules/alarms/inc/' % app.config.get('PROJECT_ROOT')) if f.endswith('.py')]:\n if not f.startswith('__'):\n cls = imp.load_source('emonitor.modules.alarms.inc', 'emonitor/modules/alarms/inc/%s' % f)\n checker = getattr(cls, cls.__all__[0])()\n if isinstance(checker, AlarmFaxChecker) and checker.getId() != 'Dummy':\n events.addEvent('alarm_added.%s' % checker.getId(), handlers=[], parameters=['out.alarmid'])\n events.addEvent('alarm_changestate.%s' % checker.getId(), handlers=[], parameters=['out.alarmid', 'out.state'])\n\n events.addEvent('alarm_added', handlers=[], parameters=['out.alarmid']) # for all checkers\n events.addEvent('alarm_changestate', handlers=[], parameters=['out.alarmid', 'out.state']) # for all checkers\n \n events.addHandlerClass('file_added', 'emonitor.modules.alarms.alarm.Alarms', Alarm.handleEvent, ['in.text', 'out.id', 'out.fields'])\n events.addHandlerClass('file_added', 'emonitor.modules.alarms.alarmtype.AlarmTypes', AlarmType.handleEvent, ['in.text', 'out.type'])\n\n # signals and handlers\n signal.addSignal('alarm', 'changestate')\n signal.addSignal('alarm', 'added')\n signal.addSignal('alarm', 'updated')\n signal.connect('alarm', 'changestate', frontendAlarmHandler.handleAlarmChanges)\n signal.connect('alarm', 'added', frontendAlarmHandler.handleAlarmChanges)\n signal.connect('alarm', 'updated', frontendAlarmHandler.handleAlarmChanges)\n signal.connect('alarm', 'deleted', frontendAlarmHandler.handleAlarmChanges)\n\n signal.connect('alarm', 'testupload_start', adminAlarmHandler.handleAlarmTestUpload)\n\n # static folders\n @app.route('/alarms/inc/')\n def alarms_static(filename):\n return send_from_directory(\"%s/emonitor/modules/alarms/inc/\" % app.config.get('PROJECT_ROOT'), filename)\n\n @app.route('/alarms/export/') # filename = [id]-[style].pdf\n def export_static(filename):\n filename, extension = os.path.splitext(filename)\n id, template = filename.split('-')\n if extension not in ['.pdf', '.html', '.png']:\n abort(404)\n elif extension == '.pdf':\n return Response(Module.getPdf(Alarm.getExportData('.html', id=id, style=template, args=request.args)), mimetype=\"application/pdf\")\n elif extension == '.html':\n return Response(Alarm.getExportData(extension, id=id, style=template, args=request.args), mimetype=\"text/html\")\n elif extension == '.png':\n return Response(Alarm.getExportData(extension, id=id, style=template, filename=filename, args=request.args), mimetype=\"image/png\")\n \n # translations\n babel.gettext(u'module.alarms')\n babel.gettext(u'alarms.base')\n babel.gettext(u'module.alarms.types')\n babel.gettext(u'module.alarms.test')\n babel.gettext(u'alarms_income')\n babel.gettext(u'alarms_timer')\n babel.gettext(u'alarms_remark')\n babel.gettext(u'alarms')\n babel.gettext(u'alarms.prio0')\n babel.gettext(u'alarms.prio1')\n babel.gettext(u'alarms.prio2')\n babel.gettext(u'emonitor.modules.alarms.alarm.Alarms')\n babel.gettext(u'emonitor.modules.alarms.alarmtype.AlarmTypes')\n babel.gettext(u'alarms.test.protocol')\n babel.gettext(u'alarms.test.result')\n babel.gettext(u'alarmstate.active')\n babel.gettext(u'alarmstate.created')\n babel.gettext(u'alarmstate.done')\n babel.gettext(u'alarmstate.archive')\n babel.gettext(u'active')\n babel.gettext(u'created')\n babel.gettext(u'done')\n babel.gettext(u'archive')\n babel.gettext(u'alarms.statechangeactivated')\n babel.gettext(u'alarms.prioshort0')\n babel.gettext(u'alarms.prioshort1')\n babel.gettext(u'alarms.prioshort2')\n babel.gettext(u'alarms.carsinuse')\n babel.gettext(u'history.autochangeState')\n babel.gettext(u'history.message')\n babel.gettext(u'trigger.alarm_added')\n babel.gettext(u'trigger.alarm_changestate')\n\n babel.gettext(u'trigger.alarm_added_sub')\n babel.gettext(u'trigger.alarm_changestate_sub')\n\n babel.gettext(u'alarms.print.slightleft')\n babel.gettext(u'alarms.print.slightright')\n babel.gettext(u'alarms.print.right')\n babel.gettext(u'alarms.print.left')\n babel.gettext(u'alarms.print.straight')\n babel.gettext(u'alarms.print.exit')\n babel.gettext(u'alarms.print.bus')\n babel.gettext(u'alarms.print.positive')\n babel.gettext(u'alarms.print.negative')\n\n babel.gettext(u'alarms.filter.0')\n babel.gettext(u'alarms.filter.1')\n babel.gettext(u'alarms.filter.7')\n babel.gettext(u'alarms.filter.31')\n\n # init\n # Do init script for alarms at start and add active alarms (state = 1)\n #from modules.alarms.alarm import Alarm\n #from core.extensions import classes, scheduler, events\n aalarms = classes.get('alarm').getActiveAlarms() # get last active alarm\n \n if aalarms: # add active alarm and closing time\n try:\n for aalarm in aalarms:\n scheduler.add_job(events.raiseEvent, args=['alarm_added', dict({'alarmid': aalarm.id})])\n closingtime = time.mktime(aalarm.timestamp.timetuple()) + float(Settings.get('alarms.autoclose', 1800))\n\n if closingtime > time.time(): # add close event\n scheduler.add_job(Alarm.changeState, args=[aalarm.id, 2])\n else:\n scheduler.add_job(Alarm.changeState, args=[aalarm.id, 2])\n except:\n logger.exception('error in aalarm')\n\n def frontendContent(self):\n return 1\n\n def getAdminContent(self, **params):\n \"\"\"\n Call *getAdminContent* of alarms class\n\n :param params: send given parameters to :py:class:`emonitor.modules.alarms.content_admin.getAdminContent`\n \"\"\"\n return getAdminContent(self, **params)\n\n def getAdminData(self):\n \"\"\"\n Call *getAdminData* method of alarms class and return values\n\n :return: return result of method\n \"\"\"\n return getAdminData(self)\n\n def getFrontendContent(self, **params):\n \"\"\"\n Call *getFrontendContent* of alarms class\n\n :param params: send given parameters to :py:class:`emonitor.modules.alarms.content_frontend.getFrontendContent`\n \"\"\"\n return getFrontendContent(**params)\n \n def getFrontendData(self):\n \"\"\"\n Call *getFrontendData* of alarms class\n \"\"\"\n return getFrontendData(self)\n\n\nclass frontendAlarmHandler(SocketHandler):\n \"\"\"\n Handler class for frontend socked events of alarms\n \"\"\"\n @staticmethod\n def handleAlarmChanges(sender, **extra):\n \"\"\"\n Implementation of changes in alarm states\n\n :param sender: event sender\n :param extra: extra parameters for event\n \"\"\"\n SocketHandler.send_message(sender, **extra)\n\n\nclass adminAlarmHandler(SocketHandler):\n \"\"\"\n Handler class for admin socked events of alarms\n \"\"\"\n @staticmethod\n def handleAlarmTestUpload(sender, **extra):\n \"\"\"\n Implementation of test upload of alarm files\n\n :param sender: event sender\n :param extra: extra parameters for event\n \"\"\"\n SocketHandler.send_message(extra)\n","sub_path":"emonitor/modules/alarms/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"626070171","text":"\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport pandas as pd\n\n\ndef getHtmlText(url): # 爬取网络\n\n try:\n r = requests.get(url, timeout=30)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n return \"爬取失败!\"\ndef fillUlist(ulist, html): # 解析网络信息\n soup = BeautifulSoup(html, 'html.parser')\n for tr in soup.find('tbody').children:\n tds = tr('td')\n ulist.append([tds[0].text, tds[1].text, tds[2].text])\ndef printUlist(ulist, num): # 输出结果\n with open('爬取结果.txt','w',encoding='utf-8') as f:\n for i in range(num):\n u = ulist[i]\n print(\"{:^4}\\t{:^20}\\t{:^10}\".format(u[0], u[1], u[2], chr(12288)))\n f.write(\"{}\\t{}\\t{}\\n\".format(u[0], u[1], u[2], chr(12288)))\n\ndef sortedU(file):\n with open(file, 'r', encoding='utf-8') as f:\n content = f.readlines()\n\n f=open('强制排序.csv','w',encoding='utf-8-sig',newline='')\n writer=csv.writer(f)\n writer.writerow(['排名','大学','国家'])\n for n in range(1,len(content)):\n _,name,area=content[n].split('\\t')\n writer.writerow([n,name,area.replace('\\n','')])\n f.close()\n\ndef calU(file):\n data=pd.read_csv(file)\n\n data.groupby('国家').size().sort_values(ascending=False).to_csv('各国大学数量统计.csv',encoding='utf-8-sig')\n\n rank=[]\n for country,colleges in data.groupby('国家'):\n rank.append([country,colleges.shape[0],colleges['排名'].mean(),colleges.shape[0]*colleges['排名'].mean()])\n\n rank=pd.DataFrame(rank,columns=['国家','大学数量','大学排名均值','rank'])\n rank.sort_values('rank',ascending=False).to_csv('国家教育质量排名.csv',index=None,encoding='utf-8-sig')\n\n\n\n\nif __name__ == \"__main__\":\n ulist = []\n url = \"https://www.dxsbb.com/news/42613.html\"\n html = getHtmlText(url)\n fillUlist(ulist, html)\n printUlist(ulist, 1003)\n sortedU(file='爬取结果.txt')\n calU(file='强制排序.csv')","sub_path":"job/玛卡瑞纳-作业-爬大学排名,分析/作业.py","file_name":"作业.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"108648310","text":"# coding:utf-8\n\"\"\"\n@company: qwgas\n@author: kris\n@usage: 日志工具类和日志装饰器类\n@created: 2019/10/18\n\"\"\"\nimport logging\nimport time\nimport os\nfrom app import app\n\n\nclass Logger:\n def __init__(self, logger, cmd_level=logging.INFO, file_level=logging.DEBUG):\n try:\n self.logger = logging.getLogger(logger)\n self.logger.setLevel(file_level)\n fmt = logging.Formatter('%(asctime)s - [%(levelname)s] %(message)s')\n current_time = time.strftime('%Y-%m-%d')\n\n log_dir = app.config.get('LOG_DIR')\n\n if not os.path.exists(log_dir):\n os.mkdir(log_dir)\n self.LogFileName = os.path.join(log_dir, current_time + '.log')\n fh = logging.FileHandler(self.LogFileName)\n fh.setFormatter(fmt)\n fh.setLevel(file_level)\n self.logger.addHandler(fh)\n sh = logging.StreamHandler()\n sh.setLevel(cmd_level)\n self.logger.addHandler(sh)\n except Exception as e:\n raise e\n\n\n# logger = Logger(__name__, cmd_level=logging.INFO, file_level=logging.INFO)\n\n\n# 打印日志装饰器\n# 目前只支持作为函数装饰器,对类的方法装饰无效\n'''\nclass setlog(object):\n def __init__(self, func):\n self.__func = func\n\n def __call__(self, *args, **kwargs):\n try:\n start = time.time()\n logger.logger.debug('args参数: %s | kwargs参数: %s' % (args, kwargs))\n f = self.__func(*args, **kwargs)\n end = time.time()\n duration = (end - start) * 1000\n logger.logger.info('调用[%s]成功,耗时: %.2fms' % (self.__func.__name__, duration))\n return f\n\n except Exception as e:\n logger.logger.error('调用[%s]失败!' % self.__func.__name__)\n logger.logger.error(e)\n raise e\n'''","sub_path":"app/utils/logging_utils.py","file_name":"logging_utils.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"551700694","text":"import dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table\nfrom dash.dependencies import Input, Output, State\nimport plotly\nimport plotly.graph_objs as go\nfrom db import getEngine,db_execute,db_fetchone,db_fetchall\nfrom datetime import datetime as dt\nimport requests\nfrom app import app\n\n# https://dash.plotly.com/datatable/reference\n# Satellites\ninstrument_map = dict(\n AMAZONIA1 = ['WFI'],\n\t\tCBERS4A = ['MUX','WFI','WPM'],\n\t\tCBERS4 = ['MUX','AWFI','PAN5M','PAN10M'],\n\t\tCBERS2B = ['CCD','WFI','HRC'],\n\t\tLANDSAT1 = ['MSS'],\n\t\tLANDSAT2 = ['MSS'],\n\t\tLANDSAT3 = ['MSS'],\n\t\tLANDSAT5 = ['TM'],\n\t\tLANDSAT7 = ['ETM'],\n\t\t)\nband_map = dict(\n\t\tMUX = ['nir','red','green','blue'],\n\t\tAWFI = ['nir','red','green','blue'],\n\t\tWFI = ['nir','red','green','blue'],\n\t\tWPM = ['nir','red','green','blue','pan'],\n\t\tPAN10M = ['nir','red','green'],\n\t\tPAN5M = ['pan'],\n\t\tCCD = ['nir'],\n\t\tMSS = ['nir'],\n\t\tTM = ['nir'],\n\t\tETM = ['nir'],\n\t\t)\n############ Operation ##############\n# Operation Utilities\ndef get_start_date():\n\tsql = 'SELECT MIN(launch) as start_date FROM Activities'\n\tresult = db_fetchone(sql,db='operation')\n\tprint('get_start_date - result',result)\n\tif result is not None and result[0] is not None:\n\t\tstart_date = result[0].strftime(\"%Y-%m-%d\")\n\telse:\n\t\tstart_date = dt.now().strftime(\"%Y-%m-%d\")\n\tprint('get_start_date - result',result,'start_date',start_date)\n\treturn start_date\n# Layouts\n# Processing Parameters\ndf = [\n\tdict(id='SATELLITE_DROPDOWN',parameter= 'Satellite', type='dropdown',options=list(instrument_map.keys()),default=0),\n\tdict(id='INSTRUMENT_DROPDOWN',parameter= 'Instrument', type='dropdown',options=[]),\n\tdict(id='PATH_INPUT',parameter= 'Path', type='input',options=[]),\n\tdict(id='ROW_INPUT',parameter= 'Row', type='input',options=[]),\n\tdict(id='PERIOD_DATERANGE',parameter= 'Period', type='daterange',options=[],default=dt.now().strftime(\"%Y-%m-%d\")),\n\tdict(id='LEVEL_DROPDOWN',parameter= 'Level', type='checklist',options=['2','2B','4']),\n\tdict(id='RADIOMETRIC_CHECKLIST',parameter= 'Radiometry', type='checklist',options=['DN','SR'],default=[0]),\n\tdict(id='PROCESSING_DROPDOWN',parameter= 'Action', type='dropdown',options=['Publish','Unzip'],default=0)\n\n]\n\ndef renderTable(df):\n# Header\n\tcolumns = [('Parameter',100),('Value',200)]\n\tthead = html.Thead(html.Tr([html.Th(col[0],style={\"text-align\":\"center\",\"border\":\"2px black solid\",\"width\":\"{}px\".format(col[1])}) for col in columns]))\n\ttable_rows = list()\n\tfor i in range(len(df)):\n\t\trow = []\n\t\tprint(df[i])\n\t\tparameter = df[i]['parameter']\n\t\ttd = html.Td(parameter,style={\"text-align\":\"center\",\"border\":\"1px black solid\"})\n\t\trow.append(td)\n\t\tcp = ''\n\t\tif df[i]['type'] == 'dropdown':\n\t\t\toptions = []\n\t\t\tfor option in df[i]['options']:\n\t\t\t\toptions.append({'label':option, 'value':option})\n\t\t\t\t\n\t\t\tdefault = df[i]['options'][df[i]['default']] if 'default' in df[i] and len(df[i]['options']) > 0 else None\n\t\t\tcp = html.Div(\n\t\t\tchildren=[\n\t\t\t\tdcc.Dropdown(\n\t\t\t\t\tid=df[i]['id'],\n\t\t\t\t\toptions=options,\n\t\t\t\t\tvalue=default,\n\t\t\t\t\tstyle=dict(width='100%', display='inline-block',verticalAlign=\"middle\")\n\t\t\t\t),\n\t\t\t],\n\t\t\tid=df[i]['id']+'_DIV'\n\t\t\t)\n\t\telif df[i]['type'] == 'daterange':\n\t\t\tdefault = df[i]['default'] if 'default' in df[i] else None\n\t\t\tcp = html.Div(\n\t\t\tchildren=[\n\t\t\t\tdcc.DatePickerRange(\n\t\t\t\t\tid=df[i]['id'],\n\t\t\t\t\tdisplay_format='YYYY-MM-DD',\n\t\t\t\t\tend_date=default,\n\t\t\t\t\twith_portal=True,\n\t\t\t\t\tstart_date_placeholder_text='YYYY-MM-DD',\n\t\t\t\t\tminimum_nights=0\n\t\t\t\t)\n\t\t\t],\n\t\t\tstyle={'margin-bottom': '1px','margin-left': '0px','margin-right': '0px', 'width': '100%','padding': '0'},\n\t\t\tid=df[i]['id']+'_DIV'\n\t\t\t)\n\t\telif df[i]['type'] == 'input':\n\t\t\tdefault = df[i]['default'] if 'default' in df[i] else None\n\t\t\tcp = dcc.Input(\n\t\t\t\tid=df[i]['id'],\n\t\t\t\ttype='text',\n\t\t\t\tvalue=default,\n\t\t\t\tplaceholder=\"Enter {}\".format(df[i]['parameter'])\n\t\t\t)\n\t\telif df[i]['type'] == 'checklist':\n\t\t\toptions = []\n\t\t\tfor option in df[i]['options']:\n\t\t\t\toptions.append({'label':option, 'value':option})\n\t\t\tdefault = []\n\t\t\tif 'default' in df[i]:\n\t\t\t\tfor j in df[i]['default']:\n\t\t\t\t\tdefault.append(options[j]['value'])\n\n\t\t\tcp = dcc.Checklist(\n\t\t\t\tid=df[i]['id'],\n\t\t\t\toptions=options,\n\t\t\t\tvalue=default,\n\t\t\t\tlabelStyle={'display': 'inline-block'} if len(df[i]['options'][0]) < 3 else None\n\t\t\t)\n\t\t\t\n\t\ttd = html.Td(cp,style={\"border\": \"1px black solid\" , \"margin-left\": \"0px\"})\n\t\trow.append(td)\n\t\ttable_rows.append(html.Tr(row,style={\"height\":\"1px\"}))\n\ttbody = html.Tbody(children=table_rows)\n\ttable = html.Table(children=[thead, tbody], id='my-table', className='row', style={\"border\":\"3px black solid\"})\n\treturn table\n\ndef renderDatePicker(sd):\n\tprint('renderDatePicker now {}'.format(dt.now().strftime(\"%Y-%m-%d\")))\n\tdp = dcc.DatePickerSingle( \n\t\tid='TASKS_date', \n\t\tplaceholder='Enter a start date...', \n\t\tdisplay_format='YYYY-MM-DD', \n\t\tmin_date_allowed=sd, \n\t\t#max_date_allowed=dt.now().strftime(\"%Y-%m-%d\"), \n\t\tinitial_visible_month=sd, \n\t\tdate=str(sd))\n\treturn dp\n\ncolumns = ['Task','Dataset','LAUNCHED','STARTED','FINISHED','ERROR','Max','Avg','Min']\nlayout = html.Div(\n\t\t[\n\t\t\thtml.Div(\n\t\t\t\t[\n\t\t\t\t\thtml.H4('Operation',style={'display': 'flex', 'justify-content': 'left'}),\n\t\t\t\t],\n\t\t\t\tstyle={'width': '100%', 'display': 'flex', 'align-items': 'center', 'justify-content': 'left'}\n\t\t\t),\n\t\t\thtml.Div(\n\t\t\t\t[\n\t\t\t\t\trenderTable(df),\n\t\t\t\t\thtml.Button('Submit', id='submit-val', n_clicks=0),\n\t\t\t\t\thtml.Div(id='container-button-basic',children='Press submit')\n\t\t\t\t],\n \t\t\t\tclassName='five columns'\n \t\t\t),\n\t\t\thtml.Div(\n\t\t\t\t[\n\t\t\t\t\thtml.Div(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\thtml.Label('Start Date'),\n\t\t\t\t\t\t\trenderDatePicker(get_start_date())\n\t\t\t\t\t\t],\n\t\t\t\t\t\tstyle={'width': '100%', 'display': 'flex', 'align-items': 'center', 'justify-content': 'center'}\n\t\t\t\t\t),\n\t\t\t\t\thtml.Div(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tdcc.Graph(id='TASKS_bargraph', animate=True),\n\t\t\t\t\t\t\tdcc.Interval(id='TASKS_interval', interval=10*1000)\n\t\t\t\t\t\t],\n\t\t\t\t\t\tstyle={'width': '100%', 'display': 'flex', 'align-items': 'center', 'justify-content': 'center'}\n\t\t\t\t\t),\n\t\t\t\t\thtml.Div(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\thtml.Br(),\n\t\t\t\t\t\t\thtml.Label('Operation Statistics',style={\"font-weight\": \"bold\"}),\n\t\t\t\t\t\t],\n\t\t\t\t\t\tstyle={'width': '100%', 'display': 'flex', 'align-items': 'center', 'justify-content': 'center'}\n\t\t\t\t\t\t),\n\t\t\t\t\thtml.Div(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tdash_table.DataTable(\n\t\t\t\t\t\t\t\tid='TASKS_datatable',\n\t\t\t\t\t\t\t\tstyle_header={\n \t\t\t\t\t\t\t'backgroundColor': 'rgb(230, 230, 230)',\n \t\t\t\t\t\t\t'textAlign': 'center',\n \t\t\t\t\t\t\t'fontWeight': 'bold',\n \t\t\t\t\t\t\t'width': '100%'\n \t\t\t\t\t\t\t},\n \t\t\t\t\t\t\tstyle_cell={'textAlign': 'right'},\n\t\t\t\t\t\t\t\tstyle_cell_conditional=[\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t'if': {'column_id': 'Task'},\n\t\t\t\t\t\t\t\t\t'textAlign': 'left'\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tcolumns=[{\"name\": i, \"id\": i, \"deletable\": False, \"selectable\": False} for i in columns],\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t],\n\t\t\t\t\t\tstyle={'marginLeft': 0, 'marginRight': 0, 'marginTop': 0, 'marginBottom': 0,'width': '100%', 'display': 'flex', 'align-items': 'center', 'justify-content': 'center'}\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\tclassName='five columns'\n\t\t\t)\n\t\t])\n\n# Operation Callbacks\n\n####################################\n@app.callback(Output('INSTRUMENT_DROPDOWN_DIV', 'children'),\n\t\t\t[Input('SATELLITE_DROPDOWN', 'value')])\ndef update_instrument(sat):\n\tinstrument_options = [{'label': 'All', 'value': 'All'}]\n\tfor inst in instrument_map[sat]:\n\t\tinstrument_options.append({'label': inst, 'value': inst})\n\tcp = dcc.Dropdown(\n\t\tid='INSTRUMENT_DROPDOWN',\n\t\toptions=instrument_options,\n\t\tvalue=instrument_options[0]['value'],\n\t\tstyle=dict(width='100%', display='inline-block',verticalAlign=\"middle\")\n\t)\n\treturn cp\n\n###################################\n@app.callback(Output('BAND_DROPDOWN_DIV', 'children'),\n\t\t\t[Input('INSTRUMENT_DROPDOWN', 'value')])\ndef update_band(inst):\n\tband_options = []\n\tif inst is None or inst == 'All':\n\t\tband_options.append({'label': 'nir', 'value': 'nir'})\n\telse:\n\t\tfor band in band_map[inst]:\n\t\t\tband_options.append({'label': band, 'value': band})\n\tprint('update_band - inst {} band_options {}'.format(inst,band_options))\n\tcp = dcc.Dropdown(\n\t\tid='BAND_DROPDOWN',\n\t\toptions=band_options,\n\t\tvalue=band_options[0]['value'],\n\t\tstyle=dict(width='100%', display='inline-block',verticalAlign=\"middle\")\n\t)\n\treturn cp\n\n#####################################\n@app.callback(Output('container-button-basic', 'children'),\n\t[Input('submit-val', 'n_clicks')],\n\t[\n\tState('SATELLITE_DROPDOWN', 'value'),\n\tState('INSTRUMENT_DROPDOWN', 'value'),\n\tState('PATH_INPUT', 'value'),\n\tState('ROW_INPUT', 'value'),\n\tState('PERIOD_DATERANGE', 'start_date'),\n\tState('PERIOD_DATERANGE', 'end_date'),\n\tState('LEVEL_DROPDOWN', 'value'),\n\tState('RADIOMETRIC_CHECKLIST', 'value'),\n\tState('PROCESSING_DROPDOWN', 'value')\n\t])\ndef submit(n_clicks, sat, inst,path,row,start_date,end_date,level,rp,action):\n\tprint('submit - sat {} inst {} clicked {} times'.format(sat,inst,n_clicks))\n\tif n_clicks == 0:\n\t\treturn 'Just started'\n\tkeyval = {}\n\tflags = ''\n\tquery = 'http://inpe_cdsr_publisher_api:5000/'\n\n\tkeyval['sat'] = sat\n\n# Only register an specific instrument\n\tif inst is not None and inst != 'All':\n\t\tkeyval['inst'] = inst\n\n# Path and Row\n\tif path is not None and path != '':\n\t\tkeyval['path'] = path\n\tif row is not None and row != '':\n\t\tkeyval['row'] = row\n\n# Period\n\tif start_date is not None:\n\t\tkeyval['start_date'] = start_date\n\tif end_date is not None:\n\t\tkeyval['end_date'] = end_date\n\n# Only register an specific level, if None or both, dont register\n\tif level is not None and len(level) == 1:\n\t\tkeyval['level'] = level[0]\n\n# Only register an specific radiometric processing, if None or both, dont register\n\tif rp is not None and len(rp) == 1:\n\t\tkeyval['rp'] = rp[0]\n\n# action publish may have positioning as a flag\n\tif 'Publish' in action:\n\t\tquery += 'publish?'\n\t\tif 'Positioning' in action:\n\t\t\tflags += '&positioning'\n\telif 'Positioning' in action:\n\t\tquery += 'positioning?'\n\telif 'Registering' in action:\n\t\tquery += 'registering?'\n\telif 'Upload' in action:\n\t\tquery += 'upload?'\n\telif 'Unzip' in action:\n\t\tquery += 'unzip?'\n\telse:\n\t\treturn 'Please choose an action'\n\n# Build the query\n\tfor key,val in keyval.items():\n\t\tquery += '{}={}&'.format(key,val)\n\tquery = query[:-1]\n\tquery += flags\n\n\tr = requests.get(query)\n\n\tprint('query: {}\\n r.text: {}'.format(query, r.text))\n\treturn 'query: {}\\n r.text: {}'.format(query, r.text)\n\n#####################################\n@app.callback([Output('TASKS_bargraph', 'figure'),\n\t\t\tOutput('TASKS_datatable', 'data')],\n\t\t\t[Input('TASKS_date', 'date'),\n\t\t\tInput('TASKS_interval', 'n_intervals')])\ndef update_graph_scatter(start_date,input_data):\n\t#print('update_graph_scatter - start_date',start_date,'input_data',input_data)\n\tsql = \"SELECT task,dataset,MAX(elapsed) as maxe,AVG(elapsed) as avg ,MIN(elapsed) as mine FROM Activities WHERE launch >= '{}' AND status='FINISHED' AND elapsed > 0 GROUP BY task,dataset\".format(start_date)\n\tresult = db_fetchall(sql,db='operation')\n\t#print(result)\n# Fill the data graph\n\tsql = \"SELECT task,status,count(*) as amount FROM Activities WHERE launch >= '{}' GROUP BY task,status ORDER BY task\".format(start_date)\n\tresult = db_fetchall(sql,db='operation')\n\tstatuscolor = dict(\n\t\tERROR = \"rgb(255, 0, 0)\",\n\t\tFINISHED = \"rgb(0, 0, 255)\",\n\t\tSTARTED = \"rgb(0, 255, 0)\",\n\t\tLAUNCHED = \"rgb(127, 127, 0)\",\n\t)\n\tdata_graph = {}\n\tmaxy = 0\n\n\tif result is None:\n\t\treturn None, None\n\n\tfor i in result:\n\t\ttask = i[0]\n\t\tstatus = i[1]\n\t\tamount = i[2]\n\t\tmaxy = max(maxy,amount)\n\t\tif status not in data_graph:\n\t\t\tdata_graph[status] = {'x':[task],'y':[amount],'type': 'bar', 'name': status}\n\t\telse:\n\t\t\tdata_graph[status]['x'].append(task)\n\t\t\tdata_graph[status]['y'].append(amount)\n\tdata_graph_list = [go.Bar(x=data_graph[i]['x'],y=data_graph[i]['y'],name=data_graph[i]['name'],marker_color=statuscolor[i]) for i in data_graph]\n\n# Fill the data table\n\tsql = \"SELECT task,dataset,status,count(*) as amount FROM Activities WHERE launch >= '{}' GROUP BY task,dataset,status ORDER BY task,dataset\".format(start_date)\n\tsql = \"SELECT task,dataset,status,count(*) as amount,MAX(elapsed) as maxe,AVG(elapsed) as avg ,MIN(elapsed) as mine FROM Activities WHERE launch >= '{}' GROUP BY task,dataset,status ORDER BY dataset,task\".format(start_date)\n\n\t#print('update_graph_scatter - sql {}'.format(sql))\n\n\tresult = db_fetchall(sql,db='operation')\n\n\t#print('update_graph_scatter - result {}'.format(result))\n\n\tdata_table_list = []\n\tfor i in result:\n\t\tdata_table = {}\n\t\ttask = i[0]\n\t\tdataset = i[1]\n\t\tstatus = i[2]\n\t\tamount = i[3]\n\t\tmaxe = i[4]\n\t\tavge = i[5]\n\t\tmine = i[6]\n\t\tdata_table['Task'] = task\n\t\tdata_table['Dataset'] = dataset\n\t\tdata_table[status] = amount\n\t\tdata_table['Max'] = maxe\n\t\tdata_table['Avg'] = int(avge) if avge is not None else None\n\t\tdata_table['Min'] = mine\n\n\t\t#print('update_graph_scatter - data_table {}'.format(data_table))\n\n\t\tdata_table_list.append(data_table)\n\n\treturn {'data': data_graph_list,'layout' : go.Layout(title='Number of Tasks per Status',yaxis=dict(range=[0,maxy]),)},data_table_list\n","sub_path":"operation/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":12916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"389707833","text":"'''\n/*문제 정보 */\n5557번 - 1학년\n난이도 - 골드 5\n/*풀이 방법 */\nhttps://ddiyeon.tistory.com/59\n코드 리뷰 했습니다.\ndp 테이블의 구성을 가로를 0 ~ 20, 세로를 수식의 숫자를 순서대로 설정.\n각 줄 마다 각 숫자를 더하거나 뺀 숫자의 경우의 수를 다음 줄에 저장.\n각줄에 저장된 숫자의 의미는 i번 째 숫자까지 계산해 j를 만들 수 있는 경우의 수.\n'''\nN = int(input())\n\nnums = list(map(int, input().split()))\n\ndp = [[0]*21 for i in range(N-1)]\ndp[0][nums[0]] = 1\n\nfor i in range(1, N-1):\n for j in range(21):\n # 뺐을 때, 0보다 작지 않을 때\n if j-nums[i]>=0: dp[i][j-nums[i]] += dp[i-1][j]\n # 더했을 때, 20보다 크지 않을 때\n if j+nums[i]<=20: dp[i][j+nums[i]] += dp[i-1][j]\nprint(dp[-1][nums[-1]])\n\n'''\n/*오답 노트*/\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nl = list(map(int, input().split()))\nanswer = l[-1]\ndel l[-1]\nsum = l[0]\n\ncount = 0\n\nfor i in range(1,len(l)):\n if sum >= l[i]:\n \n누가봐도 1차원으로 풀 수 없을 거 같아서..... 포기 했습니다...\n/*느낀 점*/\n2차원 배열되면 생각보다 너무 어렵게 느껴진다... \n'''","sub_path":"season2/season2/week7/sunghoon/5557.py","file_name":"5557.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"560313995","text":"#!/usr/bin/env python3\n# 演示测试效果\n# 输入: query 一张图片\n# 输出: gallery 中选出的图片\n# @wieSeele :3\n\nimport numpy as np\nimport os\nimport os.path as osp\nimport matplotlib.pyplot as plt\nimport pickle\nimport argparse\nfrom PIL import Image\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import precision_recall_curve\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import DataParallel\nimport shutil\n\nfrom aligned_reid.dataset import create_dataset\nfrom aligned_reid.model.Model import Model\nfrom aligned_reid.utils.utils import str2bool\nfrom aligned_reid.utils.utils import load_state_dict\nfrom aligned_reid.utils.utils import load_ckpt\nfrom aligned_reid.utils.utils import set_devices\nfrom aligned_reid.utils.utils import measure_time\nfrom aligned_reid.utils.re_ranking import re_ranking\nfrom aligned_reid.utils.distance import compute_dist\nfrom aligned_reid.utils.distance import low_memory_matrix_op\nfrom aligned_reid.utils.distance import local_dist\n\n\ndef save_typical(test_set, q_name, g_names, save_path):\n \"\"\"根据图像名称找到原始图像,并将索引的图像保存起来\"\"\"\n im_path = osp.join(test_set.im_dir, q_name)\n img = Image.open(im_path)\n save_path = save_path + q_name[:-4] + '/'\n if not osp.exists(save_path):\n os.makedirs(save_path)\n img.save(save_path + '0_' + q_name)\n for name in g_names:\n im_path = osp.join(test_set.im_dir, name)\n img = Image.open(im_path)\n img.save(save_path + name)\n\n\ndef save_min_distance(dataset, num_query, distmat, path, max_distance = 0.2):\n if osp.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)\n for i in range(num_query):\n path_image = dataset.im_names[i]\n name_image = osp.basename(path_image)\n path_target = osp.join(path, ('%04d_query_' % i) + name_image)\n shutil.copy(path_image, path_target)\n for i, dists in enumerate(distmat):\n for j, dist in enumerate(dists):\n if dist <= max_distance:\n path_image = dataset.im_names[num_query + j]\n name_image = osp.basename(path_image)\n path_target = osp.join(path, ('%04d_gallery_%.4f_' % (i, dist)) + name_image)\n shutil.copy(path_image, path_target)\n\n\ndef save_top_k(dataset, num_query, indices, path, k = 5):\n if osp.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)\n\n for i in range(num_query):\n path_image = dataset.im_names[i]\n name_image = osp.basename(path_image)\n path_target = osp.join(path, ('%04d_query_' % i) + name_image)\n shutil.copy(path_image, path_target)\n for i, ranks in enumerate(indices):\n for j in range(k):\n # print(ranks)\n # print(dataset.im_names)\n path_image = dataset.im_names[num_query + int(ranks[j])]\n name_image = osp.basename(path_image)\n path_target = osp.join(path, ('%04d_gallery_%d_' % (i, j)) + name_image)\n shutil.copy(path_image, path_target)\n\n\ndef exp_summary(test_set):\n # 1. extract features\n with measure_time('Extracting feature...'):\n global_feats, local_feats, im_names, marks = test_set.extract_feat(normalize_feat = True)\n # 2. build q-g-distmat, q_ids, g_ids, q_cams, g_cams, q_idx, g_idx\n q_inds = marks == 0\n g_inds = marks == 1\n mq_inds = marks == 2\n\n ###########################\n # A helper function just for avoiding code duplication.\n def low_memory_local_dist(x, y):\n with measure_time('Computing local distance...'):\n x_num_splits = int(len(x) / 200) + 1\n y_num_splits = int(len(y) / 200) + 1\n z = low_memory_matrix_op(\n local_dist, x, y, 0, 0, x_num_splits, y_num_splits, verbose = True)\n return z\n\n ###################\n # Global Distance #\n ###################\n # query-gallery distance using global distance\n global_q_g_dist = compute_dist(global_feats[q_inds], global_feats[g_inds], type = 'euclidean')\n # query-query distance using global distance\n global_q_q_dist = compute_dist(global_feats[q_inds], global_feats[q_inds], type = 'euclidean')\n # gallery-gallery distance using global distance\n global_g_g_dist = compute_dist(global_feats[g_inds], global_feats[g_inds], type = 'euclidean')\n\n ##################\n # Local Distance #\n ##################\n # query-gallery distance using local distance\n local_q_g_dist = low_memory_local_dist(local_feats[q_inds], local_feats[g_inds])\n # query-query distance using local distance\n local_q_q_dist = low_memory_local_dist(local_feats[q_inds], local_feats[q_inds])\n # gallery-gallery distance using local distance\n local_g_g_dist = low_memory_local_dist(local_feats[g_inds], local_feats[g_inds])\n\n #########################\n # Global+Local Distance #\n #########################\n global_local_q_g_dist = global_q_g_dist + local_q_g_dist\n global_local_q_q_dist = global_q_q_dist + local_q_q_dist\n global_local_g_g_dist = global_g_g_dist + local_g_g_dist\n\n #########################\n # Re_Ranking #\n #########################\n # re-ranked query-gallery distance\n re_r_global_q_g_dist = re_ranking(global_q_g_dist, global_q_q_dist, global_g_g_dist)\n re_r_global_local_q_g_dist = re_ranking(re_r_global_q_g_dist, local_q_q_dist, local_g_g_dist)\n\n # re_r_global_local_q_g_dist = re_ranking(global_local_q_g_dist, global_local_q_q_dist, global_local_g_g_dist)\n\n ###########################\n\n # distmat = compute_dist(\n # global_feats[q_inds], global_feats[g_inds], type = 'euclidean')\n distmat = re_r_global_local_q_g_dist\n numaxis = np.arange(len(q_inds))\n q_idx = numaxis[q_inds]\n g_idx = numaxis[g_inds]\n\n indices = np.argsort(distmat, axis = 1)\n num_query = len(q_idx)\n # print(distmat, indices)\n save_top_k(test_set, num_query, indices, path = 'result_5', k = 5)\n save_min_distance(test_set, num_query, distmat, path = 'result_0.2', max_distance = 0.3)\n # print(numaxis,q_idx,g_idx)\n\n\nclass ExtractFeature(object):\n \"\"\"A function to be called in the val/test set, to extract features.\n Args:\n TVT: A callable to transfer images to specific device.\n \"\"\"\n\n def __init__(self, model, TVT):\n self.model = model\n self.TVT = TVT\n\n def __call__(self, ims):\n old_train_eval_model = self.model.training\n # Set eval mode.\n # Force all BN layers to use global mean and variance, also disable\n # dropout.\n self.model.eval()\n ims = Variable(self.TVT(torch.from_numpy(ims).float()))\n global_feat, local_feat = self.model(ims)[:2]\n global_feat = global_feat.data.cpu().numpy()\n local_feat = local_feat.data.cpu().numpy()\n # Restore the model to its old train/eval mode.\n self.model.train(old_train_eval_model)\n return global_feat, local_feat\n\n\ndef main():\n # name_data = '20180525184611494'\n name_data = '20180717103311494'\n\n TVT, TMO = set_devices((0,))\n\n dataset_kwargs = dict(\n name = name_data,\n resize_h_w = (256, 128),\n scale = True,\n im_mean = [0.486, 0.459, 0.408],\n im_std = [0.229, 0.224, 0.225],\n batch_dims = 'NCHW',\n num_prefetch_threads = 1)\n test_set_kwargs = dict(\n part = 'val',\n batch_size = 32,\n final_batch = True,\n shuffle = False,\n mirror_type = ['random', 'always', None][2],\n prng = np.random)\n test_set_kwargs.update(dataset_kwargs)\n test_set = create_dataset(**test_set_kwargs)\n\n with measure_time('Load model'):\n model = Model(local_conv_out_channels = 128,\n num_classes = 1000)\n model_w = DataParallel(model)\n optimizer = optim.Adam(model.parameters(),\n lr = 2e-4,\n weight_decay = 0.0005)\n modules_optims = [model, optimizer]\n with measure_time('Load checkpoint'):\n load_ckpt(modules_optims, 'ckpt.pth')\n\n test_set.set_feat_func(ExtractFeature(model_w, TVT))\n\n exp_summary(test_set)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"demo-180710.py","file_name":"demo-180710.py","file_ext":"py","file_size_in_byte":8252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"190066999","text":"# coding: utf-8\nfrom datetime import datetime\nfrom ._base import db\n\n\nclass Team(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n avatar = db.Column(db.String(200))\n qrcode = db.Column(db.String(200))\n name = db.Column(db.String(50), unique=True)\n created_at = db.Column(db.DateTime, default=datetime.now)\n\n def __repr__(self):\n return '' % self.name\n\n\nclass UserTeam(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.now)\n\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n user = db.relationship('User', backref=db.backref('teams',\n lazy='dynamic',\n order_by='desc(UserTeam.created_at)'))\n\n team_id = db.Column(db.Integer, db.ForeignKey('team.id'))\n team = db.relationship('Team', backref=db.backref('users',\n lazy='dynamic',\n order_by='desc(UserTeam.created_at)'))\n","sub_path":"application/models/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"480605661","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: C:\\Projects\\GitHub\\AeroSandbox\\aerosandbox\\aerodynamics\\vlm2.py\n# Compiled at: 2019-08-07 12:55:29\n# Size of source mod 2**32: 56928 bytes\nfrom .aerodynamics import *\n\nclass vlm2(AeroProblem):\n\n def run(self, verbose=True):\n self.verbose = verbose\n print('DEPRECATION WARNING: VLM2 has been wholly eclipsed in performance and functionality by VLM3. The VLM2 source code has been left intact for validation purposes and backwards-compatibility, but it will not be supported going forward.')\n if self.verbose:\n print('Running VLM2 calculation...')\n self.make_panels()\n self.setup_geometry()\n self.setup_operating_point()\n self.calculate_vortex_strengths()\n self.calculate_forces()\n if self.verbose:\n print('VLM2 calculation complete!')\n\n def run_stability(self, verbose=True):\n self.verbose = verbose\n\n def make_panels(self):\n if self.verbose:\n print('Meshing...')\n self.mcl_coordinates_structured_list = []\n self.normals_structured_list = []\n for wing_num in range(len(self.airplane.wings)):\n wing = self.airplane.wings[wing_num]\n n_chordwise_coordinates = wing.chordwise_panels + 1\n if wing.chordwise_spacing == 'uniform':\n nondim_chordwise_coordinates = np.linspace(0, 1, n_chordwise_coordinates)\n elif wing.chordwise_spacing == 'cosine':\n nondim_chordwise_coordinates = cosspace(0, 1, n_chordwise_coordinates)\n else:\n raise Exception('Bad value of wing.chordwise_spacing!')\n xsec_xyz_le = np.empty((0, 3))\n xsec_xyz_te = np.empty((0, 3))\n for xsec in wing.xsecs:\n xsec_xyz_le = np.vstack((xsec_xyz_le, xsec.xyz_le + wing.xyz_le))\n xsec_xyz_te = np.vstack((xsec_xyz_te, xsec.xyz_te() + wing.xyz_le))\n\n xsec_xyz_quarter_chords = 0.75 * xsec_xyz_le + 0.25 * xsec_xyz_te\n section_quarter_chords = xsec_xyz_quarter_chords[1:, :] - xsec_xyz_quarter_chords[:-1, :]\n section_quarter_chords_proj = section_quarter_chords[:, 1:] / np.expand_dims(np.linalg.norm((section_quarter_chords[:, 1:]), axis=1), axis=1)\n section_quarter_chords_proj = np.hstack((\n np.zeros((section_quarter_chords_proj.shape[0], 1)), section_quarter_chords_proj))\n if len(wing.xsecs) > 2:\n xsec_local_normal_inners = section_quarter_chords_proj[:-1, :] + section_quarter_chords_proj[1:, :]\n xsec_local_normal_inners = xsec_local_normal_inners / np.expand_dims(np.linalg.norm(xsec_local_normal_inners, axis=1), axis=1)\n xsec_local_normal = np.vstack((\n section_quarter_chords_proj[0, :],\n xsec_local_normal_inners,\n section_quarter_chords_proj[-1, :]))\n else:\n xsec_local_normal = np.vstack((\n section_quarter_chords_proj[0, :],\n section_quarter_chords_proj[-1, :]))\n xsec_local_back = xsec_xyz_te - xsec_xyz_le\n xsec_chord = np.linalg.norm(xsec_local_back, axis=1)\n xsec_local_back = xsec_local_back / np.expand_dims(xsec_chord, axis=1)\n xsec_local_up = np.cross(xsec_local_back, xsec_local_normal, axis=1)\n xsec_scaling_factor = 1 / np.sqrt((1 + np.sum((section_quarter_chords_proj[1:, :] * section_quarter_chords_proj[:-1, :]),\n axis=1)) / 2)\n xsec_scaling_factor = np.hstack((1, xsec_scaling_factor, 1))\n xsec_camber = np.empty((n_chordwise_coordinates, 0))\n for xsec in wing.xsecs:\n camber = xsec.airfoil.get_camber_at_chord_fraction(nondim_chordwise_coordinates)\n camber = np.expand_dims(camber, axis=1)\n xsec_camber = np.hstack((xsec_camber, camber))\n\n xsec_mcl_coordinates = xsec_xyz_le + xsec_local_back * np.expand_dims(xsec_chord, axis=2) * np.expand_dims(np.expand_dims(nondim_chordwise_coordinates, 1), 2) + xsec_local_up * np.expand_dims((xsec_chord * xsec_scaling_factor), axis=2) * np.expand_dims(xsec_camber, 2)\n wing_mcl_coordinates = np.empty((n_chordwise_coordinates, 0, 3))\n for section_num in range(len(wing.xsecs) - 1):\n xsec = wing.xsecs[section_num]\n n_spanwise_coordinates = xsec.spanwise_panels + 1\n if xsec.spanwise_spacing == 'uniform':\n nondim_spanwise_coordinates = np.linspace(0, 1, n_spanwise_coordinates)\n elif xsec.spanwise_spacing == 'cosine':\n nondim_spanwise_coordinates = cosspace(n_points=n_spanwise_coordinates)\n else:\n raise Exception('Bad value of section.spanwise_spacing!')\n is_last_section = section_num == len(wing.xsecs) - 2\n if not is_last_section:\n nondim_spanwise_coordinates = nondim_spanwise_coordinates[:-1]\n section_mcl_coordinates = np.expand_dims(1 - nondim_spanwise_coordinates, 2) * np.expand_dims(xsec_mcl_coordinates[:, section_num, :], 1) + np.expand_dims(nondim_spanwise_coordinates, 2) * np.expand_dims(xsec_mcl_coordinates[:, section_num + 1, :], 1)\n wing_mcl_coordinates = np.hstack((wing_mcl_coordinates, section_mcl_coordinates))\n\n self.mcl_coordinates_structured_list.append(wing_mcl_coordinates)\n if wing.symmetric:\n wing_mcl_coordinates_sym = reflect_over_XZ_plane(wing_mcl_coordinates)\n wing_mcl_coordinates_sym = np.fliplr(wing_mcl_coordinates_sym)\n self.mcl_coordinates_structured_list.append(wing_mcl_coordinates_sym)\n nondim_xsec_normals = np.empty((\n wing.chordwise_panels, 0, 2))\n nondim_collocation_coordinates = 0.25 * nondim_chordwise_coordinates[:-1] + 0.75 * nondim_chordwise_coordinates[1:]\n for xsec in wing.xsecs:\n nondim_normals = xsec.airfoil.get_mcl_normal_direction_at_chord_fraction(nondim_collocation_coordinates)\n nondim_normals = np.expand_dims(nondim_normals, 1)\n nondim_xsec_normals = np.hstack((nondim_xsec_normals, nondim_normals))\n\n wing_normals = np.empty((wing.chordwise_panels, 0, 3))\n for section_num in range(len(wing.xsecs) - 1):\n xsec = wing.xsecs[section_num]\n n_spanwise_coordinates = xsec.spanwise_panels + 1\n if xsec.spanwise_spacing == 'uniform':\n nondim_spanwise_coordinates = np.linspace(0, 1, n_spanwise_coordinates)\n elif xsec.spanwise_spacing == 'cosine':\n nondim_spanwise_coordinates = cosspace(n_points=n_spanwise_coordinates)\n else:\n raise Exception('Bad value of section.spanwise_spacing!')\n is_last_section = section_num == len(wing.xsecs) - 2\n nondim_spanwise_coordinates = (nondim_spanwise_coordinates[1:] + nondim_spanwise_coordinates[:-1]) / 2\n inner_xsec_back = xsec_local_back[section_num]\n outer_xsec_back = xsec_local_back[(section_num + 1)]\n section_normal = section_quarter_chords_proj[section_num]\n inner_xsec_up = np.cross(inner_xsec_back, section_normal)\n outer_xsec_up = np.cross(outer_xsec_back, section_normal)\n control_surface_hinge_point_index = np.interp(x=(xsec.control_surface_hinge_point),\n xp=nondim_collocation_coordinates,\n fp=(np.arange(wing.chordwise_panels)))\n deflection_angle = xsec.control_surface_deflection\n rot_matrix = angle_axis_rotation_matrix(angle=(np.radians(deflection_angle)),\n axis=section_normal,\n axis_already_normalized=True)\n inner_xsec_back_rotated = np.matmul(rot_matrix, inner_xsec_back)\n outer_xsec_back_rotated = np.matmul(rot_matrix, outer_xsec_back)\n inner_xsec_up_rotated = np.matmul(rot_matrix, inner_xsec_up)\n outer_xsec_up_rotated = np.matmul(rot_matrix, outer_xsec_up)\n if control_surface_hinge_point_index <= 0:\n inner_xsec_backs = inner_xsec_back_rotated * np.ones((wing.chordwise_panels, 3))\n outer_xsec_backs = outer_xsec_back_rotated * np.ones((wing.chordwise_panels, 3))\n inner_xsec_ups = inner_xsec_up_rotated * np.ones((wing.chordwise_panels, 3))\n outer_xsec_ups = outer_xsec_up_rotated * np.ones((wing.chordwise_panels, 3))\n elif control_surface_hinge_point_index >= wing.chordwise_panels:\n inner_xsec_backs = inner_xsec_back * np.ones((wing.chordwise_panels, 3))\n outer_xsec_backs = outer_xsec_back * np.ones((wing.chordwise_panels, 3))\n inner_xsec_ups = inner_xsec_up * np.ones((wing.chordwise_panels, 3))\n outer_xsec_ups = outer_xsec_up * np.ones((wing.chordwise_panels, 3))\n else:\n last_unmodified_index = np.int(np.floor(control_surface_hinge_point_index))\n fraction_to_modify = 1 - (control_surface_hinge_point_index - last_unmodified_index)\n rot_matrix = angle_axis_rotation_matrix(angle=(np.radians(xsec.control_surface_deflection * fraction_to_modify)),\n axis=section_normal,\n axis_already_normalized=True)\n inner_xsec_back_semirotated = np.matmul(rot_matrix, inner_xsec_back)\n outer_xsec_back_semirotated = np.matmul(rot_matrix, outer_xsec_back)\n inner_xsec_up_semirotated = np.matmul(rot_matrix, inner_xsec_up)\n outer_xsec_up_semirotated = np.matmul(rot_matrix, outer_xsec_up)\n inner_xsec_backs = np.vstack((\n np.tile(inner_xsec_back, reps=(last_unmodified_index, 1)),\n inner_xsec_back_semirotated,\n np.tile(inner_xsec_back_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n inner_xsec_ups = np.vstack((\n np.tile(inner_xsec_up, reps=(last_unmodified_index, 1)),\n inner_xsec_up_semirotated,\n np.tile(inner_xsec_up_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n outer_xsec_backs = np.vstack((\n np.tile(outer_xsec_back, reps=(last_unmodified_index, 1)),\n outer_xsec_back_semirotated,\n np.tile(outer_xsec_back_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n outer_xsec_ups = np.vstack((\n np.tile(outer_xsec_up, reps=(last_unmodified_index, 1)),\n outer_xsec_up_semirotated,\n np.tile(outer_xsec_up_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n inner_xsec_normals = np.expand_dims(nondim_xsec_normals[:, section_num, 0], 1) * inner_xsec_backs + np.expand_dims(nondim_xsec_normals[:, section_num, 1], 1) * inner_xsec_ups\n outer_xsec_normals = np.expand_dims(nondim_xsec_normals[:, section_num + 1, 0], 1) * outer_xsec_backs + np.expand_dims(nondim_xsec_normals[:, section_num + 1, 1], 1) * outer_xsec_ups\n section_normals = np.expand_dims(1 - nondim_spanwise_coordinates, 2) * np.expand_dims(inner_xsec_normals, 1) + np.expand_dims(nondim_spanwise_coordinates, 2) * np.expand_dims(outer_xsec_normals, 1)\n section_normals = section_normals / np.expand_dims(np.linalg.norm(section_normals, axis=2), 2)\n wing_normals = np.hstack((wing_normals, section_normals))\n\n self.normals_structured_list.append(wing_normals)\n if wing.symmetric:\n if wing.has_symmetric_control_surfaces():\n self.normals_structured_list.append(np.fliplr(reflect_over_XZ_plane(wing_normals)))\n else:\n wing_normals = np.empty((wing.chordwise_panels, 0, 3))\n for section_num in range(len(wing.xsecs) - 1):\n xsec = wing.xsecs[section_num]\n n_spanwise_coordinates = xsec.spanwise_panels + 1\n if xsec.spanwise_spacing == 'uniform':\n nondim_spanwise_coordinates = np.linspace(0, 1, n_spanwise_coordinates)\n elif xsec.spanwise_spacing == 'cosine':\n nondim_spanwise_coordinates = cosspace(n_points=n_spanwise_coordinates)\n else:\n raise Exception('Bad value of section.spanwise_spacing!')\n is_last_section = section_num == len(wing.xsecs) - 2\n nondim_spanwise_coordinates = (nondim_spanwise_coordinates[1:] + nondim_spanwise_coordinates[:-1]) / 2\n inner_xsec_back = xsec_local_back[section_num]\n outer_xsec_back = xsec_local_back[(section_num + 1)]\n section_normal = section_quarter_chords_proj[section_num]\n inner_xsec_up = np.cross(inner_xsec_back, section_normal)\n outer_xsec_up = np.cross(outer_xsec_back, section_normal)\n control_surface_hinge_point_index = np.interp(x=(xsec.control_surface_hinge_point),\n xp=nondim_collocation_coordinates,\n fp=(np.arange(wing.chordwise_panels)))\n deflection_angle = xsec.control_surface_deflection\n if xsec.control_surface_type == 'asymmetric':\n deflection_angle = -deflection_angle\n else:\n rot_matrix = angle_axis_rotation_matrix(angle=(np.radians(deflection_angle)),\n axis=section_normal,\n axis_already_normalized=True)\n inner_xsec_back_rotated = np.matmul(rot_matrix, inner_xsec_back)\n outer_xsec_back_rotated = np.matmul(rot_matrix, outer_xsec_back)\n inner_xsec_up_rotated = np.matmul(rot_matrix, inner_xsec_up)\n outer_xsec_up_rotated = np.matmul(rot_matrix, outer_xsec_up)\n if control_surface_hinge_point_index <= 0:\n inner_xsec_backs = inner_xsec_back_rotated * np.ones((wing.chordwise_panels, 3))\n outer_xsec_backs = outer_xsec_back_rotated * np.ones((wing.chordwise_panels, 3))\n inner_xsec_ups = inner_xsec_up_rotated * np.ones((wing.chordwise_panels, 3))\n outer_xsec_ups = outer_xsec_up_rotated * np.ones((wing.chordwise_panels, 3))\n elif control_surface_hinge_point_index >= wing.chordwise_panels:\n inner_xsec_backs = inner_xsec_back * np.ones((wing.chordwise_panels, 3))\n outer_xsec_backs = outer_xsec_back * np.ones((wing.chordwise_panels, 3))\n inner_xsec_ups = inner_xsec_up * np.ones((wing.chordwise_panels, 3))\n outer_xsec_ups = outer_xsec_up * np.ones((wing.chordwise_panels, 3))\n else:\n last_unmodified_index = np.int(np.floor(control_surface_hinge_point_index))\n fraction_to_modify = 1 - (control_surface_hinge_point_index - last_unmodified_index)\n rot_matrix = angle_axis_rotation_matrix(angle=(np.radians(xsec.control_surface_deflection * fraction_to_modify)),\n axis=section_normal,\n axis_already_normalized=True)\n inner_xsec_back_semirotated = np.matmul(rot_matrix, inner_xsec_back)\n outer_xsec_back_semirotated = np.matmul(rot_matrix, outer_xsec_back)\n inner_xsec_up_semirotated = np.matmul(rot_matrix, inner_xsec_up)\n outer_xsec_up_semirotated = np.matmul(rot_matrix, outer_xsec_up)\n inner_xsec_backs = np.vstack((\n np.tile(inner_xsec_back, reps=(last_unmodified_index, 1)),\n inner_xsec_back_semirotated,\n np.tile(inner_xsec_back_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n inner_xsec_ups = np.vstack((\n np.tile(inner_xsec_up, reps=(last_unmodified_index, 1)),\n inner_xsec_up_semirotated,\n np.tile(inner_xsec_up_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n outer_xsec_backs = np.vstack((\n np.tile(outer_xsec_back, reps=(last_unmodified_index, 1)),\n outer_xsec_back_semirotated,\n np.tile(outer_xsec_back_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n outer_xsec_ups = np.vstack((\n np.tile(outer_xsec_up, reps=(last_unmodified_index, 1)),\n outer_xsec_up_semirotated,\n np.tile(outer_xsec_up_rotated, reps=(\n wing.chordwise_panels - last_unmodified_index - 1, 1))))\n inner_xsec_normals = np.expand_dims(nondim_xsec_normals[:, section_num, 0], 1) * inner_xsec_backs + np.expand_dims(nondim_xsec_normals[:, section_num, 1], 1) * inner_xsec_ups\n outer_xsec_normals = np.expand_dims(nondim_xsec_normals[:, section_num + 1, 0], 1) * outer_xsec_backs + np.expand_dims(nondim_xsec_normals[:, section_num + 1, 1], 1) * outer_xsec_ups\n section_normals = np.expand_dims(1 - nondim_spanwise_coordinates, 2) * np.expand_dims(inner_xsec_normals, 1) + np.expand_dims(nondim_spanwise_coordinates, 2) * np.expand_dims(outer_xsec_normals, 1)\n section_normals = section_normals / np.expand_dims(np.linalg.norm(section_normals, axis=2), 2)\n wing_normals = np.hstack((wing_normals, section_normals))\n\n self.normals_structured_list.append(np.flip((reflect_over_XZ_plane(wing_normals)), axis=1))\n\n if self.verbose:\n print('Meshing complete!')\n self.n_wings = len(self.mcl_coordinates_structured_list)\n self.front_left_vertices_list = []\n self.front_right_vertices_list = []\n self.back_left_vertices_list = []\n self.back_right_vertices_list = []\n self.vortex_left_list = []\n self.vortex_right_list = []\n self.collocations_list = []\n self.normals_list = []\n for wing_num in range(self.n_wings):\n wing_front_left_vertices = self.mcl_coordinates_structured_list[wing_num][:-1, :-1, :]\n wing_front_right_vertices = self.mcl_coordinates_structured_list[wing_num][:-1, 1:, :]\n wing_back_left_vertices = self.mcl_coordinates_structured_list[wing_num][1:, :-1, :]\n wing_back_right_vertices = self.mcl_coordinates_structured_list[wing_num][1:, 1:, :]\n self.front_left_vertices_list.append(np.reshape(wing_front_left_vertices, (-1,\n 3)))\n self.front_right_vertices_list.append(np.reshape(wing_front_right_vertices, (-1,\n 3)))\n self.back_left_vertices_list.append(np.reshape(wing_back_left_vertices, (-1,\n 3)))\n self.back_right_vertices_list.append(np.reshape(wing_back_right_vertices, (-1,\n 3)))\n self.collocations_list.append(np.reshape(0.5 * (0.25 * wing_front_left_vertices + 0.75 * wing_back_left_vertices) + 0.5 * (0.25 * wing_front_right_vertices + 0.75 * wing_back_right_vertices), (-1,\n 3)))\n self.vortex_left_list.append(np.reshape(0.75 * wing_front_left_vertices + 0.25 * wing_back_left_vertices, (-1,\n 3)))\n self.vortex_right_list.append(np.reshape(0.75 * wing_front_right_vertices + 0.25 * wing_back_right_vertices, (-1,\n 3)))\n self.normals_list.append(np.reshape(self.normals_structured_list[wing_num], (-1,\n 3)))\n\n self.front_left_vertices_unrolled = np.vstack(self.front_left_vertices_list)\n self.front_right_vertices_unrolled = np.vstack(self.front_right_vertices_list)\n self.back_left_vertices_unrolled = np.vstack(self.back_left_vertices_list)\n self.back_right_vertices_unrolled = np.vstack(self.back_right_vertices_list)\n self.collocations_unrolled = np.vstack(self.collocations_list)\n self.vortex_left_unrolled = np.vstack(self.vortex_left_list)\n self.vortex_right_unrolled = np.vstack(self.vortex_right_list)\n self.vortex_centers_unrolled = (self.vortex_left_unrolled + self.vortex_right_unrolled) / 2\n self.normals_unrolled = np.vstack(self.normals_list)\n self.n_panels = len(self.normals_unrolled)\n\n def setup_geometry(self):\n if self.verbose:\n print('Calculating the collocation influence matrix...')\n self.Vij_collocations = self.calculate_Vij(self.collocations_unrolled)\n normals_expanded = np.expand_dims(self.normals_unrolled, 1)\n self.AIC = np.sum((self.Vij_collocations * normals_expanded),\n axis=2)\n if self.verbose:\n print('Calculating the vortex center influence matrix...')\n self.Vij_centers = self.calculate_Vij(self.vortex_centers_unrolled)\n\n def setup_operating_point(self):\n if self.verbose:\n print('Calculating the freestream influence...')\n self.steady_freestream_velocity = self.op_point.compute_freestream_velocity_geometry_axes() * np.ones((\n self.n_panels, 1))\n self.rotation_freestream_velocities = self.op_point.compute_rotation_velocity_geometry_axes(self.collocations_unrolled)\n self.freestream_velocities = self.steady_freestream_velocity + self.rotation_freestream_velocities\n self.freestream_influences = np.sum((self.freestream_velocities * self.normals_unrolled), axis=1)\n\n def calculate_vortex_strengths(self):\n if self.verbose:\n print('Calculating vortex strengths...')\n self.vortex_strengths = np.linalg.solve(self.AIC, -self.freestream_influences)\n\n def calculate_forces(self):\n if self.verbose:\n print('Calculating forces on each panel...')\n else:\n Vi_x = self.Vij_centers[:, :, 0] @ self.vortex_strengths + self.freestream_velocities[:, 0]\n Vi_y = self.Vij_centers[:, :, 1] @ self.vortex_strengths + self.freestream_velocities[:, 1]\n Vi_z = self.Vij_centers[:, :, 2] @ self.vortex_strengths + self.freestream_velocities[:, 2]\n Vi_x = np.expand_dims(Vi_x, axis=1)\n Vi_y = np.expand_dims(Vi_y, axis=1)\n Vi_z = np.expand_dims(Vi_z, axis=1)\n Vi = np.hstack((Vi_x, Vi_y, Vi_z))\n li_pieces = []\n for wing_num in range(self.n_wings):\n wing_mcl_coordinates = self.mcl_coordinates_structured_list[wing_num]\n wing_vortex_points = 0.75 * wing_mcl_coordinates[:-1, :, :] + 0.25 * wing_mcl_coordinates[1:, :, :]\n li_piece = wing_vortex_points[:, 1:, :] - wing_vortex_points[:, :-1, :]\n li_piece = np.reshape(li_piece, (-1, 3))\n li_pieces.append(li_piece)\n\n self.li = np.vstack(li_pieces)\n density = self.op_point.density\n Vi_cross_li = np.cross(Vi, (self.li), axis=1)\n vortex_strengths_expanded = np.expand_dims((self.vortex_strengths), axis=1)\n self.Fi_geometry = density * Vi_cross_li * vortex_strengths_expanded\n if self.verbose:\n print('Calculating total forces and moments...')\n self.Ftotal_geometry = np.sum((self.Fi_geometry), axis=0)\n self.Ftotal_wind = np.transpose(self.op_point.compute_rotation_matrix_wind_to_geometry()) @ self.Ftotal_geometry\n self.Mtotal_geometry = np.sum((np.cross(self.vortex_centers_unrolled - self.airplane.xyz_ref, self.Fi_geometry)), axis=0)\n self.Mtotal_wind = np.transpose(self.op_point.compute_rotation_matrix_wind_to_geometry()) @ self.Mtotal_geometry\n q = self.op_point.dynamic_pressure()\n s_ref = self.airplane.s_ref\n b_ref = self.airplane.b_ref\n c_ref = self.airplane.c_ref\n self.CL = -self.Ftotal_wind[2] / q / s_ref\n self.CDi = -self.Ftotal_wind[0] / q / s_ref\n self.CY = self.Ftotal_wind[1] / q / s_ref\n self.Cl = self.Mtotal_wind[0] / q / b_ref\n self.Cm = self.Mtotal_wind[1] / q / c_ref\n self.Cn = self.Mtotal_wind[2] / q / b_ref\n if self.CDi == 0:\n self.CL_over_CDi = 0\n else:\n self.CL_over_CDi = self.CL / self.CDi\n if self.verbose:\n print('\\nForces\\n-----')\n if self.verbose:\n print('CL: ', self.CL)\n if self.verbose:\n print('CDi: ', self.CDi)\n if self.verbose:\n print('CY: ', self.CY)\n if self.verbose:\n print('CL/CDi: ', self.CL_over_CDi)\n if self.verbose:\n print('\\nMoments\\n-----')\n if self.verbose:\n print('Cl: ', self.Cl)\n if self.verbose:\n print('Cm: ', self.Cm)\n if self.verbose:\n print('Cn: ', self.Cn)\n\n def calculate_Vij_wing_by_wing(self, points):\n points = np.reshape(points, (-1, 3))\n n_points = len(points)\n Vij_pieces = []\n for wing_num in range(self.n_wings):\n wing_mcl_coordinates = self.mcl_coordinates_structured_list[wing_num]\n wing_vortex_points = 0.75 * wing_mcl_coordinates[:-1, :, :] + 0.25 * wing_mcl_coordinates[1:, :, :]\n wing_ab = np.expand_dims(np.expand_dims(points, 1), 2) - wing_vortex_points\n wing_ab_shape = wing_ab.shape\n wing_ab_cross_x = np.stack((\n np.zeros((n_points, wing_ab_shape[1], wing_ab_shape[2])),\n wing_ab[:, :, :, 2],\n -wing_ab[:, :, :, 1]),\n axis=3)\n wing_ab_dot_x = wing_ab[:, :, :, 0]\n wing_a_cross_b = np.cross((wing_ab[:, :, :-1, :]),\n (wing_ab[:, :, 1:, :]),\n axis=3)\n wing_a_dot_b = np.einsum('ijkl,ijkl->ijk', wing_ab[:, :, :-1, :], wing_ab[:, :, 1:, :])\n wing_ab_norm = np.linalg.norm(wing_ab, axis=3)\n wing_ab_norm_inv = 1 / wing_ab_norm\n bound_vortex_singularity_indices = np.einsum('ijkl,ijkl->ijk', wing_a_cross_b, wing_a_cross_b) < 3e-16\n wing_a_dot_b = wing_a_dot_b + bound_vortex_singularity_indices\n side_vortex_singularity_indices = np.einsum('ijkl,ijkl->ijk', wing_ab_cross_x, wing_ab_cross_x) < 3e-16\n wing_ab_dot_x = wing_ab_dot_x + side_vortex_singularity_indices\n wing_a_cross_x = wing_ab_cross_x[:, :, :-1, :]\n wing_b_cross_x = wing_ab_cross_x[:, :, 1:, :]\n wing_a_dot_x = wing_ab_dot_x[:, :, :-1]\n wing_b_dot_x = wing_ab_dot_x[:, :, 1:]\n wing_a_norm = wing_ab_norm[:, :, :-1]\n wing_b_norm = wing_ab_norm[:, :, 1:]\n wing_a_norm_inv = wing_ab_norm_inv[:, :, :-1]\n wing_b_norm_inv = wing_ab_norm_inv[:, :, 1:]\n wing_a_cross_b = np.reshape(wing_a_cross_b, (n_points, -1, 3))\n wing_a_cross_x = np.reshape(wing_a_cross_x, (n_points, -1, 3))\n wing_b_cross_x = np.reshape(wing_b_cross_x, (n_points, -1, 3))\n wing_a_dot_b = np.reshape(wing_a_dot_b, (n_points, -1))\n wing_a_dot_x = np.reshape(wing_a_dot_x, (n_points, -1))\n wing_b_dot_x = np.reshape(wing_b_dot_x, (n_points, -1))\n wing_a_norm = np.reshape(wing_a_norm, (n_points, -1))\n wing_b_norm = np.reshape(wing_b_norm, (n_points, -1))\n wing_a_norm_inv = np.reshape(wing_a_norm_inv, (n_points, -1))\n wing_b_norm_inv = np.reshape(wing_b_norm_inv, (n_points, -1))\n term1 = (wing_a_norm_inv + wing_b_norm_inv) / (wing_a_norm * wing_b_norm + wing_a_dot_b)\n term2 = wing_a_norm_inv / (wing_a_norm - wing_a_dot_x)\n term3 = wing_b_norm_inv / (wing_b_norm - wing_b_dot_x)\n term1 = np.expand_dims(term1, 2)\n term2 = np.expand_dims(term2, 2)\n term3 = np.expand_dims(term3, 2)\n Vij_piece = 1 / (4 * np.pi) * (wing_a_cross_b * term1 + wing_a_cross_x * term2 - wing_b_cross_x * term3)\n Vij_pieces.append(Vij_piece)\n\n Vij = np.hstack(Vij_pieces)\n return Vij\n\n def calculate_Vij(self, points):\n left_vortex_points = self.vortex_left_unrolled\n right_vortex_points = self.vortex_right_unrolled\n points = np.reshape(points, (-1, 3))\n n_points = len(points)\n n_vortices = self.n_panels\n points = np.expand_dims(points, 1)\n a = points - left_vortex_points\n b = points - right_vortex_points\n a_cross_b = np.cross(a, b, axis=2)\n a_dot_b = np.einsum('ijk,ijk->ij', a, b)\n a_cross_x = np.stack((\n np.zeros((n_points, n_vortices)),\n a[:, :, 2],\n -a[:, :, 1]),\n axis=2)\n a_dot_x = a[:, :, 0]\n b_cross_x = np.stack((\n np.zeros((n_points, n_vortices)),\n b[:, :, 2],\n -b[:, :, 1]),\n axis=2)\n b_dot_x = b[:, :, 0]\n norm_a = np.linalg.norm(a, axis=2)\n norm_b = np.linalg.norm(b, axis=2)\n norm_a_inv = 1 / norm_a\n norm_b_inv = 1 / norm_b\n bound_vortex_singularity_indices = np.einsum('ijk,ijk->ij', a_cross_b, a_cross_b) < 3e-16\n a_dot_b = a_dot_b + bound_vortex_singularity_indices\n left_vortex_singularity_indices = np.einsum('ijk,ijk->ij', a_cross_x, a_cross_x) < 3e-16\n a_dot_x = a_dot_x + left_vortex_singularity_indices\n right_vortex_singularity_indices = np.einsum('ijk,ijk->ij', b_cross_x, b_cross_x) < 3e-16\n b_dot_x = b_dot_x + right_vortex_singularity_indices\n term1 = (norm_a_inv + norm_b_inv) / (norm_a * norm_b + a_dot_b)\n term2 = norm_a_inv / (norm_a - a_dot_x)\n term3 = norm_b_inv / (norm_b - b_dot_x)\n term1 = np.expand_dims(term1, 2)\n term2 = np.expand_dims(term2, 2)\n term3 = np.expand_dims(term3, 2)\n Vij = 1 / (4 * np.pi) * (a_cross_b * term1 + a_cross_x * term2 - b_cross_x * term3)\n return Vij\n\n def calculate_delta_cp(self):\n diag1 = self.front_left_vertices_unrolled - self.back_right_vertices_unrolled\n diag2 = self.front_right_vertices_unrolled - self.back_left_vertices_unrolled\n self.areas = np.linalg.norm(np.cross(diag1, diag2, axis=1), axis=1) / 2\n self.Fi_normal = np.einsum('ij,ij->i', self.Fi_geometry, self.normals_unrolled)\n self.pressure_normal = self.Fi_normal / self.areas\n self.delta_cp = self.pressure_normal / self.op_point.dynamic_pressure()\n\n def get_induced_velocity_at_point(self, point):\n point = np.reshape(point, (-1, 3))\n Vij = self.calculate_Vij(point)\n vortex_strengths_expanded = np.expand_dims(self.vortex_strengths, 1)\n Vi_x = Vij[:, :, 0] @ vortex_strengths_expanded\n Vi_y = Vij[:, :, 1] @ vortex_strengths_expanded\n Vi_z = Vij[:, :, 2] @ vortex_strengths_expanded\n Vi = np.hstack((Vi_x, Vi_y, Vi_z))\n return Vi\n\n def get_velocity_at_point(self, point):\n point = np.reshape(point, (-1, 3))\n Vi = self.get_induced_velocity_at_point(point)\n freestream = self.op_point.compute_freestream_velocity_geometry_axes()\n V = Vi + freestream\n return V\n\n def calculate_streamlines(self):\n n_steps = 100\n length = 1\n length_per_step = length / n_steps\n seed_points_list = []\n for wing_num in range(self.n_wings):\n wing_mcl_coordinates = self.mcl_coordinates_structured_list[wing_num]\n wing_te_coordinates = wing_mcl_coordinates[-1, :, :]\n wing_seed_points = (wing_te_coordinates[:-1, :] + wing_te_coordinates[1:, :]) / 2\n seed_points_list.append(wing_seed_points)\n\n seed_points = np.vstack(seed_points_list)\n n_streamlines = len(seed_points)\n streamlines = np.zeros((n_streamlines, n_steps, 3))\n streamlines[:, 0, :] = seed_points\n for step_num in range(1, n_steps):\n update_amount = self.get_velocity_at_point(streamlines[:, step_num - 1, :])\n update_amount = update_amount * length_per_step / np.expand_dims(np.linalg.norm(update_amount, axis=1), axis=1)\n streamlines[:, step_num, :] = streamlines[:, step_num - 1, :] + update_amount\n\n self.streamlines = streamlines\n\n def draw(self, draw_delta_cp=True, draw_streamlines=True):\n print('Drawing...')\n vertices = np.vstack((\n self.front_left_vertices_unrolled,\n self.front_right_vertices_unrolled,\n self.back_right_vertices_unrolled,\n self.back_left_vertices_unrolled))\n faces = np.transpose(np.vstack((\n 4 * np.ones(self.n_panels),\n np.arange(self.n_panels),\n np.arange(self.n_panels) + self.n_panels,\n np.arange(self.n_panels) + 2 * self.n_panels,\n np.arange(self.n_panels) + 3 * self.n_panels)))\n faces = np.reshape(faces, (-1), order='C')\n wing_surfaces = pv.PolyData(vertices, faces)\n plotter = pv.Plotter()\n if draw_delta_cp:\n if not hasattr(self, 'delta_cp'):\n self.calculate_delta_cp()\n delta_cp_min = -1.5\n delta_cp_max = 1.5\n scalars = np.minimum(np.maximum(self.delta_cp, delta_cp_min), delta_cp_max)\n cmap = plt.cm.get_cmap('viridis')\n plotter.add_mesh(wing_surfaces, scalars=scalars, cmap=cmap, color='tan', show_edges=True, smooth_shading=True)\n plotter.add_scalar_bar(title='Pressure Coefficient Differential', n_labels=5, shadow=True, font_family='arial')\n if draw_streamlines:\n if not hasattr(self, 'streamlines'):\n self.calculate_streamlines()\n for streamline_num in range(len(self.streamlines)):\n plotter.add_lines((self.streamlines[streamline_num, :, :]), width=1, color='#50C7C7')\n\n plotter.show_grid(color='#444444')\n plotter.set_background(color='black')\n plotter.show(cpos=(-1, -1, 1), full_screen=False)","sub_path":"pycfiles/AeroSandbox-2.2.2-py3-none-any/vlm2.cpython-37.py","file_name":"vlm2.cpython-37.py","file_ext":"py","file_size_in_byte":36214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"345224629","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom .models import User\n\n\n# Create your views here.\ndef index(request):\n \"\"\"Renders all users in a user list\"\"\"\n all_users = User.objects.all()\n\n context = {\n 'all_users':all_users\n }\n return render(request, 'users/users_list.html', context)\n\n\ndef new(request):\n return render(request, 'users/new.html')\n\ndef update_user(request, id):\n '''Gets user from Edit.html and verifies if email is the same,\n if it is, validates at models.validate_update, else goes to\n models.validate.\n Then if errors are found it displays the errors, else saves the\n new values for the user and displays them.'''\n\n if User.objects.get(id=id).email==request.POST['email']:\n errors = User.objects.validate_update(request.POST)\n else:\n errors = User.objects.validate(request.POST)\n if errors:\n for error in errors:\n messages.error(request, error)\n else:\n user = User.objects.get(id=id)\n user.l_name = request.POST['l_name'].capitalize()\n user.f_name = request.POST['f_name'].capitalize()\n user.email = request.POST['email']\n user.save()\n\n\n context = {\n 'id': id,\n 'f_name': User.objects.get(id=id).f_name,\n 'l_name': User.objects.get(id=id).l_name,\n 'email': User.objects.get(id=id).email,\n 'created': User.objects.get(id=id).updated_at\n }\n return render(request, 'users/edit.html', context)\n\ndef create_verify(request):\n '''Creates a user object from user_list.html verifies\n the data in User.objects.validate in the models.py file.\n Then creates the user objects from User.objects.create_user in the\n models.py file'''\n errors = User.objects.validate(request.POST)\n if errors:\n for error in errors:\n messages.error(request, error)\n else:\n user = User.objects.create_user(request.POST)\n request.session['user_id'] = user.id\n return redirect('/users/new')\n\ndef show(request, id):\n '''creates a temp dict object to render the specific id\n of the user clicked on for more detailed info'''\n context = {\n 'id' : id,\n 'f_name': User.objects.get(id=id).f_name,\n 'l_name': User.objects.get(id=id).l_name,\n 'email': User.objects.get(id=id).email,\n 'created': User.objects.get(id=id).created_at,\n }\n return render(request,'users/user.html', context)\n\ndef delete(request, id):\n \"\"\"Deletes specific user object\"\"\"\n dead = User.objects.get(id=id)\n dead.delete()\n return redirect('/users/index/')\n\ndef edit(request, id):\n '''creates a temp dict object to render the specific id\n of the user clicked on to edit user'''\n context = {\n 'id' : id,\n 'f_name': User.objects.get(id=id).f_name,\n 'l_name': User.objects.get(id=id).l_name,\n 'email': User.objects.get(id=id).email,\n 'created': User.objects.get(id=id).created_at,\n }\n return render(request, 'users/edit.html', context)\n","sub_path":"apps/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"602618281","text":"#DC POWER SUPPLY Agilent E3631A\nimport numpy as np\nimport time\ndef init():\n dc.write(\"INST P6V\")\n dc.write(\"CURR 1.0\")\n\ndef voltageScan(timeSleep, voltage):\n time.sleep(timeSleep);\n dc.write(\"VOLT %f\" %voltage)\n\nsteps = np.arange(0,11,1) #numbre of steps of a scan\ndt = 60 #time interval between each step\nc = 0.013 #define a constant\n\ninit()\n#heating steps\nfor step in steps:\n voltageScan(timeSleep = dt, voltage = c * np.sqrt(step*dt))\ntime.sleep(5*60);\n#cooling steps\nfor step in np.flip(steps,0):\n voltageScan(timeSleep = dt, voltage = c * np.sqrt(step*dt))\n","sub_path":"suspended_wire/DC_power_supply_step_scan.py","file_name":"DC_power_supply_step_scan.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"549883846","text":"import time\nfrom os import path as osp\n\nimport torch\nfrom sklearn.model_selection import KFold\nimport numpy as np\n\nfrom torch_geometric.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch_geometric.utils import f1_score\n\nfrom dataset import ABIDE\nfrom model_hcp import GGRU_ABIDE\nfrom utils import count_parameters, save_code, draw_curves, style\n\nEPOCHS = 40\nNUM_NODES = 111\nLABEL = 'autism' # comment: declare it only here\nTHRESHOLD = 0.878\nLR = 0.001\nCOMMENT = 'Time_test'\n\n\ndef train(train_loader, model, criterion, optimizer):\n model.train()\n correct = 0\n running_loss = 0\n for data in train_loader: # Iterate in batches over the training dataset.\n out = model.forward(data) # Perform a single forward pass.\n loss = criterion(out, data[0].y) # Compute the loss.\n\n running_loss += loss\n loss.backward() # Derive gradients.\n optimizer.step() # Update parameters based on gradients.\n optimizer.zero_grad() # Clear gradients.\n pred = out.argmax(dim=1) # Use the class with highest probability.\n correct += int((pred == data[0].y).sum()) # Check against ground-truth labels.\n return running_loss / len(train_loader.dataset), correct / len(train_loader.dataset)\n\n\n\ndef train_undersampling(train_loader, model, criterion, optimizer):\n model.train()\n correct = 0\n running_loss = 0\n\n subj = 0\n total = 0\n\n for data in train_loader: # Iterate in batches over the training dataset.\n subj += 1 - data[0].y\n if subj >= 144 and data[0].y == 0:\n continue\n total += 1\n\n out = model.forward(data) # Perform a single forward pass.\n loss = criterion(out, data[0].y) # Compute the loss.\n running_loss += loss\n loss.backward() # Derive gradients.\n optimizer.step() # Update parameters based on gradients.\n optimizer.zero_grad() # Clear gradients.\n pred = out.argmax(dim=1) # Use the class with highest probability.\n correct += int((pred == data[0].y).sum()) # Check against ground-truth labels.\n return running_loss / total, correct / total\n\n\ndef val(loader, model, criterion):\n model.eval()\n correct = 0\n running_loss = 0\n\n target = torch.empty((0,), device='cuda')\n predict = torch.empty((0,), device='cuda')\n\n with torch.no_grad():\n for data in loader: # Iterate in batches over the training/test dataset.\n out = model.forward(data)\n # out = model(data.x, data.edge_index, data.batch)\n loss = criterion(out, data[0].y) # Compute the loss.\n running_loss += loss\n pred = out.argmax(dim=1) # Use the class with highest probability.\n correct += int((pred == data[0].y)) # Check against ground-truth labels.\n target = torch.cat((target, data[0].y), dim=0)\n predict = torch.cat((predict, pred), dim=0)\n f1 = f1_score(predict, target, num_classes=2)\n\n return running_loss / len(loader.dataset), correct / len(loader.dataset), f1 # Derive ratio of correct predictions.\n\n\ndef main_timecuts():\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n #dataset = HCPDataset_Timepoints(root='data/', is_sex=IS_SEX, num_cuts=4, threshold=THRESHOLD, num_nodes=NUM_NODES)\n dataset = ABIDE(root='data/', label='autism', num_cuts=4, threshold=THRESHOLD, num_nodes=NUM_NODES)\n print(f'num_cuts: {dataset.num_cuts}')\n\n dataset = dataset.shuffle()\n\n model = GGRU_ABIDE(feature_size=dataset[0][0].num_node_features, num_classes=2, num_nodes=dataset.num_nodes).to(device)\n\n count_parameters(model)\n\n tb = SummaryWriter(comment='ABIDE_{}_{}_{}'.format(model.__class__.__name__, 'autism', dataset.num_nodes))\n save_code(tb.get_logdir())\n\n #if IS_SEX:\n # train = train_undersampling\n\n val_accuracies = np.array([])\n kfold = KFold(n_splits=5) # StratifiedKFold -> preserves the class\n\n try:\n for fold, (train_index, test_index) in enumerate(kfold.split(dataset)):\n print(f'Fold {fold+1}:')\n model.reset_parameters()\n\n train_dataset = dataset[torch.tensor(train_index)]\n val_dataset = dataset[torch.tensor(test_index)]\n\n train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True)\n val_loader = DataLoader(val_dataset, batch_size=1, shuffle=False)\n train_dist = [(train_dataset.labels[train_dataset.indices()] == i).sum() for i in [0, 1]]\n train_str = f'Train 0: {train_dist[0]}; Train 1: {train_dist[1]} '\n print(train_str)\n print(f'Val 0: {(val_dataset.labels[val_dataset.indices()] == 0).sum()}; Val 1: {(val_dataset.labels[val_dataset.indices()] == 1).sum()} ')\n train_dist /= (train_dist[0] + train_dist[1])\n weight = torch.FloatTensor(1 / train_dist).to(device)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-5) # weight_decay original 1e-6, try 1e-5\n ## TODO: regularizer for the loss\n ## TODO: check the git repo for hyperparams, layers\n decayRate = 0.9\n lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=decayRate)\n criterion_train = torch.nn.CrossEntropyLoss(weight)\n #criterion_train = torch.nn.CrossEntropyLoss()\n criterion_val = torch.nn.CrossEntropyLoss()\n\n accuracies_per_epoch = ([], [])\n losses_per_epoch = ([], [])\n\n min_loss = 100000\n max_validation_accuracy = 0\n for epoch in range(1, EPOCHS):\n t = time.time()\n val_loss, val_acc, val_f1 = val(loader=val_loader, model=model, criterion=criterion_val)\n train_loss, train_acc = train(train_loader=train_loader,\n model=model,\n criterion=criterion_train,\n optimizer=optimizer)\n print(f'Epoch: {epoch:03d}, Train Acc: {train_acc:.4f}, Train Loss: {train_loss:.4f}, '\n f'Val Acc: {style.GREEN_BOLD if val_acc > max_validation_accuracy else style.CBOLD}{val_acc:.4f}{style.RESET}, '\n f'Val Loss: {style.GREEN_BOLD if val_loss < min_loss else style.CBOLD}{val_loss:.4f}{style.RESET}, '\n f'Val F1: {val_f1[0]:.2f} | {val_f1[1]:.2f}, time: {(time.time() - t):.4f}s')\n if (epoch < 25):\n lr_decay.step()\n\n max_validation_accuracy = max(max_validation_accuracy, val_acc)\n min_loss = min(min_loss, val_loss)\n\n if train_loss < 0.0002:\n break # early stopping\n\n tb.add_scalars(f'accuracies_{fold}', {\n 'train_acc': train_acc,\n 'val_acc': val_acc,\n }, epoch)\n accuracies_per_epoch[0].append(train_acc)\n accuracies_per_epoch[1].append(val_acc)\n\n tb.add_scalars(f'losses_{fold}', {\n 'train_loss': train_loss,\n 'val_loss': val_loss,\n }, epoch)\n\n tb.add_scalars(f'f1_{fold}', {\n 'Class 0': val_f1[0],\n 'Class 1': val_f1[1],\n }, epoch)\n losses_per_epoch[0].append(float(train_loss.detach()))\n losses_per_epoch[1].append(float(val_loss.detach()))\n\n\n val_accuracies = np.append(val_accuracies, max_validation_accuracy)\n print('Max validation accuracy: ', max_validation_accuracy)\n draw_curves(list(range(len(accuracies_per_epoch[0]))), losses_per_epoch, accuracies_per_epoch, f'Fold {fold + 1}')\n\n finally:\n mean_acc, std_acc = np.mean(val_accuracies), np.std(val_accuracies)\n print(f'Mean: {mean_acc} Std: {std_acc}')\n # save the validation as a file\n f = open(osp.join(tb.get_logdir(), f'val_{mean_acc:.4f}_std_{std_acc:.4f}'), \"x\")\n f.close()\n\n\nif __name__ == \"__main__\":\n print(f'LR: {LR}')\n print(f'Threshold: {THRESHOLD}')\n main_timecuts()\n\n","sub_path":"train_ABIDE_timecuts_GGRU_kfold.py","file_name":"train_ABIDE_timecuts_GGRU_kfold.py","file_ext":"py","file_size_in_byte":8215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"1148982","text":"\nMEDAL_ASOUL = (\n '顶碗人', \n '嘉心糖', \n '贝极星', \n '奶淇琳', \n '王力口', \n '一个魂',\n)\n\nDEFAULT_LISTEN_EVENTS = [\n 'DANMU_MSG',\n 'INTERACT_WORD',\n 'SEND_GIFT',\n 'SUPER_CHAT_MESSAGE',\n 'ROOM_REAL_TIME_MESSAGE_UPDATE',\n 'USER_TOAST_MSG',\n 'VIEW',\n]\n\nLISTEN_ROOMS = [\n 22632157, \n 22637261, \n 22634198, \n 22625027, \n 22632424, \n 22625025,\n]","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"639663976","text":"# author: mofhu@github\n# B. Colourblindness\n\nt = int(input())\n\nfor ncase in range(1, t+1):\n n = int(input())\n s1 = [i for i in input()]\n s2 = [i for i in input()]\n for i in range(n):\n if s1[i] == 'G':\n s1[i] = 'B'\n if s2[i] == 'G':\n s2[i] = 'B'\n if s1[i] != s2[i]:\n # print(i, s1[i], s2[i])\n ans = 'NO'\n break\n else:\n ans = 'YES'\n print(ans)\n\n\n","sub_path":"codeforces/Round817/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570374187","text":"import json\nfrom urllib.parse import urljoin\n\nfrom mohawk import Sender\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nimport requests\nfrom requests.exceptions import ConnectionError, HTTPError, Timeout\n\n\nclass CompanyMatchingServiceException(Exception):\n \"\"\"\n Base exception class for Company matching service related errors.\n \"\"\"\n\n\nclass CompanyMatchingServiceHTTPError(CompanyMatchingServiceException):\n \"\"\"\n Exception for when a HTTP error is encountered when connecting to Company matching service.\n \"\"\"\n\n\nclass CompanyMatchingServiceTimeoutError(CompanyMatchingServiceException):\n \"\"\"\n Exception for when a timeout was encountered when connecting to Company matching service.\n \"\"\"\n\n\nclass CompanyMatchingServiceConnectionError(CompanyMatchingServiceException):\n \"\"\"\n Exception for when an error was encountered when connecting to Company matching service.\n \"\"\"\n\n\ndef _post(path, json_body):\n \"\"\"\n Sends a HAWK authenticated post request to the company matching service\n with a json body.\n \"\"\"\n url = urljoin(settings.COMPANY_MATCHING_SERVICE_BASE_URL, path)\n # Signs a request\n sender = Sender(\n {\n 'id': settings.COMPANY_MATCHING_HAWK_ID,\n 'key': settings.COMPANY_MATCHING_HAWK_KEY,\n 'algorithm': 'sha256'\n },\n url=url,\n method='POST',\n content_type='application/json',\n content=json.dumps(json_body),\n )\n # Post JSON to the company matching service\n response = requests.post(\n url,\n json=json_body,\n headers={\n 'Authorization': sender.request_header,\n 'Content-Type': 'application/json',\n }\n )\n response.raise_for_status()\n if response.ok:\n # Verify response from the company matching service\n sender.accept_response(\n response.headers['Server-Authorization'],\n content=response.content,\n content_type=response.headers['Content-Type'],\n )\n return response\n\n\ndef _request_match_companies(json_body):\n \"\"\"\n Queries the company matching service with the given json_body. E.g.:\n {\n \"descriptions\": [\n {\n \"id\": \"1\",\n \"companies_house_id\": \"0921309\",\n \"duns_number\": \"d210\"\n \"company_name\":\"apple\",\n \"contact_email\": \"john@apple.com\",\n \"cdms_ref\": \"782934\",\n \"postcode\": \"SW129RP\"\n }\n ]\n }\n\n Note that the ID field typically the company UUID that is returned by the api for data mapping.\n ID and at least one of the following fields companies_house_id, duns_number, company_name,\n contact_email, cdms_ref and postcode are required.\n \"\"\"\n if not all([\n settings.COMPANY_MATCHING_SERVICE_BASE_URL,\n settings.COMPANY_MATCHING_HAWK_ID,\n settings.COMPANY_MATCHING_HAWK_KEY,\n ]):\n raise ImproperlyConfigured('The all COMPANY_MATCHING_SERVICE_* setting must be set')\n\n response = _post('api/v1/company/match/', json_body)\n return response\n\n\ndef _company_house_or_cdms_number(ref):\n \"\"\"Validate the data to return a company house or cdms number.\"\"\"\n if bool(ref):\n if len(ref) == 8:\n \"\"\"\n Attempt to convert the company house number to an int, we're not going to use the value\n because we do not want to make any assumptions for the format we only care if all the chracters are\n numbers and are 8 digits long. e.g if a number is 000123 the int will return 123.\n \"\"\"\n try:\n int(ref)\n return {'companies_house_id': ref}\n except ValueError:\n pass\n return {'cdms_ref': ref}\n else:\n return {}\n\n\ndef _format_company_for_post(wins):\n \"\"\"Format the Company model to json for the POST body.\"\"\"\n return {\n 'descriptions': [\n {\n 'id': str(win.pk),\n 'company_name': win.company_name,\n 'contact_email': win.customer_email_address,\n **_company_house_or_cdms_number(win.cdms_reference),\n } for win in wins\n ],\n }\n\n\ndef get_match_ids(wins):\n \"\"\"\n Get companies match from a Win queryset and updates the match_id fields from the company matching service.\n Raises exception an requests.exceptions.HTTPError for status, timeout and a connection error.\n \"\"\"\n try:\n response = _request_match_companies(_format_company_for_post(wins))\n except ConnectionError as exc:\n error_message = 'Encountered an error connecting to Company matching service'\n raise CompanyMatchingServiceConnectionError(error_message) from exc\n except Timeout as exc:\n error_message = 'Encountered a timeout interacting with Company matching service'\n raise CompanyMatchingServiceTimeoutError(error_message) from exc\n except HTTPError as exc:\n error_message = (\n 'The Company matching service returned an error status: '\n f'{exc.response.status_code}'\n )\n raise CompanyMatchingServiceHTTPError(error_message) from exc\n return response\n","sub_path":"wins/company_matching_utils.py","file_name":"company_matching_utils.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97021061","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 13 13:21:04 2019\n\n@author: catalin\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mylib_dataset as md\nimport mylib_normalize as mn\n\n#from matplotlib.finance import candlestick\nimport matplotlib.ticker as mticker\nimport matplotlib.dates as mdates\nimport talib as ta\nimport math\nimport time\n \n\nstart_time = time.time()\ndirectory = '/home/catalin/databases/klines_2014-2018_15min/'\nhard_coded_file_number = 0\n\ndata = md.get_dataset_with_descriptors(concatenate_datasets_preproc_flag = True, \n preproc_constant = 0.99, \n normalization_method = \"rescale\",\n dataset_directory = directory,\n hard_coded_file_number = hard_coded_file_number)\nX = data['preprocessed_data'] ## this will be used for training\nX_unprocessed = data['data']\n\nopen_prices = X_unprocessed[:,0]\nclose_prices = X_unprocessed[:,1]\nhigh_prices = X_unprocessed[:,2]\nlow_prices = X_unprocessed[:,3]\nvolume = X_unprocessed[:,4]\n\n#def DCT_transform_II(vector):\n#\tresult = []\n#\tfactor = math.pi / len(vector)\n#\tfor i in range(len(vector)):\n#\t\tsumm = 0.0\n#\t\tfor (j, val) in enumerate(vector):\n#\t\t\tsumm += val * math.cos((j + 0.5) * i * factor)\n#\t\tresult.append(summ)\n#\treturn np.array(result)\n\ndef DCT_transform_II(vector):\n\tif vector.ndim != 1:\n\t\traise ValueError()\n\tn = vector.size\n\tif n == 1:\n\t\treturn vector.copy()\n\telif n == 0 or n % 2 != 0:\n\t\traise ValueError()\n\telse:\n\t\thalf = n // 2\n\t\tgamma = vector[ : half]\n\t\tdelta = vector[n - 1 : half - 1 : -1]\n\t\talpha = DCT_transform_II(gamma + delta)\n\t\tbeta = DCT_transform_II((gamma - delta) / (np.cos(np.arange(0.5, half + 0.5) * (np.pi / n)) * 2.0))\n\t\tresult = np.zeros_like(vector)\n\t\tresult[0 : : 2] = alpha\n\t\tresult[1 : : 2] = beta\n\t\tresult[1 : n - 1 : 2] += beta[1 : ]\n\t\treturn result\n\ndef RLS_indicator(close, time_period = 128, lam = 0.9, delta = 1, smoothing = 0.9, dct_transform = False):\n sample_circular_buffer = np.zeros(time_period)\n dct_sample_circular_buffer = np.zeros(time_period)\n rls_filter = np.zeros(time_period)\n rls_indicator_error = []\n rls_indicator_output = []\n rls_smoothed_indicator = []\n P = (delta**(-1)) * np.identity(time_period);\n for i in range(len(close)):\n if(dct_transform == \"type II\"):\n dct_sample_circular_buffer = np.hstack((close[i], dct_sample_circular_buffer[:-1]))\n sample_circular_buffer = DCT_transform_II(dct_sample_circular_buffer)\n else:\n sample_circular_buffer = np.hstack((close[i], sample_circular_buffer[:-1]))\n z = np.matmul(sample_circular_buffer,P)\n k = np.matmul(P, sample_circular_buffer.T) / (lam + np.matmul(z, sample_circular_buffer.T))\n y = np.matmul(rls_filter, sample_circular_buffer.T)\n error = close[i] - y\n rls_filter = rls_filter + np.multiply(k, np.conj(error))\n P = (1 / lam) * (P - np.multiply(np.matmul(z, k), P))\n rls_indicator_error.append(error)\n rls_indicator_output.append(y)\n if(i==0):\n rls_smoothed_indicator.append(rls_indicator_error[-1])\n else:\n rls_smoothed_indicator.append(rls_smoothed_indicator[-1] * smoothing + \\\n (1 - smoothing) * rls_indicator_error[-1])\n return np.array(rls_indicator_error), np.array(rls_indicator_output)\n\nrls_indicator_error, rls_indicator_output = RLS_indicator(close_prices,\n time_period = 256,\n lam = 0.9, \n delta = 1/(np.var(close_prices)*100),\n dct_transform = \"type II\")\n\nplt.figure()\nplt.title('RLS indicator. filter length = 128, lam = 0.9, delta = 1')\nplt.plot(rls_indicator_error,label = 'RLS error signal')\nplt.plot(rls_indicator_output,label = 'RLS filter output')\nplt.plot(close_prices, label = 'close prices')\nplt.legend(loc='best')\nplt.show()\n\nend_time = time.time()\nprint('process time: '+ str(end_time-start_time))","sub_path":"TA_testbench/TA_testbench_RLS.py","file_name":"TA_testbench_RLS.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45541698","text":"# 递归加self!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nclass Solution:\n def verifyPostorder(self, postorder):\n if not postorder:\n return True\n rootIdx = len(postorder) - 1\n rootVal = postorder[-1]\n rightTreeStart = 0\n for s in range(1, rootIdx + 1):\n if postorder[rootIdx - s] < rootVal:\n rightTreeStart = rootIdx - s + 1\n break\n \n for s in range(0, rightTreeStart):\n if postorder[s] > rootVal:\n return False\n \n return self.verifyPostorder(postorder[0:rightTreeStart]) and self.verifyPostorder(postorder[rightTreeStart:-1])\n\ndef main():\n lis = [1, 2, 3, 4]\n print(lis[1:-1])\n\nmain()","sub_path":"剑指offer/树/ex33bstPosto.py","file_name":"ex33bstPosto.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293658951","text":"# coding: utf-8\n#\n# Copyright 2018 The Oppia 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\n\"\"\"Domain objects for topics, and related models.\"\"\"\n\nimport copy\n\nfrom constants import constants\nfrom core.domain import user_services\nfrom core.platform import models\nimport feconf\nimport utils\n\n(topic_models,) = models.Registry.import_models([models.NAMES.topic])\n\nCMD_CREATE_NEW = 'create_new'\nCMD_CHANGE_ROLE = 'change_role'\n\nROLE_MANAGER = 'manager'\nROLE_NONE = 'none'\n# Do not modify the values of these constants. This is to preserve backwards\n# compatibility with previous change dicts.\nTOPIC_PROPERTY_NAME = 'name'\nTOPIC_PROPERTY_DESCRIPTION = 'description'\nTOPIC_PROPERTY_CANONICAL_STORY_IDS = 'canonical_story_ids'\nTOPIC_PROPERTY_ADDITIONAL_STORY_IDS = 'additional_story_ids'\nTOPIC_PROPERTY_SKILL_IDS = 'skill_ids'\nTOPIC_PROPERTY_LANGUAGE_CODE = 'language_code'\n\n\n# These take additional 'property_name' and 'new_value' parameters and,\n# optionally, 'old_value'.\nCMD_UPDATE_TOPIC_PROPERTY = 'update_topic_property'\n\n\nclass TopicChange(object):\n \"\"\"Domain object for changes made to topic object.\"\"\"\n TOPIC_PROPERTIES = (\n TOPIC_PROPERTY_NAME, TOPIC_PROPERTY_DESCRIPTION,\n TOPIC_PROPERTY_CANONICAL_STORY_IDS, TOPIC_PROPERTY_ADDITIONAL_STORY_IDS,\n TOPIC_PROPERTY_SKILL_IDS, TOPIC_PROPERTY_LANGUAGE_CODE)\n\n OPTIONAL_CMD_ATTRIBUTE_NAMES = [\n 'property_name', 'new_value', 'old_value', 'name'\n ]\n\n def __init__(self, change_dict):\n \"\"\"Initialize a TopicChange object from a dict.\n\n Args:\n change_dict: dict. Represents a command. It should have a 'cmd'\n key, and one or more other keys. The keys depend on what the\n value for 'cmd' is. The possible values for 'cmd' are listed\n below, together with the other keys in the dict:\n - 'update_topic_property' (with property_name, new_value\n and old_value)\n\n Raises:\n Exception: The given change dict is not valid.\n \"\"\"\n if 'cmd' not in change_dict:\n raise Exception('Invalid change_dict: %s' % change_dict)\n self.cmd = change_dict['cmd']\n\n if self.cmd == CMD_UPDATE_TOPIC_PROPERTY:\n if change_dict['property_name'] not in self.TOPIC_PROPERTIES:\n raise Exception('Invalid change_dict: %s' % change_dict)\n self.property_name = change_dict['property_name']\n self.new_value = copy.deepcopy(change_dict['new_value'])\n self.old_value = copy.deepcopy(change_dict['old_value'])\n elif self.cmd == CMD_CREATE_NEW:\n self.name = change_dict['name']\n else:\n raise Exception('Invalid change_dict: %s' % change_dict)\n\n def to_dict(self):\n \"\"\"Returns a dict representing the TopicChange domain object.\n\n Returns:\n A dict, mapping all fields of TopicChange instance.\n \"\"\"\n topic_change_dict = {}\n topic_change_dict['cmd'] = self.cmd\n for attribute_name in self.OPTIONAL_CMD_ATTRIBUTE_NAMES:\n if hasattr(self, attribute_name):\n topic_change_dict[attribute_name] = getattr(\n self, attribute_name)\n\n return topic_change_dict\n\n\nclass Topic(object):\n \"\"\"Domain object for an Oppia Topic.\"\"\"\n\n def __init__(\n self, topic_id, name, description, canonical_story_ids,\n additional_story_ids, skill_ids, language_code, version,\n created_on=None, last_updated=None):\n \"\"\"Constructs a Topic domain object.\n\n Args:\n topic_id: str. The unique ID of the topic.\n name: str. The name of the topic.\n description: str. The description of the topic.\n canonical_story_ids: list(str). A set of ids representing the\n canonical stories that are part of this topic.\n additional_story_ids: list(str). A set of ids representing the\n additional stories that are part of this topic.\n skill_ids: list(str). This consists of the full list of skill ids\n that are part of this topic.\n created_on: datetime.datetime. Date and time when the topic is\n created.\n last_updated: datetime.datetime. Date and time when the\n topic was last updated.\n language_code: str. The ISO 639-1 code for the language this\n topic is written in.\n version: int. The version of the topic.\n \"\"\"\n self.id = topic_id\n self.name = name\n self.description = description\n self.canonical_story_ids = canonical_story_ids\n self.additional_story_ids = additional_story_ids\n self.skill_ids = skill_ids\n self.language_code = language_code\n self.created_on = created_on\n self.last_updated = last_updated\n self.version = version\n\n def to_dict(self):\n \"\"\"Returns a dict representing this Topic domain object.\n\n Returns:\n A dict, mapping all fields of Topic instance.\n \"\"\"\n return {\n 'id': self.id,\n 'name': self.name,\n 'description': self.description,\n 'canonical_story_ids': self.canonical_story_ids,\n 'additional_story_ids': self.additional_story_ids,\n 'language_code': self.language_code,\n 'skill_ids': self.skill_ids,\n 'version': self.version\n }\n\n @classmethod\n def require_valid_topic_id(cls, topic_id):\n \"\"\"Checks whether the topic id is a valid one.\n\n Args:\n topic_id: str. The topic id to validate.\n \"\"\"\n if not isinstance(topic_id, basestring):\n raise utils.ValidationError(\n 'Topic id should be a string, received: %s' % topic_id)\n\n if len(topic_id) != 12:\n raise utils.ValidationError('Topic id %s is invalid' % topic_id)\n\n @classmethod\n def require_valid_name(cls, name):\n \"\"\"Checks whether the name of the topic is a valid one.\n\n Args:\n name: str. The name to validate.\n \"\"\"\n if not isinstance(name, basestring):\n raise utils.ValidationError('Name should be a string.')\n\n if name == '':\n raise utils.ValidationError('Name field should not be empty')\n\n def delete_skill(self, skill_id):\n \"\"\"Removes a skill from the skill_ids list.\n\n Args:\n skill_id: str. The skill id to remove from the list.\n\n Raises:\n Exception. The skill_id is not present in the topic.\n \"\"\"\n if skill_id not in self.skill_ids:\n raise Exception(\n 'The skill id %s is not present in the topic.' % skill_id)\n self.skill_ids.remove(skill_id)\n\n def add_skill(self, skill_id):\n \"\"\"Adds a skill to the skill_ids list.\n\n Args:\n skill_id: str. The skill id to add to the list.\n \"\"\"\n if skill_id in self.skill_ids:\n raise Exception(\n 'The skill id %s is already present in the topic.' % skill_id)\n self.skill_ids.append(skill_id)\n\n def delete_story(self, story_id):\n \"\"\"Removes a story from the canonical_story_ids list.\n\n Args:\n story_id: str. The story id to remove from the list.\n\n Raises:\n Exception. The story_id is not present in the canonical story ids\n list of the topic.\n \"\"\"\n if story_id not in self.canonical_story_ids:\n raise Exception(\n 'The story_id %s is not present in the canonical '\n 'story ids list of the topic.' % story_id)\n self.canonical_story_ids.remove(story_id)\n\n def add_canonical_story(self, story_id):\n \"\"\"Adds a story to the canonical_story_ids list.\n\n Args:\n story_id: str. The story id to add to the list.\n \"\"\"\n if story_id in self.canonical_story_ids:\n raise Exception(\n 'The story_id %s is already present in the canonical '\n 'story ids list of the topic.' % story_id)\n self.canonical_story_ids.append(story_id)\n\n def validate(self):\n \"\"\"Validates all properties of this topic and its constituents.\n\n Raises:\n ValidationError: One or more attributes of the Topic are not\n valid.\n \"\"\"\n self.require_valid_name(self.name)\n if not isinstance(self.description, basestring):\n raise utils.ValidationError(\n 'Expected description to be a string, received %s'\n % self.description)\n\n if not isinstance(self.language_code, basestring):\n raise utils.ValidationError(\n 'Expected language code to be a string, received %s' %\n self.language_code)\n if not any([self.language_code == lc['code']\n for lc in constants.ALL_LANGUAGE_CODES]):\n raise utils.ValidationError(\n 'Invalid language code: %s' % self.language_code)\n\n if not isinstance(self.canonical_story_ids, list):\n raise utils.ValidationError(\n 'Expected canonical story ids to be a list, received %s'\n % self.canonical_story_ids)\n if len(self.canonical_story_ids) > len(set(self.canonical_story_ids)):\n raise utils.ValidationError(\n 'Expected all canonical story ids to be distinct.')\n\n if not isinstance(self.additional_story_ids, list):\n raise utils.ValidationError(\n 'Expected additional story ids to be a list, received %s'\n % self.additional_story_ids)\n if len(self.additional_story_ids) > len(set(self.additional_story_ids)):\n raise utils.ValidationError(\n 'Expected all additional story ids to be distinct.')\n\n for story_id in self.additional_story_ids:\n if story_id in self.canonical_story_ids:\n raise utils.ValidationError(\n 'Expected additional story ids list and canonical story '\n 'ids list to be mutually exclusive. The story_id %s is '\n 'present in both lists' % story_id)\n\n if not isinstance(self.skill_ids, list):\n raise utils.ValidationError(\n 'Expected skill ids to be a list, received %s'\n % self.skill_ids)\n\n @classmethod\n def create_default_topic(cls, topic_id, name):\n \"\"\"Returns a topic domain object with default values. This is for\n the frontend where a default blank topic would be shown to the user\n when the topic is created for the first time.\n\n Args:\n topic_id: str. The unique id of the topic.\n name: str. The initial name for the topic.\n\n Returns:\n Topic. The Topic domain object with the default values.\n \"\"\"\n return cls(\n topic_id, name,\n feconf.DEFAULT_TOPIC_DESCRIPTION, [], [], [],\n constants.DEFAULT_LANGUAGE_CODE, 0)\n\n def update_name(self, new_name):\n \"\"\"Updates the name of a topic object.\n\n Args:\n new_name: str. The updated name for the topic.\n \"\"\"\n self.name = new_name\n\n def update_description(self, new_description):\n \"\"\"Updates the description of a topic object.\n\n Args:\n new_description: str. The updated description for the topic.\n \"\"\"\n self.description = new_description\n\n def update_language_code(self, new_language_code):\n \"\"\"Updates the language code of a topic object.\n\n Args:\n new_language_code: str. The updated language code for the topic.\n \"\"\"\n self.language_code = new_language_code\n\n def update_canonical_story_ids(self, new_canonical_story_ids):\n \"\"\"Updates the canonical story id list of a topic object.\n\n Args:\n new_canonical_story_ids: list(str). The updated list of canonical\n story ids.\n \"\"\"\n self.canonical_story_ids = new_canonical_story_ids\n\n def update_additional_story_ids(self, new_additional_story_ids):\n \"\"\"Updates the additional story id list of a topic object.\n\n Args:\n new_additional_story_ids: list(str). The updated list of additional\n story ids.\n \"\"\"\n self.additional_story_ids = new_additional_story_ids\n\n def update_skill_ids(self, new_skill_ids):\n \"\"\"Updates the skill id list of a topic object.\n\n Args:\n new_skill_ids: list(str). The updated list of skill ids.\n \"\"\"\n self.skill_ids = new_skill_ids\n\n\nclass TopicSummary(object):\n \"\"\"Domain object for Topic Summary.\"\"\"\n\n def __init__(\n self, topic_id, name, language_code, version,\n canonical_story_count, additional_story_count, skill_count,\n topic_model_created_on, topic_model_last_updated):\n \"\"\"Constructs a TopicSummary domain object.\n\n Args:\n topic_id: str. The unique id of the topic.\n name: str. The name of the topic.\n language_code: str. The language code of the topic.\n version: int. The version of the topic.\n canonical_story_count: int. The number of canonical stories present\n in the topic.\n additional_story_count: int. The number of additional stories\n present in the topic.\n skill_count: int. The number of skills the topic teaches.\n topic_model_created_on: datetime.datetime. Date and time when\n the topic model is created.\n topic_model_last_updated: datetime.datetime. Date and time\n when the topic model was last updated.\n \"\"\"\n self.id = topic_id\n self.name = name\n self.language_code = language_code\n self.version = version\n self.canonical_story_count = canonical_story_count\n self.additional_story_count = additional_story_count\n self.skill_count = skill_count\n self.topic_model_created_on = topic_model_created_on\n self.topic_model_last_updated = topic_model_last_updated\n\n def to_dict(self):\n \"\"\"Returns a dictionary representation of this domain object.\n\n Returns:\n dict. A dict representing this TopicSummary object.\n \"\"\"\n return {\n 'id': self.id,\n 'name': self.name,\n 'language_code': self.language_code,\n 'version': self.version,\n 'canonical_story_count': self.canonical_story_count,\n 'additional_story_count': self.additional_story_count,\n 'skill_count': self.skill_count,\n 'topic_model_created_on': self.topic_model_created_on,\n 'topic_model_last_updated': self.topic_model_last_updated\n }\n\n\nclass TopicRights(object):\n \"\"\"Domain object for topic rights.\"\"\"\n\n def __init__(self, topic_id, manager_ids):\n self.id = topic_id\n self.manager_ids = manager_ids\n\n def to_dict(self):\n \"\"\"Returns a dict suitable for use by the frontend.\n\n Returns:\n dict. A dict version of TopicRights suitable for use by the\n frontend.\n \"\"\"\n return {\n 'topic_id': self.id,\n 'manager_names': user_services.get_human_readable_user_ids(\n self.manager_ids)\n }\n\n def is_manager(self, user_id):\n \"\"\"Checks whether given user is a manager of the topic.\n\n Args:\n user_id: str or None. Id of the user.\n\n Returns:\n bool. Whether user is a topic manager of this topic.\n \"\"\"\n return bool(user_id in self.manager_ids)\n","sub_path":"core/domain/topic_domain.py","file_name":"topic_domain.py","file_ext":"py","file_size_in_byte":16314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316211990","text":"'''\nДан набор чисел. Необходимо вывести множество повторяющихся чисел (т.е те, которые встречаются больше 1 раза) в порядке возрастания.\n\nФормат входных данных: Список чисел, введенных в одной строке через пробел\n\nФормат выходных данных: Числа на одной строке через пробел в порядке возрастания.\n\nSample Input 1:\n\n1 2 3 3 1 1 7 4 7 3\nSample Output 1:\n\n1 3 7\nSample Input 2:\n\n3 6 7 2 5 7 1 4 6 6\nSample Output 2:\n\n6 7\n'''\n\na = [int(i) for i in input().split(\" \")]\n\nb = set(a)\nc = []\nfor i in b:\n if a.count(i) > 1:\n c.append(i)\n\nfor i in sorted(c):\n print(i, end=\" \")\n","sub_path":"iTutor/Множества и словари/1.7.1.py","file_name":"1.7.1.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"418470299","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 9 17:52:14 2019\n\n Script enforces the intersection between readiness months (serial number x month) and fault spells,\n to ensure the same population between readiness and fault data.\n\n@author: jking\n\"\"\"\n\n\nimport pandas as pd\nimport os\npd.options.display.max_rows = 200\npd.options.display.max_columns = 75\npd.options.mode.chained_assignment = None # turns of SettingWithCopyWarning\n\n\nif __name__ == '__main__':\n\n \n ##################################################\n ##### READ AND PROCESS #####\n ##################################################\n \n # Fault Data\n try:\n fault_dir = r'C:\\Users\\jking\\Documents\\FTS2B\\data'\n except:\n fault_dir = r'X:\\Pechacek\\ARNG Aircraft Readiness\\Data\\Processed\\Master fault data intermediate\\NGB Blackhawk'\n f = pd.read_csv(os.path.join(fault_dir, 'NMC_spells.csv'))\n f.rename(columns={'SERNO':'serial_number'}, inplace=True)\n serno = f.serial_number.unique().tolist() # blackhawk serial numbers in fault data, for subsetting below \n \n # Readiness Data\n readiness_dir = r'X:\\Pechacek\\ARNG Aircraft Readiness\\Data\\Processed\\Tables for merge'\n r = pd.read_csv(os.path.join(readiness_dir, 'readiness_covariates_201011_201909.csv'),\n encoding='ISO-8859-1', low_memory=False); del readiness_dir\n\n r = r.loc[r.serial_number.isin(serno) & (r.report_date >='2010-10-01'), \n ['serial_number', 'report_date', 'facility_id']]; del serno\n r['serial_number'] = r['serial_number'].astype(int)\n r = r.loc[r.facility_id.notnull()] # drop any serial numbers missing facility ID\n r.sort_values(by=['serial_number', 'report_date'], inplace=True)\n r.reset_index(drop=True, inplace=True)\n\n #################################################################\n ##### Convert to datetime, create readiness month for merge #####\n #################################################################\n\n f['spell_bgn'] = pd.to_datetime(f['spell_bgn'], format ='%Y-%m-%d %H:%M', errors='raise')\n f['spell_end'] = pd.to_datetime(f['spell_end'], format ='%Y-%m-%d %H:%M', errors='raise')\n\n f.loc[f.spell_bgn.dt.day <= 15, 'read_startmo'] = \\\n (f['spell_bgn']).dt.strftime('%Y-%m') + '-15'\n f.loc[f.spell_bgn.dt.day > 15, 'read_startmo'] = \\\n (f['spell_bgn'] + pd.DateOffset(months=1)).dt.strftime('%Y-%m') + '-15'\n # Spell end readiness month\n f.loc[f.spell_end.dt.day <= 15, 'read_endmo'] = \\\n (f['spell_end']).dt.strftime('%Y-%m') + '-15'\n f.loc[f.spell_end.dt.day > 15, 'read_endmo'] = \\\n (f['spell_end'] + pd.DateOffset(months=1)).dt.strftime('%Y-%m') + '-15'\n\n f['read_startmo'] = pd.to_datetime(f['read_startmo'], format ='%Y-%m-%d', errors='raise')\n f['read_endmo'] = pd.to_datetime(f['read_endmo'], format ='%Y-%m-%d', errors='raise')\n r['report_date'] = pd.to_datetime(r['report_date'], format ='%Y-%m-%d', errors='raise')\n \n # Roll back readiness month of spell by 1 to ensure chopper at same facility_id throughout whole spell\n f['read_startmo'] = (f['read_startmo'] + pd.DateOffset(months=-1))\n \n # Serial number x spell number, uniquely identifies spell\n f['spell_num'] = f.groupby('serial_number').cumcount()\n uniq_spells_orig = f.shape[0] # number of unique spells before merge\n \n ##################################################\n ##### INTERSECTION WITH READINESS DATA #####\n ##################################################\n \n # Subset to relevant columns\n foo = f[['serial_number', 'read_startmo', 'read_endmo', 'spell_num']]\n \n # Convert wide to long for read_startmo and read_endmo, ignoring duplicate start and/or end months\n long = pd.melt(foo, id_vars=['serial_number', 'spell_num'], value_name='report_date') # report_date is either start or end month\n long = long.sort_values(by=['serial_number', 'spell_num', 'report_date']).reset_index(drop=True) # sort for forward fill\n \n # Wide to long conversion\n print(\"\\nConverting wide to long..\")\n mo = long.set_index('report_date').groupby(['serial_number', 'spell_num']).resample('M').ffill()\n mo = mo[[]].reset_index(drop=False) \n mo['report_date'] = mo['report_date'].dt.strftime('%Y-%m') + '-15' # pandas annoyingly sets to the end of the month, this resets back to 15th\n mo['report_date'] = pd.to_datetime(mo['report_date'], format ='%Y-%m-%d', errors='raise')\n del foo, long\n \n # Full outer join with readiness data\n mo['nr_months'] = mo.groupby(['serial_number', 'spell_num']).transform('count') # number of readiness months per spell, should be same after intersection else drop (below)\n uniq_fault_months_orig = mo.drop_duplicates(subset=['serial_number', 'report_date']).shape[0] # total unique fault months before merge\n join = r.merge(mo, on=['serial_number', 'report_date'], how='outer', indicator=True) # retain duplicates in merge to link back to original spells\n join = join.sort_values(by=['serial_number','spell_num', 'report_date']).reset_index(drop=True)\n \n \n # Summary stats of merge\n stats = join.drop_duplicates(subset=['serial_number', 'report_date'])['_merge'].value_counts()\\\n .rename({'both':'intersection', 'right_only':'fault_only', 'left_only':'readiness_only'})\\\n .reset_index().rename(columns={'index':'merge_type', '_merge':'n_months'})\n stats['share_merge'] = stats['n_months'] / len(join.drop_duplicates(subset=['serial_number', 'report_date']))\n print(stats)\n \n # Keep intersection\n inters = join.loc[join._merge == 'both'].sort_values(by=['serial_number', 'spell_num', 'report_date']).reset_index(drop=True).drop(columns=['_merge'])\n uniq_fault_months_inters = len(inters.drop_duplicates(subset=['serial_number', 'report_date'])) # total unique fault months in intersection\n \n # Keep only spells where total number of spell months (orig) equals total number spell months after intersection\n inters['post'] = inters.groupby(['serial_number', 'spell_num'])['serial_number'].transform('count')\n inters = inters.loc[inters['post'] == inters['nr_months']]\n inters.drop(columns=['post', 'nr_months'], inplace=True)\n uniq_fault_months_drop_part_spells = inters.drop_duplicates(subset=['serial_number', 'report_date']).shape[0] # unique fault months \n \n \n # What proportion of spell-months are reported a different facility_id?\n inters['uniq_facid'] = inters.groupby(['serial_number', 'spell_num'])['facility_id'].transform('nunique')\n uniq_facids = inters.drop_duplicates(subset=['serial_number', 'spell_num'])['uniq_facid'].value_counts().reset_index().rename(columns={'index':'uniq_facil_count', 'uniq_facid':'n_spells'}) # uniq facilities grouped by serial number & spell\n uniq_facids['share'] = uniq_facids['n_spells'] / len(inters.drop_duplicates(subset=['serial_number', 'spell_num']))\n \n # Drop all spell-months (and thereby spells in subsequent merge) if changed facility_id during spell\n inters = inters.loc[inters['uniq_facid'] == 1]\n uniq_fault_months_facid = inters.drop_duplicates(subset=['serial_number', 'report_date']).shape[0]\n \n \n # Merge back with spell data\n inters = inters[['serial_number', 'spell_num']].drop_duplicates()\n f = f.merge(inters, on=['serial_number', 'spell_num'], how='inner')\n final_spells = len(f)\n \n del f['spell_num']\n \n # Roll forward readiness month of spell back to where was originally\n f['read_startmo'] = (f['read_startmo'] + pd.DateOffset(months=1))\n \n print(\"\\nDone processing, outputting file to disk\")\n final_dir = r'\\\\div-sfrd.sfrd.ida.org\\public\\Pechacek\\ARNG Aircraft Readiness\\Data\\Processed\\Tables for merge'\n f.to_csv(os.path.join(final_dir, 'NMC_spells_final.csv'), index=False)\n f.to_csv(os.path.join(fault_dir, 'NMC_spells_final.csv'), index=False) # put copy in intermediate directory\n \n \n ##################################################\n ##### SUMMARY STATS OF MERGES #####\n ##################################################\n \n # Combine various counts\n df = pd.DataFrame()\n df = pd.DataFrame([uniq_spells_orig, uniq_fault_months_orig, uniq_fault_months_inters,\n uniq_fault_months_drop_part_spells, uniq_fault_months_facid, final_spells]).rename({0:'orig spells', 1:'spell months', 2:'spell months intersection',\n 3:'spell months drop part spells', 4:'spell months constant facility_id',\n 5:'final spells'}).reset_index().rename(columns={'index':'explanation', 0:'n_unique'})\n print(df)\n \n # Output merge stats to Excel workbook\n writer = pd.ExcelWriter(os.path.join(fault_dir+'\\\\summary_stats', 'readiness_fault_merge_stats.xlsx'), engine='openpyxl')\n stats.to_excel(writer, sheet_name='merge_month', index=False)\n df.to_excel(writer, sheet_name='merge_counts', index=False)\n uniq_facids.to_excel(writer, sheet_name='facility_counts', index=False)\n writer.save()","sub_path":"6_intersect_spell_readiness.py","file_name":"6_intersect_spell_readiness.py","file_ext":"py","file_size_in_byte":9072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"80539062","text":"import numpy as np\nimport cv2\n\nimg = cv2.imread('images/1_03b_0.png')\n\ndef graying(img):\n row, col, channel = img.shape\n img_gray=np.zeros((row,col),np.uint8)\n\n for r in range(row):\n for c in range(col):\n img_gray[r,c] = 0.11 * img[r,c,0] + 0.59*img[r,c,1] + 0.3*img[r,c,2]\n\n return img_gray\n\ncv2.imshow('img_gray',graying(img))\ncv2.imwrite('gray.jpg',graying(img))\ncv2.waitKey(0)","sub_path":"all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"117421355","text":"import numpy as np\nfrom scipy.spatial import cKDTree\n\n\ndef compute_map(lat1, lon1, lat2, lon2):\n \"\"\"Compute a mapping from one grid to another\n\n Takes an array of lats and lons, finds the closest matching point in a\n second array of lats and lons, and returns an array with the indices of\n those points.\n\n :param lat1: Array of lats to map\n :param lon1: Array of lons to map\n :param lat2: Array of lats to map to\n :param lon2: Array of lons to map to\n :return: Two arrays with the same shape as lat1/lon1 that contains the\n indices of the closest point in lat2/lon2\n \"\"\"\n\n # Combine lats and lons for processing\n original = np.dstack([lat1.ravel(), lon1.ravel()])[0].tolist()\n map2 = np.dstack([lat2.ravel(), lon2.ravel()])[0]\n\n # Build cKDTree\n tree = cKDTree(map2)\n\n # Get matching indices\n _, indices = tree.query(original)\n\n # Create map\n index = [i for i in np.ndindex(lat2.shape)]\n indices = np.reshape(indices, lat1.shape)\n latlon_map = np.empty(indices.shape, dtype=tuple)\n\n for i in np.ndindex(indices.shape):\n latlon_map[i] = index[indices[i]]\n\n return latlon_map\n\n\ndef map2grid(lat1, lon1, lat2, lon2, data, latlon_map=[], method='max'):\n \"\"\"Map the values from one grid to another\n\n :param lat1: Array containing the original latitudes of the data\n :param lon1: Array containing the original longitudes of the data\n :param lat2: Array containing the new latitudes to map to\n :param lon2: Array containing the new latitudes to map to\n :param data: Array with the data to map (must be same shape as lat1 / lon1)\n :param latlon_map: (Optional) Existing map produced by compute_map()\n :param method: How to handle multiple data at the same point\n Options are 'max' (default) and 'min'\n :return: Array with the same shape as lat2 / lon2 containing the processed data\n \"\"\"\n\n # Get map if not provided\n if len(latlon_map) == 0:\n latlon_map = compute_map(lat1, lon1, lat2, lon2)\n\n # Create an empty array of the new size\n new_data = np.empty(lat2.shape)\n new_data.fill(np.nan)\n\n # Copy the data over to the new grid\n for i in np.ndindex(data.shape):\n if method == 'max':\n new_data[latlon_map[i]] = max(data[i], new_data[latlon_map[i]])\n elif method == 'min':\n new_data[latlon_map[i]] = min(data[i], new_data[latlon_map[i]])\n else:\n print('FATAL ERROR: Unknown method: ' + method)\n\n # Fill any remaining NaNs with 0\n new_data = np.nan_to_num(new_data)\n\n return new_data\n\n","sub_path":"ush/href_calib_thunder/calib_thunder/util/grid_util.py","file_name":"grid_util.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"228376113","text":"yaml = '''\n- a: A1\n b: B1\n- a: A2\n'''\n\nfrom yamap import *\nfrom yamap.util import pair\nfrom dataclasses import dataclass\n\n@dataclass\nclass entry:\n a: str\n b: str = 'EMPTY'\n\nschema = (\n yaseq(type=pair, unpack=True)\n .case(\n yamap(type=entry, unpack=True)\n .exactly_one('a', yastr)\n .zero_or_one('b', yastr)\n )\n)\n\nprint(schema.load(yaml))\n","sub_path":"examples/unpack.py","file_name":"unpack.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"398892489","text":"import torch\nimport argparse\nimport os\nfrom dist_stat.application.pet_utils import *\nfrom dist_stat.application.pet_l1 import PET_L1\nimport numpy as np\nfrom scipy.sparse import coo_matrix, csr_matrix\nfrom scipy import sparse\n\ndef coo_to_sparsetensor(spm, TType=torch.DoubleTensor):\n typename = torch.typename(TType).split('.')[-1]\n TType_cuda = TType.is_cuda\n densemodule = torch.cuda if TType_cuda else torch\n spmodule = torch.cuda.sparse if TType_cuda else torch.sparse\n TType_sp = getattr(spmodule, typename)\n i = densemodule.LongTensor(np.vstack([spm.row, spm.col]))\n v = TType(spm.data)\n return TType_sp(i, v, spm.shape)\n\nimport torch.distributed as dist\ndist.init_process_group('mpi')\nrank = dist.get_rank()\nsize = dist.get_world_size()\n\nfrom dist_stat import distmat\nfrom dist_stat.distmat import THDistMat\nnum_gpu = torch.cuda.device_count()\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser(description=\"PET with TV penalty\")\n parser.add_argument('--gpu', dest='with_gpu', action='store_const', const=True, default=False, \n help='whether to use gpu')\n parser.add_argument('--double', dest='double', action='store_const', const=True, default=False, \n help='use this flag for double precision. otherwise single precision is used.')\n parser.add_argument('--nosubnormal', dest='nosubnormal', action='store_const', const=True, default=False, \n help='use this flag to avoid subnormal number.')\n parser.add_argument('--tol', dest='tol', action='store', default=0, \n help='error tolerance')\n parser.add_argument('--rho', dest='rho', action='store', default=0, \n help='penalty parameter')\n parser.add_argument('--offset', dest='offset', action='store', default=0, \n help='gpu id offset')\n parser.add_argument('--data', dest='data', action='store', default='../data/pet_gen_v2_100_120.npz', \n help='data file (.npz)')\n parser.add_argument('--dense', dest='dense', action='store_const', default=False, const=True, \n help='use dense data matrix')\n parser.add_argument('--iter', dest='iter', action='store', default=1000, \n help='max iter')\n args = parser.parse_args()\n if args.with_gpu:\n torch.cuda.set_device(rank % num_gpu)\n if args.double:\n TType=torch.cuda.DoubleTensor\n else:\n TType=torch.cuda.FloatTensor\n else:\n if args.double:\n TType=torch.DoubleTensor\n else:\n TType=torch.FloatTensor\n if args.nosubnormal:\n torch.set_flush_denormal(True)\n #floatlib.set_ftz()\n #floatlib.set_daz()\n\n rank = dist.get_rank()\n size = dist.get_world_size()\n\n\n\n datafile = np.load(args.data)\n\n\n n_x = datafile['n_x']\n n_t = datafile['n_t']\n \n # load e\n TType_name = torch.typename(TType).split('.')[-1]\n TType_sp = getattr(torch.sparse, TType_name)\n if args.with_gpu:\n TType_sp = getattr(torch.cuda.sparse, TType_name)\n #print(TType_sp)\n\n #e = torch.Tensor(datafile['e']).type(TType)\n e_indices = datafile[\"e_indices\"]\n e_values = datafile[\"e_values\"]\n\n p = n_x**2\n d = n_t * (n_t - 1) // 2\n p_chunk_size = p//size\n\n \n e_coo = coo_matrix((e_values, (e_indices[0,:], e_indices[1,:])), shape=(d, p))\n e_csc = e_coo.tocsc()\n e_csc_chunk = e_csc[:, (rank*p_chunk_size):((rank+1)*p_chunk_size)]\n e_coo_chunk = e_csc_chunk.tocoo()\n e_values = TType(e_coo_chunk.data)\n e_rows = torch.LongTensor(e_coo_chunk.row)\n e_cols = torch.LongTensor(e_coo_chunk.col)\n if e_values.is_cuda:\n e_rows = e_rows.cuda()\n e_cols = e_cols.cuda()\n e_indices = torch.stack([e_rows, e_cols], dim=1).t()\n e_shape = e_coo_chunk.shape\n e_size = torch.Size([int(e_shape[0]), int(e_shape[1])])\n e_chunk = TType_sp(e_indices, e_values, e_size).t()\n\n if not args.dense:\n e_dist = THDistMat.from_chunks(e_chunk).t()\n else:\n e_chunk = e_chunk.to_dense().t()\n e_dist = THDistMat.from_chunks(e_chunk, force_bycol=True)\n #print(e_dist.shape)\n\n # load D\n D_coo = sparse.coo_matrix((datafile['D_values'], \n (datafile['D_indices'][0,:], datafile['D_indices'][1,:])), \n shape=datafile['D_shape'])\n D_csr = D_coo.tocsr()\n D_csr_chunk = D_csr[:, (rank*p_chunk_size):((rank+1)*p_chunk_size)]\n D_coo_chunk = D_csr_chunk.tocoo()\n D_values = TType(D_coo_chunk.data)\n D_rows = torch.LongTensor(D_coo_chunk.row)\n D_cols = torch.LongTensor(D_coo_chunk.col)\n if D_values.is_cuda:\n D_rows = D_rows.cuda()\n D_cols = D_cols.cuda()\n D_indices = torch.stack([D_rows, D_cols], dim=1).t()\n D_shape = D_coo_chunk.shape\n D_size = torch.Size([int(D_shape[0]), int(D_shape[1])])\n D_chunk = TType_sp(D_indices, D_values, D_size).t()\n D_dist = THDistMat.from_chunks(D_chunk).t()\n\n counts = TType(datafile['counts']) # put everywhere\n\n pet = PET_L1(counts, e_dist, D_dist, sig=1/3, tau=1/3, rho=float(args.rho), TType=TType)\n pet.run(check_obj=True, tol=float(args.tol), check_interval=100, maxiter=int(args.iter))\n","sub_path":"examples/test_pet_l1.py","file_name":"test_pet_l1.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82985587","text":"import numpy as np\r\nimport math\r\n\r\n\"\"\"calculXYZfromGPS retourne les coordonnees dans le referentiel geocentrique\r\n(T,XT,YT,ZT) d'un point defini par sa longitude long (en degre), sa latitude\r\nlat (en degre) et sa hauteur h (en metre par rapport au niveau de la mer),\r\net le rayon de la Terre a cette latitude\r\n\r\nLa Terre etant approximee a un ellipsoide de rayon equatorial 6 378,137 km\r\net de rayon polaire 6 356,7523142 km, le rayon de la Terre depend de la latitude\"\"\"\r\n\r\ndef calculXYZfromGPS(longi, lat, h) :\r\n\trlong = math.radians(longi)\r\n\trlat = math.radians(lat)\r\n\tre = 6378137\r\n\trp = 6356752.3142\r\n\tRterre = (rp**2 / (1 + (math.cos(rlat))**2 * (rp**2 / re**2 - 1)))**0.5;\r\n\tM_T = [(Rterre+h) * math.cos(rlat)*math.cos(rlong),\r\n\t\t\t(Rterre+h) * math.cos(rlat)*math.sin(rlong),\r\n\t\t\t(Rterre+h) * math.sin(rlat)];\r\n\treturn [M_T, Rterre]\r\n\r\n","sub_path":"scripts/GeoScale/calculXYZfromGPS.py","file_name":"calculXYZfromGPS.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343181605","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport os\nfrom gensim.models.keyedvectors import KeyedVectors\nimport utils.FontUtil as FontUtil\nimport numpy as np\npd.set_option(\"display.max_rows\", 15)\n\n\n# In[2]:\n\n\ntitle = \"stanby-jobs-200d-word2vector.bin\"\nif not os.path.exists(title):\n print('Downloading ', title)\n url = \"https://github.com/bizreach/ai/releases/download/2018-03-13/stanby-jobs-200d-word2vector.bin\"\n urllib.request.urlretrieve(url, title)\nelse:\n print('Exists')\nw2v = KeyedVectors.load_word2vec_format(title, binary=True)\n\n\n# In[3]:\n\n\ndf = pd.read_csv('./words.csv')\nvectors = []\nzero_vec = np.zeros(200)\nfor value in df['words'].values:\n try:\n vectors.append(w2v[value])\n except:\n vectors.append(zero_vec)\n pass\n\n\n# In[4]:\n\n\nfrom sklearn.decomposition import PCA\n\n\n# In[5]:\n\n\npca = PCA(n_components=2)\n\n\n# In[6]:\n\n\nV = pca.fit_transform(vectors)\ntype(V)\n\n\n# In[7]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.font_manager as font_manager\nimport os\n\n\n# In[8]:\n\n\n# fontの設定\nif not os.path.exists(FontUtil.get_font_file_name()):\n font_path = FontUtil.retrieveOsaka()\nelse:\n font_path = FontUtil.get_font_file_name()\nprop = font_manager.FontProperties(fname = font_path)\n\n\n# In[9]:\n\n\nplt.figure(figsize=(20,20))\nplt.scatter(V[:,0], V[:,1])\nfor w,x,y in zip(df['words'].values, V[:,0], V[:,1]):\n plt.annotate(w, xy=(x,y), xytext=(3,3), textcoords = 'offset points', fontproperties=prop, fontsize=12)\n\n\n# # (2)\n\n# In[10]:\n\n\nfrom sklearn.cluster import KMeans\n\n\n# In[11]:\n\n\nk_means = KMeans(n_clusters=10, init='random')\n\n\n# In[12]:\n\n\nk_means.fit(V)\n\n\n# In[13]:\n\n\nclusters = k_means.predict(V)\n\n\n# In[14]:\n\n\ndf_V = pd.DataFrame(V, columns = ['X','Y'])\ndf_V['Cluster'] = clusters\ndf_V\n\n\n# In[15]:\n\n\ncolors = df_V['Cluster'].astype(np.float)\n\n\n# In[16]:\n\n\nplt.figure(figsize=(20,20))\nplt.scatter(V[:,0], V[:,1], c = colors)\nfor color, w, x, y in zip(colors, df['words'], V[:,0], V[:,1]):\n plt.annotate(w, xy=(x,y), xytext=(3,3), textcoords = 'offset points', fontproperties=prop, fontsize=12)\n\n\n# # (3)\n\n# In[17]:\n\n\nfrom sklearn.manifold import TSNE\n\n\n# In[18]:\n\n\nt = TSNE(n_components = 2, random_state=0)\n\n\n# In[19]:\n\n\nV = t.fit_transform(vectors)\n\n\n# In[20]:\n\n\nplt.figure(figsize=(20, 20))\nplt.scatter(V[:,0], V[:,1])\nfor w, x, y in zip(df['words'], V[:,0], V[:,1]):\n plt.annotate(w, xy=(x,y), xytext=(3,3), textcoords = 'offset points', fontproperties=prop, fontsize=12)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"section_1/1-14.py","file_name":"1-14.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"243248226","text":"\"\"\"\n5476. 找出数组游戏的赢家\n\"\"\"\n\n\nclass Solution:\n def getWinner(self, arr, k: int) -> int:\n k = len(arr) - 1 if k > len(arr) - 1 else k\n winner = arr[0]\n for i in range(len(arr)):\n round = 0 # 获胜轮次\n left = right = 1\n if i - left >= 0 and arr[i] > arr[i - left]:\n round += 1\n left += 1\n while arr[i] > arr[(i + right) % len(arr)]:\n round += 1\n right += 1\n if round >= k:\n winner = arr[i]\n break\n\n return winner\n\n\nif __name__ == '__main__':\n s = Solution()\n assert (s.getWinner([2, 1, 3, 5, 4, 6, 7], 2) == 5)\n assert (s.getWinner([3, 2, 1], 10) == 3)\n assert (s.getWinner([1, 9, 8, 2, 3, 7, 6, 4, 5], 7) == 9)\n assert (s.getWinner([1, 11, 22, 33, 44, 55, 66, 77, 88, 99], 1000000000) == 99)\n","sub_path":"array/5476.py","file_name":"5476.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"551691117","text":"import collections\n\nclass Solution:\n def orangeRotting(self, grid):\n m, n = len(grid), len(grid[0])\n fresh = 0\n q = collections.deque()\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n fresh += 1\n elif grid[i][j] == 2:\n q.append((i, j))\n if fresh == 0:\n return 0\n dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n step = 0\n while q:\n size = len(q)\n for i in range(size):\n x, y = q.popleft()\n for d in dirs:\n nx, ny = x + d[0], y + d[1]\n if nx < 0 or nx >= m or ny < 0 or ny >= n or grid[nx][ny] != 1:\n continue\n grid[nx][ny] = 2\n q.append((nx, ny))\n fresh -= 1\n step += 1\n if fresh:\n return -1\n return step - 1\n\nif __name__ == '__main__':\n grid = [[2,1,1], [1,1,0], [0,1,1]]\n s = Solution()\n print(s.orangeRotting(grid))","sub_path":"Python/0994_rotting_oranges.py","file_name":"0994_rotting_oranges.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644938152","text":"##Muhammad Rasheed Azeez\n##30355788\n\njess = ([\"php\", \"java\"], 200)\nclark = ([\"php\", \"c++\", \"go\"], 1000)\njohn = ([\"lua\"], 500)\ncindy = ([\"php\", \"go\", \"word\"], 240)\n\ncandidates = [jess, clark, john, cindy]\nproject = [\"php\", \"java\", \"c++\", \"lua\", \"go\"]\n\ndef cost(candidates):\n cost = 0\n for i in range(len(candidates)):\n cost += candidates[i][1] ##append cost from corresponding index position\n return cost\n\ndef skills(candidates):\n skills = []\n for i in range(len(candidates)): ##goes over all candidates\n for j in range(len(candidates[i][0])): ##to go over all skills of each candidate\n if candidates[i][0][j] not in skills:\n skills.append(candidates[i][0][j])\n return skills\n\ndef uncovered(project, skills):\n unc = []\n for i in range(len(project)):\n if project[i] not in skills: ##look for project skill in skills\n unc.append(project[i])\n return unc\n\ndef best_individual_candidate(project, candidates):\n best_rate = 0\n best_cand = 0\n for i in range(len(candidates)): ##goes over all candidates\n cov = []\n rate = 0\n for j in range(len(candidates[i][0])): ##finds each candidate's skills corresponding to project\n if candidates[i][0][j] in project:\n cov.append(candidates[i][0][j])\n rate = len(cov)/candidates[i][1] ##find rate of each candidate\n if rate > best_rate: ##update best rate and best candidate \n best_rate = rate\n best_cand = i\n return best_cand\n\ndef team_of_best_individuals(project, candidates):\n team = []\n rem_cand = candidates\n rem_skills = project\n for i in range(len(candidates)):\n j = best_individual_candidate(rem_skills, rem_cand) ##finds best candidate for uncovered skills in project\n team.append(rem_cand[j]) ##updates team\n rem_skills = uncovered(rem_skills, rem_cand[j][0]) ##updates uncovered skills\n rem_cand.pop(j) ##updates remaining candidates\n return team\n\ndef best_team(project, candidates):\n best_team = []\n best_rate = cost(candidates)\n in_list = bit_list(len(candidates)) ##generates bit list\n for x in range((2**len(candidates))):\n for i in range(len(in_list)): ##loops through bit list\n team = []\n for j in range(len(candidates)):\n if in_list[i][j] == 1:\n team.append(candidates[j]) ##creates team corresponding to bit sequence\n if uncovered(project, skills(team))==[]: ##considers valid teams only\n rate = cost(team)\n if rate < best_rate: ##updates best rate and best team\n best_rate = rate\n best_team = team\n return best_team\n\ndef bit_list(n):\n l = [[0 for i in range(n)]] ##initial case\n end = [1 for i in range(n)] ##end case\n while l[-1] != end:\n lst = l[-1][:]\n r = bit_calc(lst, n) ##calculates next sequence of bits\n l.append(r)\n return l\n\ndef bit_calc(r, n):\n i = 1\n while r[-i]==1: ##looks for 0\n if i <= n:\n i += 1 ##increases i until 0 found\n r[-i] = 1 ##converts 0 to 1\n while i != 1: ##converts all remaining bits to 0\n i -= 1\n r[-i] = 0\n return r\n","sub_path":"1045/a2-30355788_muhammadRasheed_azeez/hiring.py","file_name":"hiring.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526340523","text":"# coding=utf-8\n\nfrom framework.base_page import BasePage\nimport time\nfrom framework.logger import Logger\n\nlogger = Logger(logger = \"Logout\").getlog()\n\nclass Logout():\n @staticmethod\n def log_out(self):\n self.driver.find_element_by_xpath('//*[@id=\"topFrame\"]/ul/li[4]/a/i').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[2]/button[2]').click()\n time.sleep(1)\n txt = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/div/form/div/div[2]/a').text\n logoutpage = BasePage(self.driver)\n try:\n assert \"修改密码\" in txt\n logger.info(\"登出成功。\")\n except Exception as e:\n logger.error(\"登出失败。\", e)\n logoutpage.get_windows_img() # 调用基类截图方法","sub_path":"xy_pageobjects/logout.py","file_name":"logout.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"76737820","text":"#!/usr/bin/python3\nimport sqlite3\nimport sys\n\n#Setting up SQL basics\nconnection = sqlite3.connect(\"db.sqlite3\")\ncrsr = connection.cursor()\n\n\n#Creating the table\nsqlCommand = \"\"\"CREATE TABLE IF NOT EXISTS taxInfo_tax (\nidNumber INTEGER PRIMARY KEY,\nparent INTEGER,\nrank VARCHAR,\nsciName VARCHAR,\ncomName VARCHAR,\ngenComName VARCHAR,\ngcID INTEGER,\nmgcID INTEGER);\"\"\"\ncrsr.execute(sqlCommand)\n\n#Table with alternative names\nsqlCommand = \"\"\"CREATE TABLE IF NOT EXISTS taxInfo_names (\naltName VARCHAR,\nidNumber INTEGER);\"\"\"\ncrsr.execute(sqlCommand)\n\n\n#Adding each entry to the ID database\ndef writeEntry(entryDict):\n dictKeys = sorted(entryDict.keys())\n values = []\n for i in dictKeys:\n if type(entryDict[i]) == str:\n values.append('\"{}\"'.format(entryDict[i]))\n else:\n values.append(str(entryDict[i]))\n dictKeys = \", \".join(dictKeys)\n values = \", \".join(values)\n sqlCommand = \"\"\"INSERT INTO taxInfo_tax ({})\n VALUES ({});\"\"\".format(dictKeys, values)\n return sqlCommand\n\n#Making sure all strings have the same quotation marks to avoid issues importing into database\ndef quotationReplace(string):\n out = string.replace('\"', \"'\")\n return out\n\n#Creating dictionary with names\ndef addNewName(name, nameDict, ID):\n if name not in nameDict.keys():\n nameDict[name] = ID\n else:\n nameDict[name] = 0 #If a name is found for multiple species it is not useful for the search\n\n#Inserting data into table\nwith open(sys.argv[1], 'r') as data:\n entry = {}\n altNames = {}\n alternatives = [\"SYNONYM\", \"INCLUDES\", \"MISSPELLING\", \"ACRONYM\", \"ANAMORPH\", \"BLAST NAME\", \"EQUIVALENT NAME\", \"GENBANK ACRONYM\", \"GENBANK ANAMORPH\", \"GENBANK SYNONYM\", \"IN-PART\", \"MISNOMER\", \"TELEOMORPH\"]\n for line in data:\n line = line.strip()\n if line == \"//\":\n #Add entry into table\n sqlCommand = writeEntry(entry)\n crsr.execute(sqlCommand)\n entry = {}\n else:\n line = line.split(\":\")\n if line[0].strip() == \"ID\":\n entry[\"idNumber\"] = int(line[1].strip())\n elif line[0].strip() == \"PARENT ID\":\n entry[\"parent\"] = int(line[1].strip())\n elif line[0].strip() == \"RANK\":\n entry[\"rank\"] = quotationReplace(line[1].strip())\n elif line[0].strip() == \"GC ID\":\n entry[\"gcID\"] = int(line[1].strip())\n elif line[0].strip() == \"MGC ID\":\n entry[\"mgcID\"] = int(line[1].strip())\n elif line[0].strip() == \"SCIENTIFIC NAME\":\n name = quotationReplace(line[1].strip())\n entry[\"sciName\"] = name\n addNewName(name, altNames, entry[\"idNumber\"])\n elif line[0].strip() == \"GENBANK COMMON NAME\":\n name = quotationReplace(line[1].strip())\n entry[\"genComName\"] = name\n addNewName(name, altNames, entry[\"idNumber\"])\n elif line[0].strip() == \"COMMON NAME\":\n name = quotationReplace(line[1].strip())\n entry[\"comName\"] = name\n addNewName(name, altNames, entry[\"idNumber\"])\n elif line[0].strip() in alternatives:\n name = quotationReplace(line[1].strip())\n addNewName(name, altNames, entry[\"idNumber\"])\n\nfor name in altNames.keys():\n sqlCommand = \"\"\"INSERT INTO taxInfo_names (altName, idNumber)\n VALUES (\"{}\", {});\"\"\".format(name, str(altNames[name]))\n crsr.execute(sqlCommand)\n\nconnection.commit()\nconnection.close()\n","sub_path":"taxSite/createTaxDb.py","file_name":"createTaxDb.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364636459","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a Empleonuevo spider created on top of the ATSSpider\nscrapy crawl empleonuevo -a url=\"https://www.empleonuevo.com/\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n https://www.empleonuevo.com/\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix\n\n\nclass Empleonuevo(ATSSpider):\n\n name = \"empleonuevo\"\n ref_re = compile(\"\\/(\\d+)\\/\")\n count_re = compile(\"total de (\\d+)\")\n\n def parse(self, response):\n sel = Selector(response=response)\n if not self.expected_job_count_set:\n count = \"\".join(\n sel.xpath(\n \"//form[span[text()='Mostrando']]/text()\"\n ).extract()\n )\n count_res = self.count_re.search(count)\n if count_res:\n self.expected_job_count = count_res.group(1)\n\n jobs = sel.xpath(\"//section[@id='quicklist']/table/tbody/tr\")\n for job in jobs:\n job_link = job.xpath(\"./td[3]/a/@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n 'title': job.xpath(\"./td[3]/a/text()\").extract(),\n 'company': job.xpath(\"./td[4]/a/text()\").extract(),\n 'location': job.xpath(\"./td[2]/text()\").extract(),\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n next_page = sel.xpath(\"//a[text()=' > ']/@href\").extract()\n if next_page:\n next_url = urljoin(response.url, next_page[0])\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_value('company', response.meta['company'])\n loader.add_xpath(\"description\", \"//*[@class='descripcion']/node()\")\n loader.add_xpath(\n \"requirements\",\n \"//h5[text()='Experiencia y requisitos']/following-sibling::p/node()\"\n )\n loader.add_xpath(\n \"location\",\n \"//dt[contains(text(),'Ciudad')]/following-sibling::dd/text()\"\n )\n if not loader.get_output_value(\"location\"):\n loader.add_value('location', response.meta['location'])\n loader.add_value(\n \"referencenumber\", response.url, Prefix(\"%s-\" % self.name),\n re=self.ref_re\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/empleonuevo.py","file_name":"empleonuevo.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119675455","text":"import pandas as pd\nimport io, sys, os\nfrom os import path, listdir\nfrom datetime import datetime, timedelta\nfrom flask import Flask, make_response\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET', 'POST'])\ndef hello_world(request):\n \"\"\"Responds to any HTTP request.\n Args:\n request (flask.Request): HTTP request object.\n Returns:\n The response text or any set of values that can be turned into a\n Response object using\n `make_response `.\n \"\"\"\n raw_text = request.form.get('raw_text')\n paydate = request.form.get('raw_date')\n raw_csv = request.files.get('raw_csv').read()\n print(f'raw_text: {raw_text}')\n print(f'paydate: {paydate}')\n print(f'raw_csv: {raw_csv}')\n #print(f'{pd.__version__}')\n # can't do this:\n # print(f'csv3 head regular bytes: {pd.read_csv(csv3).head(1)}')\n # flask.Response('', headers={'Content-Type': 'text/html'})\n # return str(pd.read_csv(io.BytesIO(csv3)).to_dict())\n # res = make_response('JBoss - Error report', {'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*'})\n #res = make_response(pd.read_csv(io.BytesIO(raw_csv)).to_html(), {'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*'})\n #file_name = make_response(pd.read_csv(io.BytesIO(raw_csv), encoding='unicode_escape'), {'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*'})\n df = pd.read_csv(io.BytesIO(raw_csv), encoding='unicode_escape')\n #print(f'df: {df}, type df: {type(df)}')\n \n result = reconcile_month(df, paydate)\n result = result.to_html()\n\n #print(f'result of reconcile_month: {result}')\n return result\n\n# Start reconcile.py\n\ndef reconcile_month(df, paydate):\n '''\n Takes two strings as args. file_name, paydate 'M-D-YYYY' or 'MM-DD-YYYY'\n Returns final dataframe dfs_x\n '''\n # Find path to file, assign file_name, and print name of file we're running\n #path = os.getcwd()\n #file_name = os.path.join(path, file_name)\n #pd.set_option('max_colwidth', 400)\n #print(f'file_name: {file_name}')\n\n # Create datetime object YYYY-MM-DD from user input\n our_dt = datetime.strptime(paydate, '%Y-%m-%d').date()\n #print(f'our_dt: {our_dt}')\n\n # FUNCTION CALL to all other functs via coop_df\n # Return compiled dataframe at html\n final_df = coop_df(df, our_dt)\n # try:\n # final_df.to_html(\n # 'file.html',\n # columns=['Month', 'Week', 'Totals_WnT', 'Wages', 'Taxes', 'Employees'],\n # justify='left',\n # float_format='$%.2f')\n # except KeyError:\n # final_df.to_html(\n # 'file.html',\n # columns=['Month', 'Totals_WnT', 'Wages', 'Taxes', 'Employees'],\n # justify='left',\n # float_format='$%.2f')\n\n return final_df\n #print(f'final_df output: {final_df}')\n #print(f'res: {res}, type res: {type(res)}')\n\n #if __name__ == '__main__':\n # reconcile_month(sys.argv[1], sys.argv[2])\n\n\n# Start coop_df.py\ndef coop_df(df, datetime_obj):\n '''\n Intermediary funct btw reconcile.py and mums_little_helper.py\n\n Takes file_name & date as datetime object from reconcile_month\n Runs all other functions.\n\n Returns dataframe to reconcile.py. Dataframe returned represents one paycheck week,\n unless it detects a week that straddles two months, in which case the dataframe\n returned will represent two paycheck weeks.\n\n '''\n\n # Parse datetime_obj into year, month, day\n y = datetime_obj.year\n m = datetime_obj.month\n d = datetime_obj.day\n\n #ps_a, ps_b, dr_a, dr_b = slice_the_cack('datasets/Test file MMG2.CSV', 2019, 10, 10)\n ps_a, dr_a = slice_the_cack(df, y, m, d)\n depts = get_employees_by_dept(ps_a, dr_a)\n account_sums = get_sums(ps_a, dr_a, depts)\n piece_dict = pieces_of_me(account_sums, depts)\n dfs = sum_and_separate_by_dept(piece_dict)\n dfs_x = merge_dfs(dfs)\n\n # Check number of months present in initial dfs_x here\n if dfs_x['Month'].nunique() > 1:\n # if > 1, find previous week\n prev_dt = datetime_obj - timedelta(weeks = 1)\n # if previous week's month == initial week's month, run second time with previous week\n if prev_dt.month == m:\n dfs_pw = coop_df(df, prev_dt)\n dfs_pw['Week'] = dfs_pw['Wages'].apply(lambda x: 'A')\n dfs_x['Week'] = dfs_x['Wages'].apply(lambda x: 'B')\n dfs_x = pd.concat([dfs_pw, dfs_x])\n #print(f'This is concat with PW:\\n {dfs_x}')\n return dfs_x\n #print(f'prev_dt loop: {prev_dt, list_of_dfs_x}')\n else:\n #print(f'This found PW was out of month:\\n {dfs_x}')\n return dfs_x\n else:\n #print(f'This is returning only one initial week:\\n {dfs_x}')\n return dfs_x\n\n\n\n# Start mums_little_helper.py\n\ndef slice_the_cack(df, year, month, day,):\n '''\n Takes a Timestamp.\n\n Returns a dictionary of the Saturday through Sunday\n daterange before the previous Thursday where the keys\n are the int month numbers and the values\n are the percentage of days in each month\n of the total days returned in all months.\n\n '''\n\n pr = df\n pr['Date'] = pd.to_datetime(pr['Date'])\n pr.dropna(subset=['Date'], inplace=True)\n pr['Year'] = pr.copy()['Date'].dt.year\n pr['Month'] = pr.copy()['Date'].dt.month\n\n paydate_entered = pd.Timestamp(year=year, month=month, day=day, freq='D')\n\n #Based on paydate_entered, assign either week-immediately-before or week-of to dr_a\n if paydate_entered.weekday() <= 2:\n su = paydate_entered - ((paydate_entered.weekday() + 8) * paydate_entered.freq)\n sa = paydate_entered - ((paydate_entered.weekday() + 2) * paydate_entered.freq)\n else:\n su = paydate_entered - ((paydate_entered.weekday() + 1) * paydate_entered.freq)\n sa = su + 6 * paydate_entered.freq\n #\n # if paydate_entered.weekday() <= 2:\n # su = paydate_entered - ((paydate_entered.weekday() + 15) * paydate_entered.freq)\n # sa = paydate_entered - ((paydate_entered.weekday() + 9) * paydate_entered.freq)\n # else:\n # su = paydate_entered - ((paydate_entered.weekday() + 8) * paydate_entered.freq)\n # sa = paydate_entered - ((paydate_entered.weekday() + 2) * paydate_entered.freq)\n\n\n #EX. for 10-3, we assign dr_a the week-of 9-29 thru 10-5\n dr_a = pd.date_range(start=su, end=sa, freq='D')\n su = dr_a[0]\n\n #paycheck_span = first arg of get_sums AND a df displaying the sat to sun of dr_a\n ps_a = pr[ (pr['Date'] >= dr_a[0]) & (pr['Date'] <= dr_a[-1]) ]\n\n # # dr_b as week following dr_a\n # nexsu = dr_a[-1]+1*dr_a.freq\n # nexsa = dr_a[-1]+7*dr_a.freq\n # dr_b = pd.date_range(start=nexsu, end=nexsa, freq='D')\n # ps_b = pr[ (pr['Date'] >= dr_b[0]) & (pr['Date'] <= dr_b[-1]) ]\n\n return ps_a, dr_a\n\n\ndef get_sums(paycheck_span, dr, depts):\n\n '''\n Takes a df and a pd.date_range\n Returns\n {'fractmo': {9: 1.0},\n 'txs_by_emp': {'Adams, L': 46.32,\n 'Avery, B': 25.77,\n 'Bingo, Nolan': 39.650000000000006,\n 'Conde, Barb': 23.59,\n 'Clyde-Owens, L': 48.42,\n 'Chorse, MD': 33.42,\n 'Fray-Chase, Jay': 27.94,\n 'Gunn, Jim': 46.88,\n 'Graybranch, Linne': 57.209999999999994,\n 'Hedrovin, Zed': 15.509999999999998,\n 'Heart, Ray': 48.14,\n 'LaRay, Jane': 43.42,\n 'Lentifold, Eddie': 22.65,\n 'Mattison, Ronnie G.': 38.1,\n 'Peace, Jesse B.'': 31.34,\n 'Peet, Angela L': 61.23,\n 'Pino, Kola': 29.37,\n 'Picken, James': 42.79,\n 'Rich, Chiccie SR.': 35.74,\n 'Ryan, Noam': 31.37,\n 'Stark, Nancy B': 3.35,\n 'Teddy, Aimee': 31.02,\n 'Van Wilson, Len P.': 61.56,\n 'Wavering, Lindsay': 41.96},\n 'wgs': {'61101 · Salary & Wages-Packaging': 444.38,\n '61104 · Salary & Wages-Bakery': 2602.4799999999996,\n '61107 · Salary & Wages-Deli': 774.28,\n '61109 · Salary & Wages-Produce': 643.31,\n '61141 · Salary & Wages-Admin': 4110.31,\n '61142 · Salary & Wages-Store': 2804.06}}\n\n '''\n\n fractmo_dict = {}\n #print(f'paycheck_span: {paycheck_span}')\n\n #Finds the week before dr passed originally\n #This daterange represents the days that were actually worked\n #Allows fractmo_dict to iterate over appropriate week\n prevsun = dr[0] - 7 * dr.freq\n prevsat = dr[0] - 1 * dr.freq\n dr = pd.date_range(start=prevsun, end=prevsat, freq='D')\n\n for d in dr:\n try:\n fractmo_dict[d.month] = fractmo_dict[d.month] + 1\n except:\n fractmo_dict[d.month] = 1\n\n #divide each value by the sum\n total = sum(fractmo_dict.values(), 0.0)\n for key in fractmo_dict:\n fractmo_dict[key] = fractmo_dict[key] / total\n #print(f'get_sums: {fractmo_dict[key]}')\n\n paycheck_span = paycheck_span[ (paycheck_span['Num'] != 'Accrued Pay')]\n\n #Group paycheck_span by summed amount in each account for the week\n wnt = paycheck_span.groupby(['Account'], as_index=False)['Amount'].sum()\n\n #Dict of taxes sums per week by employee name\n vnt = paycheck_span.groupby(['Account', 'Name'], as_index=False)['Amount'].sum()\n #print(f'vnt: {vnt}')\n emp_txs = vnt[ (vnt['Account'] == '61210 · FICA Expense') | (vnt['Account'] == '61230 · NYUI Expense') ]\n #print(f'emp_txs: {emp_txs}')\n txs_by_emp = emp_txs.groupby(['Name'])['Amount'].sum().to_dict()\n\n #Dict of taxes sums per week, by department, according to emp-dept assignments\n\n # hold_tbe = {}\n # for n, t in txs_by_emp.items():\n #\n # hold_tbe[n] = t\n\n dept_taxes = {}\n for d, l in depts.items():\n dept_taxes[d] = 0\n\n for n in l:\n dept_taxes[d] += txs_by_emp[n]\n\n # print(f'hold_tbe: {hold_tbe}')\n # print(f'dept_taxes: {dept_taxes}')\n\n txs_for_depts_emps = dept_taxes\n\n #Dict of only salary & wages accounts' sums\n wgs = wnt[ (wnt['Account'] != '61210 · FICA Expense') & (wnt['Account'] != '61230 · NYUI Expense') ]\n wgs_sums_dict = wgs.groupby(['Account'])['Amount'].sum().iloc[:].to_dict()\n\n return {'txs_for_depts_emps': txs_for_depts_emps, 'txs_by_emp': txs_by_emp, 'wgs': wgs_sums_dict, 'fractmo': fractmo_dict}\n\n\ndef get_tax_dept(ps):\n '''\n Returns the department and amount for the employee\n where the employee made the highest total amount for\n that month.\n\n file_name (str): path to csv file\n year (int): year over which to look for dept\n month (int): month over which to look for dept\n employee_name (str): name of employee to look up\n '''\n\n #concatenate your two paycheck_spans\n #frames = [ps, pst]\n #print(pr['Date'])\n\n #pr = pd.read_csv(pr, encoding='unicode_escape')\n #pr['Date'] = pd.to_datetime(pr['Date'])\n # drop null dates (just the last row)\n # drop that weird first column, the useless Clr and Balance cols too\n #pr.drop(columns=['Unnamed: 0', 'Clr', 'Balance'], inplace=True)\n\n# # Remove FUPAs\n# pr = pr[ (pr['Account'] != '61210 · FICA Expense') & \\\n# (pr['Account'] != '61220 · FUTA Expense') & \\\n# (pr['Account'] != '61230 · NYUI Expense') ]\n\n # create month and year cols\n #pr['Year'] = pr.copy()['Date'].dt.year\n #pr['Month'] = pr.copy()['Date'].dt.month\n\n # get sum totals per employee by y/m/name/dept\n ps = ps.groupby(['Name', 'Account']).sum().reset_index()\n\n # Sort the df based on Year, Month, Name, Account, then Amount\n # We need this for the next rank step, and will then join\n # the two results together.\n ps.sort_values(['Name', 'Amount'], inplace=True, ascending=False)\n\n # create the ranks for each month/name combination. Record number\n # 1 should (but isn't) the department where the employee made the\n # most money that month\n ranks = ps.groupby(by=['Name'])['Amount'].rank(method='first')\n ranks = ranks.astype('int32')\n ranks.name = 'Rank'\n #print(ranks.head(20))\n\n # Join the pr dataframe and the ranks dataframe back together\n wbd = pd.merge(ps, ranks, left_index=True, right_index=True)\n\n # create a composite join key for wbd\n wbd['cjk'] = wbd['Name'] + wbd['Rank'].astype('str')\n\n # the rank that corresponds to the employee's highest earning department for that month\n max_ranks = wbd.groupby(['Name'])['Rank'].max().reset_index()\n # create a composite join key for max_ranks\n max_ranks['cjk'] = max_ranks['Name'] + \\\n max_ranks['Rank'].astype('str')\n\n # join the wbd and max_ranks table on their composite keys\n res = pd.merge(\n max_ranks,\n wbd,\n how='left',\n on='cjk',\n suffixes=('_mr', '')\n )[['Name', 'Account']]\n #print(res)\n res = res.set_index('Name')\n # fetch the user requested information from the res dataframe\n #vals = res[ (res['Year'] == year) & (res['Month'] == month) & (res['Name'] == employees) ].values\n\n# out_dict = {}\n\n# for i, j in zip(vals[0], ['year', 'month', 'name', 'dept', 'amount']):\n# out_dict[j] = i\n\n# out_df = pd.DataFrame(out_dict, index=[1])\n\n #res_dict = res.set_index('Name').to_dict()\n return res\n\ndef get_employees_by_dept(ps, dr):\n\n depts = get_tax_dept(ps)\n depts = depts.reset_index()\n depts = depts.groupby(['Account'])['Name']\n\n ebd = {}\n\n for d, n in depts:\n ebd[d] = []\n #print(f'd: {d}\\ntype of d: {type(d)}\\n')\n #print(f'n: {n}\\ntype of n: {type(n)}')\n\n for v in n:\n ebd[d].append(v)\n\n return ebd\n\ndef pieces_of_me(account_sums, depts):\n '''\n Takes dict that looks like dis.\n ratio of days in months within our one week paycheck range,\n sum of taxes by account,\n sum of salary and wages by dept.\n\n {'fractmo': {9: 1.0},\n 'txs_by_emp': {'Adams, L': 46.32,\n 'Avery, B': 25.77,\n 'Bingo, Nolan': 39.650000000000006,\n 'Conde, Barb': 23.59,\n 'Clyde-Owens, L': 48.42,\n 'Chorse, MD': 33.42,\n 'Fray-Chase, Jay': 27.94,\n 'Gunn, Jim': 46.88,\n 'Graybranch, Linne': 57.209999999999994,\n 'Hedrovin, Zed': 15.509999999999998,\n 'Heart, Ray': 48.14,\n 'LaRay, Jane': 43.42,\n 'Lentifold, Eddie': 22.65,\n 'Mattison, Ronnie G.': 38.1,\n 'Peace, Jesse B.'': 31.34,\n 'Peet, Angela L': 61.23,\n 'Pino, Kola': 29.37,\n 'Picken, James': 42.79,\n 'Rich, Chiccie SR.': 35.74,\n 'Ryan, Noam': 31.37,\n 'Stark, Nancy B': 3.35,\n 'Teddy, Aimee': 31.02,\n 'Van Wilson, Len P.': 61.56,\n 'Wavering, Lindsay': 41.96},\n 'wgs': {'61101 · Salary & Wages-Packaging': 444.38,\n '61104 · Salary & Wages-Bakery': 2602.4799999999996,\n '61107 · Salary & Wages-Deli': 774.28,\n '61109 · Salary & Wages-Produce': 643.31,\n '61141 · Salary & Wages-Admin': 4110.31,\n '61142 · Salary & Wages-Store': 2804.06}}\n\n\n Returns dict that looks like dis\n {9: {'txs_by_emp': {'Adams, L': 46.32,\n 'Avery, B': 25.77,\n 'Bingo, Nolan': 39.650000000000006,\n 'Conde, Barb': 23.59,\n 'Clyde-Owens, L': 48.42,\n 'Chorse, MD': 33.42,\n 'Fray-Chase, Jay': 27.94,\n 'Gunn, Jim': 46.88,\n 'Graybranch, Linne': 57.209999999999994,\n 'Hedrovin, Zed': 15.509999999999998,\n 'Heart, Ray': 48.14,\n 'LaRay, Jane': 43.42,\n 'Lentifold, Eddie': 2222.65,\n 'Mattison, Ronnie G.': 38.1,\n 'Peace, Jesse B.': 31.34,\n 'Peet, Angela L': 61.23,\n 'Pino, Kola': 29.37,\n 'Picken, James': 42.79,\n 'Rich, Chiccie SR.': 35.74,\n 'Ryan, Noam': 31.37,\n 'Stark, Nancy B': 3.35,\n 'Teddy, Aimee': 31.02,\n 'Van Wilson, Len P.': 61.56,\n 'Wavering, Lindsay': 41.96},\n 'wgs': {'61101 · Salary & Wages-Packaging': 444.38,\n '61104 · Salary & Wages-Bakery': 2602.4799999999996,\n '61107 · Salary & Wages-Deli': 774.28,\n '61109 · Salary & Wages-Produce': 643.31,\n '61141 · Salary & Wages-Admin': 4110.31,\n '61142 · Salary & Wages-Store': 2804.06}}}\n '''\n\n\n #iterate thru each of the account dicts\n #mult'ing by the ratio of days in first month (from fractmo_dict)\n #populate a dcit or df with\n# {key = month:\n# {key = account: value = sum as ratio of number of days within key month}.\n# {key = month:\n# {key = account: value = sum as ratio of number of days within key month}.\n\n\n piece_dict = {}\n\n for k, v in account_sums['fractmo'].items():\n piece_dict[k] = {}\n\n piece_dict[k]['wgs'] = {}\n for i, j in account_sums['wgs'].items():\n # This is how we get weekly fractional wages\n piece_dict[k]['wgs'][i] = j * v\n\n piece_dict[k]['txs_for_depts_emps'] = {}\n for m, n in account_sums['txs_for_depts_emps'].items():\n # This is how we get weekly sums of taxes according to depts emps are assigned\n piece_dict[k]['txs_for_depts_emps'][m] = n * v\n\n # tbe = {}\n # for m, n in account_sums['txs_by_emp'].items():\n # # This is how we get weekly fractional taxes by employee\n # tbe[m] = n * v\n\n # This adds emps listed by dept to piece_dict for later use in sum_and_separate_by_dept\n #piece_dict[k]['depts'] = depts\n\n tbebd = {}\n for d, l in depts.items():\n tbebd[d] = {}\n for n in l:\n tbebd[d][n] = round(account_sums['txs_by_emp'][n] * v, 2)\n\n piece_dict[k]['depts'] = tbebd\n\n # print(f'tbebd')\n # pprint(tbebd)\n cn = {}\n for d, t in account_sums['txs_for_depts_emps'].items():\n cn[d] = (t + account_sums['wgs'][d]) * v\n\n piece_dict[k]['cn'] = cn\n\n #one col be the dept names --- one col be wages plus txs_for_depts_emps\n\n\n\n return piece_dict\n\ndef make_lists_for_laterframes(generic_dict):\n\n '''\n\n Returns mini dfs out of series fed\n 'wages','taxes','employees' indexed by dept\n\n '''\n\n# print(f'generic_dict')\n# pprint(generic_dict)\n\n list_of_depts = []\n list_of_things = []\n\n for d, t in generic_dict.items():\n list_of_depts.append(d)\n list_of_things.append(t)\n\n return list_of_depts, list_of_things\n\ndef sum_and_separate_by_dept(piece_dict):\n '''\n Takes a dict that looks like dis\n {9: {'txs_by_emp': {'Adams, L': 46.32,\n 'Avery, B': 25.77,\n 'Bingo, Nolan': 39.650000000000006,\n 'Conde, Barb': 23.59,\n 'Clyde-Owens, L': 48.42,\n 'Chorse, MD': 33.42,\n 'Fray-Chase, Jay': 27.94,\n 'Gunn, Jim': 46.88,\n 'Graybranch, Linne': 57.209999999999994,\n 'Hedrovin, Zed': 15.509999999999998,\n 'Heart, Ray': 48.14,\n 'LaRay, Jane': 43.42,\n 'Lentifold, Eddie': 2222.65,\n 'Mattison, Ronnie G.': 38.1,\n 'Peace, Jesse B.': 31.34,\n 'Peet, Angela L': 61.23,\n 'Pino, Kola': 29.37,\n 'Picken, James': 42.79,\n 'Rich, Chiccie SR.': 35.74,\n 'Ryan, Noam': 31.37,\n 'Stark, Nancy B': 3.35,\n 'Teddy, Aimee': 31.02,\n 'Van Wilson, Len P.': 61.56,\n 'Wavering, Lindsay': 41.96},\n 'wgs': {'61101 · Salary & Wages-Packaging': 444.38,\n '61104 · Salary & Wages-Bakery': 2602.4799999999996,\n '61107 · Salary & Wages-Deli': 774.28,\n '61109 · Salary & Wages-Produce': 643.31,\n '61141 · Salary & Wages-Admin': 4110.31,\n '61142 · Salary & Wages-Store': 2804.06}}}\n\n Returns a list of dicts that looks like dis\n list_of_wgs_by_dept\n [{'61101 · Salary & Wages-Packaging': 89.43714285714285,\n '61104 · Salary & Wages-Bakery': 632.0857142857143,\n '61107 · Salary & Wages-Deli': 239.61714285714282,\n '61109 · Salary & Wages-Produce': 178.0971428571428,\n '61141 · Salary & Wages-Admin': 1342.802857142857,\n '61142 · Salary & Wages-Store': 566.3571428571428}]\n list_of_wgs_by_dept\n [{'61101 · Salary & Wages-Packaging': 89.43714285714285,\n '61104 · Salary & Wages-Bakery': 632.0857142857143,\n '61107 · Salary & Wages-Deli': 239.61714285714282,\n '61109 · Salary & Wages-Produce': 178.0971428571428,\n '61141 · Salary & Wages-Admin': 1342.802857142857,\n '61142 · Salary & Wages-Store': 566.3571428571428},\n {'61101 · Salary & Wages-Packaging': 223.59285714285713,\n '61104 · Salary & Wages-Bakery': 1580.2142857142858,\n '61107 · Salary & Wages-Deli': 599.0428571428571,\n '61109 · Salary & Wages-Produce': 445.2428571428571,\n '61141 · Salary & Wages-Admin': 3357.0071428571428,\n '61142 · Salary & Wages-Store': 1415.892857142857}]\n '''\n # print(f'piece_dict')\n # pprint(piece_dict)\n\n dfs = []\n\n for m in piece_dict:\n\n # Create wage dataframe\n depts, wages = make_lists_for_laterframes(piece_dict[m]['wgs'])\n df = pd.DataFrame(([0] * len(depts)), columns=['Wages'], index=[depts])\n df['Wages'] = wages\n df['Month'] = [m] * df.shape[0]\n dfs.append(df)\n\n # Create tax dataframe\n depts, taxes = make_lists_for_laterframes(piece_dict[m]['txs_for_depts_emps'])\n tax_df = pd.DataFrame(([0] * len(depts)), columns=['Taxes'], index=[depts])\n tax_df.columns = ['Taxes']\n tax_df['Taxes'] = taxes\n dfs.append(tax_df)\n\n # Create employee dataframe\n depts, emps = make_lists_for_laterframes(piece_dict[m]['depts'])\n emp_df = pd.DataFrame(([0] * len(depts)), columns=['Employees'], index=[depts])\n emp_df['Employees'] = emps\n dfs.append(emp_df)\n\n depts, credit_new = make_lists_for_laterframes(piece_dict[m]['cn'])\n cn_df = pd.DataFrame(([0] * len(depts)), columns=['Totals_WnT'], index=[depts])\n cn_df['Totals_WnT'] = credit_new\n dfs.append(cn_df)\n\n return dfs\n\ndef merge_dfs(dfs):\n\n # This is a trial way to loop through dfs indices and build dfs_x dataframe\n # group_df = []\n # x = []\n # for i, df in enumerate(dfs):\n # print(i)\n # if i % 2 == 0 and i != 0:\n # x.append(df)\n # print(x)\n # group_df.append(x)\n # x = []\n # else:\n # x.append(df)\n\n dfs_x = []\n\n dfs_a = dfs[0].merge(dfs[1], left_index=True, right_index=True)\\\n .merge(dfs[2], left_index=True, right_index=True)\\\n .merge(dfs[3], left_index=True, right_index=True)\n\n dfs_x.append(dfs_a)\n if len(dfs) > 4:\n dfs_b = dfs[4].merge(dfs[5], left_index=True, right_index=True)\\\n .merge(dfs[6], left_index=True, right_index=True)\\\n .merge(dfs[7], left_index=True, right_index=True)\n\n dfs_x.append(dfs_b)\n\n #dfs_x = pd.concat([dfs_a, dfs_b])\n dfs_x = pd.concat(dfs_x)\n\n return dfs_x\n","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":23880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235672727","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime\n\n# Django imports\nfrom django import forms\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import Http404\nfrom django.shortcuts import redirect\nfrom django.utils import timezone\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\nfrom django.utils.translation import ugettext_lazy as _, ugettext_lazy, pgettext_lazy\n\n# Devilry/cradmin imports\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.views.generic import View\nfrom django_cradmin import crapp\nfrom django_cradmin.viewhelpers import update, delete\nfrom django_cradmin.crispylayouts import PrimarySubmit, DefaultSubmit\nfrom django_cradmin.acemarkdown.widgets import AceMarkdownWidget\nfrom django_cradmin.widgets.datetimepicker import DateTimePickerWidget\nfrom devilry.devilry_group.views import cradmin_feedbackfeed_base\nfrom devilry.apps.core import models as core_models\nfrom devilry.devilry_group import models as group_models\nfrom devilry.utils import datetimeutils\n\n\nclass AbstractFeedbackForm(cradmin_feedbackfeed_base.GroupCommentForm):\n \"\"\"\n Feedback-related forms regarding grading or creating a new FeedbackSet inherits from this.\n \"\"\"\n def get_grading_points(self):\n raise NotImplementedError()\n\n\nclass PassedFailedFeedbackForm(AbstractFeedbackForm):\n \"\"\"\n Form for passed/failed grade plugin.\n \"\"\"\n\n #: Set delivery as passed or failed.\n passed = forms.BooleanField(\n label=pgettext_lazy('grading', 'Passed?'),\n help_text=pgettext_lazy('grading', 'Check to provide a passing grade.'),\n initial=True,\n required=False)\n\n @classmethod\n def get_field_layout(cls):\n return ['passed']\n\n def get_grading_points(self):\n if self.cleaned_data['passed']:\n return self.group.assignment.max_points\n else:\n return 0\n\n\nclass PointsFeedbackForm(AbstractFeedbackForm):\n \"\"\"\n Form for point-based grade plugin.\n \"\"\"\n\n #: Set points that should be given to the delivery.\n points = forms.IntegerField(\n required=True,\n min_value=0,\n label=_('Points'))\n\n def __init__(self, *args, **kwargs):\n super(PointsFeedbackForm, self).__init__(*args, **kwargs)\n self.fields['points'].max_value = self.group.assignment.max_points\n self.fields['points'].help_text = pgettext_lazy('grading', 'Number between 0 and %(max_points)s.') % {\n 'max_points': self.group.assignment.max_points\n }\n\n @classmethod\n def get_field_layout(cls):\n return ['points']\n\n def get_grading_points(self):\n return self.cleaned_data['points']\n\n\nclass EditGroupCommentForm(forms.ModelForm):\n \"\"\"\n Form for editing existing Feedback drafts.\n \"\"\"\n class Meta:\n fields = ['text']\n model = group_models.GroupComment\n\n @classmethod\n def get_field_layout(cls):\n return ['text']\n\n\nclass CreateFeedbackSetForm(cradmin_feedbackfeed_base.GroupCommentForm):\n \"\"\"\n Form for creating a new FeedbackSet (deadline).\n \"\"\"\n #: Deadline to be added to the new FeedbackSet.\n deadline_datetime = forms.DateTimeField(widget=DateTimePickerWidget)\n\n @classmethod\n def get_field_layout(cls):\n return ['deadline_datetime']\n\n\nclass ExaminerBaseFeedbackFeedView(cradmin_feedbackfeed_base.FeedbackFeedBaseView):\n \"\"\"\n Base view for examiner.\n \"\"\"\n def get_devilryrole(self):\n \"\"\"\n Get the devilryrole for the view.\n\n Returns:\n str: ``examiner`` as devilryrole.\n \"\"\"\n return 'examiner'\n\n def set_automatic_attributes(self, obj):\n super(ExaminerBaseFeedbackFeedView, self).set_automatic_attributes(obj)\n obj.user_role = 'examiner'\n\n\nclass ExaminerFeedbackView(ExaminerBaseFeedbackFeedView):\n \"\"\"\n The examiner feedbackview.\n This is the view where examiner corrects the delivery made by a student\n and is only able to create drafted comments, or publish grading.\n\n If the last FeedbackSet is published, this view redirects to :class:`.ExaminerFeedbackCreateFeedbackSetView`.\n See :func:`dispatch`.\n \"\"\"\n template_name = 'devilry_group/feedbackfeed_examiner/feedbackfeed_examiner_feedback.django.html'\n\n def dispatch(self, request, *args, **kwargs):\n \"\"\"\n Checks if the last FeedbackSet in the group is published. If it's published, a redirect response to\n :class:`~.ExaminerFeedbackCreateFeedbackSetView is returned.\n\n Args:\n request: request object.\n\n Returns:\n HttpResponse: The HTTP response.\n \"\"\"\n group = self.request.cradmin_role\n # # NOTE: :func:`~devilry.apps.core.models.AssignmentGroup.last_feedbackset_is_published` performs a query.\n if group.last_feedbackset_is_published:\n raise Http404\n return super(ExaminerFeedbackView, self).dispatch(request, *args, **kwargs)\n\n def get_form_class(self):\n \"\"\"\n Get the correct form based on what grade plugin that is used.\n\n Returns:\n A :class:`devilry.devilry_group.views.cradmin_feedbackfeed_base.GroupCommentForm`\n \"\"\"\n assignment = self.request.cradmin_role.assignment\n if assignment.grading_system_plugin_id == core_models.Assignment.GRADING_SYSTEM_PLUGIN_ID_PASSEDFAILED:\n return PassedFailedFeedbackForm\n elif assignment.grading_system_plugin_id == core_models.Assignment.GRADING_SYSTEM_PLUGIN_ID_POINTS:\n return PointsFeedbackForm\n else:\n raise ValueError('Unsupported grading_system_plugin_id: {}'.format(assignment.grading_system_plugin_id))\n\n def get_buttons(self):\n buttons = super(ExaminerFeedbackView, self).get_buttons()\n buttons.extend([\n DefaultSubmit('examiner_add_comment_to_feedback_draft',\n _('Save draft and preview'),\n css_class='btn btn-default'),\n PrimarySubmit('examiner_publish_feedback',\n _('Publish feedback'),\n css_class='btn btn-primary')\n ])\n return buttons\n\n def _add_feedback_draft(self, form, group_comment):\n \"\"\"\n Sets ``GroupComment.visibility`` to ``private`` and\n ``GroupComment.part_of_grading`` to ``True``.\n\n Args:\n group_comment (:obj:`~.devilry.devilry_group.models.GroupComment`): instance.\n\n Returns:\n (GroupComment): The update ``GroupComment``\n \"\"\"\n if form.cleaned_data['temporary_file_collection_id'] or len(group_comment.text) > 0:\n group_comment.visibility = group_models.GroupComment.VISIBILITY_PRIVATE\n group_comment.part_of_grading = True\n group_comment = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)\n return group_comment\n\n def _publish_feedback(self, form, feedback_set, user):\n \"\"\"\n\n Args:\n group_comment:\n\n Returns:\n\n \"\"\"\n # publish FeedbackSet\n result, error_msg = feedback_set.publish(\n published_by=user,\n grading_points=form.get_grading_points())\n if result is False:\n messages.error(self.request, ugettext_lazy(error_msg))\n\n def save_object(self, form, commit=False):\n comment = super(ExaminerFeedbackView, self).save_object(form=form)\n if comment.feedback_set.grading_published_datetime is not None:\n messages.warning(self.request, ugettext_lazy('Feedback is already published!'))\n else:\n if 'examiner_add_comment_to_feedback_draft' in self.request.POST:\n # If comment is part of a draft, the comment should only be visible to\n comment = self._add_feedback_draft(form=form, group_comment=comment)\n elif 'examiner_publish_feedback' in self.request.POST:\n # Add comment or files provided as draft, and let FeedbackSet handle the publishing.\n comment = self._add_feedback_draft(form=form, group_comment=comment)\n self._publish_feedback(form=form, feedback_set=comment.feedback_set, user=comment.user)\n return comment\n\n def get_form_invalid_message(self, form):\n return 'Cannot publish feedback until deadline has passed!'\n\n\nclass ExaminerPublicDiscussView(ExaminerBaseFeedbackFeedView):\n \"\"\"\n View for discussing with everyone on the group.\n\n All comments posted here are visible to everyone that has access to the group.\n \"\"\"\n template_name = 'devilry_group/feedbackfeed_examiner/feedbackfeed_examiner_discuss.django.html'\n\n def get_form_heading_text_template_name(self):\n return 'devilry_group/include/examiner_commentform_discuss_public_headingtext.django.html'\n\n def get_buttons(self):\n buttons = super(ExaminerPublicDiscussView, self).get_buttons()\n buttons.extend([\n DefaultSubmit(\n 'examiner_add_public_comment',\n _('Add comment'),\n css_class='btn btn-default')\n ])\n return buttons\n\n def save_object(self, form, commit=False):\n comment = super(ExaminerPublicDiscussView, self).save_object(form=form)\n comment.visibility = group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE\n comment.published_datetime = timezone.now()\n return super(ExaminerPublicDiscussView, self).save_object(form=form, commit=True)\n\n def get_success_url(self):\n return self.request.cradmin_app.reverse_appurl(viewname='public-discuss')\n\n\nclass ExaminerWithAdminsDiscussView(ExaminerBaseFeedbackFeedView):\n \"\"\"\n View for discussing with other examiners on the group and admins.\n\n All comments posted here are only visible to examiners and admins with access to\n the group.\n \"\"\"\n template_name = 'devilry_group/feedbackfeed_examiner/feedbackfeed_examiner_examiner_admin_discuss.django.html'\n\n def get_form_heading_text_template_name(self):\n return 'devilry_group/include/examiner_commentform_discuss_examiner_headingtext.django.html'\n\n def get_buttons(self):\n buttons = super(ExaminerWithAdminsDiscussView, self).get_buttons()\n buttons.extend([\n DefaultSubmit(\n 'examiner_add_comment_for_examiners_and_admins',\n _('Add comment'),\n css_class='btn btn-default')\n ])\n return buttons\n\n def save_object(self, form, commit=False):\n comment = super(ExaminerWithAdminsDiscussView, self).save_object(form=form)\n comment.visibility = group_models.GroupComment.VISIBILITY_VISIBLE_TO_EXAMINER_AND_ADMINS\n comment.published_datetime = timezone.now()\n return super(ExaminerWithAdminsDiscussView, self).save_object(form=form, commit=True)\n\n def get_success_url(self):\n return self.request.cradmin_app.reverse_appurl(viewname='examiner-admin-discuss')\n\n\nclass ExaminerFeedbackCreateFeedbackSetView(ExaminerBaseFeedbackFeedView):\n \"\"\"\n View to create a new FeedbackSet if the current last feedbackset is published.\n\n When a new unpublished FeedbackSet is created, this view redirects to :class:`.ExaminerFeedbackView`.\n See :func:`dispatch`.\n \"\"\"\n template_name = 'devilry_group/feedbackfeed_examiner/feedbackfeed_examiner_feedback.django.html'\n\n def dispatch(self, request, *args, **kwargs):\n \"\"\"\n Checks if the last FeedbackSet in the group is published. If it's published, a redirect response to\n :class:`~.ExaminerFeedbackView` is returned.\n\n Args:\n request (HttpRequest): request object.\n\n Returns:\n HttpResponse: The HTTP response.\n \"\"\"\n group = self.request.cradmin_role\n if not group.last_feedbackset_is_published:\n return HttpResponseRedirect(self.request.cradmin_app.reverse_appindexurl())\n return super(ExaminerFeedbackCreateFeedbackSetView, self).dispatch(request, *args, **kwargs)\n\n def get_form_class(self):\n return CreateFeedbackSetForm\n\n def get_buttons(self):\n buttons = super(ExaminerFeedbackCreateFeedbackSetView, self).get_buttons()\n buttons.extend([\n DefaultSubmit('examiner_create_new_feedbackset',\n _('Give new attempt'),\n css_class='btn btn-primary'),\n ])\n return buttons\n\n @staticmethod\n def __update_current_feedbackset(comment):\n \"\"\"\n Get the current :obj:`~devilry.devilry_group.models.FeedbackSet` from ``comment``, update it's fields and\n save it the changes.\n\n Args:\n comment (GroupComment): Get :obj:`~devilry.devilry_group.models.FeedbackSet` from.\n \"\"\"\n current_feedbackset = group_models.FeedbackSet.objects.get(id=comment.feedback_set_id)\n current_feedbackset.is_last_in_group = None\n current_feedbackset.grading_published_by = comment.user\n current_feedbackset.full_clean()\n current_feedbackset.save()\n\n def __create_new_feedbackset(self, comment, new_deadline):\n \"\"\"\n Creates a new :class:`devilry.devilry_group.models.FeedbackSet` as long as the ``new_deadline`` is\n in the future.\n\n :Note: Extra constraints to the new deadline and creation of a FeedbackSet may be added.\n\n Args:\n comment (GroupComment): Comment to be posted with the new FeedbackSet\n new_deadline (DateTime): The deadline.\n\n Returns:\n FeedbackSet: returns the newly created :class:`devilry.devilry_group.models.FeedbackSet` instance.\n\n \"\"\"\n # Make sure the deadline is in the future.\n if new_deadline <= datetimeutils.get_current_datetime():\n messages.error(self.request, ugettext_lazy('Deadline must be ahead of current date and time'))\n return None\n\n # Update current last feedbackset in group before\n # creating the new feedbackset.\n self.__update_current_feedbackset(comment)\n\n # Create a new :class:`~devilry.devilry_group.models.FeedbackSet` and save it.\n feedbackset = group_models.FeedbackSet(\n group=self.request.cradmin_role,\n feedbackset_type=group_models.FeedbackSet.FEEDBACKSET_TYPE_NEW_ATTEMPT,\n created_by=comment.user,\n deadline_datetime=new_deadline\n )\n feedbackset.full_clean()\n feedbackset.save()\n return feedbackset\n\n def save_object(self, form, commit=False):\n comment = super(ExaminerFeedbackCreateFeedbackSetView, self).save_object(form=form)\n if 'deadline_datetime' in form.cleaned_data:\n new_deadline = datetime.strptime(self.request.POST['deadline_datetime'], '%Y-%m-%d %H:%M')\n # Create a new :obj:`~devilry.devilry_group.models.FeedbackSet`.\n new_feedbackset = self.__create_new_feedbackset(comment=comment, new_deadline=new_deadline)\n if new_feedbackset is None:\n return comment\n if form.cleaned_data['temporary_file_collection_id'] or len(comment.text) > 0:\n # Also save comment and set the comments feedback_set to the newly\n # created new_feedbackset.\n comment.visibility = group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE\n comment.feedback_set = new_feedbackset\n comment.published_datetime = new_feedbackset.created_datetime + timezone.timedelta(seconds=1)\n commit = True\n return super(ExaminerFeedbackCreateFeedbackSetView, self).save_object(form=form, commit=commit)\n\n\nclass GroupCommentEditDeleteMixin(object):\n \"\"\"\n Basic mixin/super-class for GroupCommentDeleteView and GroupCommentEditView.\n \"\"\"\n model = group_models.GroupComment\n\n class Meta:\n abstract = True\n\n def get_queryset_for_role(self, role):\n \"\"\"\n Filter out :obj:`~devilry.devilry_group.models.GroupComment`s based on the role of role of the\n crinstance and the primarykey of the comment since in this case only a single comment should be fetched.\n\n Args:\n role (GroupComment): The roleclass for the crinstance.\n\n Returns:\n QuerySet: Set containing one :obj:`~devilry.devilry_group.models.GroupComment`.\n \"\"\"\n return group_models.GroupComment.objects.filter(\n feedback_set__group=role,\n id=self.kwargs.get('pk')).exclude_comment_is_not_draft_from_user(self.request.user)\n\n\nclass GroupCommentDeleteView(GroupCommentEditDeleteMixin, delete.DeleteView):\n \"\"\"\n View for deleting an existing groupcomment with visibility set to private.\n When a groupcomment has visibility set to private, this means it's a feedbackdraft.\n \"\"\"\n template_name = 'devilry_group/feedbackfeed_examiner/feedbackfeed_examiner_delete_groupcomment.html'\n\n def dispatch(self, request, *args, **kwargs):\n \"\"\"\n Checks if the GroupComment id passed is for a drafted comment.\n If the comment is not a draft, PermissionDenied is raised.\n\n Args:\n request (HttpRequest): request object.\n\n Returns:\n HttpResponseRedirect: Reponse redirect object.\n\n Raises:\n PermissionDenied: If comment is not a draft, this exception is raised.\n \"\"\"\n if len(self.get_queryset_for_role(request.cradmin_role)) == 0:\n raise PermissionDenied\n return super(GroupCommentDeleteView, self).dispatch(request, *args, **kwargs)\n\n def get_object_preview(self):\n return 'Groupcomment'\n\n def get_success_url(self):\n return self.request.cradmin_app.reverse_appindexurl()\n\n\nclass GroupCommentEditView(GroupCommentEditDeleteMixin, update.UpdateView):\n \"\"\"\n View to edit an existing feedback draft.\n\n Makes it possible for an Examiner to edit the ``text``-attribute value of a\n :class:`~devilry.devilry_group.models.GroupComment` that's saved as a draft.\n \"\"\"\n template_name = 'devilry_group/feedbackfeed_examiner/feedbackfeed_examiner_edit_groupcomment.html'\n\n def dispatch(self, request, *args, **kwargs):\n \"\"\"\n Checks if the GroupComment id passed is for a drafted comment.\n If the comment is not a draft, PermissionDenied is raised.\n\n Args:\n request (HttpRequest): request object.\n\n Returns:\n HttpResponseRedirect: Reponse redirect object.\n\n Raises:\n PermissionDenied: If comment is not a draft, this exception is raised.\n \"\"\"\n if len(self.get_queryset_for_role(request.cradmin_role)) == 0:\n raise PermissionDenied\n return super(GroupCommentEditView, self).dispatch(request, *args, **kwargs)\n\n def get_form_class(self):\n \"\"\"\n Get the formclass to use.\n\n Returns:\n EditGroupCommentForm: The form class.\n \"\"\"\n return EditGroupCommentForm\n\n def get_form(self, form_class=None):\n \"\"\"\n Set ``AceMarkdownWidget`` on the text form field and do not show the field label.\n Args:\n form_class: Defaults to None\n\n Returns:\n EditGroupCommentForm: Form with field-representations set.\n \"\"\"\n form = super(GroupCommentEditView, self).get_form(form_class=form_class)\n form.fields['text'].widget = AceMarkdownWidget()\n form.fields['text'].label = False\n return form\n\n def get_field_layout(self):\n \"\"\"\n Override get field layout as we're using ``AceMarkdownWidget`` to define\n the form field in our form class :class:`~.EditGroupCommentForm`.\n\n Returns:\n list: List extended with the field layout of :class:`~.EditGroupCommentForm`.\n \"\"\"\n field_layout = []\n field_layout.extend(self.get_form_class().get_field_layout())\n return field_layout\n\n def save_object(self, form, commit=True):\n \"\"\"\n Save the edited :obj:`~devilry.devilry_group.models.GroupComment`.\n\n Args:\n form: The :class:`~.EditGroupCommentForm` passed.\n commit: Should it be saved? (Defaults to True)\n\n Returns:\n GroupComment: The saved comment.\n \"\"\"\n comment = super(GroupCommentEditView, self).save_object(form=form, commit=commit)\n self.add_success_messages('GroupComment updated!')\n return comment\n\n def get_success_url(self):\n \"\"\"\n The success url is for this view if the user wants to continue editing, else it redirects to\n the indexview, :class:`~.ExaminerFeedbackView`.\n\n Returns:\n url: Redirected to view for that url.\n \"\"\"\n if self.get_submit_save_and_continue_edititing_button_name() in self.request.POST:\n return self.request.cradmin_app.reverse_appurl(\n 'groupcomment-edit',\n args=self.args,\n kwargs=self.kwargs)\n else:\n return self.request.cradmin_app.reverse_appindexurl()\n\n\nclass ExaminerFeedbackfeedRedirectView(View):\n def dispatch(self, request, *args, **kwargs):\n viewname = 'public-discuss'\n return redirect(self.request.cradmin_app.reverse_appurl(viewname=viewname))\n\n\nclass App(crapp.App):\n appurls = [\n crapp.Url(\n r'^$',\n ExaminerFeedbackfeedRedirectView.as_view(),\n name=crapp.INDEXVIEW_NAME),\n crapp.Url(\n r'^feedback$',\n ensure_csrf_cookie(ExaminerFeedbackView.as_view()),\n name='feedback'),\n crapp.Url(\n r'^public-discuss',\n ExaminerPublicDiscussView.as_view(),\n name='public-discuss'\n ),\n crapp.Url(\n r'^examiner-admin-discuss',\n ExaminerWithAdminsDiscussView.as_view(),\n name='examiner-admin-discuss'\n ),\n crapp.Url(\n r'^new-deadline$',\n ExaminerFeedbackCreateFeedbackSetView.as_view(),\n name='new-deadline'),\n crapp.Url(\n r'^groupcomment-delete/(?P\\d+)$',\n GroupCommentDeleteView.as_view(),\n name=\"groupcomment-delete\"),\n crapp.Url(\n r'^groupcomment-edit/(?P\\d+)$',\n GroupCommentEditView.as_view(),\n name='groupcomment-edit'),\n ]\n","sub_path":"devilry/devilry_group/views/examiner/feedbackfeed_examiner.py","file_name":"feedbackfeed_examiner.py","file_ext":"py","file_size_in_byte":22412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325284690","text":"### Name: Blake Buthod, Ethan Brizendine, Thomas Goodman, & George Wood\r\n### Date: 12-9-2016\r\n### File tile.py\r\n### The tile object that is manipulated in the unblock me style puzzle\r\n\r\nfrom display import *\r\n\r\nclass Block:\r\n \"\"\"\r\n The basic play object of the puzzle. Can only move in the direction\r\n of its orientation. The x and y coordinates are the upper leftmost\r\n spaces of the block.\r\n \"\"\"\r\n def __init__(self, blockNum, x, y, size, orientation):\r\n self.blockNum = blockNum\r\n self.x = x\r\n self.y = y\r\n self.size = size\r\n self.orientation = orientation\r\n\r\n #Get the file name for the image\r\n self.imageName = \"images/\"\r\n if size == 3:\r\n self.imageName += \"3\"\r\n elif size == 2:\r\n self.imageName += \"2\"\r\n \r\n if orientation == \"v\":\r\n self.coords = [(x,y),(x,y+1)]\r\n if size == 3:\r\n self.coords.append((x,y+2))\r\n #Add to imageName\r\n self.imageName += \"_vert\"\r\n elif orientation == \"h\":\r\n self.coords = [(x,y),(x+1,y)]\r\n if size == 3:\r\n self.coords.append((x+2,y))\r\n #Add to imageName\r\n self.imageName += \"_hor\"\r\n\r\n #Check if this is the red block for the image name\r\n if blockNum == 1:\r\n self.imageName += \"_red\"\r\n #Add the file extension for the image name\r\n self.imageName += \".png\"\r\n \r\n self.boardSize = 6\r\n self.collidedPieces = 0\r\n\r\n def __str__(self):\r\n \"\"\"\r\n Returns a string representation of the block.\r\n \"\"\"\r\n return (str(self.blockNum) + \" \" + str(self.coords))\r\n def setCoords(self):\r\n\r\n self.coords[0] = (self.x, self.y)\r\n if self.orientation == \"v\":\r\n self.coords[1] = (self.x,self.y+1)\r\n if self.size == 3:\r\n self.coords[2] = (self.x,self.y+2)\r\n elif self.orientation == \"h\":\r\n self.coords[1] = (self.x+1, self.y)\r\n if self.size == 3:\r\n self.coords[2] = (self.x+2, self.y)\r\n \r\n def copy(self):\r\n return Block(self.blockNum, self.x, self.y,\r\n self.size, self.orientation)\r\n \r\n def possibleMove(self, dist, blockList):\r\n \"\"\"\r\n Moves the block by an input distance in the plane of the\r\n block's orientation. Marks the state if a piece has crossed\r\n over another piece.\r\n \"\"\"\r\n \r\n if self.orientation == \"v\":\r\n for block in blockList:\r\n if dist >= 0:\r\n for n in range(dist):\r\n for coords in self.getCoords():\r\n if ((coords[0], coords[1] + n) in\r\n block.getCoords()) and (block.getNum() !=\r\n self.getNum()):\r\n self.collidedPieces = 1\r\n else:\r\n for n in range(0, dist, -1):\r\n for coords in self.getCoords():\r\n if ((coords[0], coords[1] +n) in\r\n block.getCoords()) and (block.getNum() !=\r\n self.getNum()):\r\n self.collidedPieces = 1\r\n \r\n self.y += dist\r\n self.setCoords()\r\n \r\n elif self.orientation == \"h\":\r\n for block in blockList:\r\n if dist >= 0:\r\n for n in range(dist):\r\n for coords in self.getCoords():\r\n if ((coords[0] + n, coords[1]) in\r\n block.getCoords()) and (block.getNum() !=\r\n self.getNum()):\r\n self.collidedPieces = 1\r\n else:\r\n for n in range(0, dist, -1):\r\n for coords in self.getCoords():\r\n if ((coords[0] + n, coords[1]) in\r\n block.getCoords()) and(block.getNum() !=\r\n self.getNum()):\r\n self.collidedPieces = 1\r\n \r\n self.x += dist\r\n self.setCoords()\r\n\r\n def getNum(self):\r\n \"\"\"\r\n Returns the block's number designation. 1 means it's the target block.\r\n \"\"\"\r\n return self.blockNum\r\n \r\n def getCoords(self):\r\n \"\"\"\r\n Returns the x and y coordinates of the block.\r\n \"\"\"\r\n \r\n return self.coords\r\n\r\n def getSize(self):\r\n \"\"\"\r\n Returns the size of the block.\r\n \"\"\"\r\n return self.size\r\n\r\n def getOrientation(self):\r\n \"\"\"\r\n Returns the orientation of the block.\r\n \"\"\"\r\n return self.orientation\r\n\r\n def getImageName(self):\r\n \"\"\"\r\n Returns the image name string used by the block. This is the file path to the image.\r\n \"\"\"\r\n return self.imageName\r\n\r\n def getWidth(self):\r\n \"\"\"\r\n Returns the width of the block.\r\n \"\"\"\r\n width = 1\r\n if self.orientation == \"h\":\r\n width = self.size\r\n return width\r\n \r\n def getHeight(self):\r\n \"\"\"\r\n Returns the height of the block.\r\n \"\"\"\r\n height = 1\r\n if self.orientation == \"v\":\r\n height = self.size\r\n return height\r\n \r\n","sub_path":"ProjectFiles2/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"65536921","text":"import tqdm\nimport torch\n\n\ndef test_model(hp, model, test_loader, writer):\n model.net.eval()\n total_test_loss = 0\n with torch.no_grad():\n for model_input, target in tqdm.tqdm(test_loader):\n target = target.to(hp.model.device)\n model_input = model_input.to(hp.model.device)\n output = model.net(model_input)\n total_test_loss += model.get_loss(output, target)\n\n total_test_loss /= len(test_loader.dataset) / hp.test.batch_size\n\n writer.test_logging(total_test_loss, model.step)\n","sub_path":"utils/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385833154","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plot\n\n\ndef add_layer(inputs, in_size, out_size, activation_function=None, name=\"\"):\n with tf.name_scope(name):\n weights = tf.Variable(tf.random_normal([in_size, out_size]))\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n tf.summary.histogram(name + \"_weights\", weights)\n tf.summary.histogram(name + \"_biases\", biases)\n wx_plus_b = tf.matmul(inputs, weights) + biases\n if activation_function is None:\n outputs = wx_plus_b\n else:\n outputs = activation_function(wx_plus_b)\n tf.summary.histogram(name + \"_outputs\", outputs)\n return outputs\n\n\nx_data = np.linspace(-1, 1, 300)[:, np.newaxis] # make x_data two-dimension\nnoise = np.random.normal(0, 0.05, x_data.shape)\ny_data = np.square(x_data) - 0.5 + noise\n\nxs = tf.placeholder(tf.float32, [None, 1], name=\"x_in\") # [None, 1] is a n-by-1 tensor. n can be any value\nys = tf.placeholder(tf.float32, [None, 1], name=\"y_in\") # [None, 1] is a n-by-1 tensor. n can be any value\n\n# Network\nl1 = add_layer(xs, 1, 10, tf.nn.relu, \"hidden_layer\")\nprediction = add_layer(l1, 10, 1, None, \"output_layer\")\n\nwith tf.name_scope(\"loss\"):\n loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), 1))\n tf.summary.scalar(\"loss\", loss)\n\nwith tf.name_scope(\"sgd\"):\n train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n\n# For TensorBoard\nsummary_all = tf.summary.merge_all()\nwriter = tf.summary.FileWriter(\"log/\", sess.graph)\n\nfig = plot.figure()\nplot.ion()\nfor i in range(1000):\n # Training\n sess.run(train_step, {xs: x_data, ys: y_data})\n # Check every 50 steps\n if i % 50 == 0:\n writer.add_summary(sess.run(summary_all, {xs: x_data, ys: y_data}), i)\n print(\"Loss after\", i, \"step(s):\", sess.run(loss, {xs: x_data, ys: y_data}))\n # Plot\n plot.clf()\n subplot = fig.add_subplot(1, 1, 1)\n subplot.scatter(x_data, y_data)\n subplot.plot(x_data, sess.run(prediction, {xs: x_data}), \"r-\")\n plot.pause(0.1) # second\n","sub_path":"python/parabola_fitting/parabola_fitting.py","file_name":"parabola_fitting.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"28142989","text":"from threading import Thread\r\nimport time\r\n\r\ndef test(id):\r\n for i in range(10):\r\n time.sleep(0.2)\r\n print('*'*5,i)\r\n\r\ntlist = [Thread(target=test,args=(i,)) for i in range(3)]\r\n\r\nfor temp in tlist:\r\n temp.daemon = True # main이 죽으면 모든 thread 소멸\r\n # idle는 shell이 최상위 main이기 때문에 shell이 꺼져야 thread 소멸\r\nfor temp in tlist:\r\n temp.start()\r\n\r\nprint('Main End')","sub_path":"11_01.10/Jan_10_04.py","file_name":"Jan_10_04.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597536709","text":"\"\"\"\n\nWrite contents to local files.\n\nCopyright (C) 2017 The Pylp Authors.\nLicense GPL3\n\n\"\"\"\n\nimport os\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pylp.lib.transformer import Transformer\n\n\n\ndef dest(path, cwd = None):\n\t\"\"\"Return a transformer that writes contents to local files.\"\"\"\n\treturn FileWriter(path, cwd)\n\n\n\ndef get_path(dest, file, cwd = None):\n\t\"\"\"Get the writing path of a file.\"\"\"\n\tif callable(dest):\n\t\treturn dest(file)\n\n\tif not cwd:\n\t\tcwd = file.cwd\n\tif not os.path.isabs(dest):\n\t\tdest = os.path.join(cwd, dest)\n\n\trelative = os.path.relpath(file.path, file.base)\n\treturn os.path.join(dest, relative)\n\n\ndef write_file(path, contents):\n\t\"\"\"Write contents to a local file.\"\"\"\n\tos.makedirs(os.path.dirname(path), exist_ok=True)\n\twith open(path, \"w\") as file:\n\t\tfile.write(contents)\n\n\n\nclass FileWriter(Transformer):\n\t\"\"\"Transformer that saves contents to local files.\"\"\"\n\n\tdef __init__(self, path, cwd = None):\n\t\tsuper().__init__()\n\n\t\tself.dest = path\n\t\tself.cwd = cwd\n\n\t\tself.exe = ThreadPoolExecutor()\n\t\tself.loop = asyncio.get_event_loop()\n\n\n\tasync def transform(self, file):\n\t\t\"\"\"Function called when a file need to be transformed.\"\"\"\n\t\tpath = get_path(self.dest, file)\n\t\tawait self.loop.run_in_executor(self.exe, write_file, path, file.contents)\n\t\treturn file\n","sub_path":"pylp/lib/dest.py","file_name":"dest.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"425738631","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patheffects as PathEffects\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef StochasticNeighborEmbedding(X,Y,dimension):\n tsne = TSNE(n_components=dimension,perplexity=40,learning_rate=300,n_iter=5000,\n verbose=1)\n X_embedded = tsne.fit_transform(X)\n if dimension == 2:\n scatter2D(X_embedded, Y) \n plt.savefig('Images/quotients_tsne-2D.png', dpi=120)\n else:\n scatter3D(X_embedded, Y) \n plt.savefig('Images/quotients_tsne-3D.png', dpi=120)\n \ndef PrincipalComponents(X,Y,dimension):\n pca = PCA(n_components=dimension)\n X_embedded = pca.fit_transform(X)\n if dimension == 2: \n scatter2D(X_embedded, Y)\n plt.savefig('Images/quotients_pca-2D.png', dpi=120)\n else:\n scatter3D(X_embedded, Y)\n plt.savefig('Images/quotients_pca-3D.png', dpi=120)\n \n \n#https://github.com/oreillymedia/t-SNE-tutorial\ndef scatter2D(x, y):\n \n fig = plt.figure(figsize=(8, 8))\n ax = fig.add_subplot(111,aspect='equal')\n \n colors = ['navy', 'turquoise']\n target_names = ['Lose (0)','Win (1)']\n lw = 2\n \n for color, i, target_name in zip(colors, [0, 1], target_names):\n ax.scatter(x[y == i, 0], x[y == i, 1], color=color, \n alpha=.8, lw=lw,label=target_name)\n plt.legend(loc='best', shadow=False, scatterpoints=1)\n plt.title('Quotients 2D')\n\n # We add the labels for each digit.\n txts = []\n for i in range(2):\n # Position of each label.\n xtext, ytext = np.median(x[y == i, :], axis=0)\n txt = ax.text(xtext, ytext, str(i), fontsize=24)\n txt.set_path_effects([\n PathEffects.Stroke(linewidth=5, foreground=\"w\"),\n PathEffects.Normal()])\n txts.append(txt)\n\ndef scatter3D(X_embedded, Y):\n fig = plt.figure(figsize=(8, 8))\n ax = fig.add_subplot(111, projection='3d')\n \n colors = ['navy', 'turquoise']\n target_names = ['Lose (0)','Win (1)']\n lw = 2\n \n for color, i, target_name in zip(colors, [0, 1], target_names):\n ax.scatter(X_embedded[Y == i, 0], X_embedded[Y == i, 1],X_embedded[Y == i, 2], color=color, \n alpha=.8, lw=lw,label=target_name)\n plt.legend(loc='best', shadow=False, scatterpoints=1)\n plt.title('Quotients 3D')","sub_path":"src/VisualizeData/VisualizeQuotients.py","file_name":"VisualizeQuotients.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411179474","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom odps.tests.core import TestBase, snappy_case\nfrom odps.compat import unittest, BytesIO\nfrom odps.tunnel.io import *\n\nimport io\n\ntry:\n from string import letters\nexcept ImportError:\n from string import ascii_letters as letters\n\n\nclass Test(TestBase):\n TEXT = u\"\"\"\n 上善若水。水善利万物而不争,处众人之所恶,故几於道。居善地,心善渊,与善仁,言善信,正善\n\n治,事善能,动善时。夫唯不争,故无尤。\n\n 绝学无忧,唯之与阿,相去几何?善之与恶,相去若何?人之所畏,不可不畏。荒兮其未央哉!众人\n\n熙熙如享太牢、如春登台。我独泊兮其未兆,如婴儿之未孩;儡儡兮若无所归。众人皆有馀,而\n\n我独若遗。我愚人之心也哉!沌沌兮。俗人昭昭,我独昏昏;俗人察察,我独闷闷。众人皆有以,而我独\n\n顽且鄙。我独异於人,而贵食母。\n\n 宠辱若惊,贵大患若身。何谓宠辱若惊?宠为下。得之若惊失之若惊是谓宠辱若惊。何谓贵大患若身\n\n?吾所以有大患者,为吾有身,及吾无身,吾有何患。故贵以身为天下,若可寄天下。爱以身为天下,若\n\n可托天下。\"\"\"\n\n def testCompressAndDecompressDflate(self):\n tube = io.BytesIO()\n\n outstream = DeflateOutputStream(tube)\n outstream.write(self.TEXT.encode('utf8'))\n outstream.flush()\n\n tube.seek(0)\n instream = DeflateInputStream(tube)\n\n b = bytearray()\n while True:\n part = instream.read(1)\n if not part:\n break\n b += part\n\n self.assertEquals(self.TEXT.encode('utf8'), b)\n\n @snappy_case\n def testCompressAndDecompressSnappy(self):\n tube = io.BytesIO()\n\n outstream = SnappyOutputStream(tube)\n outstream.write(self.TEXT.encode('utf8'))\n outstream.flush()\n\n tube.seek(0)\n instream = SnappyInputStream(tube)\n\n b = bytearray()\n while True:\n part = instream.read(1)\n if not part:\n break\n b += part\n\n self.assertEquals(self.TEXT.encode('utf8'), b)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"odps/tunnel/tests/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"623629692","text":"import numpy as np \nimport random \n\n# GAMBLER'S Problem: \n\n# State: Capital (maximmum value = 10)\n\n# Action: Bets/Stakes waged \n\n# Reward: 0 ~ Lossed or 1 ~ if Won \n\nif __name__ == '__main__': \n max_num_states = 10\n V = np.zeros(max_num_states)\n\n init_state = 5\n gamma = 1\n\n theta = .001\n betting_style = 0\n\n counter = 0\n current_state = None\n\n while True: \n\n delta = 0 \n counter += 1\n\n for state in range(0, max_num_states): \n\n if state == 0: \n P_h = 0 \n P_t = 0\n \n else: \n P_h = .9 \n P_t = .1\n\n v = 0 \n v_state = V[state]\n current_state = state\n\n if state == 0: \n pi = 0\n else: \n pi = 1.0/state\n\n for bet in range(1, state+1): \n\n # win_state = min((state + bet), 10)\n # loss_state = max((state - bet), 0)\n\n win_state = (state + bet)\n loss_state = (state - bet)\n\n R_win = bet\n R_loss = -bet \n\n if win_state >=10: \n win_state =0\n if loss_state <=0: \n loss_state = 0\n\n v_win = pi*P_h*(R_win + gamma*V[win_state])\n v_loss = pi*P_t*(R_loss + gamma*V[loss_state])\n\n v += v_win + v_loss\n\n # v += pi*P_h*(R_win + gamma*V[win_state]) + pi*P_t*(R_loss + gamma*V[loss_state])\n\n V[state] = v\n delta = max(delta, np.abs(v_state - V[state]))\n\n if delta < theta: \n break \n\n print(f\"Gambler's Problem: Value Function: - Num Itter {counter}\")\n print(V)\n\n\n \n\n\n\n\n \n\n\n\n\n\n","sub_path":"Algorithms/Chapter4_DynamicProgramming/hw3/hw2_1c_template.py","file_name":"hw2_1c_template.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"406326121","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 7 10:48:14 2017\n2017-7-7 11:37:54\n@author: wangxj\n\"\"\"\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nstart =time.clock()\n\ndef initCenters(dataSet,k):\n# numSamples,dim=dataSet.shape\n# centers=np.zeros((k,dim))\n# for i in range(k):\n# index =int(np.random.uniform(0,numSamples))#random get k centers\n# centers[i,:]=dataSet[index,:]\n index=np.random.choice(dataSet.shape[0],k)\n centers=dataSet[index,:]\n print(centers)\n return centers\n\ndef Dist2Centers(sample,centers):\n k=centers.shape[0]\n dis2cents=np.zeros(k)\n for i in range(k):\n dis2cents[i]=np.sqrt(np.sum(np.power(sample-centers[i,:],2)))\n return dis2cents\n\ndef kmeans(dataSet,k,iterNum):\n numsamples=dataSet.shape[0]\n iterCount=0\n #clusterAssignment stores which cluster this sample belongs to,\n clusterAssignment=np.zeros(numsamples)\n clusterChanged=True\n\n ##step 1 initialize centers\n centers=initCenters(dataSet,k)\n while clusterChanged and iterCount AVATAR_MAX_SIZE:\n raise ValidationError('Avatar can not bigger than %s' % filesizeformat(AVATAR_MAX_SIZE))\n return value\n\n def get_link_url(self, instance):\n return \"http://testapi.gowithtommy.com/anchor.html?anchor_id=%s\" % (instance.id,)\n\n\nclass AnchorDataSerializer(AnchorSerializer):\n class Meta:\n model = Anchor\n fields = (\n 'id',\n 'nickname',\n 'avatar',\n 'role',\n )\n\n\nclass BelongTagSerializer(serializers.ModelSerializer):\n anchor = AnchorDataSerializer()\n\n class Meta:\n model = BelongTag\n fields = ('id', 'type', 'tag', 'anchor')\n\n\nclass DefinedTagSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = DefinedTag\n fields = ('id', 'tag')\n\n\nclass CityTagSerializer(serializers.ModelSerializer):\n anchor = AnchorDataSerializer()\n\n class Meta:\n model = CityTag\n fields = ('id', 'type', 'tag', 'anchor')\n\n\nclass CountryTagSerializer(serializers.ModelSerializer):\n anchor = AnchorDataSerializer()\n\n class Meta:\n model = CountryTag\n fields = ('id', 'type', 'tag', 'anchor')\n\n\nclass NewAnchorSerializer(AnchorSerializer):\n class Meta:\n model = NewAnchor\n fields = ('id', 'nickname', 'avatar', 'description', 'link_url')\n\n\nclass CurrentUser(object):\n def set_context(self, serializer_field):\n self.user = serializer_field.context['request'].user\n\n def __call__(self):\n return self.user\n\n\nclass CurrentAlbum(object):\n def set_context(self, serializer_field):\n album_id = serializer_field.context['view'].kwargs.get('album_pk', 0)\n try:\n self.album = AnchorAlbum.objects.get(id=album_id)\n except ObjectDoesNotExist:\n raise NotFound\n\n def __call__(self):\n return self.album\n\n\n# class GetOrCreateSlugRelatedField(serializers.SlugRelatedField):\n# def to_internal_value(self, data):\n# tag, created = AlbumTag.objects.get_or_create(**{self.slug_field: data})\n# return tag\n\n#\n# class AnchorAlbumTagShipSerializer(serializers.ModelSerializer):\n# anchor = serializers.PrimaryKeyRelatedField(\n# read_only=True,\n# default=CurrentUser(),\n# )\n# album = serializers.PrimaryKeyRelatedField(\n# read_only=True,\n# default=CurrentAlbum(),\n# )\n# tag = GetOrCreateSlugRelatedField(\n# queryset=AlbumTag.no_deleted.all(),\n# many=False,\n# slug_field='tag',\n# )\n#\n# class Meta:\n# model = AnchorAlbumTagShip\n# fields = ('id', 'album', 'anchor', 'tag')\n#\n# def validate_user(self, value):\n# if value.is_anonymous():\n# raise PermissionDenied\n# elif not type(value) is CustomUser:\n# raise ValidationError('Invalid User.')\n# return value\n#\n# def save(self):\n# if not self.instance:\n# validated_data = dict(\n# list(self.validated_data.items() + [('is_deleted', False)])\n# )\n# self.instance, created = AnchorAlbumTagShip.objects.get_or_create(**validated_data)\n# return super(self.__class__, self).save()\nclass CommonAnchorAlbumSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = AnchorAlbum\n fields = ('id', 'name')\n\n\nclass CommonCategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('id', 'name')\n\n\nclass AnchorProgramSerializer(serializers.ModelSerializer):\n audio = serializers.SerializerMethodField()\n duration = serializers.SerializerMethodField()\n publish_date = serializers.SerializerMethodField()\n anchor = CommonCustomUserProfileSerializer()\n play_times = serializers.SerializerMethodField()\n category_id = serializers.SerializerMethodField()\n category = serializers.SerializerMethodField()\n anchor_album = CommonAnchorAlbumSerializer()\n\n\n class Meta:\n model = AnchorProgram\n fields = ('id', 'name', 'audio', 'anchor_album', 'image', 'duration', 'play_times',\n 'publish_date', 'category_id', 'category', 'anchor', 'link_url')\n\n def get_audio(self, instance):\n if not instance.audio and instance.file_url:\n return instance.file_url\n elif instance.audio:\n return instance.audio.url\n else:\n return None\n\n def get_duration(self, instance):\n return '%d: %d' % divmod(float(instance.duration), 60)\n\n def get_publish_date(self, instance):\n if instance.status_finished_at:\n return instance.status_finished_at.strftime('%Y.%m.%d')\n return ''\n\n def get_play_times(self, instance):\n return instance.play_times + instance.virtual_times\n\n def get_category_id(self, instance):\n return instance.anchor_album.category.id if instance.anchor_album.category else None\n\n def get_category(self, instance):\n return instance.anchor_album.category.name if instance.anchor_album.category else None\n\n def get_album_name(self, instance):\n return instance.anchor_album.name if instance.anchor_album else None\n\n\nclass AnchorAlbumSerializer(serializers.ModelSerializer):\n image_url = serializers.SerializerMethodField()\n update_date = serializers.SerializerMethodField()\n latest_program = serializers.SerializerMethodField()\n program_total = serializers.SerializerMethodField()\n play_times = serializers.SerializerMethodField()\n category = CommonCategorySerializer()\n anchor = AnchorDataSerializer()\n program = serializers.SerializerMethodField()\n link_url = serializers.SerializerMethodField()\n\n class Meta:\n model = AnchorAlbum\n fields = ('id', 'name', 'anchor', 'is_default', 'play_times', 'image', 'image_url', 'category',\n 'description', 'update_date', 'latest_program', 'program_total', \"program\", 'link_url')\n\n def get_image_url(self, instance):\n return instance.thumb_url()\n\n def get_update_date(self, instance):\n return instance.dt_updated.strftime('%Y.%m.%d')\n\n def get_latest_program(self, instance):\n qs = instance.programs.filter(is_deleted=False, status=AnchorProgram.PUBLISHED).order_by('-status_finished_at')\n if qs:\n return qs[0].name\n return ''\n\n def get_program_total(self, instance):\n # return instance.count_program\n return AnchorProgram.available.filter(anchor_album=instance).count()\n\n def get_play_times(self, instance):\n return AnchorProgram.available.filter(anchor_album=instance).aggregate(count=Sum(F('play_times') + F('virtual_times')))['count'] or 0\n\n def get_program(self, instance):\n program = AnchorProgram.available.filter(anchor_album_id=instance).order_by('-dt_created')\n program_list = AnchorProgramSerializer(program[:5], many=True).data\n return program_list\n\n def get_link_url(self, instance):\n return \"https://api.gowithtommy.com/special_detail.html?album_id=%s\" % (instance.id,)\n\n\nclass ReadOnlyAnchorAlbumSerializer(AnchorAlbumSerializer):\n anchor = CommonCustomUserProfileSerializer(read_only=True)\n\n class Meta:\n model = AnchorAlbum\n fields = ('id', 'name', 'anchor', 'is_default', 'play_times', 'image', 'image_url', 'category',\n 'description', 'update_date', 'latest_program', 'program_total', 'link_url')\n\n\nclass ReadOnlyCategoryAlbumSerializer(AnchorAlbumSerializer):\n anchor = CommonCustomUserProfileSerializer(read_only=True)\n\n class Meta:\n model = AnchorAlbum\n fields = ('id', 'name', 'anchor', 'is_default', 'play_times', 'image', 'image_url', 'category',\n 'description', 'update_date', 'latest_program', 'program_total', 'link_url')\n\n\nclass CategoryAlbumSerializer(CategorySerializer):\n album = serializers.SerializerMethodField()\n\n class Meta:\n model = Category\n fields = ('id', 'name', 'sort', 'album')\n\n def get_album(self, instance):\n program = AnchorProgram.available.values('anchor_album').annotate(count=Count('anchor_album')).filter(count__gt=0, is_deleted=False)\n album_list = map(lambda x: x['anchor_album'], program)\n album = AnchorAlbum.no_deleted.filter(id__in=album_list, category_id=instance.id)[:4]\n # album = AnchorAlbum.no_deleted.filter(count_program__gt=0, category_id=instance.id)[:4]\n album_list = ReadOnlyCategoryAlbumSerializer(album, many=True).data\n return album_list\n\n\n# class BelongTagSerializer(serializers.ModelSerializer):\n#\n# class Meta:\n# model = BelongTag\n# fields = ('id', 'tag')\n\n\nclass AnchorAlbumWebSerializer(AnchorAlbumSerializer):\n name = serializers.CharField(required=False)\n status_time = serializers.SerializerMethodField()\n status_explication = serializers.SerializerMethodField()\n status = serializers.SerializerMethodField()\n # tags = serializers.SerializerMethodField()\n # city_tag = serializers.SerializerMethodField()\n # country_tag = serializers.SerializerMethodField()\n category = serializers.SerializerMethodField()\n category_name = serializers.SerializerMethodField()\n play_times = serializers.IntegerField(read_only=True)\n anchor = serializers.PrimaryKeyRelatedField(\n default=CurrentUser(),\n queryset=Anchor.no_deleted.filter(is_available=True))\n\n program_total = serializers.SerializerMethodField()\n\n class Meta:\n model = AnchorAlbum\n fields = ('id', 'name', 'anchor', 'is_default', 'play_times', 'image', 'image_url',\n 'description', 'category', 'category_name', 'status', 'status_time', 'status_explication',\n 'program_total', 'latest_program',\n 'attribute_tag', 'defined_tag', 'city_tag', 'country_tag'\n )\n\n def _target_program(self, instance):\n if self.get_program_total(instance) > 0:\n queryset = AnchorProgram.no_deleted.filter(anchor_album=instance)\n if queryset.filter(status=AnchorProgram.REFUSED).exists():\n obj = queryset.filter(status=AnchorProgram.REFUSED).last()\n return (dict(AnchorProgram.CHOICES)[AnchorProgram.REFUSED],\n timezone.localtime(obj.status_finished_at).strftime('%Y-%m-%d %H:%M') if obj.status_finished_at else None,\n obj.status_explication)\n\n elif queryset.filter(status=AnchorProgram.CHECKING).exists():\n obj = queryset.filter(status=AnchorProgram.CHECKING).last()\n return (dict(AnchorProgram.CHOICES)[AnchorProgram.CHECKING],\n # obj.dt_created.strftime('%Y-%m-%d %H:%M'),\n timezone.localtime(obj.dt_created).strftime('%Y-%m-%d %H:%M') if obj.dt_created else None,\n '')\n else:\n obj = queryset.last()\n return (dict(AnchorProgram.CHOICES)[AnchorProgram.PUBLISHED],\n timezone.localtime(obj.status_finished_at).strftime('%Y-%m-%d %H:%M') if obj.status_finished_at else None,\n '')\n else:\n return '', '', ''\n\n def get_status_time(self, instance):\n status, status_time, status_explication = self._target_program(instance)\n return status_time\n\n def get_status(self, instance):\n status, status_time, status_explication = self._target_program(instance)\n return status\n\n def get_status_explication(self, instance):\n status, status_time, status_explication = self._target_program(instance)\n return status_explication\n\n def get_program_total(self, instance):\n # return instance.count_program\n return AnchorProgram.no_deleted.filter(anchor_album=instance).count()\n\n def get_category(self, instance):\n return instance.category.id if instance.category else None\n\n def get_category_name(self, instance):\n return instance.category.name if instance.category else None\n\n def validate_name(self, value):\n if len(value) >= 20:\n raise ValidationError('Name length can not bigger than 20')\n return value\n\n\nclass PopularAlbumSerializer(AnchorAlbumSerializer):\n class Meta:\n model = PopularAlbum\n fields = ('id', 'name', 'anchor', 'category', 'is_default', 'play_times', 'image', 'image_url', 'description',\n 'update_date', 'latest_program', 'program_total', 'link_url')\n\n\n# class ReadOnlyAnchorSerializer(serializers.ModelSerializer):\n# anchor, _ = UserType.objects.get_or_create(code='ANCHOR', defaults={'name': 'ANCHOR'})\n# type = serializers.SlugRelatedField(slug_field='code', default=anchor, queryset=UserType.objects.all())\n# authority = serializers.SlugRelatedField(slug_field='code', queryset=UserAuthority.objects.all(), required=False)\n#\n# class Meta:\n# model = Anchor\n# fields = (\n# 'id',\n# 'nickname',\n# 'avatar',\n# )\n\n\nclass RequiredAnchorAlbumWebSerializer(AnchorAlbumWebSerializer):\n name = serializers.CharField(\n required=False\n )\n description = serializers.CharField(\n required=False\n )\n category = serializers.PrimaryKeyRelatedField(\n required=False,\n queryset=Category.published_objects.all()\n )\n\n class Meta:\n model = AnchorAlbum\n fields = ('id', 'name', 'anchor', 'is_default', 'play_times', 'image', 'image_url',\n 'description', 'category',\n 'attribute_tag', 'defined_tag', 'city_tag', 'country_tag',\n )\n\n def validate_name(self, value):\n if len(value) >= 20:\n raise ValidationError('Name length can not bigger than 20')\n return value\n\n def validate_category(self, value):\n if value not in Category.published_objects.filter(type=Category.ALBUM):\n raise ValidationError('Invalid Category')\n return value\n\n def update(self, instance, validated_data):\n # tag_data = validated_data.pop('tags')\n for attr, value in validated_data.items():\n setattr(instance, attr, value)\n instance.save()\n return instance\n\n # AnchorAlbumTagShip.objects.filter(anchor_album=instance).delete()\n # for tag in tag_data:\n # AnchorAlbumTagShip.objects.get_or_create(anchor_album=instance, tag=tag)\n # return instance\n\n\nclass RecommendProgramSerializer(AnchorProgramSerializer):\n anchor_album = CommonAnchorAlbumSerializer()\n\n class Meta:\n model = RecommendProgram\n fields = ('id', 'name', 'audio', 'anchor_album', 'image', 'duration', 'play_times',\n 'publish_date', 'category_id', 'category', 'anchor', 'link_url')\n\n def get_anchor_album(self, instance):\n return instance.anchor_album.id if instance.anchor_album else None\n\n\nclass ProgramListSerializer(AnchorProgramSerializer):\n anchor_album = CommonAnchorAlbumSerializer()\n\n class Meta:\n model = ProgramList\n fields = ('id', 'name', 'audio', 'anchor_album', 'image', 'duration', 'play_times',\n 'publish_date', 'category_id', 'category', 'anchor_album', 'link_url')\n\n def get_anchor_album(self, instance):\n return instance.anchor_album.name\n\n\nclass AnchorProgramWebSerializer(AnchorProgramSerializer):\n audio_name = serializers.SerializerMethodField()\n status = serializers.SerializerMethodField()\n status_time = serializers.SerializerMethodField()\n anchor_album = CommonAnchorAlbumSerializer()\n\n class Meta:\n model = AnchorProgram\n fields = ('id', 'name', 'anchor_album', 'audio', 'audio_name', 'duration', 'image',\n 'publish_date', 'status', 'status_time', 'status_explication',)\n\n def get_status_time(self, instance):\n if instance.status == AnchorProgram.CHECKING:\n return timezone.localtime(instance.dt_created).strftime('%Y-%m-%d %H:%M')\n elif instance.status_finished_at:\n return timezone.localtime(instance.status_finished_at).strftime('%Y-%m-%d %H:%M')\n else:\n return ''\n\n def get_status(self, instance):\n return dict(AnchorProgram.CHOICES)[instance.status]\n\n def get_audio_name(self, instance):\n if instance.audio:\n return '%s.%s' % (instance.title, instance.audio.name.split('.')[-1])\n return ''\n\n\nclass RequiredAnchorProgramWebSerializer(AnchorProgramWebSerializer):\n name = serializers.CharField(required=False)\n anchor_album = serializers.PrimaryKeyRelatedField(\n required=False,\n # default=CurrentAlbum(),\n queryset=AnchorAlbum.no_deleted.all()\n )\n audio = serializers.FileField(required=False)\n image = serializers.FileField(required=False)\n\n def validate_audio(self, value):\n content_type = mimetypes.guess_type(value.name)[0]\n if content_type not in AUDIO_ALLOWED_CONTENT_TYPE:\n raise ValidationError('Invalid Audio')\n\n size = value.size\n if size > PROGRAM_AUDIO_MAX_SIZE:\n raise ValidationError('Audio can not bigger than %s' % filesizeformat(PROGRAM_AUDIO_MAX_SIZE))\n\n return value\n\n def validate_anchor_album(self, value):\n if value.anchor != self.context['request'].user:\n raise ValidationError('Invalid Album')\n return value\n\n\nclass BannerSerializer(serializers.ModelSerializer):\n image = serializers.SerializerMethodField()\n redirect_type_name = serializers.SerializerMethodField()\n anchor = serializers.SerializerMethodField()\n album = serializers.SerializerMethodField()\n\n class Meta:\n model = Banner\n fields = ('id', 'image', 'redirect_type', 'redirect_type_name', 'detail_id',\n 'sort', 'anchor', 'link_url', 'album')\n\n def get_image(self, instance):\n return instance.thumb_url()\n\n def get_redirect_type_name(self, instance):\n return dict(Banner.CHOICES)[instance.redirect_type]\n\n def get_anchor(self, instance):\n if instance.redirect_type == Banner.ANCHOR_DETAIL:\n try:\n anchor = CustomUser.available_objects.get(id=instance.detail_id)\n return AnchorSerializer(anchor).data\n except:\n return {}\n return {}\n\n def get_album(self, instance):\n if instance.redirect_type == Banner.ALBUM_DETAIL:\n try:\n album = AnchorAlbum.no_deleted.get(id=instance.detail_id)\n return ReadOnlyAnchorAlbumSerializer(album).data\n except:\n return {}\n return {}\n\n\nclass ButtonIconSerializer(serializers.ModelSerializer):\n class Meta:\n model = ButtonIcon\n fields = ('id', 'name', 'image', 'icon_type', 'link_url', 'manage_status',)\n\n\nclass CopyRightSerializer(serializers.ModelSerializer):\n class Meta:\n model = CopyRight\n fields = ('id', 'title', 'content', 'is_read')\n","sub_path":"radio/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":22610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"417722094","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns=[\n url(r'^$',views.index),\n url(r'^register$',views.register),\n url(r'^login$',views.login),\n #\n url(r'^dashboard$',views.dashboard),\n #\n url(r'^logout$',views.logout),\n\n url(r'^trips/new$',views.newtrip),\n url(r'^trips/new/process$',views.trips_new_process),\n \n url(r'^trips/edit/(?P[0-9]+)$',views.edit_trip),\n url(r'^edit/process/(?P[0-9]+)$',views.edit_process),\n\n url(r'^trips/(?P[0-9]+)$',views.show_trip_info),\n\n url(r'^cancel/(?P[0-9]+)$',views.cancel),\n \n url(r'^remove/(?P[0-9]+)$',views.remove),\n url(r'^join/(?P[0-9]+)$',views.join_trip),\n\n ]","sub_path":"django/django_orm/belt_exam/apps/exam/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"310422878","text":"from .base import Base\nimport logging\n\n\nclass Filter(Base):\n def __init__(self, vim):\n super().__init__(vim)\n\n self.name = 'sorter_beancount'\n self.description = 'beancount sorter'\n\n def filter(self, context):\n complete_str = context['complete_str'].lower()\n input_len = len(complete_str)\n return sorted(context['candidates'],\n key=lambda x: (\n self.rank_account(x['word']),\n abs(x['word'].lower().find(complete_str, 0, input_len))\n )\n )\n\n def rank_account(self, account):\n if account.startswith('Expenses'):\n return 1\n elif account.startswith('Equity'):\n return 3\n return 2\n","sub_path":"rplugin/python3/deoplete/filter/sorter_beancount.py","file_name":"sorter_beancount.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"580253107","text":"\"\"\"\nThis script will get the explorer-like graph for a type. It will get the type and calculate the path down.\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nfrom graphviz import Digraph\nfrom lib import sqlitestore\nfrom lib import my_env\n\n\ndef get_edge_app(rel_type):\n \"\"\"\n This procedure will create the dictionary that defines the edge appearance for this type of relations.\n @param rel_type: Type of the relation\n @return: dictionary to define appearance of the edge.\n \"\"\"\n if rel_type == \"in_procedure\":\n edge_appearance = {'color': \"#DC3800\"}\n elif rel_type == \"in_procedurestap\":\n edge_appearance = {'color': \"#75B095\"}\n elif rel_type == \"bij_procedurestap\":\n edge_appearance = {'color': \"#75B095\"}\n elif rel_type == \"voor_dossiertype\":\n edge_appearance = {'color': \"#DC3800\"}\n else:\n logging.error(\"Relation Type {rt} not defined.\".format(rt=rel_type))\n edge_appearance = {'color': \"#000000\"}\n return edge_appearance\n\n\ndef get_node_app(node_class):\n \"\"\"\n This procedure will create the dictionary that defines the node appearance for this class of nodes.\n @param node_class: Class of the Node\n @return: dictionary to define appearance of the node\n \"\"\"\n if node_class == \"Document\":\n node_appearance = {'fillcolor': \"#EAD800\",\n 'shape': \"box\",\n 'style': \"filled\"}\n elif node_class == \"ProcedureStap\":\n node_appearance = {'fillcolor': \"#B3801C\",\n 'shape': \"box\",\n 'style': \"filled\"}\n elif node_class == \"Procedure\":\n node_appearance = {'fillcolor': \"#EAD800\",\n 'shape': \"box\",\n 'style': \"filled\"}\n elif node_class == \"Dossiertype\":\n node_appearance = {'fillcolor': \"#B3801C\",\n 'shape': \"box\",\n 'style': \"filled\"}\n else:\n logging.error(\"Node Class {nc} not defined.\".format(nc=node_class))\n node_appearance = {'fillcolor': \"#DC3800\",\n 'shape': \"egg\",\n 'style': \"filled\"}\n return node_appearance\n\n\ndef go_down(item, branch, level):\n \"\"\"\n This function will collect all items for which this item is higher in hierarchy.\n So item is target, find all sources.\n @param item:\n @param branch: Remembers the branch of the tree. This allows to handle items more than once, depending on the start\n point.\n @param level: Shows how deep (how many levels) are required\n @return:\n \"\"\"\n item_list = ds.go_down(item)\n level += 1\n for attribs in item_list:\n item_label = \"{br}.{s}\".format(br=branch, s=attribs[\"source\"])\n eapp = get_edge_app(attribs[\"rel_type\"])\n dot.edge(item_label, branch, label=attribs[\"rel_type\"], **eapp)\n if item_label not in items:\n # New item, add node and relation, explore item\n items.append(item_label)\n napp = get_node_app(attribs[\"class\"])\n dot.node(item_label, attribs[\"naam\"], **napp)\n if level < args.depth:\n go_down(attribs[\"source\"], item_label, level)\n\n\nif __name__ == \"__main__\":\n # Configure Command line arguments\n parser = argparse.ArgumentParser(\n description=\"Script to create a explorer-like graph for components in 'Omgevingsvergunning' Archief\"\n )\n parser.add_argument('-t', '--type', default='Dossiertype',\n help='Set the component type to start with. Default is \"Dossiertype\".',\n choices=['Dossiertype', 'Procedure', 'ProcedureStap', 'Document'])\n parser.add_argument('-d', '--depth', type=int, default=2,\n help=\"Set the depth of the graph (default=2). Note that values above 3 don't result \"\n \"in readable graphs.\")\n args = parser.parse_args()\n cfg = my_env.init_env(\"convert_protege\", __file__)\n logging.info(\"Arguments: {a}\".format(a=args))\n # items is the list of components that have been handled.\n items = []\n ds = sqlitestore.DataStore(cfg)\n # Configure Graph\n dot = Digraph(comment=\"Overzicht van de structuur.\")\n # Configure Graph\n dot.graph_attr['rankdir'] = 'RL'\n dot.graph_attr['bgcolor'] = \"#ffffff\"\n dot.node_attr['style'] = 'rounded'\n # Get Protege IDs for the required types\n component_list = ds.get_components_type(args.type)\n for comp in component_list:\n # Get Node/Component attributes\n comp_rec = ds.get_comp_attribs(comp)\n if comp_rec is None:\n logging.error(\"No component record found for {c}.\".format(c=comp))\n else:\n items.append(comp)\n node_app = get_node_app(comp_rec[\"class\"])\n dot.node(comp, comp_rec[\"naam\"], **node_app)\n go_down(comp, branch=comp, level=1)\n # Now create and show the graph\n fid = \"{t}_{d}\".format(t=args.type, d=args.depth)\n graphfile = os.path.join(cfg[\"Main\"][\"graphdir\"], fid)\n dot.render(graphfile, view=True)\n logging.info('End Application')\n","sub_path":"Python/graph_type.py","file_name":"graph_type.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"553427032","text":"#hata copy paste barname gozashtam bazam hal nashod.\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pandas as pd\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import random_split, DataLoader\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net,self).__init__()\n self.linear1 = nn.Linear(3,5)\n self.linear2 = nn.Linear(5,2)\n\n def forward(self, x):\n y1 = self.linear1(x)\n y2 = F.relu(y1)\n y3 = self.linear2(y2)\n return y3\n\nclass Data(Dataset):\n def __init__(self,dataset_path):\n self.data = pd.read_csv(dataset_path)\n self.data_numeric = self.data.apply(pd.to_numeric)\n self.data_array = self.data_numeric.values\n print(self.data_array[1])\n self.x = torch.Tensor(self.data_array[:, :3]).float()\n self.y = torch.Tensor(self.data_array[:, 3]).long()\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n sample = (self.x[idx,:], self.y[idx])\n return sample\n\nprint(\"start\")\nmodel = Net()\nprint(\"created model\")\ndata = Data('E:\\proposal&payan nameh\\projectpython\\ProjectHowsamDL\\dataskin.csv')\nprint(\"created data\")\nprint(\"len\",len(data))\nprint(\"data[4]\",data[4])\n\nnumber_of_train=(0.7*len(data)).__int__()\nnumber_of_test=(0.2*len(data)).__int__()\nnumber_of_valid=(0.1*len(data)).__int__()\nprint(\"number_of_valid\",number_of_valid)\n\ntrain, valid, test = random_split\\\n (data,[number_of_train, number_of_valid, number_of_test]) #??howsam - inja error dare ... chera ?\nprint(\"self.train\",train)\n\ndataloader = DataLoader(train, batch_size=10, shuffle=True)\nprint(\"created dataloader\")\nloss_function = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(),lr=0.01)\n\nfor data_batch, label_batch in dataloader:\n x = data_batch\n y = label_batch\nfor i ,data_batch, label_batch in data :\n optimizer.zero_grad()\n print(\"shape\",data_batch.shape)\n out = model(data_batch)\n loss = optimizer(out,label_batch)\n print(i,loss.item())\n loss.backward()\n optimizer.step()\n\n\n\n\n\n\n\n","sub_path":"h3-MLP-with class-2.py","file_name":"h3-MLP-with class-2.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"351023858","text":"from graphics import*\nimport time\nfrom graphics import Point\n\n#Set up Window\n\nwin = GraphWin('Creature',1000,1000)\nwin.setBackground('yellow')\n\ntime.sleep(2)\n\n# set up delta variables to help move eyes more efficiently/quicker\ndelta_y = -60\ndelta_x = 0\n\n#sets up end points for the smile oval\n\nsmile_point_one = Point(80,200)\nsmile_point_two = Point(886,690)\n\n#draw smile\n\nsmiles = Oval(smile_point_one,smile_point_two)\nsmiles.draw(win)\nsmiles.setFill('yellow')\nsmiles.setOutline('black')\nsmiles.setWidth(30)\n\n#draw teeth\n\nleft_tooth = Rectangle(Point(388,698),Point(444,755))\nleft_tooth.draw(win)\nleft_tooth.setFill('white')\nleft_tooth.setWidth(10)\nleft_tooth.setOutline('black')\n\nright_tooth = Rectangle(Point(504,698),Point(555,755))\nright_tooth.draw(win)\nright_tooth.setFill('white')\nright_tooth.setWidth(10)\nright_tooth.setOutline('black')\n\n\n#draw yellow box designed to cover up top half of smile oval in order to create a half oval, creating a smile\n\nyellow_box = Rectangle(Point(57,97),Point(8794,479))\nyellow_box.draw(win)\nyellow_box.setFill('yellow')\nyellow_box.setOutline('yellow')\n\ntime.sleep(1)\n\n#generic function that draws spots on window. Takes x/y coordinates and size of desired spot as input values\n\ndef make_spots(x,y,size):\n spot_center = Point(x,y)\n spot = Circle(spot_center,size)\n spot.setFill('#CCCC00')\n spot.setOutline('#CCCC00')\n spot.draw(win)\n \n#multiple calls to make_spots functions that draws multiple spots on the window \nmake_spots (100,200,50)\nmake_spots (800,900,60)\nmake_spots (400,100,45)\nmake_spots (100,700, 80)\nmake_spots (900,100, 100)\nmake_spots (900,700, 80)\n\n\n\n#draws left cheek\n\n\nleft_cheek = Oval(Point(37,417),Point(104,488))\nleft_cheek.draw(win)\nleft_cheek.setFill('#FF7519')\n\n#draws cover for left cheek to create the illusion of a cheek\n\nleft_cheek_cover = Oval(Point(37,417),Point(104,478))\nleft_cheek_cover.draw(win)\nleft_cheek_cover.move(7,10)\nleft_cheek_cover.setFill('yellow')\nleft_cheek_cover.setOutline('yellow')\n\nright_cheek = Oval(Point(837,417),Point(904,488))\nright_cheek.draw(win)\nright_cheek.setFill('#FF7519')\n\n\nright_cheek_cover = Oval(Point(837,417),Point(904,478))\nright_cheek_cover.draw(win)\nright_cheek_cover.move(-5,10)\nright_cheek_cover.setFill('yellow')\nright_cheek_cover.setOutline('yellow')\n\n#series of freckles for cheeks\n\nright_freckle_one = Circle(Point(865,452),6)\nright_freckle_one.draw(win)\nright_freckle_one.setFill('#FF7519')\n\n\nright_freckle_two = Circle(Point(870,470),6)\nright_freckle_two.draw(win)\nright_freckle_two.setFill('#FF7519')\n\n\nright_freckle_three = Circle(Point(885,460),6)\nright_freckle_three.draw(win)\nright_freckle_three.setFill('#FF7519')\n\nfreckle_one = Circle(Point(77,462),6)\nfreckle_one.draw(win)\nfreckle_one.setFill('#FF7519')\n\n\nfreckle_two = Circle(Point(85,440),6)\nfreckle_two.draw(win)\nfreckle_two.setFill('#FF7519')\n\n\nfreckle_three = Circle(Point(55,450),6)\nfreckle_three.draw(win)\nfreckle_three.setFill('#FF7519')\n\ntime.sleep(1)\n\n#draws eyeballs, pupils, and iris of the eye\n\n#eye\n\nleft_eye_center = Point(295,380+delta_y)\nleft_eye = Circle(left_eye_center,175)\nleft_eye.setFill('white') \nleft_eye.setOutline('black')\nleft_eye.setWidth(5)\nleft_eye.draw(win)\n\n#iris\n\nleft_eye_center_inner = Point(305,420+delta_y)\nleft_eye_inner = Circle(left_eye_center_inner,70)\nleft_eye_inner.setFill('#19A3FF') \nleft_eye_inner.setOutline('black')\nleft_eye_inner.setWidth(5)\nleft_eye_inner.draw(win)\n\n#pupil\n\nleft_eye_center_inner_inner = Point(315,425+delta_y)\nleft_eye_inner_inner = Circle(left_eye_center_inner_inner,30)\nleft_eye_inner_inner.setFill('black') \nleft_eye_inner_inner.setOutline('black')\nleft_eye_inner_inner.setWidth(5)\nleft_eye_inner_inner.draw(win)\n\n#eye\n\nright_eye_center = Point(645,380+delta_y)\nright_eye = Circle(right_eye_center,175)\nright_eye.setFill('white') \nright_eye.setOutline('black')\nright_eye.setWidth(5)\nright_eye.draw(win)\n\n#iris\n\nright_eye_center_inner = Point(625,420+delta_y)\nright_eye_inner = Circle(right_eye_center_inner,70)\nright_eye_inner.setFill('#19A3FF') \nright_eye_inner.setOutline('black')\nright_eye_inner.setWidth(5)\nright_eye_inner.draw(win)\n\n#pupil\n\nright_eye_center_inner_inner = Point(615,425+delta_y)\nright_eye_inner_inner = Circle(right_eye_center_inner_inner,30)\nright_eye_inner_inner.setFill('black') \nright_eye_inner_inner.setOutline('black')\nright_eye_inner_inner.setWidth(5)\nright_eye_inner_inner.draw(win)\n\n#draws nose\n\nnose = Oval(Point(465,387),Point(532,475))\nnose.draw(win)\nnose.move(-10, -15)\nnose.setFill('yellow')\nnose.setOutline('black')\nnose.setWidth(10)\n\n#draws nose cover to give illusion of nose\n\nnose.cover = Oval(Point(465,387),Point(500,410))\nnose.cover.draw(win)\nnose.cover.move(-12, 50)\nnose.cover.setFill('yellow')\nnose.cover.setOutline('yellow')\nnose.cover.setWidth(10)\n\ntime.sleep(1)\n\n#creates 6 eyelashes (3 on each eye)\n\ndef make_eyelash_l3():\n \n p1 = Point(380,227+delta_y)\n p2 = Point(408,178+delta_y)\n p3 = Point(426,193+delta_y)\n p4 = Point(400,241+delta_y)\n \n eyelash = Polygon(p1,p2,p3,p4)\n eyelash.draw(win)\n eyelash.setFill('black')\n\n\ndef make_eyelash_l2():\n \n p1 = Point(284,203+delta_y)\n p2 = Point(312,206+delta_y)\n p3 = Point(314,166+delta_y)\n p4 = Point(289,169+delta_y)\n \n eyelash = Polygon(p1,p2,p3,p4)\n eyelash.draw(win)\n eyelash.setFill('black')\n \ndef make_eyelash_l1():\n \n p1 = Point(233,216+delta_y)\n p2 = Point(223,180+delta_y)\n p3 = Point(205,192+delta_y)\n p4 = Point(215,227+delta_y)\n \n eyelash = Polygon(p1,p2,p3,p4)\n eyelash.draw(win)\n eyelash.setFill('black')\n \n \ndef make_eyelash_r3():\n \n p1 = Point(380+29+322,227+delta_y)\n p2 = Point(408+29+322,178+delta_y)\n p3 = Point(426+29+322,193+delta_y)\n p4 = Point(400+29+322,241+delta_y)\n \n eyelash = Polygon(p1,p2,p3,p4)\n eyelash.draw(win)\n eyelash.setFill('black')\n\n\ndef make_eyelash_r2():\n \n p1 = Point(284+29+322,203+delta_y)\n p2 = Point(312+29+322,206+delta_y)\n p3 = Point(314+29+322,166+delta_y)\n p4 = Point(289+29+322,169+delta_y)\n \n eyelash = Polygon(p1,p2,p3,p4)\n eyelash.draw(win)\n eyelash.setFill('black')\n \ndef make_eyelash_r1():\n \n p1 = Point(233+29+322,216+delta_y)\n p2 = Point(223+29+322,180+delta_y)\n p3 = Point(205+29+322,192+delta_y)\n p4 = Point(215+29+322,227+delta_y)\n \n eyelash = Polygon(p1,p2,p3,p4)\n eyelash.draw(win)\n eyelash.setFill('black')\n \nmake_eyelash_l2()\nmake_eyelash_l3()\nmake_eyelash_l1()\n\nmake_eyelash_r2()\nmake_eyelash_r3()\nmake_eyelash_r1()\n\n\n'''\nwhile True:\n \n\n point=win.getMouse()\n point.draw(win)\n point.setFill('blue')\n \n x_point = point.getX()\n y_point= point.getY()\n \n info = (x_point,y_point)\n \n ancor_point = Point(50,50)\n fact = Text(ancor_point,info)\n \n fact.draw(win)\n fact.setFill('blue')\n haha = win.getMouse()\n fact.undraw()\n \n \n'''\n#allows for image to remain running until user terminates program by entering any input\naba = input()\n\n","sub_path":"tzinov_creature.py","file_name":"tzinov_creature.py","file_ext":"py","file_size_in_byte":6991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"619758292","text":"# -*- coding: utf-8 -*-\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\nfrom ui_rectangularpoints import Ui_RectangularPoints\n\nclass RectangularPointsGui(QDialog, QObject, Ui_RectangularPoints):\n MSG_BOX_TITLE = \"Arc Intersection\"\n\n coordSegments = pyqtSignal(float, float, bool, int, int, str)\n closeRectangularPointsGui = pyqtSignal()\n unsetTool = pyqtSignal()\n \n def __init__(self, parent, fl):\n QDialog.__init__(self, parent, fl)\n self.setupUi(self)\n \n def initGui(self):\n self.sboxA.setMaximum(10000000)\n self.sboxA.setMinimum(-10000000)\n self.sboxA.setDecimals(4)\n self.sboxA.setValue(0)\n\n self.sboxO.setMaximum(10000000)\n self.sboxO.setMinimum(-10000000)\n self.sboxO.setDecimals(4)\n self.sboxO.setValue(0)\n\n\n self.picNum.setMinimum(1)\n self.picNum.setValue(1)\n\n \n self.proNum.setMinimum(1)\n self.proNum.setValue(1)\n\n self.dX.setMaximum(10000000)\n self.dX.setMinimum(-10000000)\n self.dX.setDecimals(4)\n self.dX.setValue(1)\n\n self.dY.setMaximum(10000000)\n self.dY.setMinimum(-10000000)\n self.dY.setDecimals(4)\n self.dY.setValue(0)\n\n self.firstPK.setMaximum(10000000)\n self.firstPK.setMinimum(0)\n self.firstPK.setDecimals(0)\n self.firstPK.setValue(0)\n\n self.firstPR.setMaximum(10000000)\n self.firstPR.setMinimum(0)\n self.firstPR.setDecimals(0)\n self.firstPR.setValue(1)\n\n @pyqtSignature(\"on_btnAdd_clicked()\") \n def on_btnAdd_clicked(self):\n LayerName = self.lineEdit.text()\n i = 0\n j = 0\n firstPointX = self.sboxA.value()\n firstPointY = self.sboxO.value()\n picketNum = int(self.firstPK.value())\n profileNum = int(self.firstPR.value())\n for i in range(self.proNum.value()):\n for j in range(self.picNum.value()):\n self.coordSegments.emit(firstPointX, firstPointY, self.chckBoxInvert.isChecked(), profileNum, picketNum, LayerName)\n firstPointX += self.dX.value()\n picketNum += 1\n picketNum = int(self.firstPK.value())\n firstPointY += self.dY.value()\n firstPointX = self.sboxA.value()\n profileNum += 1\n self.firstPR.setValue(profileNum)\n QMessageBox.information(None, \"Cancel\", u'Точки добавлены')\n self.close()\n \n @pyqtSignature(\"on_btnCancel_clicked()\") \n def on_btnCancel_clicked(self): \n self.closeRectangularPointsGui.emit()\n self.unsetTool.emit()\n self.close()\n","sub_path":"tools/rectangularpointsgui.py","file_name":"rectangularpointsgui.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364816162","text":"\"\"\"\nInteractive Python console.\n\nRun Python code through IRC messages.\n\"\"\"\n\nimport code\nimport sys\n\nfrom io import StringIO\n\nfrom kochira.auth import requires_permission\nfrom kochira.service import Service\n\nservice = Service(__name__, __doc__)\n\n\n@service.setup\ndef setup_console(ctx):\n ctx.storage.console = code.InteractiveConsole({\"bot\": ctx.bot})\n\n\n@service.command(r\">>>(?: (?P.+))?\", priority=3000)\n@requires_permission(\"admin\")\ndef eval_code(ctx, code):\n \"\"\"\n Evaluate code.\n\n Evaluate code inside the bot. The local ``bot`` is provided for access to\n bot internals.\n \"\"\"\n\n code = code or \"\"\n\n stdout = StringIO()\n stderr = StringIO()\n\n sys.stdout = stdout\n sys.stderr = stderr\n\n err = None\n\n ctx.storage.console.locals[\"client\"] = ctx.client\n\n try:\n r = ctx.storage.console.push(code)\n except BaseException as e:\n err = \"{}: {}\".format(e.__class__.__qualname__, e)\n ctx.storage.console.resetbuffer()\n finally:\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n\n out = stdout.getvalue().rstrip(\"\\n\")\n\n if err is None:\n err = stderr.getvalue().rstrip(\"\\n\")\n\n if out:\n for line in out.split(\"\\n\"):\n ctx.message(\"<<< {}\".format(line))\n elif err:\n ctx.message(\"<[0-9]+)/$',\n views.OrdersListView.as_view(), name='orders-list'),\n url(r'^upload_file_with_products/$',\n views.upload_file_with_products, name='upload_file'),\n url(r'^get-orders/(?P[0-9]+)/$',\n views.get_orders_in_xlsx, name='get-orders'),\n url(r'^stop-file-tasks/(?P[0-9]+)/$',\n views.stop_not_processed_tasks, name='stop-file-tasks'),\n]\n","sub_path":"checkout_bot/checkout_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"305350249","text":"import requests\nimport json\n\n\nbase_url = (\n \"https://www.pals.pa.gov/api/Search/SearchForPersonOrFacilty\")\npage_number = 199\ndata = {\"OptPersonFacility\": \"Person\", \"ProfessionID\": 8, \"LicenseTypeId\": 383, \"LicenseNumber\": \"\",\n \"State\": \"\", \"Country\": \"ALL\", \"IsFacility\": 0, \"PageNo\": page_number}\nurl_List = list()\nrequests_session = requests.Session()\nresponse = requests_session.post(\n base_url, data)\nprint(response.status_code)\nprint(response.json())\n","sub_path":"MedPro/PALicSys/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259336798","text":"#Lista IV\n#Questao 02\nimport random\n\nprint(\"\\n ===============================================================================\\n\")\nprint('''\n\tSorteie 20 inteiros entre 1 e 100 numa lista. Armazene os números pares\n\tna lista PAR e os números ímpares na lista IMPAR. Imprima a s três listas\n\t ''')\n\nlista = []\npar = []\nimpar = []\n\nwhile len(lista) < 20:\n\tx = random.randint(1,100)\n\tif x not in lista:\n\t\tif x % 2 == 0:\n\t\t\tlista.append(x)\n\t\t\tpar.append(x)\n\t\telse:\n\t\t\tlista.append(x)\n\t\t\timpar.append(x)\n\nlista.sort()\npar.sort()\nimpar.sort()\n\nprint(\"Lista: \", lista, \"\\nPAR: \", par, \"\\nIMPAR: \", impar)\n\n\n\nprint(\"\\n ===============================================================================\\n\")","sub_path":"Lista_IV/questao02.py","file_name":"questao02.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"211416572","text":"from django.conf.urls import url\nfrom lab.views import user\n\nurlpatterns = [\n url(r'^login/$', user.login_user, name='user_login'),\n url(r'^register/$', user.register, name='user_register'),\n url(r'^logout/$', user.logout_user, name='user_logout'),\n url(r'^join_in_DMALab/$', user.join_in_DMALab, name='user_join_in_DMALab'),\n url(r'^homepage/$', user.homepage, name='user_homepage'),\n url(r'^lab_profile/$', user.lab_profile, name='user_lab_profile'),\n url(r'^settings/$', user.settings, name='user_settings'),\n]","sub_path":"lab/urls/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"631532709","text":"# -*- coding: utf-8 -*-\n\nimport setting\n# frame\nimport tools\nimport statistics\n# build-in\nimport sys\nfrom collections import defaultdict\nimport importlib\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\npipe_logger = tools.get_logger(__name__)\n\n\nclass NoPipeError(KeyError):\n pass\n\n\npipelines = defaultdict(list)\n\n\ndef init_pipelines(spiders):\n for spider in spiders:\n pipe_logger.debug(\"Init spider<%s>'s pipelines\", spider)\n try:\n spider_pipelines = getattr(setting, 'spiders')[spider.__class__.__name__]['pipelines']\n for each in spider_pipelines:\n each = each.split('.')\n module_name = 'pipelines.'+'.'.join(each[:-1])\n pipe_name = each[-1]\n module = importlib.import_module(module_name)\n pipe = getattr(module, pipe_name)()\n pipelines[spider.__class__.__name__].append(pipe)\n except KeyError:\n pipe_logger.warning(NoPipeError(\"Spider<%s> has no pipeline\" % spider))\n\n\nclass OutPutManager(object):\n def __init__(self, spiders):\n init_pipelines(spiders)\n\n def __call__(self, item, spider):\n statistics.add_item_num()\n try:\n for each in pipelines[spider.__class__.__name__]:\n item = each.through(item)\n if not item:\n return\n except Exception as err:\n pipe_logger.error('Unexpected error happened when item<%s> going through pipelines, reason: %s',\n statistics.get_item_num(), err)\n raise\n OutPutManager.__print_item(item)\n\n @staticmethod\n def __print_item(item):\n msg = 'Save Item<%s>:\\n' % statistics.get_item_num()\n msg += '\\n'.join([str(key)[:70] + ': ' + str(value)[:70] for key, value in item.items()])\n pipe_logger.info(msg)\n","sub_path":"core/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"7067976","text":"# This script adds an entry to the current lab session based on the template\n\nimport os\nfrom datetime import datetime \nfrom shutil import copyfile\n\n# IDENTIFIER\nCODENAME = 'INTERFEROMETRY'\n\n# Get the lab session number\nsession_number = max([int(x[0]) for x in os.listdir('.') if x[1] == '.']) + 1\n\n# Get the new directory name\nnow = datetime.now()\nname = now.strftime(str(session_number)+\".\"+CODENAME+\"__%b-%d-%Y__%H-%M-%S\")\n\n# Make the new directory\nos.mkdir(name)\n\n# Copy the tutorial directory to the new one\ncopyfile('0.TEMPLATE/csvlib.py',name+'/csvlib.py')\ncopyfile('0.TEMPLATE/data.csv',name+'/data.csv')\ncopyfile('0.TEMPLATE/README.md',name+'/README.md')\ncopyfile('0.TEMPLATE/0.Template.ipynb',name+'/'+str(session_number)+'.ANALYSIS.ipynb')\n","sub_path":"3.Interferometry/1.Lab-Data/add_entry.py","file_name":"add_entry.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"253959604","text":"########################################\n#\n# Program Code for Fred Inmoov\n# Of the Cyber_One YouTube Channel\n#\n# This is version 2 with Blink and TTS\n#\n######################################### generate random integer values\nfrom random import seed\nfrom random import randint\n# seed random number generator\nseed(1)\n# start the service\nraspi = Runtime.createAndStart(\"raspi\",\"RasPi\")\n\n# Head.setController(\"RasPi\",\"1\",\"0x40\")\nHead = Runtime.createAndStart(\"Head\",\"Adafruit16CServoDriver\")\nHead.attach(\"raspi\",\"1\",\"0x40\")\n\n# Start the clock services\nBlinkClock = Runtime.createAndStart(\"BlinkClock\",\"Clock\")\nAwakeClock = Runtime.createAndStart(\"AwakeClock\",\"Clock\")\nAwake = False\n\n# Change the names of the servos and the pin numbers to your usage\nRightEyeLR = Runtime.createAndStart(\"RightEyeLR\", \"Servo\")\n# attach it to the pwm board - pin 15\nRightEyeLR.attach(Head,15)\n# Next lets set the various limits and mappings.\nRightEyeLR.setMinMax(0,180)\nRightEyeLR.map(0,180,1,180)\nRightEyeLR.setRest(90)\nRightEyeLR.setInverted(False)\nRightEyeLR.setVelocity(60)\nRightEyeLR.setAutoDisable(True)\nRightEyeLR.rest()\n\nRightEyeUD = Runtime.createAndStart(\"RightEyeUD\", \"Servo\")\n# attach it to the pwm board - pin 14\nRightEyeUD.attach(Head,14)\nRightEyeUD.setMinMax(0,180)\nRightEyeUD.map(0,180,1,180)\nRightEyeUD.setRest(90)\nRightEyeUD.setInverted(False)\nRightEyeUD.setVelocity(120)\nRightEyeUD.setAutoDisable(True)\nRightEyeUD.rest()\n\n\nLeftEyeLR = Runtime.createAndStart(\"LefttEyeLR\", \"Servo\")\n# attach it to the pwm board - pin 13\nLeftEyeLR.attach(Head,13)\nLeftEyeLR.setMinMax(0,180)\nLeftEyeLR.map(0,180,1,180)\nLeftEyeLR.setRest(90)\nLeftEyeLR.setInverted(False)\nLeftEyeLR.setVelocity(120)\nLeftEyeLR.setAutoDisable(True)\nLeftEyeLR.rest()\n\n\nLeftEyeUD = Runtime.createAndStart(\"LeftEyeUD\", \"Servo\")\n# attach it to the pwm board - pin 12\nLeftEyeUD.attach(Head,12)\nLeftEyeUD.setMinMax(0,180)\nLeftEyeUD.map(0,180,1,180)\nLeftEyeUD.setRest(90)\nLeftEyeUD.setInverted(False)\nLeftEyeUD.setVelocity(60)\nLeftEyeUD.setAutoDisable(True)\nLeftEyeUD.rest()\n\n\nUpperEyeLid = Runtime.createAndStart(\"UpperEyeLid\", \"Servo\")\n# attach it to the pwm board - pin 11\nUpperEyeLid.attach(Head,11)\nUpperEyeLid.setMinMax(60,180)\nUpperEyeLid.map(0,180,60,180)\nUpperEyeLid.setRest(45)\nUpperEyeLid.setInverted(False)\nUpperEyeLid.setVelocity(-1)\nUpperEyeLid.setAutoDisable(False)\n# UpperEyeLid.rest()\n\n\nLowerEyeLid = Runtime.createAndStart(\"LowerEyeLid\", \"Servo\")\n# attach it to the pwm board - pin 10\nLowerEyeLid.attach(Head,10)\nLowerEyeLid.setMinMax(0,120)\nLowerEyeLid.map(0,180,0,120)\nLowerEyeLid.setRest(30)\nLowerEyeLid.setInverted(False)\nLowerEyeLid.setVelocity(-1)\nLowerEyeLid.setAutoDisable(False)\n# LowerEyeLid.rest()\n\n\nJaw = Runtime.createAndStart(\"Jaw\", \"Servo\")\n# attach it to the pwm board - pin 9\nJaw.attach(Head,9)\nJaw.setMinMax(0,180)\nJaw.map(0,180,1,180)\nJaw.setRest(90)\nJaw.setInverted(False)\nJaw.setVelocity(-1)\nJaw.setAutoDisable(True)\n#Jaw.rest()\n\nHeadYaw = Runtime.createAndStart(\"HeadYaw\", \"Servo\")\n# attach it to the pwm board - pin 8\nHeadYaw.attach(Head,8)\nHeadYaw.setMinMax(0,180)\nHeadYaw.map(0,180,1,180)\nHeadYaw.setRest(90)\nHeadYaw.setInverted(False)\nHeadYaw.setVelocity(120)\nHeadYaw.setAutoDisable(True)\nHeadYaw.rest()\n\nHeadPitch = Runtime.createAndStart(\"HeadPitch\", \"Servo\")\n# attach it to the pwm board - pin 7\nHeadPitch.attach(Head,7)\nHeadPitch.setMinMax(0,180)\nHeadPitch.map(0,180,1,180)\nHeadPitch.setRest(90)\nHeadPitch.setInverted(False)\nHeadPitch.setVelocity(120)\nHeadPitch.setAutoDisable(True)\nHeadPitch.rest()\n\nHeadRoll = Runtime.createAndStart(\"HeadRoll\", \"Servo\")\n# attach it to the pwm board - pin 6\nHeadRoll.attach(Head,6)\nHeadRoll.setMinMax(0,180)\nHeadRoll.map(0,180,1,180)\nHeadRoll.setRest(90)\nHeadRoll.setInverted(False)\nHeadRoll.setVelocity(120)\nHeadRoll.setAutoDisable(True)\nHeadRoll.rest()\n\n# TTS speech \nmouth = Runtime.createAndStart(\"mouth\", \"MarySpeech\")\n#mouth.setVoice(\"cmu-bdl\") # Mark\n#mouth.setVoice(\"cmu-bdl-hsmm\") # Mark\n#mouth.setVoice(\"cmu-rms\") # Henry\nmouth.setVoice(\"cmu-rms-hsmm\") # Henry\n#mouth.setVoice(\"dfki-obadiah\") # Obadiah\n#mouth.setVoice(\"dfki-obadiah-hsmm\") # Obadiah\n#mouth.setVoice(\"dfki-spike\") # Spike\n#mouth.setVoice(\"dfki-spike-hsmm\") # Spike\n#mouth.installComponentsAcceptLicense(\"dfki-obadiah-hsmm\") #Use this line to install more voice files\nmouth.setVolume(100.0)\n\n# Jaw control based on speech.\nmouthcontrol = Runtime.create(\"mouthcontrol\",\"MouthControl\")\nmouthcontrol.setJaw(Jaw)\nmouthcontrol.setMouth(mouth)\nmouthcontrol.setmouth(77, 120)\nmouthcontrol.setdelays(60, 60, 70)\nmouthcontrol.startService()\n\n# Define Wakeup and sleep routines.\ndef WakeSleep(timedata):\n\tif Awake == False:\n\t\tBlinkClock.startClock()\n\t\tAwake = True\t# need to add a wake up sequence here.\n\telse:\n\t\tBlinkClock.stopClock()\n\t\tAwake = False\t# need to add a going to sleep sequence here.\n\n# Routine to create the blinking motion\ndef blink(timedata):\n\tUpperEyeLid.moveTo(150) # close the upper eye lid\n\tLowerEyeLid.moveTo(150) # close the lower eye lid\n\tsleep(0.5)\n\tUpperEyeLid.moveTo(45) # Open the upper eye lid\n\tLowerEyeLid.moveTo(45) # Open the lower eye lid\n\tBlinkClock.setInterval(randint(5000, 10000)) # Set a new random time for the next blink\n\nsleep(10.0)\nBlinkClock.addListener(\"pulse\", python.name, \"blink\")\nBlinkClock.setInterval(10000)\nBlinkClock.startClock()\n\ndef eyesLR(eyesLRpos):\n\tRightEyeLR.moveTo(eyesLRpos)\n\tLeftEyeLR.moveTo(eyesLRpos)\n\ndef eyesUD(eyesUDpos):\n\tRightEyeUD.moveTo(eyesUDpos)\n\tLeftEyeUD.moveTo(eyesUDpos)\n\nUpperEyeLid.moveTo(45)\nLowerEyeLid.moveTo(45)\nJaw.moveTo(77)\neyesLR(0)\nsleep(2.0)\neyesLR(180)\nsleep(2.0)\neyesLR(90)\nUpperEyeLid.moveTo(45)\nLowerEyeLid.moveTo(45)\n\nmouth.speakBlocking(u\"Hello world, I am awake.\")\n\n#mouth.speak(u\"I wonder if non blocking is a good idea?\")\n","sub_path":"Old_Versions/Fred_2.py","file_name":"Fred_2.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"242129918","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nfilename = '/home/lee/Pictures/bead15.png'\n\nimg = cv2.imread(filename, 0)\nstar = cv2.xfeatures2d.StarDetector_create()\nbrief = cv2.xfeatures2d.BriefDescriptorExtractor_create()\nkp = star.detect(img,None)\nkp, des = brief.compute(img, kp)\nimg2 = cv2.drawKeypoints(img, kp, None, (255,0,0))\ncv2.imshow('img2', img2)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"brief.py","file_name":"brief.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"56347509","text":"# -*- coding: utf-8 -*-\n\"\"\"Format Python code (list of lists) as a fixed width table.\"\"\"\nimport ast\nfrom collections import defaultdict\n\nimport ast_decompiler\nimport libcst\nfrom libcst._nodes.internal import CodegenState\n\nONE_INDENT = 4 # spaces. As God intended\n\n\ndef reformat(python_code: str, align_commas=False, guess_indent=False):\n \"\"\"\n Reformat list of lists as fixed width table\n \"\"\"\n # Who says your code can't just be one massive function...\n if python_code.strip() == \"\":\n return \"\"\n try:\n code_cst = libcst.parse_expression(python_code.strip())\n except Exception:\n raise AssertionError(\"Couldn't parse input as Python code\")\n\n # Validate input\n if not isinstance(code_cst, libcst.List):\n raise AssertionError(\"Expected a list expression as single input expression.\")\n for element in code_cst.elements:\n if not isinstance(element.value, libcst.List):\n raise AssertionError(f\"Expected each sub element to be a list, found {element.value}.\")\n\n # Build all reprs of elements\n reprs = [[reformat_as_single_line(cst_node_to_code(element.value)) for\n element in sublist.value.elements] for sublist in\n code_cst.elements]\n\n # Calculate max widths\n col_widths = defaultdict(int)\n for row in reprs:\n for idx, item in enumerate(row):\n col_widths[idx] = max(col_widths[idx], len(item))\n\n # Indents\n indent = \" \" * ONE_INDENT\n initial_indent = \"\"\n final_indent = \"\"\n if python_code.startswith(\" \"):\n # Restore the initial indent, so code will copy-paste directly into\n # where it came from.\n initial_indent = \" \" * get_indent_size(python_code)\n\n if guess_indent:\n # We assuming code looks like this:\n # def test_foo():\n # assert answer == [\n # [a, b, c],\n # [def, ghi, jkl],\n # ]\n #\n # The user has selected text from first '['\n # We remove any comment lines\n lines = python_code.strip().split('\\n')\n lines = [line for line in lines if not line.strip().startswith('#')]\n if len(lines) > 1:\n indent_size = get_indent_size(lines[1])\n indent = \" \" * indent_size\n final_indent = \" \" * max(indent_size - ONE_INDENT, 0)\n\n # Collect comments.\n\n # This is the most fragile bit - it would be easy to miss things here. The\n # alternative would a very different structure for the whole code, that\n # transforms code_cst, adjusting whitespace as we go. It might be harder and\n # more bug prone however. We cannot support comments in every location either,\n # so it might be simpler this way.\n\n # Comments before first row\n if hasattr(code_cst.lbracket.whitespace_after, 'empty_lines'):\n initial_comments = [\n line.comment.value + \"\\n\"\n for line in code_cst.lbracket.whitespace_after.empty_lines\n ]\n else:\n initial_comments = []\n\n # Comments at the end of each row - paired with rows\n end_of_row_comments = []\n for element in code_cst.elements:\n if (\n hasattr(element.comma, 'whitespace_after')\n and hasattr(element.comma.whitespace_after, 'first_line')\n and getattr(element.comma.whitespace_after.first_line, 'comment', None)\n ):\n comment = element.comma.whitespace_after.first_line.comment.value\n else:\n comment = ''\n end_of_row_comments.append(comment)\n # Last row comment is attached to rbracket of main expression\n if (\n hasattr(code_cst.rbracket.whitespace_before, 'first_line')\n and getattr(code_cst.rbracket.whitespace_before.first_line, 'comment', None)\n ):\n end_of_row_comments[-1] = code_cst.rbracket.whitespace_before.first_line.comment.value\n\n # Comments on their own lines after each row - these will be paired with rows\n after_row_comments = []\n for element in code_cst.elements:\n if hasattr(element.comma, 'whitespace_after') and hasattr(element.comma.whitespace_after, 'empty_lines'):\n comment = '\\n'.join(line.comment.value for line in element.comma.whitespace_after.empty_lines)\n else:\n comment = ''\n after_row_comments.append(comment)\n\n # Comments on their own lines after the last row\n if hasattr(code_cst.rbracket.whitespace_before, 'empty_lines'):\n final_comments = [\n line.comment.value + \"\\n\"\n for line in code_cst.rbracket.whitespace_before.empty_lines\n ]\n else:\n final_comments = []\n\n # Output\n output = []\n output.append(initial_indent + \"[\\n\")\n for comment in initial_comments:\n output.append(indent + comment)\n for row, end_of_row_comment, after_row_comment in zip(reprs, end_of_row_comments, after_row_comments):\n output.append(indent + \"[\")\n for idx, item in enumerate(row):\n need_comma = idx < len(row) - 1\n separator = \", \" if need_comma else \"\"\n pre_separator = \"\" if align_commas else separator\n post_separator = separator if align_commas else \"\"\n output.append(item + pre_separator + \" \" * (col_widths[idx] - len(item)) + post_separator)\n output.append(\"],\")\n if end_of_row_comment:\n output.append(' ' + end_of_row_comment)\n output.append(\"\\n\")\n if after_row_comment:\n for comment in after_row_comment.split('\\n'):\n output.append(indent + comment + '\\n')\n for comment in final_comments:\n output.append(indent + comment)\n output.append(final_indent + \"]\")\n return \"\".join(output)\n\n\ndef cst_node_to_code(node):\n state = CodegenState(default_indent=4, default_newline='\\n')\n node._codegen(state)\n return \"\".join(state.tokens)\n\n\ndef reformat_as_single_line(python_code):\n code_ast = ast.parse(python_code.strip())\n # The following has the unfortunate effect of not preserving quote style.\n # But so far, for getting code formatted using normal PEP8 conventions, in a\n # single line, this approach seems much easier compared to other approaches\n # I've tried.\n #\n # Tried:\n #\n # - Using Black as a library: adds lots of vertical and horizontal\n # whitespace in for long argument lists etc.\n #\n # - Using libcst - would require complicated manipulation of whitespace elements\n # to produce the PEP8 spacings around operators etc.\n return ast_decompiler.decompile(code_ast, indentation=0, line_length=100000).strip()\n\n\ndef get_indent_size(text):\n return len(text) - len(text.lstrip(\" \"))\n","sub_path":"src/table_format/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635758890","text":"# Helper Code\n\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def append(self, value):\n if self.head is None:\n self.head = Node(value)\n return\n\n node = self.head\n while node.next:\n node = node.next\n\n node.next = Node(value)\n\n def __iter__(self):\n node = self.head\n while node:\n yield node.value\n node = node.next\n\n def __repr__(self):\n return str([v for v in self])\n\n # def reverse(self):\n # \"\"\"\n # Reverse the inputted linked list\n\n # Args:\n # linked_list(obj): Linked List to be reversed\n # Returns:\n # obj: Reveresed Linked List\n # \"\"\"\n\n # prev = None\n # next = None\n # current = self.head\n\n # while current is not None:\n # next = current.next\n # current.next = prev\n # prev = current\n # current = next\n\n # self.head = prev\n\n # def printList(self):\n # temp = self.head\n # while(temp):\n # print(temp.value)\n # temp = temp.next\n\n\ndef reverse(linked_list):\n \"\"\"\n Reverse the inputted linked list\n\n Args:\n linked_list(obj): Linked List to be reversed\n Returns:\n obj: Reveresed Linked List\n \"\"\"\n rev_linked_list = LinkedList()\n prev = None\n\n for value in linked_list:\n # This is a new node\n new_node = Node(value)\n new_node.next = prev\n prev = new_node\n rev_linked_list.head = prev\n\n return rev_linked_list\n\n\n# Tests\nllist = LinkedList()\nfor value in [4, 2, 5, 1, -3, 0]:\n llist.append(value)\nprint(llist)\n\nflipped = reverse(llist)\nprint(flipped)\nis_correct = list(flipped) == list(\n [0, -3, 1, 5, 2, 4]) and list(llist) == list(reverse(flipped))\nprint(\"Pass\" if is_correct else \"Fail\")\n\n# llist = LinkedList()\n# llist.append(20)\n# llist.append(4)\n# llist.append(15)\n# llist.append(85)\n\n# print(\"Given Linked List\")\n# llist.printList()\n# llist.reverse()\n# print(\"\\nReversed Linked List\")\n# llist.printList()\n","sub_path":"Problems/DataStructures/1_ArraysAndLinkedLists/2_LinkedListExercises/4_reverse_ll.py","file_name":"4_reverse_ll.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499814731","text":"#! /usr/bin/env python\nimport aipy as a, numpy as n, pylab as p\nimport sys\n\ndef apply_lpf(d, w, width, iter, lpf=None):\n N = d.size\n if lpf is None:\n _lpf = n.ones(N, dtype=n.float)\n _lpf[width+1:-width] = 0\n lpf = n.fft.fftshift(n.fft.fft(_lpf))\n if iter == 0:\n d_lpf = n.convolve(d, lpf, 'full')[N/2:3*N/2] / N\n else:\n if True:\n d_lpf = 0\n for i in range(iter):\n d_lpf += apply_lpf((d-d_lpf)*w, w, width, 0, lpf=lpf)\n else:\n d_lpf = apply_lpf(d, w, width, iter-1, lpf=lpf)\n w_lpf = apply_lpf(d_lpf*w, w, width, iter-1, lpf=lpf)\n correction = d_lpf / w_lpf\n d_lpf *= correction\n return d_lpf\n\n\nfor f in sys.argv[1:]:\n uv = a.miriad.UV(f)\n cnt = 0\n for (crd,t,(i,j)),d,f in uv.all(raw=True):\n cnt += 1\n if cnt < 41: continue\n window = a.dsp.gen_window(d.size, 'blackman-harris')\n w = n.logical_not(f).astype(n.float)\n d *= w\n d_lpf = apply_lpf(d,w,18,10)\n d_rs = (d - d_lpf) * w\n p.subplot(131); p.plot(d_lpf*w)\n p.subplot(132); p.semilogy(n.fft.fftshift(n.abs(n.fft.ifft(d_rs))))\n p.subplot(133); p.semilogy(n.fft.fftshift(n.abs(n.fft.ifft(d_rs*window))))\n\n for d_ in [d,d_rs]:\n _d,_w = n.fft.ifft(d_*window), n.fft.ifft(w*window)\n _d,info = a.deconv.clean(_d, _w, tol=1e-5)\n d_cl = n.fft.fft(_d)\n d_rs = (d_ - d_cl) * w\n p.subplot(131); p.plot(d_cl*w)\n p.subplot(132); p.semilogy(n.fft.fftshift(n.abs(n.fft.ifft(d_rs))))\n p.subplot(133); p.semilogy(n.fft.fftshift(n.abs(_d+info['res'])))\n\n #p.subplot(131); p.plot(d)\n #p.subplot(132); p.semilogy(n.fft.fftshift(n.abs(n.fft.ifft(d))))\n #p.subplot(133); p.semilogy(n.fft.fftshift(n.abs(n.fft.ifft(d*window))))\n #p.subplot(224)\n #p.semilogy(n.fft.fftshift(n.abs(n.fft.ifft(d_rs))))\n \n p.show()\n","sub_path":"arp/scripts/dwt_uv.py","file_name":"dwt_uv.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"283260954","text":"import setuptools\n\nlong_description = open('README.md', 'r').read()\n\nrequirements = list(open('requirements.txt', 'r'))\n\nsetuptools.setup(\n name='namebuster',\n version='1.0.2',\n scripts=['namebuster'],\n py_modules=['namebuster'],\n author='Ben Busby',\n author_email='contact@benbusby.com',\n install_requires=requirements,\n description='A tool for generating common username permutations from a list of names, a file, or url, to aid with username enumeration',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/benbusby/namebuster',\n packages=setuptools.find_packages(),\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"16883761","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport nibabel as nib\nimport numpy as np\nimport os\nimport shelve\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfolder_name = 'Results'\n\npooled = shelve.open(os.path.join(folder_name, 'centralizednumba'))\nparams_pooled = pooled['params']\npvalues_pooled = pooled['pvalues']\ntvalues_pooled = pooled['tvalues']\nrsquared_pooled = pooled['rsquared']\nsse_pooled = pooled['sse']\npooled.close()\n\nsingleshot = shelve.open(os.path.join(folder_name, 'singleshotWA'))\nparams_singleshot = singleshot['params']\npvalues_singleshot = singleshot['pvalues']\ntvalues_singleshot = singleshot['tvalues']\nrsquared_singleshot = singleshot['rsquared']\nsse_singleshot = singleshot['sse']\nsingleshot.close()\n\nmultishot = shelve.open(os.path.join(folder_name, 'multishotsite'))\nparams_multishot = multishot['params']\npvalues_multishot = multishot['pvalues']\ntvalues_multishot = multishot['tvalues']\nrsquared_multishot = multishot['rsquared']\nsse_multishot = multishot['sse']\nmultishot.close()\n\nmultishotexact = shelve.open(os.path.join(folder_name, 'multishotExact'))\nparams_multishotexact = multishotexact['params']\npvalues_multishotexact = multishotexact['pvalues']\ntvalues_multishotexact = multishotexact['tvalues']\nrsquared_multishotexact = multishotexact['rsquared']\nsse_multishotexact = multishotexact['sse']\nmultishotexact.close()\n# %% Head Directory where the data is stored and loading the mask\ndata_location = '/export/mialab/users/hgazula/mcic_regression/mcic_data'\nmask_location = os.path.join(data_location, 'mask')\nmask = nib.load(os.path.join(mask_location, 'mask.nii'))\n\n# =============================================================================\n# PAIRPLOT for pairwise SSE\n# =============================================================================\nsns.set(style=\"ticks\")\nabc = pd.DataFrame()\nabc[\"pooled\"] = sse_pooled[\"sse\"]\nabc[\"singleshot\"] = sse_singleshot[\"sse\"]\nabc[\"multishot\"] = sse_multishot[\"sse\"]\nsns.pairplot(abc)\n# =============================================================================\n# PAIRPLOT for rsquared\n# =============================================================================\nsns.set(style=\"ticks\")\nabcr2 = pd.DataFrame()\nabcr2[\"pooled\"] = rsquared_pooled[\"rsquared_adj\"]\nabcr2[\"singleshot\"] = rsquared_singleshot[\"rsquared_adj\"]\nabcr2[\"multishot\"] = rsquared_multishot[\"rsquared_adj\"]\nsns.pairplot(abcr2)\n# =============================================================================\n# PAIRPLOT for const\n# =============================================================================\nsns.set(style=\"ticks\")\nabccon = pd.DataFrame()\nabccon[\"pooled\"] = params_pooled[\"const\"]\nabccon[\"singleshot\"] = params_singleshot[\"const\"]\nabccon[\"multishot\"] = params_multishot[\"const\"]\nlm4 = sns.pairplot(abccon, diag_kind=\"kde\")\n# =============================================================================\n# PAIRPLOT for beta_age\n# =============================================================================\nsns.set(style=\"ticks\")\nabcba = pd.DataFrame()\nabcba[\"pooled\"] = params_pooled[\"age\"]\nabcba[\"singleshot\"] = params_singleshot[\"age\"]\nabcba[\"multishot\"] = params_multishot[\"age\"]\nlm1 = sns.pairplot(abcba, diag_kind=\"kde\")\n# =============================================================================\n# PAIRPLOT for beta_diagnosis\n# =============================================================================\nsns.set(style=\"ticks\")\nabcbd = pd.DataFrame()\nabcbd[\"pooled\"] = params_pooled[\"diagnosis_Patient\"]\nabcbd[\"singleshot\"] = params_singleshot[\"diagnosis_Patient\"]\nabcbd[\"multishot\"] = params_multishot[\"diagnosis_Patient\"]\nlm2 = sns.pairplot(abcbd)\n# =============================================================================\n# PAIRPLOT for beta_sex\n# =============================================================================\nsns.set(style=\"ticks\")\nabcbs = pd.DataFrame()\nabcbs[\"pooled\"] = params_pooled[\"sex_M\"]\nabcbs[\"singleshot\"] = params_singleshot[\"sex_M\"]\nabcbs[\"multishot\"] = params_multishot[\"sex_M\"]\nlm3 = sns.pairplot(abcbs)\n# =============================================================================\n# # PAIRPLOT for site_MGH beta\n# =============================================================================\nsns.set(style=\"ticks\")\nabcmgh = pd.DataFrame()\nabcmgh[\"pooled\"] = params_pooled[\"site_MGH\"]\nabcmgh[\"multishot\"] = params_multishot[\"site_MGH\"]\nlm5 = sns.pairplot(abcmgh, diag_kind=\"kde\")\n# =============================================================================\n# # PAIRPLOT for site_UMN beta\n# =============================================================================\nsns.set(style=\"ticks\")\nabcumn = pd.DataFrame()\nabcumn[\"pooled\"] = params_pooled[\"site_UMN\"]\nabcumn[\"multishot\"] = params_multishot[\"site_UMN\"]\nlm6 = sns.pairplot(abcumn, diag_kind=\"kde\")\n# =============================================================================\n# # PAIRPLOT for site_UNM beta\n# =============================================================================\nsns.set(style=\"ticks\")\nabcunm = pd.DataFrame()\nabcunm[\"pooled\"] = params_pooled[\"site_UNM\"]\nabcunm[\"multishot\"] = params_multishot[\"site_UNM\"]\nlm7 = sns.pairplot(abcunm, diag_kind=\"kde\")\n# =============================================================================\n# VIOLIN PLOTS for SSE\n# =============================================================================\nsse_pooled['label'] = 'pooled'\nsse_singleshot['label'] = 'singleshot'\nsse_multishot['label'] = 'multishot'\n\nsse_new = pd.concat([sse_pooled, sse_singleshot, sse_multishot])\n\nax1 = sns.violinplot(x=\"label\", y=\"sse\", data=sse_new)\nax1.set_xlabel(\"Type of Regression\")\nax1.set_ylabel(\"Sum Square of Errors\")\nax1.set_title('Violin plot of Sum Square of Errors for each Regression')\n# =============================================================================\n# VIOLIN PLOTS for sse differences\n# =============================================================================\nsse1 = pd.DataFrame()\nsse2 = pd.DataFrame()\nsse3 = pd.DataFrame()\nsse1['diff'] = sse_pooled['sse'] - sse_singleshot['sse']\nsse2['diff'] = sse_pooled['sse'] - sse_multishot['sse']\nsse3['diff'] = sse_singleshot['sse'] - sse_multishot['sse']\nsse1['label'] = 'P - SS'\nsse2['label'] = 'P - MS'\nsse3['label'] = 'SS - MS'\n\nsse_new2 = pd.concat([sse1, sse2, sse3])\n\nsns.set_style('darkgrid')\nax2 = sns.violinplot(x=\"label\", y=\"diff\", data=sse_new2)\nax2.set_xlabel(\"Regression pairs (P - pooled, SS - Singleshot, MS - Multishot)\")\nax2.set_ylabel(\"Diff. of Sum Square of Errors\")\nax2.set_title('Violin plot of SSE differences for every pair of regression')\n# =============================================================================\n# plotting violin plots for sse comparisons\n# =============================================================================\nmat1 = pd.concat([sse_pooled, sse_singleshot])\nmat1['diff_label'] = 'P_vs_SS'\n\nmat2 = pd.concat([sse_pooled, sse_multishot])\nmat2['diff_label'] = 'P_vs_MS'\n\nmat3 = pd.concat([sse_singleshot, sse_multishot])\nmat3['diff_label'] = 'SS_vs_MS'\n\nmat = pd.concat([mat1, mat2, mat3])\nax3 = sns.violinplot(x=\"diff_label\", y=\"sse\", hue=\"label\", data=mat)\nax3.set_xlabel(\"Pairs of Regression\")\nax3.set_ylabel('Sum Square of Errors')\nax3.set_title('Comparison of SSE for every pair of regression')\nax3.legend(\n bbox_to_anchor=(0, -0.098, 1., -.102),\n loc=9,\n ncol=3,\n mode=\"expand\",\n borderaxespad=0.)\n# =============================================================================\n# Violin plots of rsquared for each regression\n# =============================================================================\nsns.set_style(\"darkgrid\")\nrsquared_pooled['label'] = 'Pooled'\nrsquared_singleshot['label'] = 'Single-shot'\nrsquared_multishot['label'] = 'Multi-shot'\n\nrsquared_new = pd.concat(\n [rsquared_pooled, rsquared_singleshot, rsquared_multishot])\nax1 = sns.violinplot(x=\"label\", y=\"rsquared_adj\", data=rsquared_new)\nax1.set_xlabel(\"Type of Regression\")\nax1.set_ylabel(\"Adjusted R-square\")\nax1.set_title('Violin plot of Adjusted R-squared for each Regression')\n# =============================================================================\n# pvalues\n# =============================================================================\npvalues_pooled1 = -np.log10(pvalues_pooled)\npvalues_singleshot1 = -np.log10(pvalues_singleshot)\npvalues_multishot1 = -np.log10(pvalues_multishot)\n\npvalues_pooled1['label'] = 'Pooled'\npvalues_singleshot1['label'] = 'Single-shot'\npvalues_multishot1['label'] = 'Multi-shot'\n\nmat_old = pd.concat([pvalues_pooled1, pvalues_singleshot1, pvalues_multishot])\nplt.figure()\nax8 = sns.violinplot(x=\"label\", y=\"age\", data=mat)\nax8.set_xlabel(\"Type of Regression\")\nax8.set_ylabel(\"-$\\log_{10} p$-value for Age\")\nax8.set_title(\n \"Violin plot of -$\\log_{10} p$-values from each type of regression\")\n\nmat1 = pd.concat([pvalues_pooled1, pvalues_singleshot1])\nmat1['diff_label'] = 'P_vs_SS'\n\nmat2 = pd.concat([pvalues_pooled1, pvalues_multishot1])\nmat2['diff_label'] = 'P_vs_MS'\n\nmat3 = pd.concat([pvalues_singleshot1, pvalues_multishot1])\nmat3['diff_label'] = 'SS_vs_MS'\n\nmat = pd.concat([mat2, mat1, mat3])\n\nplt.figure()\nax5 = sns.violinplot(x=\"diff_label\", y=\"age\", hue=\"label\", data=mat)\nax5.set_xlabel(\"Pair of Regressions\")\nax5.set_ylabel(\"Age\")\nax5.set_title(\n \"Comparison of -$\\log_{10} p$-values for every pair of regression\")\nax5.legend(\n bbox_to_anchor=(0., -0.098, 1., -.102),\n loc=9,\n ncol=3,\n mode=\"expand\",\n borderaxespad=0.)\n\nplt.figure()\nax6 = sns.violinplot(\n x=\"diff_label\", y=\"diagnosis_Patient\", hue=\"label\", data=mat)\nax6.set_xlabel(\"Pair of Regressions\")\nax6.set_ylabel(\"Diagnosis\")\nax6.set_title(\n \"Comparison of -$\\log_{10} p$-values for every pair of regression\")\nax6.legend(\n bbox_to_anchor=(0., -0.098, 1., -.102),\n loc=9,\n ncol=3,\n mode=\"expand\",\n borderaxespad=0.)\n\nplt.figure()\nax7 = sns.violinplot(x=\"diff_label\", y=\"sex_M\", hue=\"label\", data=mat)\nax7.set_xlabel(\"Pair of Regressions\")\nax7.set_ylabel(\"Gender\")\nax7.set_title(\n \"Comparison of -$\\log_{10} p$-values for every pair of regression\")\nax7.legend(\n bbox_to_anchor=(0., -0.098, 1., -.102),\n loc=9,\n ncol=3,\n mode=\"expand\",\n borderaxespad=0.)\n\n# =============================================================================\n# BRAIN IMAGES\n# =============================================================================\n\n# =============================================================================\n# Plotting SSE\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = sse_pooled['sse']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized_sse_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = sse_singleshot['sse']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot_sse_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = sse_multishot['sse']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'multishot_sse_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and singleshot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = sse_pooled['sse'] - sse_singleshot['sse']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized-singleshot'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = sse_pooled['sse'] - sse_multishot['sse']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized-multishot'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between singleshot and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = sse_singleshot['sse'] - sse_multishot['sse']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot-multishot'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Plotting adjusted-rsquared\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = rsquared_pooled['rsquared_adj']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized_rsquared_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = rsquared_singleshot['rsquared_adj']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot_rsquared_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = rsquared_multishot['rsquared_adj']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'multishot_rsquared_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and singleshot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[\n mask.get_data() >\n 0] = rsquared_pooled['rsquared_adj'] - rsquared_singleshot['rsquared_adj']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized-singleshot_rsquared'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[\n mask.get_data() >\n 0] = rsquared_pooled['rsquared_adj'] - rsquared_multishot['rsquared_adj']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized-multishot_rsquared'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between singleshot and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[\n mask.get_data() >\n 0] = rsquared_singleshot['rsquared_adj'] - rsquared_multishot['rsquared_adj']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot-multishot_rsquared'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Plotting params['Age']\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_pooled['age']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized_age_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_singleshot['age']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot_age_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_multishot['age']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'multishot_age_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and singleshot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_pooled['age'] - params_singleshot['age']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'pooled-singleshot_age_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_pooled['age'] - params_multishot['age']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'pooled-multishot_age_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between singleshot and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() >\n 0] = params_singleshot['age'] - params_multishot['age']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot-multishot_age_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Plotting params['diagnosis_Patient']\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_pooled['diagnosis_Patient']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized_diagnosis_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_singleshot['diagnosis_Patient']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot_diagnosis_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_multishot['diagnosis_Patient']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'multishot_diagnosis_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and singleshot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[\n mask.get_data() >\n 0] = params_pooled['diagnosis_Patient'] - params_singleshot['diagnosis_Patient']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'pooled-singleshot_diagnosis_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[\n mask.get_data() >\n 0] = params_pooled['diagnosis_Patient'] - params_multishot['diagnosis_Patient']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'pooled-multishot_diagnosis_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between singleshot and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[\n mask.get_data() >\n 0] = params_singleshot['diagnosis_Patient'] - params_multishot['diagnosis_Patient']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot-multishot_diagnosis_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Plotting params['sex_M']\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_pooled['sex_M']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'centralized_gender_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_singleshot['sex_M']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot_gender_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() > 0] = params_multishot['sex_M']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'multishot_gender_beta_on_brain'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and singleshot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() >\n 0] = params_pooled['sex_M'] - params_singleshot['sex_M']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'pooled-singleshot_gender_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between pooled and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() >\n 0] = params_pooled['sex_M'] - params_multishot['sex_M']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'pooled-multishot_gender_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n\n# =============================================================================\n# Difference in sse between singleshot and multishot\n# =============================================================================\nnew_data = np.zeros(mask.shape)\nnew_data[mask.get_data() >\n 0] = params_singleshot['sex_M'] - params_multishot['sex_M']\nclipped_img = nib.Nifti1Image(new_data, mask.affine, mask.header)\nimage_string = 'singleshot-multishot_gender_beta'\nprint('Saving ', image_string)\nnib.save(clipped_img, image_string)\n","sub_path":"draft_codes/untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":23232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589525810","text":"from django.urls import path, include\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\nfrom .views import (\n LogoutView,\n SaveUserClothes,\n DeleteUserClothes,\n GetUserClothes,\n RequestToMicroservice\n)\n\n\nurlpatterns = [\n path('auth/', include('djoser.urls')),\n path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('logout/', LogoutView.as_view(), name='auth_logout'),\n path('save/', SaveUserClothes.as_view(), name='save_clothes'),\n path('delete/', DeleteUserClothes.as_view(), name='delete_clothes'),\n path('get/', GetUserClothes.as_view(), name='get_clothes'),\n path('filters/', RequestToMicroservice.as_view(), name='filters_clothes'),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"211596303","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def largestValues(self, root: Optional[TreeNode]) -> List[int]:\n res=[]\n if root==None: return res\n q=[root]\n while q:\n size, mx=len(q), float('-inf')\n for _ in range(size):\n f=q.pop(0)\n mx=max(mx, f.val)\n if f.left: q.append(f.left)\n if f.right: q.append(f.right)\n res.append(mx)\n\n return res \n\n\n","sub_path":"python/find-largest-value-in-each-tree-row.py","file_name":"find-largest-value-in-each-tree-row.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"642585548","text":"import matplotlib.pyplot as plt\nfrom numpy import *\nimport numpy as np\n\ndef problem4():\n N_max = 50\n some_threshold= 50.\n x = np.linspace(-2,1,500)\n y = np.linspace(-1.5,1.5,500)\n c = x[:,newaxis] + 1j * y[newaxis,:]\n z = c\n\n for j in range(N_max):\n z = z**2 + c\n\n answer = (abs(z) < some_threshold)\n\n plt.imshow(answer.T, extent = [-2, 1, -1.5, 1.5])\n plt.gray()\n plt.savefig(\"mandelbrot.png\")\n\n","sub_path":"tw991/package/problem4.py","file_name":"problem4.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"376358018","text":"# -*- coding:utf-8 -*-\n# ! python3\n\n\"\"\"\n定义参数和参量\n\"\"\"\n\n# 版本号\nVERSION = \"v0.3.1.190306_beta\"\n# 一年内交易日\nN = 245\n# 历史交易日数据长度\nT = 66\n# 默认波动率 or 标准差\nDEFAULT_VOL = 0.15\n# 默认现金收益率\nCASH_RETURN = 0.0\n# 默认回测开始区间\nDEFAULT_START_T = \"2012-01\"\n# 默认回测结束区间\nDEFAULT_END_T = \"2017-12\"\n# 默认单股最大权重\nDEFAULT_UP = float(\"inf\")\n# 重要参数字典\nCONF_DICT = {\"dir\": [\"code_file\", \"work_file\"],\n \"constraints\": [\"mode\", \"vol\", \"short\", \"max_weight\", \"cash_return\"],\n \"calculation\": [\"calc_time\", \"num_d\", \"start_time\", \"end_time\", \"frequency\"]}\n# configue参数配置文件名\nCONF_NAME = \"configParam_mkv.conf\"\n# 文件地址为空错误信息\nFILE_EMPTY_MSG = \"文件地址不能为空,请输入正确文件地址\"\n# 文件地址不正确错误信息\nFILE_EXIST_MSG = \"文件地址错误,请重新确认后输入【注意后缀名,支持.txt.xls.xlsx】:\\n\"\n# 空头限制语句缺失警告\nSHORT_MISS_WARNING = \"空头限制为空或无效,为您选择默认设置:仅多头\"\n# 股票信息变量名\nSTOCK_SEC = \"sec_name,exch_eng\"\n# 优化问题限制条件个数\nNUMCON = 2\n","sub_path":"codes/Mkv_constant.py","file_name":"Mkv_constant.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309905953","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 29 23:35:06 2019\r\n\r\n@author: ganapathy\r\n\r\nThis problem was recently asked by Google.\r\nGiven a list of numbers and a number k, return whether any two numbers from the list add up to k.\r\nFor example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\r\n\r\n\"\"\"\r\n\r\ndef add_2_num_to_k(k,inlist):\r\n \r\n value='False'\r\n itr1=0\r\n while itr1 < len(inlist)-1:\r\n itr2=itr1+1\r\n while itr2 < len(inlist):\r\n print(itr1,itr2)\r\n if (inlist[itr1]+inlist[itr2]) == k:\r\n value='True'\r\n itr1=len(inlist)-1\r\n itr2=len(inlist)\r\n else:\r\n itr2+=1\r\n itr1+=1\r\n \r\n return value\r\n\r\nk_=int(input())\r\ninlist_=list(map(int,input().split()))\r\nadd_2_num_to_k(k_,inlist_)\r\n","sub_path":"0001_add_2num_to_k_29_03_2019.py","file_name":"0001_add_2num_to_k_29_03_2019.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576042471","text":"\"\"\"ActivityStreams API handler classes.\n\nImplements the OpenSocial ActivityStreams REST API:\nhttp://opensocial-resources.googlecode.com/svn/spec/2.0.1/Social-API-Server.xml#ActivityStreams-Service\nhttp://opensocial-resources.googlecode.com/svn/spec/2.0.1/Core-Data.xml\n\nRequest paths are of the form /user_id/group_id/app_id/activity_id, where\neach element is optional. user_id may be @me. group_id may be @all, @friends\n(currently identical to @all), or @self. app_id may be @app, but it doesn't\nmatter, it's currently ignored.\n\nThe supported query parameters are startIndex and count, which are handled as\ndescribed in OpenSocial (above) and OpenSearch.\n\nOther relevant activity REST APIs:\nhttp://status.net/wiki/Twitter-compatible_API\nhttp://wiki.activitystrea.ms/w/page/25347165/StatusNet%20Mapping\nhttps://developers.google.com/+/api/latest/activities/list\n\nActivityStreams specs:\nhttp://activitystrea.ms/specs/\n\nAtom format spec:\nhttp://atomenabled.org/developers/syndication/\n\"\"\"\n\n__author__ = ['Ryan Barrett ']\n\nimport json\nimport logging\nimport urllib\n\nfrom google.appengine.ext import ndb\nfrom oauth_dropins.webutil import handlers\nfrom oauth_dropins.webutil import util\nfrom webob import exc\n\nfrom granary import appengine_config\nfrom granary import atom\nfrom granary import facebook\nfrom granary import flickr\nfrom granary import googleplus\nfrom granary import instagram\nfrom granary import microformats2\nfrom granary import source\nfrom granary import twitter\n\nimport webapp2\n\nXML_TEMPLATE = \"\"\"\\\n\n%s\n\"\"\"\nITEMS_PER_PAGE = 100\n\n# default values for each part of the API request path except the site, e.g.\n# /twitter/@me/@self/@all/...\nPATH_DEFAULTS = ((source.ME,), (source.ALL, source.FRIENDS), (source.APP,), ())\nMAX_PATH_LEN = len(PATH_DEFAULTS) + 1\n\n\nclass Handler(webapp2.RequestHandler):\n \"\"\"Base class for ActivityStreams API handlers.\n\n Attributes:\n source: Source subclass\n \"\"\"\n handle_exception = handlers.handle_exception\n\n def get(self):\n \"\"\"Handles an API GET.\n\n Request path is of the form /site/user_id/group_id/app_id/activity_id ,\n where each element except site is an optional string object id.\n \"\"\"\n # parse path\n args = urllib.unquote(self.request.path).strip('/').split('/')\n if not args or len(args) > MAX_PATH_LEN:\n raise exc.HTTPNotFound('Expected 1-%d path elements; found %d' %\n (MAX_PATH_LEN, len(args)))\n\n # make source instance\n site = args.pop(0)\n if site == 'twitter':\n src = twitter.Twitter(\n access_token_key=util.get_required_param(self, 'access_token_key'),\n access_token_secret=util.get_required_param(self, 'access_token_secret'))\n elif site == 'facebook':\n src = facebook.Facebook(\n access_token=util.get_required_param(self, 'access_token'))\n elif site == 'flickr':\n src = flickr.Flickr(\n access_token_key=util.get_required_param(self, 'access_token_key'),\n access_token_secret=util.get_required_param(self, 'access_token_secret'))\n elif site == 'instagram':\n src = instagram.Instagram(scrape=True)\n elif site == 'google+':\n auth_entity = util.get_required_param(self, 'auth_entity')\n src = googleplus.GooglePlus(auth_entity=ndb.Key(urlsafe=auth_entity).get())\n else:\n src_cls = source.sources.get(site)\n if not src_cls:\n raise exc.HTTPNotFound('Unknown site %r' % site)\n src = src_cls(**self.request.params)\n\n # handle default path elements\n args = [None if a in defaults else a\n for a, defaults in zip(args, PATH_DEFAULTS)]\n user_id = args[0] if args else None\n\n # get activities\n try:\n response = src.get_activities_response(*args, **self.get_kwargs(src))\n except NotImplementedError as e:\n self.abort(400, str(e))\n\n # fetch actor if necessary\n actor = response.get('actor')\n if not actor and self.request.get('format') == 'atom':\n # atom needs actor\n args = [None if a in defaults else a # handle default path elements\n for a, defaults in zip(args, PATH_DEFAULTS)]\n user_id = args[0] if args else None\n actor = src.get_actor(user_id) if src else {}\n\n self.write_response(response, actor=actor, url=src.BASE_URL)\n\n def write_response(self, response, actor=None, url=None, title=None):\n \"\"\"Converts ActivityStreams activities and writes them out.\n\n Args:\n response: response dict with values based on OpenSocial ActivityStreams\n REST API, as returned by Source.get_activities_response()\n actor: optional ActivityStreams actor dict for current user. Only used\n for Atom output.\n url: the input URL\n title: string, Used in Atom output\n \"\"\"\n expected_formats = ('activitystreams', 'json', 'atom', 'xml', 'html', 'json-mf2')\n format = self.request.get('format') or self.request.get('output') or 'json'\n if format not in expected_formats:\n raise exc.HTTPBadRequest('Invalid format: %s, expected one of %r' %\n (format, expected_formats))\n\n activities = response['items']\n\n self.response.headers['Access-Control-Allow-Origin'] = '*'\n if format in ('json', 'activitystreams'):\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(json.dumps(response, indent=2))\n elif format == 'atom':\n self.response.headers['Content-Type'] = 'text/xml'\n hub = self.request.get('hub')\n self.response.out.write(atom.activities_to_atom(\n activities, actor,\n host_url=url or self.request.host_url + '/',\n request_url=self.request.url,\n xml_base=util.base_url(url),\n title=title,\n rels={'hub': hub} if hub else None))\n self.response.headers.add('Link', str('<%s>; rel=\"self\"' % self.request.url))\n if hub:\n self.response.headers.add('Link', str('<%s>; rel=\"hub\"' % hub))\n elif format == 'xml':\n self.response.headers['Content-Type'] = 'text/xml'\n self.response.out.write(XML_TEMPLATE % util.to_xml(response))\n elif format == 'html':\n self.response.headers['Content-Type'] = 'text/html'\n self.response.out.write(microformats2.activities_to_html(activities))\n elif format == 'json-mf2':\n self.response.headers['Content-Type'] = 'application/json'\n items = [microformats2.object_to_json(a) for a in activities]\n self.response.out.write(json.dumps({'items': items}, indent=2))\n\n if 'plaintext' in self.request.params:\n # override response content type\n self.response.headers['Content-Type'] = 'text/plain'\n\n def get_kwargs(self, source):\n \"\"\"Extracts, normalizes and returns the startIndex, count, and search\n query params.\n\n Args:\n source: Source instance\n\n Returns:\n dict with 'start_index' and 'count' keys mapped to integers\n \"\"\"\n start_index = self.get_positive_int('startIndex')\n count = self.get_positive_int('count')\n\n if count == 0:\n count = ITEMS_PER_PAGE - start_index\n else:\n count = min(count, ITEMS_PER_PAGE)\n\n kwargs = {'start_index': start_index, 'count': count}\n\n search_query = self.request.get('search_query') or self.request.get('q')\n if search_query:\n kwargs['search_query'] = search_query\n\n return kwargs\n\n def get_positive_int(self, param):\n try:\n val = self.request.get(param, 0)\n val = int(val)\n assert val >= 0\n return val\n except (ValueError, AssertionError):\n raise exc.HTTPBadRequest('Invalid %s: %s (should be positive int)' %\n (param, val))\n\n\napplication = webapp2.WSGIApplication([('.*', Handler)],\n debug=appengine_config.DEBUG)\n","sub_path":"activitystreams.py","file_name":"activitystreams.py","file_ext":"py","file_size_in_byte":7755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541793425","text":"from a_star import AStar\nimport Adafruit_TCS34725\nimport smbus\nimport time\nimport math\n\nclass Robot:\n def __init__(self):\n self.isLost = False\n self.nextSearchDirection = 0 # (left: 0, right: 1)\n self.veerSpeed = 30\n self.maxSpeed = 70\n self.aStar = AStar()\n self.tcs = Adafruit_TCS34725.TCS34725()\n self.initialLeftCount = self.aStar.read_encoders()[0]\n self.initialRightCount = self.aStar.read_encoders()[1]\n \n # check if currently reading green tape \n def checkGreen(self):\n r, g, b, c = self.tcs.get_raw_data()\n return (g > r and g > b)\n\n def checkRed(self):\n r, g, b, c = self.tcs.get_raw_data()\n return (r > 1.6*g or r > 1.6*b) and r > 50\n \n # set motor speeds\n def motors(self, lspeed, rspeed):\n self.aStar.motors(lspeed, rspeed)\n \n def goForward(self):\n self.motors(self.maxSpeed, self.maxSpeed)\n\n def stop(self):\n self.motors(0, 0)\n \n def veerLeft(self):\n self.motors(self.veerSpeed, self.maxSpeed)\n \n def veerRight(self):\n self.motors(self.maxSpeed, self.veerSpeed)\n \n def getTime(self):\n return time.time()\n \n def playNotes(self):\n self.aStar.play_notes(\"o4l16ceg>c8\")\n \n # turn leds on or off\n def leds(self, red, yellow, green):\n self.aStar.leds(red, yellow, green)\n \n def readAnalog(self):\n return self.aStar.read_analog()\n \n def readBatteryMillivolts(self):\n return self.aStar.read_battery_millivolts()\n \n def readButtons(self):\n return self.aStar.read_buttons()\n \n def readEncoders(self):\n encoders = self.aStar.read_encoders()\n return (encoders[0] - self.initialLeftCount, encoders[1] - self.initialRightCount)\n \n def printColorInfo(self):\n r, g, b, c = self.tcs.get_raw_data()\n temp = Adafruit_TCS34725.calculate_color_temperature(r, g, b)\n lux = Adafruit_TCS34725.calculate_lux(r, g, b)\n print('Color: r={0} g={1} b={2} temp={3} lux={4}'.format(r, g, b, temp, lux))\n \n def turnOffInterruptsRGB(self):\n self.tcs.set_interrupt(False)\n \n def turnOnInterruptsRGB(self):\n self.tcs.set_interrupt(True)\n \n # rgb sensor is enabled by default in the constructor method\n def enableRGB(self):\n self.tcs.enable()\n \n def disableRGB(self):\n self.tcs.disable()\n\n def turnLeft(self,count):\n while(self.readEncoders()[0]%744 > (-1)*count and self.readEncoders()[1]%744 < count):\n if(self.checkGreen()):\n return 1\n break\n self.motors(0, self.maxSpeed)\n self.stop()\n return 0\n\n def turnRight(self,count):\n while(self.readEncoders()[0]%744 < count and self.readEncoders()[1]%744 > (-1)*count):\n if(self.checkGreen()):\n return 1\n break\n self.motors(self.maxSpeed, 0)\n self.stop()\n return 0\n\n def changeCount(self,count):\n if(count != 0):\n count = count / 2\n\t\t\n def calibrate(self):\n count = 744\n while(self.checkGreen() == False):\n if(self.turnLeft(count)):\n pass\n elif(self.turnRight(count)):\n pass\n self.changeCount(count)\n # end while\n self.goForwardtwo()\n\n def greenIsLeft(self):\n initEncoders = self.readEncoders()\n while( self.readEncoders()[0] > initEncoders[0] - 100\n and self.readEncoders()[1] < initEncoders[1] + 100\n and self.checkGreen() == False):\n self.motors(-50, 50)\n self.stop()\n if(self.checkGreen()):\n return True\n else:\n return False\n\n def greenIsRight(self):\n initEncoders = self.readEncoders()\n while( self.readEncoders()[1] > initEncoders[1] - 100\n and self.readEncoders()[0] < initEncoders[0] + 100\n and self.checkGreen() == False):\n self.motors(50, -50)\n self.stop()\n if(self.checkGreen()):\n return True\n else:\n return False\n\n def adjustSlightly(self, direction):\n counts = 50\n initEncoders = self.readEncoders()\n if(direction == 'left'):\n while(self.readEncoders()[1] < initEncoders[1] + counts):\n self.motors(-50, 50)\n else:\n while(self.readEncoders()[0] < initEncoders[0] + counts):\n self.motors(50, -50)\n \n def calibrateTwo(self):\n self.stop()\n if(self.greenIsLeft()):\n self.adjustSlightly('left')\n elif(self.greenIsRight()):\n self.adjustSlightly('right')\n elif(self.checkRed()):\n pass\n else:\n print(\"Unable to find green\")\n '''\n def calibrateTwo(self):\n self.sweepsForGreen(80)\n '''\n \n \n def turnCounts(self, direction, counts):\n initEncoders = self.readEncoders()\n if(direction == 'left'):\n while( self.readEncoders()[0] > initEncoders[0] - counts\n and self.readEncoders()[1] < initEncoders[1] + counts):\n self.motors(self.maxSpeed * (-1), self.maxSpeed)\n elif(direction == 'right'):\n while( self.readEncoders()[1] > initEncoders[1] - counts\n and self.readEncoders()[0] < initEncoders[0] + counts):\n self.motors(self.maxSpeed, self.maxSpeed * (-1))\n else:\n print(\"Invalid turn direction\")\n self.stop()\n\n def turn90Left(self):\n self.turnCounts('left', 744)\n\n def turn90Right(self):\n self.turnCounts('right', 744)\n\n # return true is green is found within a sweep distance, false otherwise\n def sweepsForGreen(self, counts):\n # counts is equal to the number of encoders counts at both sides of\n # facing direction e.g. count = 50 searches 50 counts left and 50 right\n interval = 10\n iterations = math.ceil(counts / interval)\n initEncoders = self.readEncoders()\n # sweep left\n for i in range (1, iterations):\n self.turnCounts('left', interval)\n if(self.checkGreen()):\n return True\n #print(self.readEncoders()[1] - initEncoders[1])\n #self.turnCounts('right', self.readEncoders()[1] - initEncoders[1])\n # sweep right\n for i in range (1, iterations):\n self.turnCounts('right', interval)\n if(self.checkGreen()):\n return True\n #print(self.readEncoders()[0] - initEncoders[0])\n #self.turnCounts('left', self.readEncoders()[0] - initEncoders[0])\n return False\n\n def isPathInDirection(self, direction):\n if(direction == 'forward'):\n pass\n elif(direction == 'left'):\n self.turn90Left()\n elif(direction == 'right'):\n self.turn90Right()\n return self.sweepsForGreen(120)\n\n def getValidPaths(self):\n forward = self.isPathInDirection('forward')\n self.stop()\n time.sleep(0.5)\n left = self.isPathInDirection('left')\n self.stop()\n time.sleep(0.5)\n self.turn90Right()\n right = self.isPathInDirection('right')\n self.stop()\n time.sleep(0.5)\n self.turn90Left()\n time.sleep(0.5)\n return (left, forward, right)\n\n def noValidPaths(pathTuple):\n return not (pathTuple[0] or pathTuple[1] or pathTuple[2])\n \n def goForwardtwo(self):\n self.motors(self.maxSpeed, self.maxSpeed)\n x = self.maxSpeed\n diff = math.fabs(self.readEncoders()[1] - self.readEncoders()[0]) \n while(diff > 2):\n diff = math.fabs(self.readEncoders()[1] - self.readEncoders()[0]) \n x-=1\n if(self.readEncoders()[1] > self.readEncoders()[0]):\n self.motors(self.maxSpeed,x)\n time.sleep(1.0/1000.0)\n elif(self.readEncoders()[0] > self.readEncoders()[1]):\n self.motors(x,self.maxSpeed)\n time.sleep(1.0/1000.0)\n self.motors(self.maxSpeed, self.maxSpeed)\n\n ''' \n def calibrate(self):\n while(self.checkGreen() == False):\n for x in range(100, -20, -1):\n self.motors(100 if x+40>100 else x+40,x)\n \n '''\n\n def adjustIntersection(self):\n saveEncoders = self.readEncoders()\n while(self.readEncoders()[0] - saveEncoders[0] < 700\n and self.readEncoders()[1] - saveEncoders[1] < 700):\n self.goForwardtwo()\n print(\"Centered at intersection\")\n \n # recalibrate the robot onto the path\n def calibrateDirection(self):\n calibrated = False\n turnAmount = 500 # initial encoder count\n print(\"in calibrate\")\n \n while(calibrated == False):\n # turn the robot one direction \n if (self.nextSearchDirection == 0):\n self.veerLeft()\n else:\n self.veerRight()\n # switch turn direction for next iteration \n self.nextSearchDirection = self.nextSearchDirection ^ 1\n print(\"in first while\")\n recordEncoder = self.readEncoders()[self.nextSearchDirection]\n # wait to see if direction was correct \n while(self.readEncoders()[self.nextSearchDirection] - recordEncoder < turnAmount):\n print(\"in second while\")\n if(self.checkGreen()):\n # creep forward until centered\n self.adjustIntersection()\n print(\"done centering\")\n # reposition front of robot onto green edge\n while(self.checkGreen() == False):\n if(self.nextSearchDirection == 0):\n print(\"repositioning [left] to green edge\")\n self.veerLeft()\n else:\n print(\"repositioning [right] to green edge\")\n self.veerRight()\n print(\"done repositioning to green edge\")\n calibrated = True\n '''\n # rotate half an inch until sensor is centered on tape\n slapEncoders = self.readEncoders()\n if(self.nextSearchDirection == 0):\n while(self.readEncoders()[1] - slapEncoders[1] < 81):\n print(\"rotating left half an inch\")\n self.motors(-100, 100)\n self.stop()\n else:\n while(self.readEncoders()[0] - slapEncoders[0] < 81):\n print(\"rotating right half an inch\")\n self.motors(100, -100)\n self.stop()\n '''\n break\n else:\n pass # not green, continue to veer\n # end while\n # end calibrateDirection()\n \n# end Class Robot()\n","sub_path":"romi.py","file_name":"romi.py","file_ext":"py","file_size_in_byte":9724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"113687187","text":"from setuptools import setup\nfrom os import path\n\ndef open_file(fname):\n return open(path.join(path.dirname(__file__), fname))\n\nsetup(\n setup_requires=['pbr', 'pyversion'],\n pbr=True,\n auto_version=\"PBR\",\n install_requires=open_file('requirements.txt').readlines(),\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"93680297","text":"import os\nimport sys\nimport io\nimport json\nimport fnmatch\nimport tarfile\nimport math\nfrom PIL import Image\nfrom glob import glob\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom random import sample\n\nimport numpy as np\nimport tensorflow as tf\nimport cv2\n\nimport tensorflow.contrib.slim as slim\n\nclass Dataset:\n def __init__(self, batch_size, input_path, ground_truth, test_input_path, test_ground_truth):\n self.batch_size = batch_size\n \n train_files = os.listdir(input_path)\n train_gt = os.listdir(ground_truth)\n test_files = os.listdir(test_input_path)\n test_gt = os.listdir(test_ground_truth)\n\n self.train_inputs, self.train_paths = self.file_paths_to_images(input_path, train_files)\n self.train_outputs, self.troutput_paths = self.file_paths_to_images(ground_truth, train_gt)\n \n self.test_inputs, self.test_paths = self.file_paths_to_images(test_input_path, test_files)\n self.test_outputs, self.tsoutput_paths = self.file_paths_to_images(test_ground_truth, test_gt)\n\n self.pointer = 0\n \n self.history_buf = self.train_inputs\n\n def file_paths_to_images(self, folder, files_list):\n inputs = []\n in_path = []\n\n for file in files_list:\n input_image = os.path.join(folder, file)\n in_path.append(os.path.join(file))\n\n test_image = cv2.imread(input_image, 0)\n test_image = cv2.resize(test_image, (128, 128))\n inputs.append(test_image)\n\n return inputs, in_path\n\n def num_batches_in_epoch(self):\n return int(math.floor(len(self.train_inputs) / self.batch_size))\n\n def reset_batch_pointer(self):\n permutation = np.random.permutation(len(self.train_inputs))\n self.train_inputs = [self.train_inputs[i] for i in permutation]\n self.train_paths = [self.train_paths[i] for i in permutation]\n permutation = np.random.permutation(len(self.train_outputs))\n self.train_outputs = [self.train_outputs[i] for i in permutation]\n self.troutput_paths = [self.troutput_paths[i] for i in permutation]\n\n self.pointer = 0\n\n def next_batch(self):\n inputs = []\n targets = []\n \n for i in range(self.batch_size):\n if i <= (self.batch_size/2):\n inputs.append(np.array(self.train_inputs[self.pointer + i]))\n targets.append(np.array(self.train_outputs[self.pointer + i]))\n else:\n inputs.append(np.array(self.history_buf[self.pointer + i]))\n targets.append(np.array(self.train_outputs[self.pointer + i])) \n\n self.pointer += self.batch_size\n\n return np.array(inputs, dtype=np.uint8), np.array(targets, dtype=np.uint8)\n \n def all_test_batches(self):\n return np.array(self.test_inputs, dtype=np.uint8), self.test_paths, len(self.test_inputs)//self.batch_size\n \n def get_hist_batch(self):\n inputs = []\n lista = sample(range(len(self.train_inputs)), self.batch_size)\n for i in lista:\n inputs.append(np.array(self.train_inputs[i]))\n \n return np.array(inputs, dtype=np.uint8), lista\n \n def set_hist_batch(self, tensor, lista):\n i = 0;\n tensor = np.array(tensor[0])\n for j in range(tensor.shape[0]):\n self.history_buf[lista[i]] = cv2.resize(tensor[j], (128,128))\n i += 1\n \n \nclass Discriminador:\n IMAGE_HEIGHT = 128\n IMAGE_WIDTH = 128\n IMAGE_CHANNELS = 1\n\n def __init__(self, layers=None, name=\"\", external_input=None): \n if external_input == None:\n self.inputs = tf.placeholder(tf.float32, [None, self.IMAGE_HEIGHT, self.IMAGE_WIDTH, self.IMAGE_CHANNELS],name='{}_inputs'.format(name))\n else:\n self.inputs = tf.identity(external_input, name=\"{}_inputs\".format(name))\n \n self.targets = tf.placeholder(tf.int32, [None, 2], name='{}_targets'.format(name))\n self.is_training = tf.placeholder_with_default(False, [], name='is_training')\n self.description = \"\"\n\n self.layers = {}\n\n net = tf.reshape(self.inputs, [-1, self.IMAGE_HEIGHT*self.IMAGE_WIDTH*self.IMAGE_CHANNELS])\n #net = self.inputs\n \n with tf.variable_scope(\"convdisc\", reuse=tf.AUTO_REUSE) as scope:\n self.logits = slim.stack(net, slim.fully_connected, [4096,1024,256,128,64,32,16,8,4,2], scope=\"fc\")\n self.discrim_vars = tf.contrib.framework.get_variables(scope)\n\n self.final_result = tf.nn.softmax(logits=self.logits, name=\"{}_output\".format(name))\n\nclass Refinador:\n IMAGE_HEIGHT = 128\n IMAGE_WIDTH = 128\n IMAGE_CHANNELS = 1\n\n def __init__(self, layers=None, batch_norm=True, skip_connections=True): \n self.inputs = tf.placeholder(tf.float32, [None, self.IMAGE_HEIGHT, self.IMAGE_WIDTH, self.IMAGE_CHANNELS],name='inputs')\n self.targets = tf.placeholder(tf.float32, [None, self.IMAGE_HEIGHT, self.IMAGE_WIDTH, 1], name='targets')\n self.is_training = tf.placeholder_with_default(False, [], name='is_training')\n self.description = \"\"\n\n self.layers = {}\n\n net = self.inputs\n with tf.variable_scope(\"convref\", reuse=False) as scope:\n net = slim.conv2d(net, 64, 5, 1, scope=\"conv_1\")\n for i in range(4):\n layer = net\n net = slim.conv2d(net, 64, 5, 1, scope=\"repeat_{}_1\".format(i))\n net = slim.conv2d(net, 64, 5, 1, scope=\"repeat_{}_2\".format(i))\n net = tf.nn.relu(tf.add(net, layer))\n net = slim.conv2d(net, 1, 1, 1, scope=\"conv_2\")\n self.final_result = tf.nn.tanh(net, name=\"final_result\")\n self.refiner_vars = tf.contrib.framework.get_variables(scope) \n \n self.dis = Discriminador(name=\"fake\", external_input=self.final_result)\n \nclass Modelo: \n IMAGE_HEIGHT = 128\n IMAGE_WIDTH = 128\n IMAGE_CHANNELS = 1\n \n def __init__(self):\n \n self.ref = Refinador()\n self.refiner_step = tf.Variable(0, name=\"refiner_step\", trainable=False)\n self.discrim_step = tf.Variable(0, name=\"discrim_step\", trainable=False)\n self.learning_rate= tf.placeholder(tf.float32, [], name=\"learning_rate\")\n \n #UM discriminador para os exemplos reais e outro para os exemplos do refinador\n self.dis_real = Discriminador(name=\"real\")\n \n #Computando os loss agora\n #Refinador\n se_lossr = tf.nn.softmax_cross_entropy_with_logits(logits=self.ref.dis.logits, labels=self.ref.dis.targets)\n self.realism_loss = tf.reduce_sum(se_lossr, name=\"realism_loss\")\n self.regularization_loss = tf.reduce_sum(tf.abs(self.ref.final_result - self.ref.inputs), [1,2,3], name=\"regularization_loss\")\n self.refiner_loss = tf.reduce_mean(self.realism_loss + (0.2 * self.regularization_loss), name=\"refiner_loss\")\n \n #Discriminador\n se_lossd = tf.nn.softmax_cross_entropy_with_logits(logits=self.dis_real.logits, labels=self.dis_real.targets)\n self.synthetic_d_loss = tf.reduce_sum(se_lossd, name=\"synthetich_d_loss\")\n se_losss = tf.nn.softmax_cross_entropy_with_logits(logits=self.ref.dis.logits, labels=self.ref.dis.targets)\n self.refiner_d_loss = tf.reduce_sum(se_losss, name=\"refiner_d_loss\")\n self.discrim_loss = tf.reduce_mean(self.synthetic_d_loss + self.refiner_d_loss, name=\"discrim_loss\")\n \n #Otimizadores\n var_list = self.ref.refiner_vars\n self.refiner_optim = tf.train.AdamOptimizer(self.learning_rate).minimize(self.refiner_loss, self.refiner_step, var_list=var_list)\n self.refiner_only_optim = tf.train.AdamOptimizer(self.learning_rate).minimize(self.regularization_loss, var_list=var_list)\n \n var_list = self.dis_real.discrim_vars\n self.discrim_only_optim = tf.train.AdamOptimizer(self.learning_rate).minimize(self.synthetic_d_loss)\n self.discrim_optim = tf.train.AdamOptimizer(self.learning_rate).minimize(self.discrim_loss, self.discrim_step) \n \ndef saveImage(test_inputs, test_target, test_result, batch_num, n = 12):\n fig, axs = plt.subplots(4, n, figsize=(n * 3, 10))\n fig.suptitle(\"Accuracy: {}, {}\".format(0, \"\"), fontsize=20)\n for example_i in range(n):\n axs[0][example_i].imshow(np.reshape(test_inputs[example_i], [128,128]), cmap='gray')\n axs[1][example_i].imshow(np.reshape(test_target[example_i], [128,128]), cmap='gray')\n axs[2][example_i].imshow(np.reshape(test_result[example_i], [128,128]),cmap='gray')\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n buf.seek(0)\n\n IMAGE_PLOT_DIR = 'image_plots/gan'\n if not os.path.exists(IMAGE_PLOT_DIR):\n os.makedirs(IMAGE_PLOT_DIR)\n\n plt.savefig('{}/figure{}.jpg'.format(IMAGE_PLOT_DIR, batch_num))\n plt.close('all')\n print(\"Test sample saved in {}/figure{}.jpg\".format(IMAGE_PLOT_DIR, batch_num))\n return buf\n \ndef train():\n input_path = \"result/export\"\n ground_truth = \"data128_128/inputs/train\"\n test_input_path = \"result/inputs\"\n test_ground_truth = \"data128_128/inputs/test\"\n dataset = Dataset(batch_size=32, input_path=input_path, ground_truth=ground_truth, test_input_path=test_input_path, test_ground_truth=test_ground_truth)\n modelo = Modelo()\n \n nepoch = 3000\n \n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n summary_writer = tf.summary.FileWriter(\"logs/gan\", sess.graph)\n \n _real_labels = np.reshape(np.tile(np.array([0,1], dtype=np.int32), 256), [-1,2])\n _fake_labels = np.reshape(np.tile(np.array([1,0], dtype=np.int32), 256), [-1,2])\n \n #Treinando um pouco o refinador\n print(\"Treinando um pouco o refinador\")\n dataset.batch_size = 64\n dataset.reset_batch_pointer()\n rep = 5000\n for batch_i in range(rep):\n if batch_i % dataset.num_batches_in_epoch() == 0:\n dataset.reset_batch_pointer()\n batch_inputs, batch_targets = dataset.next_batch()\n batch_inputs = np.reshape(batch_inputs,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n batch_inputs = np.multiply(batch_inputs, 1.0 / 255)\n \n batch_targets = np.reshape(batch_targets,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n batch_targets = np.multiply(batch_targets, 1.0 / 255)\n \n ref_loss, _ = sess.run([modelo.regularization_loss, modelo.refiner_only_optim],feed_dict={modelo.ref.inputs: batch_inputs, modelo.learning_rate: 1e-4, modelo.ref.is_training: True})\n print(\"{} de {} | Refiner (Reg.) Loss: {}\".format(batch_i+1,rep,np.mean(ref_loss)))\n if (batch_i+1) % 10 == 0:\n test_input, test_target = dataset.test_inputs, dataset.test_outputs\n test_input, test_target = test_input[:dataset.batch_size], test_target[:dataset.batch_size]\n test_input = np.reshape(test_input, (dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n test_target = np.reshape(test_target, (dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n \n result, loss = sess.run([modelo.ref.final_result, modelo.regularization_loss], feed_dict={modelo.ref.inputs: test_input})\n\n imageBuffer = saveImage(test_input, test_target, result, batch_i+1)\n \n \n #Treinando um pouco o discriminador\n \"\"\"print(\"Treinando um pouco o discriminador\")\n dataset.batch_size = 256\n dataset.reset_batch_pointer()\n rep = 1000\n real_labels = _real_labels[:dataset.batch_size]\n fake_labels = _fake_labels[:dataset.batch_size]\n for batch_i in range(rep):\n if batch_i % dataset.num_batches_in_epoch() == 0:\n dataset.reset_batch_pointer()\n \n batch_inputs, batch_targets = dataset.next_batch()\n \n batch_inputs = np.reshape(batch_inputs,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n batch_inputs = np.multiply(batch_inputs, 1.0 / 255)\n batch_targets = np.reshape(batch_targets,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n batch_targets = np.multiply(batch_targets, 1.0 / 255)\n \n batch_ = np.vstack([batch_inputs, batch_targets])\n label_ = np.vstack([real_labels, fake_labels])\n \n permutation = np.random.permutation(len(batch_))\n batch = [batch_[i] for i in permutation]\n label = [label_[i] for i in permutation]\n \n batch_inputs = np.array(batch)[:dataset.batch_size]\n label_inputs = np.array(label, dtype=np.int32)[:dataset.batch_size]\n \n dis_loss, _ = sess.run([modelo.synthetic_d_loss, modelo.discrim_only_optim],feed_dict={modelo.dis_real.inputs: batch_inputs, modelo.learning_rate: 1e-4, modelo.dis_real.targets: label_inputs, modelo.dis_real.is_training: True})\n print(\"{} de {} | Discriminator Loss: {}\".format(batch_i,rep,dis_loss))\n \n if batch_i % 100 == 0:\n test_input, test_target = dataset.test_inputs, dataset.test_outputs\n test_input, test_target = test_input[:dataset.batch_size], test_target[:dataset.batch_size]\n test_input = np.reshape(test_input, (dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n test_target = np.reshape(test_target, (dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n \n batch_ = np.vstack([test_input, test_target])\n label_ = np.vstack([real_labels, fake_labels])\n \n permutation = np.random.permutation(len(batch_))\n batch = [batch_[i] for i in permutation]\n label = [label_[i] for i in permutation]\n \n result_real = sess.run([modelo.dis_real.final_result],feed_dict={modelo.dis_real.inputs: batch, modelo.dis_real.is_training: False})\n \n test_error = np.abs(result_real[0] - label)\n print(result_real[0][5], label[5])\n print(result_real[0][10], label[10])\n print(result_real[0][15], label[15])\n print(result_real[0][20], label[20]) \n print(\"Test Error > SUM:{} MEAN:{}\".format(np.sum(test_error),np.mean(test_error)))\"\"\"\n \n print(\"Treinando os dois modelos\")\n dataset.batch_size = 32\n real_labels = _real_labels[:dataset.batch_size]\n fake_labels = _fake_labels[:dataset.batch_size]\n for epoch_i in range(nepoch):\n dataset.reset_batch_pointer()\n \n for batch_i in range(dataset.num_batches_in_epoch()):\n batch_num = epoch_i * dataset.num_batches_in_epoch() + batch_i + 1\n batch_inputs, batch_targets = dataset.next_batch()\n \n batch_inputs = np.reshape(batch_inputs,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n batch_targets = np.reshape(batch_targets,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n batch_inputs = np.multiply(batch_inputs, 1.0 / 255)\n batch_targets = np.multiply(batch_targets, 1.0 / 255)\n \n ref_loss, _ = sess.run([modelo.refiner_loss, modelo.refiner_optim],feed_dict={modelo.ref.inputs: batch_inputs, modelo.ref.dis.targets: real_labels, modelo.learning_rate: 1e-4, modelo.ref.is_training: True, modelo.ref.dis.is_training: False})\n \n dis_loss, _ = sess.run([modelo.discrim_loss, modelo.discrim_optim],feed_dict={modelo.dis_real.inputs: batch_targets, modelo.dis_real.targets: real_labels, modelo.ref.inputs: batch_inputs, modelo.ref.dis.targets: fake_labels, modelo.learning_rate: 1e-6, modelo.dis_real.is_training: True})\n print(\"#{}| Disc. Loss: {} | Ref. Loss: {}\".format(batch_num, dis_loss, ref_loss))\n \n if batch_num % 100 == 0:\n #Testar e exportar o bagulho\n test_input, test_target = dataset.test_inputs, dataset.test_outputs\n test_input, test_target = test_input[:dataset.batch_size], test_target[:dataset.batch_size]\n test_input = np.reshape(test_input, (dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n test_target = np.reshape(test_target, (dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n \n result = sess.run([modelo.ref.final_result],feed_dict={modelo.ref.inputs: test_input, modelo.ref.is_training: False})\n #result = np.reshape(result,(dataset.batch_size, modelo.IMAGE_HEIGHT, modelo.IMAGE_WIDTH, 1))\n \n mse = np.mean(np.abs(result[0] - test_target))\n print(\"Test MSE: {}\".format(mse))\n \n imageBuffer = saveImage(test_input, test_target, result[0], batch_num)\n image = tf.image.decode_png(imageBuffer.getvalue(), channels=4)\n image = tf.expand_dims(image, 0)\n image_summary_op = tf.summary.image(\"plot\", image)\n image_summary = sess.run(image_summary_op)\n summary_writer.add_summary(image_summary)\n \n fake_input, lista = dataset.get_hist_batch()\n fake_input = sess.run([modelo.ref.final_result],feed_dict={modelo.ref.inputs: batch_inputs, modelo.ref.is_training: False})\n dataset.set_hist_batch(fake_input, lista)\n \n \nif __name__ == '__main__':\n train() \n","sub_path":"gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":18042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200290993","text":"\"\"\"*********************************************************************\r\n* models.py is the model definition file for the atfl app. [ads.txt]\r\n* Using the Django Administration console, authorized users can upload\r\n* ads.txt files to the Django project fbi root.\r\n* The app assumes usage of s3.botoStorage and overwrites the ads.txt\r\n* file directly to http://static.politifact.com.s3.amazonaws.com/ads.txt\r\n* with file name and size validation included.\r\n*********************************************************************\"\"\"\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.db import models\r\nimport os\r\n\r\nhelpText = \"Click 'Choose File' to select an ads.txt file from your local hard drive. The file on your hard drive MUST be named 'ads.txt' and be less than 100KB in size.\"\r\n\r\ndef validateFileName(value):\r\n \"\"\" Validate uploaded file name is ads.txt. Note: validateFileName built in this manner because\r\n calling os.path.basename() is not functioning in our environment. \"\"\"\r\n extension = str(os.path.splitext(value.name)[1])\r\n thePath = str(os.path.splitext(value.name)[0])\r\n fullPath = str(thePath + extension)\r\n testFileName = str(os.path.basename(fullPath))\r\n validFileName = ['ads.txt']\r\n if not testFileName in validFileName:\r\n raise ValidationError(u'File Naming Error! You may only upload files named \\'ads.txt\\'')\r\n\r\ndef validateFileSize(value):\r\n \"\"\" Validate file size - limited here to 100KB \"\"\"\r\n fileSize = value.file.size\r\n allowedSize = 100000\r\n if fileSize > allowedSize:\r\n raise ValidationError(u'Size Error! You may not upload files greater than 100KB.')\r\n\r\nclass LoadTextFile(models.Model):\r\n \"\"\" Pre-populates FileName field in Admin console and validates/uploads the ads.txt file. \"\"\"\r\n fileName = models.CharField(max_length=7, default='ads.txt', help_text = helpText)\r\n file = models.FileField(validators=[validateFileName, validateFileSize], null=True)","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511424911","text":"from motorDriver import Motor\nimport math\n\n\n# Default is upper left corner\nclass StringLengths:\n def __init__(self):\n self.left = 0\n self.right = WIDTH\n\n\nclass Rotations:\n def __init__(self):\n self.left = 0\n self.right = 0\n\n\nWIDTH = 1000 # constant which keeps track of width - distance between motors of canvas \nHEIGHT = 1000 # constant which keeps track of height of canvas \nCIRCUMFERENCE = 1.3 # 13 millimeters \n\nclass robot:\n def __init__(self, left_port, right_port):\n self.left_motor = Motor(left_port)\n self.right_motor = Motor(right_port)\n self.global_string_lengths = StringLengths()\n self.global_string_lengths.left = 0\n self.global_string_lengths.right = WIDTH\n self.globalX = 0 # global variable to hold x coordinate of robot \n self.globalY = 0 # global variable to hold y coordinate of robot \n\n # function to calculate left and right string lengths given an x and a y coordinate. \n def coordinate_to_string_length(self, x, y):\n string_pair = StringLengths()\n string_pair.left = math.sqrt(math.pow(x,2) + math.pow(y,2))\n string_pair.right = math.sqrt(math.pow(WIDTH,2) - 2*WIDTH*x + math.pow(x,2) + math.pow(y,2))\n return string_pair\n\n # gets the string movement change between two string lengths \n def get_string_length_change(self, current_string_lengths, desired_string_lengths):\n string_length_change = StringLengths()\n string_length_change.left = desired_string_lengths.left - current_string_lengths.left\n string_length_change.right = desired_string_lengths.right - current_string_lengths.right\n return string_length_change\n\n def get_rotations_in_degrees(self, current_string_lengths, desired_string_lengths):\n strings_change = get_string_length_change(current_string_lengths, desired_string_lengths)\n rotations_change = Rotations()\n rotations_change.left = strings_change.left/CIRCUMFERENCE * 360\n rotations_change.right = strings_change.right/CIRCUMFERENCE * 360\n return rotations_change\n\n def moveTo(self, xCord, yCord):\n new_string_pair = self.coordinate_to_string_length(xCord, yCord)\n string_pair_change = self.get_string_length_change(self.global_string_lengths, new_string_pair)\n rotations_pair_change = self.get_rotations_in_degrees(self.global_string_lengths, new_string_pair)\n self.left_motor.move(rotations_pair_change.left)\n self.right_motor.move(rotations_pair_change.right)\n\n self.globalX = xCord\n self.globalY = yCord\n self.global_string_lengths = new_string_pair\n\nwbb = robot(\"/dev/ttyACM0\", \"/dev/ttyACM1\") #WhiteBoard Bot\n\nyCoor = float(input(\"Choose a new y coor (0 to quit) \"))\nxCoor = float(input(\"Choose a new x coor (0 to quit) \"))\n\n#moves in y-direction to user-designated position\nwhile yCoor != 0 and xCoor != 0: #need a better sentinel value... idk what would make most sense\n wbb.moveTo(xCoor, yCoor)\n \n print(\"Done moving!\")\n yCoor = float(input(\"Choose a new y coor (0 to quit) \"))\n xCoor = float(input(\"Choose a new x coor (0 to quit) \"))\n","sub_path":"whiteBoardBot.py","file_name":"whiteBoardBot.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"606983095","text":"import queue\nclass MovingAverage:\n\n def __init__(self, size):\n \"\"\"\n Initialize your data structure here.\n :type size: int\n \"\"\"\n self.data = queue.Queue(size)\n self.window_size = size\n self.avg = 0\n\n def next(self, val):\n \"\"\"\n :type val: int\n :rtype: float\n \"\"\"\n if not self.data.full():\n length = self.data.qsize()\n self.avg = ((self.avg * length) + val) / (length + 1)\n else:\n old = self.data.get()\n self.avg = ((self.avg * self.window_size - old) + val) / self.window_size\n self.data.put(val)\n return self.avg\n\n\n# Your MovingAverage object will be instantiated and called as such:\nm = MovingAverage(3)\nprint(m.next(1))\nprint(m.next(10))\nprint(m.next(3))\nprint(m.next(5))\n\n\n","sub_path":"LeetCode/Queues&Stacks/moving_average.py","file_name":"moving_average.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"551949809","text":"# encoding: UTF-8\n# Autor: Carlos Pano Hernández\n# Este programa crea diversos patrones de dibujo.\n\nimport pygame\n\nimport math\n\nimport random\n\n# Dimensiones de la pantalla\nANCHO = 800\nALTO = 800\n\n# Colores\nBLANCO = (255,255,255) # R,G,B en el rango [0,255]. Paleta de colores.\nNEGRO = (0,0,0)\n\ndef dibujarEspiral():\n\n pygame.init() # Inicializa pygame\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana de dibujo\n reloj = pygame.time.Clock() # Para limitar los fps. Se debe bajar para reducir la sobrecarga a la computadora.\n termina = False # Bandera para saber si termina la ejecución\n\n while not termina:\n # Procesa los eventos que recibe\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n termina = True\n\n # Borrar pantalla\n ventana.fill(BLANCO)\n\n for a in range(0,400,10):\n\n #Líneas horizontales abajo:\n pygame.draw.line(ventana, NEGRO, (ANCHO-a, ALTO-a),(0+a, ALTO-a), 1)\n\n #Vertical Izquierda:\n pygame.draw.line(ventana,NEGRO,(0+a, ALTO-a),(0+a,10+a),1)\n\n #Horizontal Arriba\n pygame.draw.line(ventana, NEGRO, (0+a,10+a), (ANCHO-(a+10), 10 + a), 1)\n\n #Vertical derecha arriba\n pygame.draw.line(ventana, NEGRO, (ANCHO-a, ALTO-a), (ANCHO-a, 10 + a-10),1)\n\n pygame.display.flip() # Actualiza trazos\n reloj.tick(30) # 40 fps\n\n pygame.quit() # termina pygame\n\ndef dibujarParabola():\n\n pygame.init() # Inicializa pygame\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana de dibujo\n reloj = pygame.time.Clock() # Para limitar los fps. Se debe bajar para reducir la sobrecarga a la computadora.\n termina = False # Bandera para saber si termina la ejecución\n\n while not termina:\n # Procesa los eventos que recibe\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n termina = True\n\n # Borrar pantalla\n ventana.fill(BLANCO)\n\n #Cambio de color:\n RANDOM = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))\n\n #Dibujo de parábolas:\n for p in range(0, 400, 10):#Separación de 10 pixeles. 40 línes generadas\n RANDOM = (random.randint(0, 255), random.randint(0, 255), random.randint(0,255))\n\n #Cuadrante 1=\n pygame.draw.line(ventana, RANDOM, (ANCHO // 2 + p, ALTO // 2), (ALTO // 2, p), 1)\n #Cuadrante 2=\n pygame.draw.line(ventana, RANDOM, (ANCHO//2 - p, ALTO//2),(ALTO//2,p),1)\n # Cuadrante 3=\n pygame.draw.line(ventana, RANDOM, (ANCHO // 2, ALTO - p), (ANCHO // 2 - p, ALTO // 2), 1)\n #Cuadrante 4=\n pygame.draw.line(ventana, RANDOM, (ANCHO//2, ALTO-p), (ANCHO//2+p, ALTO//2), 1)\n\n pygame.display.flip() # Actualiza trazos\n reloj.tick(30) # 40 fps\n\n pygame.quit() # termina pygame\n\ndef dibujarCirculosEntrelazados():\n\n pygame.init() # Inicializa pygame\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana de dibujo\n reloj = pygame.time.Clock() # Para limitar los fps. Se debe bajar para reducir la sobrecarga a la computadora.\n termina = False # Bandera para saber si termina la ejecución\n\n while not termina:\n # Procesa los eventos que recibe\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n termina = True\n\n # Borrar pantalla\n ventana.fill(BLANCO)\n\n #Dibujar patrón de círculos.\n for r in range(1,13,1):#El ángulo máximo es 330. 360 ya está contado en el (0,0). Queremos 12 círculos: 360/11= 32.72\n pygame.draw.circle(ventana, NEGRO, (int((math.cos(r*math.pi/6) * 150) + ANCHO//2), int((math.sin(r*math.pi/6) * 150) + ALTO//2)), (150), 1)\n #Se multiplica por pi con el fin de pasar los radianes a grados\n\n pygame.display.flip() # Actualiza trazos\n reloj.tick(60) # 40 fps\n\n pygame.quit() # termina pygame\n\ndef dibujarCirculoCuadrado():\n\n pygame.init() # Inicializa pygame\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana de dibujo\n reloj = pygame.time.Clock() # Para limitar los fps. Se debe bajar para reducir la sobrecarga a la computadora.\n termina = False # Bandera para saber si termina la ejecución\n\n while not termina:\n # Procesa los eventos que recibe\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n termina = True\n\n # Borrar pantalla\n ventana.fill(BLANCO)\n\n for y in range(1, 400, 10):\n # DibujarCírculo\n pygame.draw.circle(ventana, NEGRO, (ANCHO // 2, ALTO // 2), y, 1)\n # DibujarCuadrado\n pygame.draw.rect(ventana, NEGRO, (y, y, ANCHO - y * 2, ALTO - y * 2), 1)\n\n pygame.display.flip() # Actualiza trazos\n reloj.tick(60) # 40 fps\n\n pygame.quit() # termina pygame\n\ndef imprimirPiramide():\n\n #Para columna del 8:\n incremento = 1\n for x in range(1,10,1):\n resultado = incremento * 8 + x #Primer resultado.\n print(incremento, \"* 8 +\", x, \"=\", resultado) #Imprime el primer resultado.\n\n incremento = (incremento * 10) + (x+1)#El valor del incremento cambia. Multiplicando la variable inicial X10 y sumando el facto más x para agregar el valor pasado.\n print(\"---------------------------------\")\n\n #Para columna del 8:\n incremento2=1\n\n for y in range(1,10,1):\n resultado2 = incremento2*incremento2 #Primer resultado.\n print(incremento2,\"*\",incremento2, \"=\", resultado2) #Imprime el primer resultado.\n\n incremento2 = (incremento2 * 10) + (1)#El valor del incremento cambia. Multiplicando la variable inicial X10 y sumando el factor más 1 para agregar.\n\ndef calcularNumerosDivisibles():\n d = 0\n for x in range(1000, 10000, 1): #Comienza desde el 1000 para los 4 dígitos.\n\n if x % 29 == 0:\n d += 1\n\n return d\n\ndef aproximarPI(valor):\n incremento=0 #Contador\n\n for x in range (1,valor+1):\n incremento=incremento+(1/x**2)#División más contador.\n\n pi=(incremento*6)**(1/2)\n\n return pi\n\ndef main():\n\n print(\"Tarea 5. Seleccione qué quiere hacer:\")\n\n print(\"\"\"\n 1. Dibujar cuadros y círculos\n 2. Dibujar espiral\n 3. Dibujar círculos\n 4. Dibujar parábolas\n 5. Aproximar PI\n 6. Contar divisibles entre 29\n 7. Imprimir pirámides de números\n 0. Salir\"\"\")\n\n print(\"\")\n seleccion=int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n while seleccion>=0:\n if seleccion==1:\n dibujarCirculoCuadrado()\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion == 2:\n dibujarEspiral()\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion==3:\n dibujarCirculosEntrelazados()\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion == 4:\n dibujarParabola()\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion==7:\n imprimirPiramide()\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion==6:\n print(\"Número de divisibles entre 29 es:\", calcularNumerosDivisibles())\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion==5:\n pi = int(input(\"Ingresa el rango de pi:\"))\n print(\"PI vale:\", aproximarPI(pi))\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion>=8:\n print(\"Selecciones un número del 1 al 7.\")\n print(\"\")\n seleccion = int(input(\"¿Qué desea hacer?:\"))\n print(\"---------------------------------\")\n\n elif seleccion==0:\n print(\"¡Hasta luego!\")\n break\n\nmain()\n","sub_path":"Dibujos.py","file_name":"Dibujos.py","file_ext":"py","file_size_in_byte":8679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"288059740","text":"from django.shortcuts import render\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import cross_val_score, RandomizedSearchCV\nimport numpy as np\nfrom .Test_Train import TestTrainSplit\nimport joblib\nimport os\n\n\ndef Linear_Classifiers_Logistic_Regression(request):\n if request.method == 'POST':\n try:\n if request.POST['submit'] != \"RandomSearch\":\n file_name = request.POST['filename']\n my_file = \"media/user_{0}/processed_csv/{1}\".format(request.user, file_name)\n features = request.POST.getlist('features')\n features_list = []\n for feature in features:\n feature = feature[1:-1]\n feature = feature.strip().split(\", \")\n for i in feature:\n features_list.append(i[1:-1])\n label = request.POST['label']\n ratio = request.POST['ratio']\n cv = int(request.POST['cv'])\n\n X, y, X_train, X_test, y_train, y_test = TestTrainSplit(my_file, features_list, label, int(ratio))\n if request.POST['submit'] == \"TRAIN\" or request.POST['submit'] == \"VALIDATE\":\n penalty = request.POST['penalty']\n dual = True if request.POST['dual'] == \"True\" else False\n tol = float(request.POST['tol'])\n C = float(request.POST['C'])\n fit_intercept = True if request.POST['fit_intercept'] == \"True\" else False\n intercept_scaling = float(request.POST['intercept_scaling'])\n class_weight = None if request.POST['class_weight'] == \"None\" else request.POST['class_weight']\n random_state = None if request.POST['random_state'] == \"None\" else request.POST['random_state']\n solver = request.POST['solver']\n max_iter = int(request.POST['max_iter'])\n multi_class = request.POST['multi_class']\n verbose = int(request.POST['verbose'])\n warm_start = True if request.POST['warm_start'] == \"True\" else False\n n_jobs = None if request.POST['n_jobs'] == \"None\" else request.POST['n_jobs']\n if n_jobs is not None:\n n_jobs = int(request.POST['n_jobs_value'])\n l1_ratio = None if request.POST['l1_ratio'] == \"None\" else request.POST['l1_ratio']\n if l1_ratio is not None:\n l1_ratio = float(request.POST['l1_ratio_value'])\n else:\n penalty = request.POST['penalty']\n dual = True if request.POST['dual'] == \"True\" else False\n tol = float(request.POST['tol'])\n C = float(request.POST['C'])\n fit_intercept = True if request.POST['fit_intercept'] == \"True\" else False\n intercept_scaling = float(request.POST['intercept_scaling'])\n class_weight = None if request.POST['class_weight'] == \"None\" else request.POST['class_weight']\n random_state = None if request.POST['random_state'] == \"None\" else request.POST['random_state']\n solver = request.POST['solver']\n max_iter = int(request.POST['max_iter'])\n multi_class = request.POST['multi_class']\n verbose = int(request.POST['verbose'])\n warm_start = True if request.POST['warm_start'] == \"True\" else False\n n_jobs = None if request.POST['n_jobs'] == \"None\" else request.POST['n_jobs']\n if n_jobs is not None:\n n_jobs = int(n_jobs)\n l1_ratio = None if request.POST['l1_ratio'] == \"None\" else request.POST['l1_ratio']\n if l1_ratio is not None:\n l1_ratio = float(l1_ratio)\n\n if request.POST['submit'] == \"TRAIN\" or request.POST['submit'] == \"TRAIN_Rand\":\n classifier = LogisticRegression(penalty=penalty,\n dual=dual,\n tol=tol,\n C=C,\n fit_intercept=fit_intercept,\n intercept_scaling=intercept_scaling,\n class_weight=class_weight,\n random_state=random_state,\n solver=solver,\n max_iter=max_iter,\n multi_class=multi_class,\n verbose=verbose,\n warm_start=warm_start,\n n_jobs=n_jobs,\n l1_ratio=l1_ratio)\n classifier.fit(X_train, y_train)\n if not os.path.exists(\"media/user_{}/trained_model\".format(request.user)):\n os.makedirs(\"media/user_{}/trained_model\".format(request.user))\n download_link = \"media/user_{0}/trained_model/{1}\".format(request.user, 'classifier.pkl')\n joblib.dump(classifier, download_link)\n y_pred = classifier.predict(X_test)\n result = accuracy_score(y_test, y_pred)\n print(result)\n return render(request, 'MLS/result.html', {\"model\": \"Linear_Classifiers_Logistic_Regression\",\n \"metrics\": \"Accuracy Score\",\n \"result\": result*100,\n \"link\": download_link})\n elif request.POST['submit'] == \"VALIDATE\" or request.POST['submit'] == \"VALIDATE_Rand\":\n classifier = LogisticRegression(penalty=penalty,\n dual=dual,\n tol=tol,\n C=C,\n fit_intercept=fit_intercept,\n intercept_scaling=intercept_scaling,\n class_weight=class_weight,\n random_state=random_state,\n solver=solver,\n max_iter=max_iter,\n multi_class=multi_class,\n verbose=verbose,\n warm_start=warm_start,\n n_jobs=n_jobs,\n l1_ratio=l1_ratio)\n scores = cross_val_score(classifier, X, y, cv=cv, scoring='accuracy')\n rmse_score = np.sqrt(scores)\n rmse_score = np.round(rmse_score, 3)\n mean = np.round(scores.mean(), 3)\n std = np.round(scores.std(), 3)\n scores = np.round(scores, 3)\n\n return render(request, 'MLS/validate.html', {\"model\": \"Linear_Classifiers_Logistic_Regression\",\n \"scoring\": \"accuracy\",\n \"scores\": scores,\n 'mean': mean,\n 'std': std,\n 'rmse': rmse_score,\n 'cv': range(cv),\n 'cv_list': range(1, cv + 1)})\n elif request.POST['submit'] == \"RandomSearch\":\n file_name = request.POST['filename']\n my_file = \"media/user_{0}/processed_csv/{1}\".format(request.user, file_name)\n features = request.POST.getlist('features')\n features_list = []\n for feature in features:\n feature = feature[1:-1]\n feature = feature.strip().split(\", \")\n for i in feature:\n features_list.append(i[1:-1])\n label = request.POST['label']\n ratio = request.POST['ratio']\n X, y, X_train, X_test, y_train, y_test = TestTrainSplit(my_file, features_list, label, int(ratio))\n rand_penalty = ['l2']\n rand_C = [float(x) for x in np.linspace(1.0, 10.0, num = 10)]\n rand_fit_intercept = [True, False]\n rand_intercept_scaling = [float(x) for x in np.linspace(1.0, 10.0, num = 10)]\n rand_intercept_scaling.append(None)\n rand_solver = ['newton-cg', 'lbfgs', 'liblinear', 'saga']\n rand_max_iter = [int(x) for x in np.linspace(100, 350, num = 6)]\n rand_multi_class = ['ovr', 'auto']\n rand_warm_start = [True, False]\n clf = LogisticRegression()\n hyperparameters = dict(penalty=rand_penalty,\n C=rand_C,\n fit_intercept=rand_fit_intercept,\n intercept_scaling=rand_intercept_scaling,\n solver=rand_solver,\n max_iter=rand_max_iter,\n multi_class=rand_multi_class,\n warm_start=rand_warm_start,)\n\n clf = RandomizedSearchCV(clf, hyperparameters, random_state=1, n_iter=100, cv=5, verbose=0,\n n_jobs=1)\n best_model = clf.fit(X, y)\n parameters = best_model.best_estimator_.get_params()\n print('Best Parameters:', parameters)\n return render(request, 'MLS/RandomSearch.html', {\"model\": \"Linear_Classifiers_Logistic_Regression\",\n \"parameters\": parameters,\n \"features\": features_list,\n \"label\": label,\n \"filename\": file_name})\n\n except Exception as e:\n return render(request, 'MLS/error.html', {\"Error\": e})","sub_path":"MLS/MLModels/Linear_Classifiers_Logistic_Regression.py","file_name":"Linear_Classifiers_Logistic_Regression.py","file_ext":"py","file_size_in_byte":11141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316099832","text":"import os\n\nproject_name = 'cache' \n\ntb_top_module = 'tb_cpu_top'\n \n# 仿真目录路径\nSimDirPath = project_name + '.sim/sim_1/behav/'\n# compile批处理脚本名称\nCompileBatName = 'compile.bat'\n# elaborate批处理脚本名称\nElaborateBatName = 'elaborate.bat'\n# simulate批处理脚本名称\nSimulateBatName = 'simulate.bat'\n# 由于所执行的脚本内容里存在一些相对路径,所以在执行脚本前,需要将系统路径切换到所执行脚本所在的目录下\n# 执行Compile脚本\nos.system('cd ' + SimDirPath + ' && ' + 'call ' + CompileBatName)\n# 执行Elaborate脚本\nos.system('cd ' + SimDirPath + ' && ' + 'call ' + ElaborateBatName)\n \n \n# 修改xxxxxxxx_simulate.do脚本,删除run 1000ns和quit -force,添加log -r ./*\nSimulateDoFile = open(SimDirPath + tb_top_module + '_simulate.do', 'r')\nSimulateDoFileAllLines = SimulateDoFile.readlines()\nSimulateDoFile.close()\nSimulateDoFile = open(SimDirPath + tb_top_module + '_simulate.do', 'w')\nfor EachLine in SimulateDoFileAllLines:\n if EachLine.find('run 1000ns') == -1 and EachLine.find('quit -force') == -1:\n SimulateDoFile.writelines(EachLine)\nSimulateDoFile.writelines('\\nlog -r ./*\\n')\nSimulateDoFile.close()\n \n \n# 删除simulate.bat脚本中的-c选项内容\nSimulateBatFile = open(SimDirPath + SimulateBatName, 'r')\nSimulateBatFileAllLines = SimulateBatFile.readlines()\nSimulateBatFile.close()\nSimulateBatFile = open(SimDirPath + SimulateBatName, 'w')\nfor EachLine in SimulateBatFileAllLines:\n if EachLine.find('%bin_path%/vsim -c -do') != -1:\n EachLine = EachLine.replace('%bin_path%/vsim -c -do', '%bin_path%/vsim -do')\n SimulateBatFile.writelines(EachLine)\nSimulateBatFile.close()\n \n \n# 将当前目录下信号文件wave.do中的内容覆写到仿真目录下的xxxxxxxx_wave.do文件中\n# SimWaveDoFile = open('wave.do', 'r')\n# SimWaveDoFileAllLines = SimWaveDoFile.readlines()\n# SimWaveDoFile.close()\n# SimWaveDoFile = open(SimDirPath + tb_top_module + '_wave.do', 'w')\n# SimWaveDoFile.writelines(SimWaveDoFileAllLines)\n# SimWaveDoFile.close()\n \n \n# 执行Simulate脚本\nos.system('cd ' + SimDirPath + ' && ' + 'call ' + SimulateBatName)","sub_path":"sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364866535","text":"import pandas as pd\n\n#Reads CSV file in local directory to pandas DataFrame & appends new column for month-to-month change\ndf = pd.read_csv('budget_data.csv', names=['Month','Profit'], header=0, index_col=0)\ndf['Change'] = df['Profit'].diff()\n\n#Uses pandas to calculate & store needed values into variables\ntotMonth = len(df.index)\ntotProfit = df['Profit'].sum()\navgMonthlyChange = df['Change'].sum() / (totMonth - 1)\nmaxInc = df['Change'].max()\nminDec = df['Change'].min()\nmonthInc = df['Change'].idxmax()\nmonthDec = df['Change'].idxmin()\n\n#Creates variable to hold list of output lines\noutputLines = [\n '|--------------------------------------------|', \n '| SUMMARY FINANCIAL ANALYSIS |',\n '| |',\n '|--------------------------------------------|',\n '|Total Months: ' + str(totMonth) + ' |',\n '| |',\n '|Total Profit: $ ' + f\"{totProfit:,d}\" + ' |',\n '| |',\n '|Average Monthly Change: $ ' + f\"{avgMonthlyChange:,.02f}\" + ' |',\n '| |',\n '|Greatest Increase: ' + str(monthInc) + ' $ ' + f\"{maxInc:,.0f}\" + ' |',\n '| |',\n '|Greatest Decrease: ' + str(monthDec) + ' $ ' + f\"{minDec:,.0f}\" + ' |',\n '| |',\n '|--------------------------------------------|']\n\n#Prints output line by line\nprint(*outputLines, sep='\\n')\n\n#Writes output to text file in local directory ***If file already exists, it will be overwritten***\nwith open('summaryAnalysis.txt', mode='w') as outfile: \n for s in outputLines:\n outfile.write('%s\\n' % s)","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154067801","text":"from query.builder import QueryCondSpec\nfrom query.exceptions import QueryError\nfrom query.parser import parse_field, tokenize_query\n\n\nclass BaseQueryManager(object):\n NAME = None\n FIELDS_PROXY = {}\n PARSERS_BY_FIELD = {}\n CONDITIONS_BY_FIELD = {}\n\n @classmethod\n def proxy_field(cls, field):\n field, suffix = parse_field(field)\n if field in cls.FIELDS_PROXY:\n field = cls.FIELDS_PROXY[field]\n return '{}__{}'.format(field, suffix) if suffix else field\n\n @classmethod\n def tokenize(cls, query_spec):\n tokenized_query = tokenize_query(query_spec)\n for key in tokenized_query.keys():\n field, _ = parse_field(key)\n if field and (field not in cls.PARSERS_BY_FIELD or\n field not in cls.CONDITIONS_BY_FIELD):\n raise QueryError('key `{}` is not supported by query manager `{}`.'.format(\n key, cls.NAME\n ))\n return tokenized_query\n\n @classmethod\n def parse(cls, tokenized_query):\n parsed_query = {}\n for key, expressions in tokenized_query.items():\n field, _ = parse_field(key)\n parsed_query[key] = [cls.PARSERS_BY_FIELD[field](exp) for exp in expressions]\n return parsed_query\n\n @classmethod\n def build(cls, parsed_query):\n built_query = {}\n for key, operations in parsed_query.items():\n field, _ = parse_field(key)\n built_query[key] = [\n QueryCondSpec(\n cond=cls.CONDITIONS_BY_FIELD[field](op=op_spec.op, negation=op_spec.negation),\n params=op_spec.params)\n for op_spec in operations]\n return built_query\n\n @classmethod\n def handle_query(cls, query_spec):\n tokenized_query = cls.tokenize(query_spec=query_spec)\n parsed_query = cls.parse(tokenized_query=tokenized_query)\n built_query = cls.build(parsed_query=parsed_query)\n return built_query\n\n @classmethod\n def apply(cls, query_spec, queryset):\n built_query = cls.handle_query(query_spec=query_spec)\n for key, cond_specs in built_query.items():\n key = cls.proxy_field(key)\n for cond_spec in cond_specs:\n queryset = cond_spec.cond.apply(\n queryset=queryset, name=key, params=cond_spec.params)\n\n return queryset\n","sub_path":"polyaxon/query/managers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"86084470","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpRequest, request, JsonResponse\nfrom .models import Name\nfrom django.views.decorators.csrf import csrf_exempt\n\ndef memoize(f):\n fibs = {}\n def helper(x):\n if x not in fibs:\n fibs[x] = f(x)\n return fibs[x]\n return helper\n\n@memoize\ndef F(n): \n if n < 1: \n return 0 \n if n == 1: \n return 1 \n return F(n-1) + F(n-2) \n\n@csrf_exempt\ndef hello(request):\n try:\n client_name = request.GET['name']\n # name_instance = Name()\n # name_instance.name = client_name\n # name_instance.save()\n mylist = {\n 'meta' : {'status' : 200},\n 'data' : {'message': 'hello, ' + client_name}\n }\n return JsonResponse(mylist)\n except:\n return HttpResponse(\"There is a problem with that input!\")\n\n\n@csrf_exempt\ndef fibonacci(request):\n try:\n number = request.GET['index']\n finalfib = F(int(number))\n mylist = {\n 'meta' : {'status' : 200},\n 'data' : {'fibNumber': finalfib}\n }\n return JsonResponse(mylist)\n except:\n return HttpResponse(\"There was a problem with calculating fibonnaci!\")\n\n","sub_path":"api_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"495778935","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Shelter, Puppy\n\n\nengine = create_engine(\"sqlite:///puppies.db\")\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\n\nprint(\"\\nPuppies in alphabetical order\")\nfor puppy in session.query(Puppy).order_by(Puppy.name).all():\n print(puppy.name)\n\nprint(\"\\nPuppies that are less than 6 months old ordered by youngest first\")\nfor puppy in session.query(Puppy).filter(Puppy.date_of_birth > '2017-01-06').order_by(Puppy.date_of_birth).all():\n print(\"{0} - {1}\".format(puppy.name, puppy.date_of_birth))\n\nprint(\"\\nPuppies ordered by weight\")\nfor puppy in session.query(Puppy).order_by(Puppy.weight).all():\n print(\"{0} - {1}\".format(puppy.name, puppy.weight))\n\nprint(\"\\nPuppies by shelter\")\nfor puppy in session.query(Puppy).join(Puppy.shelter).order_by(Shelter.name, Puppy.name).all():\n print(\"{0} - {1}\".format(puppy.shelter.name, puppy.name))\n\nsession.close()\n","sub_path":"vagrant/02_problem_set1/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"535491541","text":"# Do not import any modules. If you do, the tester may reject your submission.\n\n# Constants for the contents of the maze.\n\n# The visual representation of a wall.\nWALL = '#'\n\n# The visual representation of a hallway.\nHALL = '.'\n\n# The visual representation of a brussels sprout.\nSPROUT = '@'\n\n# Constants for the directions. Use these to make Rats move.\n\n# The left direction.\nLEFT = -1\n\n# The right direction.\nRIGHT = 1\n\n# No change in direction.\nNO_CHANGE = 0\n\n# The up direction.\nUP = -1\n\n# The down direction.\nDOWN = 1\n\n# The letters for rat_1 and rat_2 in the maze.\nRAT_1_CHAR = 'J'\nRAT_2_CHAR = 'P'\n\n\nclass Rat:\n \"\"\" A rat caught in a maze. \"\"\"\n\n # Write your Rat methods here.\n\nclass Maze:\n \"\"\" A 2D maze. \"\"\"\n\n # Write your Maze methods here.","sub_path":"a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355923936","text":" \r\n# Class NodeConnection\r\n# The connection that is made with other node. there are two of these between each pair of neighbors\r\n# Messages are received and sent to parent for processing\r\n# Messages could be sent to this node.\r\nclass NodeConnection(threading.Thread):\r\n\r\n # Python constructor\r\n def __init__(self, nodeServer, sock, clientAddress, callback=None, delay = 0.1):\r\n super(NodeConnection, self).__init__()\r\n\r\n self.host = clientAddress[0]\r\n self.port = clientAddress[1]\r\n self.nodeServer = nodeServer\r\n self.sock = sock\r\n self.clientAddress = clientAddress\r\n self.callback = callback\r\n self.terminate_flag = threading.Event()\r\n self.delay = delay\r\n # Variable for parsing the incoming json messages\r\n self.buffer = \"\"\r\n\r\n self.id = None\r\n \r\n def get_host(self):\r\n return self.host\r\n\r\n def get_port(self):\r\n return self.port\r\n\r\n # Send data to the node. data must be dictionary.\r\n # This data is converted into json and sent.\r\n def send(self, data):\r\n #data = self.create_message(data) # Call it yourself!!\r\n\r\n try:\r\n message = json.dumps(data, separators=(',', ':')) + \"-TSN\";\r\n time.sleep(self.delay) ## simulating the link delay\r\n self.sock.sendall(message.encode('utf-8'))\r\n\r\n # For visuals!\r\n #self.nodeServer.send_visuals(\"node-send\", data)\r\n\r\n except Exception as e:\r\n self.nodeServer.dprint(\"NodeConnection.send: Unexpected error:\" + str(sys.exc_info()[0]))\r\n self.terminate_flag.set()\r\n def check_message(self, data):\r\n return True\r\n\r\n def get_id(self):\r\n return self.id\r\n\r\n # Stop the node client. Please make sure you join the thread.\r\n def stop(self):\r\n self.terminate_flag.set()\r\n\r\n # This is the main loop of the node connection.\r\n def run(self):\r\n\r\n # Timeout, so the socket can be closed when it is dead!\r\n self.sock.settimeout(10.0)\r\n\r\n while not self.terminate_flag.is_set(): # Check whether the thread needs to be closed\r\n line = \"\"\r\n try:\r\n line = self.sock.recv(4096) # the line ends with -TSN\\n\r\n #line = line.encode('utf-8');\r\n \r\n \r\n except socket.timeout:\r\n pass\r\n\r\n except Exception as e:\r\n self.terminate_flag.set()\r\n self.nodeServer.dprint(\"NodeConnection: Socket has been terminated (%s)\" % line)\r\n print(e)\r\n if line != \"\":\r\n try:\r\n self.buffer += str(line.decode('utf-8'))\r\n except:\r\n print(\"NodeConnection: Decoding line error\")\r\n\r\n # Get the messages\r\n index = self.buffer.find(\"-TSN\")\r\n while ( index > 0 ):\r\n message = self.buffer[0:index]\r\n self.buffer = self.buffer[index+4::]\r\n\r\n try:\r\n data = json.loads(message)\r\n \r\n except Exception as e:\r\n print(\"NodeConnection: Data could not be parsed (%s) (%s)\" % (line, str(e)) )\r\n\r\n if ( self.check_message(data) ):\r\n self.nodeServer.message_count_recv = self.nodeServer.message_count_recv + 1\r\n self.nodeServer.event_node_message(self, data)\r\n \r\n \r\n \r\n\r\n else:\r\n self.nodeServer.dprint(\"-------------------------------------------\")\r\n self.nodeServer.dprint(\"Message is damaged and not correct:\\nMESSAGE:\")\r\n self.nodeServer.dprint(message)\r\n self.nodeServer.dprint(\"DATA:\")\r\n self.nodeServer.dprint(str(data))\r\n self.nodeServer.dprint(\"-------------------------------------------\")\r\n\r\n index = self.buffer.find(\"-TSN\")\r\n\r\n time.sleep(0.01)\r\n\r\n self.sock.settimeout(None)\r\n self.sock.close()\r\n self.nodeServer.dprint(\"NodeConnection: Stopped\")\r\n\r\n\r\n","sub_path":"src/NodeConnection.py","file_name":"NodeConnection.py","file_ext":"py","file_size_in_byte":4306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215626573","text":"\"\"\"\nAUTHOR: M. Montgomery \nDATE: 12/05/2018\nFILE: day05.py \n\nPROMPT: \n--- Day 5: Alchemical Reduction ---\n\nYou've managed to sneak in to the prototype suit manufacturing lab. The Elves are making decent progress, but are still struggling with the suit's size reduction capabilities. While the very latest in 1518 alchemical technology might have solved their problem eventually, you can do better. You scan the chemical composition of the suit's material and discover that it is formed by extremely long polymers (one of which is available as your puzzle input).\n\nThe polymer is formed by smaller units which, when triggered, react with each other such that two adjacent units of the same type and opposite polarity are destroyed. Units' types are represented by letters; units' polarity is represented by capitalization. For instance, r and R are units with the same type but opposite polarity, whereas r and s are entirely different types and do not react.\n\nFor example:\n In aA, a and A react, leaving nothing behind.\n In abBA, bB destroys itself, leaving aA. As above, this then destroys itself, leaving nothing.\n In abAB, no two adjacent units are of the same type, and so nothing happens.\n In aabAAB, even though aa and AA are of the same type, their polarities match, and so nothing happens.\n\nNow, consider a larger example, dabAcCaCBAcCcaDA:\n\ndabAcCaCBAcCcaDA The first 'cC' is removed.\ndabAaCBAcCcaDA This creates 'Aa', which is removed.\ndabCBAcCcaDA Either 'cC' or 'Cc' are removed (the result is the same).\ndabCBAcaDA No further actions can be taken.\n\nAfter all possible reactions, the resulting polymer contains 10 units. How many units remain after fully reacting the polymer you scanned?\n\n--- Part Two ---\n\nTime to improve the polymer.\n\nOne of the unit types is causing problems; it's preventing the polymer from collapsing as much as it should. Your goal is to figure out which unit type is causing the most problems, remove all instances of it (regardless of polarity), fully react the remaining polymer, and measure its length.\n\nFor example, again using the polymer dabAcCaCBAcCcaDA from above:\n\n Removing all A/a units produces dbcCCBcCcD. Fully reacting this polymer produces dbCBcD, which has length 6.\n Removing all B/b units produces daAcCaCAcCcaDA. Fully reacting this polymer produces daCAcaDA, which has length 8.\n Removing all C/c units produces dabAaBAaDA. Fully reacting this polymer produces daDA, which has length 4.\n Removing all D/d units produces abAcCaCBAcCcaA. Fully reacting this polymer produces abCBAc, which has length 6.\n\nIn this example, removing all C/c units was best, producing the answer 4. What is the length of the shortest polymer you can produce by removing all units of exactly one type and fully reacting the result?\n\"\"\"\n\nimport sys\n\n\ndef reactPolymer(polymer):\n \"\"\" Destroys all reactive pairs in given polymer until no more reactions\n can occur; returns resulting polymer. \"\"\"\n\n toCheck = 0\n while toCheck < len(polymer) - 1:\n \n # remove current and next element if they'll be destroyed\n if willDestroy(polymer[toCheck], polymer[toCheck+1]):\n polymer.pop(toCheck)\n polymer.pop(toCheck)\n\n # move back to check previous element w new neighbor\n if toCheck > 0:\n toCheck -= 1\n\n # otherwise, increment index from which to check\n else:\n toCheck += 1\n\n return ''.join(polymer)\n \n\ndef willDestroy(left, right):\n \"\"\" Determines whether or not given characters are equivalent letters\n but different cases. \"\"\"\n \n return left.upper() == right.upper() and left != right\n\n\ndef findFewestUnits(polymer):\n \"\"\" Determines the shortest possible length of the reacted polymer\n if a single letter may be entirely removed first (both cases). \"\"\"\n\n # get all letters used\n letters = set()\n for char in polymer:\n letters.add(char.upper())\n\n # find shortest reacted polymer\n shortest = float('inf')\n for letter in letters:\n\n # try removing a letter (both cases)\n newPolymer = polymer.replace(letter, '')\n newPolymer = newPolymer.replace(letter.lower(), '')\n\n # save reacted polymer length if shortest so far\n shortest = min(shortest, len(reactPolymer(list(newPolymer))))\n \n return shortest\n\n\ndef main():\n\n # get input\n polymer = sys.stdin.readline().strip()\n\n # PART ONE\n newPolymer = reactPolymer(list(polymer))\n print(\"There are\", len(newPolymer), \"units remaining in the reacted polymer.\")\n\n # PART TWO\n fewestUnits = findFewestUnits(newPolymer)\n print(\"The shortest reacted polymer has\", fewestUnits, \"units.\")\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"425314353","text":"from __future__ import absolute_import, unicode_literals, print_function\n\nimport unittest\nfrom .common import DocumentCollection, Covers, TestPropertyOwner2, TestPropertyOwner1\nimport uuid\n\n\nclass FrozenFunctionTestCase(unittest.TestCase):\n def setUp(self):\n self.dc1 = DocumentCollection(str(uuid.uuid4()))\n self.dc1.register(Covers)\n self.dc2 = DocumentCollection(str(uuid.uuid4()), master=self.dc1)\n self.dc2.register(Covers)\n\n def test_frozen_function_basic(self):\n test1 = Covers()\n self.dc1.add_document_object(test1)\n test1.covers = 1\n test2 = self.dc2.get_object_by_id(Covers.__name__, test1.id)\n self.dc2.freeze_dc_comms()\n\n test1.covers = 2\n test2.covers = 3\n self.assertEqual(test1.covers, 2)\n frozen_test1 = test1.frozen()\n self.assertNotEqual(frozen_test1, test1)\n self.assertNotEqual(frozen_test1, self.dc1.get_object_by_id(Covers.__name__, test1.id))\n self.dc2.unfreeze_dc_comms()\n self.assertEqual(frozen_test1.covers, 2)\n # The unfrozen version should be normal\n self.assertEqual(test1.covers, 3)\n\n def test_frozen_function_basic_back_to_main(self):\n test1 = Covers()\n self.dc1.add_document_object(test1)\n test1.covers = 1\n\n test1.covers = 2\n self.assertEqual(test1.covers, 2)\n frozen_test1 = test1.frozen()\n self.assertNotEqual(frozen_test1, test1)\n self.assertNotEqual(frozen_test1, self.dc1.get_object_by_id(Covers.__name__, test1.id))\n self.assertEqual(frozen_test1.covers, 2)\n frozen_test1.covers = 3\n # Test is pushed back into main\n self.assertEqual(frozen_test1.covers, 3)\n test1.covers = 4\n # Test main cannot push into frozen\n self.assertEqual(frozen_test1.covers, 3)\n\n\nclass FrozenFunctionCollectionsTestCase(unittest.TestCase):\n def setUp(self):\n self.dc1 = DocumentCollection(str(uuid.uuid4()))\n self.dc1.register(TestPropertyOwner1)\n self.dc1.register(TestPropertyOwner2)\n self.dc2 = DocumentCollection(str(uuid.uuid4()), master=self.dc1)\n self.dc2.register(TestPropertyOwner1)\n self.dc2.register(TestPropertyOwner2)\n\n def test_replicating_an_object_in_a_collection(self):\n test1 = TestPropertyOwner1()\n self.dc1.add_document_object(test1)\n testitem1 = TestPropertyOwner2()\n test1.propertyowner2s.add(testitem1)\n self.dc1.add_document_object(testitem1)\n testitem1.cover = 1\n self.dc2.freeze_dc_comms()\n testitem1.cover = 3\n test2 = self.dc2.get_object_by_id(TestPropertyOwner1.__name__, test1.id)\n self.assertEqual(len(test2.propertyowner2s), 1)\n for po2 in test2.propertyowner2s:\n self.assertEqual(po2.__class__.__name__ , TestPropertyOwner2.__name__)\n self.assertEqual(po2.cover, 1)\n\n frozen_test2 = test2.frozen()\n\n self.assertEqual(len(frozen_test2.propertyowner2s), 1)\n for po2 in frozen_test2.propertyowner2s:\n self.assertEqual(po2.__class__.__name__ , TestPropertyOwner2.__name__)\n self.assertEqual(po2.cover, 1)\n\n for po2 in test2.propertyowner2s:\n self.assertEqual(po2.__class__.__name__ , TestPropertyOwner2.__name__)\n po2.cover = 2\n self.assertEqual(len(test2.propertyowner2s), 1)\n for po2 in frozen_test2.propertyowner2s:\n self.assertEqual(po2.__class__.__name__ , TestPropertyOwner2.__name__)\n self.assertEqual(po2.cover, 1)\n\n self.dc2.unfreeze_dc_comms()\n\n self.assertEqual(len(test2.propertyowner2s), 1)\n for po2 in test2.propertyowner2s:\n self.assertEqual(po2.__class__.__name__ , TestPropertyOwner2.__name__)\n self.assertEqual(po2.cover, 3)\n\n self.assertEqual(len(frozen_test2.propertyowner2s), 1)\n for po2 in frozen_test2.propertyowner2s:\n self.assertEqual(po2.__class__.__name__ , TestPropertyOwner2.__name__)\n self.assertEqual(po2.cover, 1)\n","sub_path":"tests/test_frozenfunction.py","file_name":"test_frozenfunction.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"81007949","text":"# -*- coding: utf-8 -*-\n'''\naes algorithms.\n'''\nfrom __future__ import absolute_import\n\nimport struct\n\nfrom Crypto.Cipher import AES\nfrom Crypto.Hash import HMAC, SHA256, SHA384, SHA512\n\nfrom jwsteak.jwa.base import AESKW_Base, AESGCMKW_Base, AESCBC_Base, AESGCM_Base\n\nfrom .plugin import plugin\n\n\nQUAD = struct.Struct('>Q')\n\n\ndef aes_unwrap_key_and_iv(kek, wrapped):\n '''\n Unwraps an AES wrapped key and gets the IV.\n\n Args:\n kek (str): The Key Encryption Key.\n wrapped (str): The wrapped key.\n\n Returns:\n The decrypted key and the IV.\n\n Notes:\n Stolen from https://gist.github.com/doublereedkurt/4243633\n '''\n n = len(wrapped) / 8 - 1\n R = [None] + [wrapped[i*8:i*8+8] for i in range(1, n+1)]\n A = QUAD.unpack(wrapped[:8])[0]\n decrypt = AES.new(kek, AES.MODE_ECB).decrypt\n for j in range(5, -1, -1):\n for i in range(n, 0, -1):\n ciphertext = QUAD.pack(A^(n*j+i)) + R[i]\n B = decrypt(ciphertext)\n A = QUAD.unpack(B[:8])[0]\n R[i] = B[8:]\n return ''.join(R[1:]), A\n\n\ndef aes_unwrap_key(kek, wrapped, iv=0xa6a6a6a6a6a6a6a6):\n '''\n Unwraps an AES key and validates the IV.\n\n Args:\n kek (str): The Key Encryption Key.\n wrapped (str): The wrapped key.\n iv (str): The IV to validate against.\n\n Returns:\n The unwrapped key.\n\n Raises:\n ValueError: If the IV does not validate.\n '''\n key, key_iv = aes_unwrap_key_and_iv(kek, wrapped)\n if key_iv != iv:\n raise ValueError('Integrity Check Failed: %s (expected: %s)' % (hex(key_iv), hex(iv)))\n return key\n\n\ndef aes_wrap_key(kek, plaintext, iv=0xa6a6a6a6a6a6a6a6):\n '''\n Wraps a key using a KEK with a specified IV.\n\n Args:\n kek (str): The Key Encryption Key.\n plaintext (str): The key to be wrapped.\n iv (str): The IV to use. Default specified per RFC3394.\n '''\n n = len(plaintext) / 8\n if n < 2:\n raise ValueError('key data too short')\n R = [None] + [plaintext[i*8:i*8+8] for i in range(0, n)]\n A = iv\n encrypt = AES.new(kek, AES.MODE_ECB).encrypt\n for j in range(6):\n for i in range(1, n+1):\n B = encrypt(QUAD.pack(A) + R[i])\n A = QUAD.unpack(B[:8])[0] ^ (n*j + i)\n R[i] = B[8:]\n return QUAD.pack(A) + ''.join(R[1:])\n\n\nclass AESKW_PyCryptodome(AESKW_Base):\n '''\n Base class for AES Key Wrap algorithms.\n '''\n def encrypt(self, plaintext, key):\n '''\n Encrypts plaintext with AES key.\n\n Args:\n plaintext (str): Text to encrypt.\n key (SymmetricKey): A symmetric key. Must be the correct length\n corresponding to the AES algorithm.\n\n Returns:\n str: The encrypted ciphertext.\n '''\n key = self.get_key(key)\n return aes_wrap_key(key, plaintext)\n\n def decrypt(self, ciphertext, key):\n '''\n Decrypts ciphertext with AESKW key.\n\n Args:\n ciphertext (str): Text to decrypt.\n key (SymmetricKey): A symmetric key. Must be the correct length\n corresponding to the AES algorithm.\n\n Returns:\n str: The decrypted plaintext.\n '''\n key = self.get_key(key)\n return aes_unwrap_key(key, ciphertext)\n\n\nclass AESGCMKW_PyCryptodome(AESGCMKW_Base):\n '''\n Base class for AES GCM Key Wrap algorithms.\n '''\n def encrypt(self, plaintext, key, iv):\n '''\n Encrypts plaintext with AES key.\n\n Args:\n plaintext (str): Text to encrypt.\n key (SymmetricKey): A symmetric key. Must be the correct length\n corresponding to the AES algorithm.\n iv (str): The initialization vector to use.\n\n Returns:\n str: The encrypted ciphertext and authentication tag\n '''\n key = self.get_key(key)\n self.check_iv(iv)\n cipher = AES.new(key, AES.MODE_GCM, iv)\n ciphertext, tag = cipher.encrypt_and_digest(plaintext)\n return ciphertext, tag\n\n def decrypt(self, ciphertext, key, iv, tag):\n '''\n Decrypts ciphertext with AES key.\n\n Args:\n ciphertext (str): Text to decrypt.\n key (SymmetricKey): A symmetric key. Must be the correct length\n corresponding to the AES algorithm.\n iv (str): The initialization vector to use.\n\n Returns:\n str: The decrypted plaintext.\n '''\n key = self.get_key(key)\n self.check_iv(iv)\n cipher = AES.new(key, AES.MODE_GCM, iv)\n plaintext = cipher.decrypt_and_verify(ciphertext, tag)\n return plaintext\n\n\nclass AESCBC_PyCryptodome(AESCBC_Base):\n '''\n Base class for AES CBC algorithms.\n '''\n def get_tag(self, mac_key, aad, iv, ciphertext):\n '''\n Calculate Authentication Tag.\n\n Args:\n mac_key (str): Supplied MAC key.\n aad (str): Supplied Additional Authentication Data.\n iv (str): Supplied Initialization Vector.\n ciphertext (str): Supplied ciphertext.\n\n Returns:\n str: Authentication Tag.\n '''\n h = HMAC.new(mac_key, digestmod=self.hashfunc)\n h.update(aad)\n h.update(iv)\n h.update(ciphertext)\n h.update(self.aad_len(aad))\n m = h.digest()\n return m[:self.keylen // 16]\n\n def encrypt(self, plaintext, key, iv, aad):\n '''\n Encrypts plaintext with AES key.\n\n Args:\n plaintext (str): Text to encrypt.\n key (SymmetricKey): A symmetric key. Must be the correct length\n corresponding to the AES algorithm.\n iv (str): The initialization vector. Must be 128-bits.\n aad (str): Additional Authentication Data.\n\n Returns:\n (str, str): The encrypted ciphertext and tag.\n '''\n key = self.get_key(key)\n self.check_iv(iv)\n split = self.keylen // 16\n mac_key, enc_key = key[:split], key[split:]\n cipher = AES.new(enc_key, AES.MODE_CBC, iv)\n ciphertext = cipher.encrypt(self.pkcs7_pad(plaintext))\n tag = self.get_tag(mac_key, aad, iv, ciphertext)\n return ciphertext, tag\n\n def decrypt(self, ciphertext, key, iv, aad, tag):\n '''\n Decrypts ciphertext with AES key.\n\n Args:\n ciphertext (str): The encrypted ciphertext.\n key (SymmetricKey): A symmetric key. Must be the correct length\n corresponding to the AES algorithm.\n iv (str): The initialization vector. Must be 128-bits.\n aad (str): Additional Authentication Data.\n tag (str): The Authentication Tag.\n\n Returns:\n str: The unwrapped key.\n '''\n key = self.get_key(key)\n self.check_iv(iv)\n split = self.keylen // 16\n mac_key, enc_key = key[:split], key[split:]\n if not self.compare_digest(tag, self.get_tag(mac_key, aad, iv, ciphertext)):\n raise ValueError('authenticated tag did not validate')\n cipher = AES.new(enc_key, AES.MODE_CBC, iv)\n plaintext = cipher.decrypt(ciphertext)\n return self.pkcs7_unpad(plaintext)\n\n\nclass AESGCM_PyCryptodome(AESGCM_Base):\n '''\n Base class for AES GCM Algorithms.\n '''\n def encrypt(self, plaintext, key, iv, aad):\n '''\n Encrypts plaintext with AES key.\n\n Args:\n plaintext (str): Text to encrypt.\n key (SymmetricKey): An symmetric key.\n iv (str): The initialization vector.\n aad (str): Additional Authentication Data.\n\n Returns:\n (str, str): The encrypted ciphertext and tag.\n '''\n key = self.get_key(key)\n self.check_iv(iv)\n cipher = AES.new(key, AES.MODE_GCM, iv)\n cipher.update(aad)\n ciphertext, tag = cipher.encrypt_and_digest(plaintext)\n return ciphertext, tag\n\n def decrypt(self, ciphertext, key, iv, aad, tag):\n '''\n Decrypts ciphertext with AES key.\n\n Args:\n ciphertext (str): The encrypted ciphertext.\n key (SymmetricKey): An symmetric key.\n iv (str): The initialization vector.\n aad (str): Additional Authentication Data.\n tag (str): The Authentication Tag.\n\n Returns:\n str: The unwrapped key.\n '''\n key = self.get_key(key)\n self.check_iv(iv)\n cipher = AES.new(key, AES.MODE_GCM, iv)\n cipher.update(aad)\n plaintext = cipher.decrypt_and_verify(ciphertext, tag)\n return plaintext\n\n\n@plugin.register\nclass A128KW(AESKW_PyCryptodome):\n '''\n A128KW algorithm.\n '''\n name = 'A128KW'\n keylen = 128\n\n\n@plugin.register\nclass A192KW(AESKW_PyCryptodome):\n '''\n A192KW algorithm.\n '''\n name = 'A192KW'\n keylen = 192\n\n\n@plugin.register\nclass A256KW(AESKW_PyCryptodome):\n '''\n A256KW algorithm.\n '''\n name = 'A256KW'\n keylen = 256\n\n\n@plugin.register\nclass A128GCMKW(AESGCMKW_PyCryptodome):\n '''\n A128GCMKW algorithm.\n '''\n name = 'A128GCMKW'\n keylen = 128\n\n\n@plugin.register\nclass A192GCMKW(AESGCMKW_PyCryptodome):\n '''\n A192GCMKW algorithm.\n '''\n name = 'A192GCMKW'\n keylen = 192\n\n\n@plugin.register\nclass A256GCMKW(AESGCMKW_PyCryptodome):\n '''\n A256GCMKW algorithm.\n '''\n name = 'A256GCMKW'\n keylen = 256\n\n\n@plugin.register\nclass A128CBC_HS256(AESCBC_PyCryptodome):\n '''\n A128CBC-HS256 algorithm.\n '''\n name = 'A128CBC-HS256'\n keylen = 128 * 2\n hashfunc = SHA256\n\n\n@plugin.register\nclass A192CBC_HS384(AESCBC_PyCryptodome):\n '''\n A192CBC-HS384 algorithm.\n '''\n name = 'A192CBC-HS384'\n keylen = 192 * 2\n hashfunc = SHA384\n\n\n@plugin.register\nclass A256CBC_HS512(AESCBC_PyCryptodome):\n '''\n A256CBC-HS512 algorithm.\n '''\n name = 'A256CBC-HS512'\n keylen = 256 * 2\n hashfunc = SHA512\n\n\n@plugin.register\nclass A128GCM(AESGCM_PyCryptodome):\n '''\n A128GCM algorithm.\n '''\n name = 'A128GCM'\n keylen = 128\n\n\n@plugin.register\nclass A192GCM(AESGCM_PyCryptodome):\n '''\n A192GCM algorithm.\n '''\n name = 'A192GCM'\n keylen = 192\n\n\n@plugin.register\nclass A256GCM(AESGCM_PyCryptodome):\n '''\n A256GCM algorithm.\n '''\n name = 'A256GCM'\n keylen = 256\n","sub_path":"jwsteak_pycryptodome/aes.py","file_name":"aes.py","file_ext":"py","file_size_in_byte":10352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"401194755","text":"from requests_mock import Mocker\nfrom pytest import fixture, raises\nfrom json import dumps\nfrom logging import WARNING\n\nfrom wingmonkey.mailchimp_session import ClientException, MailChimpSession\nfrom wingmonkey.members import (Member, MemberSerializer, MemberCollection, MemberCollectionSerializer,\n MemberBatchRequestSerializer, MemberBatchRequest, generate_member_id,\n MemberActivitySerializer)\nfrom wingmonkey.lists import ListSerializer\nfrom wingmonkey.settings import DEFAULT_MAILCHIMP_ROOT\nfrom wingmonkey.enums import MemberStatus\n\nlist_serializer = ListSerializer()\nmember_serializer = MemberSerializer()\nmembers_serializer = MemberCollectionSerializer()\n\n\n@fixture()\ndef expected_member():\n return {\n '_links': None,\n 'email_address': 'adoringfan@stalkmail.com',\n 'email_client': 'Lookout On Purpose',\n 'email_type': 'html',\n 'id': 'KRBL101',\n 'interests': None,\n 'ip_opt': '1.1.1.1',\n 'ip_signup': '',\n 'language': '',\n 'last_changed': None,\n 'last_note': None,\n 'list_id': 'ListyMcListface',\n 'location': {\n 'country_code': '',\n 'dstoff': 0,\n 'gmtoff': 0,\n 'latitude': 0,\n 'longitude': 0,\n 'timezone': ''\n },\n 'member_rating': 2,\n 'merge_fields': {'FNAME': 'Eddie', 'LNAME': 'Emmer'},\n 'stats': {'avg_click_rate': 0, 'avg_open_rate': 0},\n 'status': MemberStatus.SUBSCRIBED,\n 'timestamp_opt': None,\n 'unique_email_id': None,\n 'unsubscribe_reason': None,\n 'vip': False\n }\n\n\n@fixture()\ndef expected_members(expected_member):\n return {\n 'members': [\n expected_member\n ],\n 'list_id': 'ListyMcListface',\n 'total_items': 1,\n '_links': None\n }\n\n\ndef compare_result(member, expected=None):\n \"\"\"\n\n :param member: List instance\n :param expected: List Instance or str\n :return: boolean\n \"\"\"\n if expected is None:\n return\n elif not isinstance(expected, dict):\n expected = expected.__dict__\n\n assert member.id == expected['id']\n assert member.email_address == expected['email_address']\n assert member.unique_email_id == expected['unique_email_id']\n assert member.email_type == expected['email_type']\n assert member.status == expected['status']\n assert member.unsubscribe_reason == expected['unsubscribe_reason']\n assert member.merge_fields == expected['merge_fields']\n assert member.interests == expected['interests']\n assert member.stats == expected['stats']\n assert member.ip_signup == expected['ip_signup']\n assert member.ip_opt == expected['ip_opt']\n assert member.timestamp_opt == expected['timestamp_opt']\n assert member.member_rating == expected['member_rating']\n assert member.last_changed == expected['last_changed']\n assert member.language == expected['language']\n assert member.vip == expected['vip']\n assert member.email_client == expected['email_client']\n assert member.location == expected['location']\n assert member.last_note == expected['last_note']\n assert member.list_id == expected['list_id']\n assert member._links == expected['_links']\n\n return True\n\n\ndef test_member_read(expected_member):\n member = Member(**expected_member)\n with Mocker() as request_mock:\n request_mock.get(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_member[\"list_id\"]}/members/{expected_member[\"id\"]}',\n text=dumps(expected_member))\n assert compare_result(member_serializer.read(member.list_id, member.id), expected_member)\n\n\ndef test_member_read_no_id(expected_member, expected_members):\n member = Member(**expected_member)\n with Mocker() as request_mock:\n request_mock.get(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_members[\"list_id\"]}/members',\n text=dumps(expected_members))\n request_mock.get(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_member[\"list_id\"]}/members/{expected_member[\"id\"]}',\n text=dumps(expected_member))\n assert compare_result(member_serializer.read(member.list_id), expected_member)\n\n\ndef test_member_read_no_id_empty_list(caplog, expected_members):\n expected_members.update(members=[])\n caplog.set_level(WARNING)\n with Mocker() as request_mock:\n request_mock.get(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_members[\"list_id\"]}/members',\n text=dumps(expected_members))\n member_serializer.read(expected_members['list_id'])\n assert 'No members found for list' in caplog.text\n\n\ndef test_member_create(expected_member):\n member = Member(**expected_member)\n with Mocker() as request_mock:\n request_mock.post(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_member[\"list_id\"]}/members',\n text=dumps(expected_member))\n assert compare_result(member_serializer.create(member.list_id, member), expected_member)\n\n\ndef test_member_update(expected_member):\n member = Member(**expected_member)\n with Mocker() as request_mock:\n request_mock.patch(\n f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_member[\"list_id\"]}/members/{expected_member[\"id\"]}',\n text=dumps(expected_member))\n assert compare_result(member_serializer.update(member.list_id, member), expected_member)\n\n\ndef test_member_delete(expected_member):\n member = Member(**expected_member)\n with Mocker() as request_mock:\n request_mock.delete(\n f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_member[\"list_id\"]}/members/{expected_member[\"id\"]}',\n text='')\n assert member_serializer.delete(member.list_id, member.id)\n\n\ndef test_members_read(expected_members):\n members = MemberCollection(**expected_members)\n with Mocker() as request_mock:\n request_mock.get(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_members[\"list_id\"]}/members',\n text=dumps(expected_members))\n assert members_serializer.read(members.list_id).members[0]['id'] == expected_members['members'][0]['id']\n\n\ndef test_member_batch_request(expected_member):\n expected_member2 = expected_member\n expected_member2['id'] = 'NR2'\n expected_member2['email_address'] = 'another1@bitesthe.dust'\n member_list = [Member(**expected_member), Member(**expected_member2)]\n member_batch_request = MemberBatchRequest(members=member_list)\n expected_batch_response = {\n 'new_members': [\n expected_member,\n expected_member2\n ],\n 'updated_members': None,\n 'errors': None,\n 'total_created': 2,\n 'total_updated': 0,\n 'error_count': 0,\n '_links': None\n }\n with Mocker() as request_mock:\n request_mock.post(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{expected_member[\"list_id\"]}',\n text=dumps(expected_batch_response))\n response = MemberBatchRequestSerializer().create(list_id=expected_member['list_id'],\n member_batch_request_instance=member_batch_request)\n assert response.new_members[0]['email_address'] == expected_batch_response['new_members'][0]['email_address']\n assert response.new_members[1]['email_address'] == expected_batch_response['new_members'][1]['email_address']\n assert response.total_created == expected_batch_response['total_created']\n\n\ndef test_member_batch_request_memberlist_too_big():\n oversized_list = [Member() for _ in range(0, 501)]\n assert raises(ClientException, MemberBatchRequest, members=oversized_list)\n\n\ndef test_member_serializer_without_session():\n session = MailChimpSession()\n serializer = MemberSerializer(session=session)\n assert serializer.session == session\n\n\ndef test_generate_member_id_without_email_address():\n assert not generate_member_id('')\n\n\ndef test_generate_member_id():\n \"\"\" Check if the md5 hash of some@email.com \"\"\"\n expected_hexdigest = 'd8ffeba65ee5baf57e4901690edc8e1b'\n assert generate_member_id(email_address='some@email.com') == expected_hexdigest\n\n\ndef test_member_empty_mergefields():\n member = Member(merge_fields=None)\n assert member.merge_fields == {}\n\n\ndef test_member_mergefield_with_none_value():\n member = Member(merge_fields={'NOTHING': None})\n assert member.merge_fields['NOTHING'] == ''\n\n\ndef test_member_activity_read():\n email_address = 'adoringfan@stalkmail.com'\n list_id = 'no-idea-123'\n expected_member_hash = 'c7e281082239e249d17360a9fffba276'\n expected_member_activity = {\n '_links': None,\n 'activity': [{'action': 'subscribe',\n 'campaign_id': '',\n 'timestamp': '2018-02-16T18:23:10+00:00',\n 'type': 'A'}\n ],\n 'email_id': expected_member_hash,\n 'list_id': list_id,\n 'total_items': 1\n }\n\n with Mocker() as request_mock:\n request_mock.get(f'{DEFAULT_MAILCHIMP_ROOT}/lists/{list_id}/members/{expected_member_hash}/activity',\n text=dumps(expected_member_activity))\n response = MemberActivitySerializer().read(list_id='no-idea-123', email_address=email_address)\n\n assert response.activity == expected_member_activity['activity']\n assert response.email_id == expected_member_hash\n","sub_path":"wingmonkey/tests/test_members.py","file_name":"test_members.py","file_ext":"py","file_size_in_byte":9461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"629700722","text":"import win32com.client\nimport os \nimport re\nimport sys\nfrom sys import exit\nfrom win32com.client import constants\nimport docx\nfrom docx.enum.text import WD_BREAK\nfrom datetime import datetime\napp=[]\ncount=0\nl=[]\nll=[]\nlll=[]\nres=[]\nfig=[]\nimport sys \niter=sys.argv[1]\nstart=datetime.now()\nprint(\"-----------------------------------------------------------------------------------------------------------------\")\nprint(\"Document Name:\", iter)\nprint(\"CheckList Rule - 37:Appendix reference Check.\")\nprint(\"Document Review Start Time:\", start,\"HH:MM:SS\")\nprint(\"-----------------------------------------------------------------------------------------------------------------\")\nprint(\"\\n\")\n##Open the Document\nif iter.endswith('.doc') or iter.endswith('.docx'):\n word1 = win32com.client.gencache.EnsureDispatch (\"Word.Application\")\n word1.Visible = True\n p = os.path.abspath(iter)\n word1.Documents.Open(p)\n sheet_1 = word1.ActiveDocument\n para = sheet_1.Hyperlinks\n para1=sheet_1.Paragraphs\n try:\n for p in para:\n m=p.Range.Text.encode('ascii','ignore').decode()\n #print(m)\n if re.search('[\\w\\s]+?APPENDIX',m) or re.search('^APPENDIX',m):\n #print(m)\n f=m.split('\\t')\n for i in f:\n f1=i.strip('\\r')\n f1=f1.strip('\\r\\x07')\n f1=f1.strip('\\x0c')\n f1=f1.strip('\\x0b')\n f1=f1.strip('\\x0a')\n f1=f1.rstrip(' ')\n f1=f1.strip('\\n')\n f1=f1.strip('\\r\\x07')\n app.append(f1.lower())\n\n if app==[]:\n print(\"No Appendix Found in the Document Table of Contents.\")\n end=datetime.now()\n print(\"\\nDocument Review End Time:\", end)\n print(\"\\nTime taken For Document Review:\", end-start,\"HH:MM:SS\") \n sheet_1.Close()\n word1.Quit() \n exit(0)\n except:\n # #end=datetime.now()\n # #print(\"\\nDocument Review End Time:\", end)\n # #print(\"\\nTime taken For Document Review:\", end-start,\"HH:MM:SS\") \n # #doc.Close()\n # #word1.Quit() \n # #exit(0)\n pass\n for para in para1:\t\n a=para.Range.Font.Bold\n b=para.Range.Style\n #print(b)\n c=para.Range.Text.encode('ascii','ignore').decode()\n if str(a) == '-1' and re.search(\"appendix\",c,re.IGNORECASE) and re.search(\"^Normal\",str(b)) : #or re.search(\"^appendix\",c,re.IGNORECASE): #\n #print(c)\n #print(\"Page number:\",para.Range.Information(constants.wdActiveEndAdjustedPageNumber))\n #print(\"Line On Page:\",para.Range.Information(constants.wdFirstCharacterLineNumber))\n c=c.strip('\\r')\n c=c.strip('\\r\\x07')\n c=c.strip('\\x0c')\n c=c.strip('\\x0b')\n c=c.strip('\\x0a')\n c=c.rstrip(' ')\n c=c.strip('\\n')\n l.append(c.lower())\n ll.append(para.Range.Information(constants.wdActiveEndAdjustedPageNumber))\n lll.append(para.Range.Information(constants.wdFirstCharacterLineNumber)) \n if str(a) == '-1' and re.search(\"appendix\",c,re.IGNORECASE) and re.search(\"^Heading\",str(b)): \n #print(c)\n #print(\"Page number:\",para.Range.Information(constants.wdActiveEndAdjustedPageNumber))\n #print(\"Line On Page:\",para.Range.Information(constants.wdFirstCharacterLineNumber))\n c=c.strip('\\r')\n c=c.strip('\\r\\x07')\n c=c.strip('\\x0c')\n c=c.strip('\\x0b')\n c=c.strip('\\x0a')\n c=c.rstrip(' ')\n c=c.strip('\\n')\n l.append(c.lower())\n ll.append(para.Range.Information(constants.wdActiveEndAdjustedPageNumber))\n lll.append(para.Range.Information(constants.wdFirstCharacterLineNumber))\n \n for i in l:\n if i in app:\n count=count+1\n else:\n res.append(i)\n if res==[]:\n print(\"Appendix in Table of Contents are referred in Document.\")\n print(\"Status:Pass\")\n else:\n print(\"Appendix Not Referred:\\n\",res)\n print(\"Status:Fail\")\nend=datetime.now()\nprint(\"\\nDocument Review End Time:\", end)\nprint(\"\\nTime taken For Document Review:\", end-start,\"HH:MM:SS\") \nsheet_1.Close()\nword1.Quit() \n \n ","sub_path":"Debug/setup/source1/appendix_ref/appendix_ref.py","file_name":"appendix_ref.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"171614012","text":"import sys\nimport unittest\nimport json\nfrom unittest import mock\n\nsys.path.append('../')\nfrom pair_chooser import is_jp_unique, should_include_jobpair # noqa: E402\n\n\nclass Test(unittest.TestCase):\n\n def _mock_response(self, status=200, content='CONTENT', json_data=None, raise_for_status=None):\n mock_resp = mock.Mock()\n # mock raise_for_status call w/ optional error\n mock_resp.raise_for_status = mock.Mock()\n if raise_for_status:\n mock_resp.raise_for_status.side_effect = raise_for_status\n mock_resp.status = status\n mock_resp.content = content\n if json_data:\n mock_resp.json = mock.Mock(\n return_value=json_data\n )\n return mock_resp\n\n def _mock_json_data(self, filename):\n with open('pair_chooser_files/' + filename, 'r') as f:\n return json.loads(f.read())\n\n def test_pair_uniqueness_1(self):\n scout_filename = 'Scout24-minedBuildPairs-data'\n scout_mock_resp = self._mock_response(\n json_data=self._mock_json_data(scout_filename)\n )\n\n immobilien_filename = 'ImmobilienScout24-minedBuildPairs-data'\n immobilien_mock_resp = self._mock_response(\n json_data=self._mock_json_data(immobilien_filename)\n )\n\n artifact_filename = '131735009-artifact-data'\n artifact_mock_resp = self._mock_response(\n json_data=self._mock_json_data(artifact_filename)\n )\n\n # simulates repo: Scout24/deadcode4j's failed job ID: 131735009 and passed job ID: 131741120\n # to be included for reproducing, but will be filtered out due to already being associated with\n # Artifact: ImmobilienScout24-deadcode4j-131735009\n false_count = 0\n include_jobpair_count = 0\n for jp in scout_mock_resp.json.return_value['jobpairs']:\n include_jobpair = should_include_jobpair(jp, 131735009, 131741120)\n if include_jobpair:\n include_jobpair_count += 1\n is_unique = is_jp_unique('Scout24/deadcode4j', jp, artifact_mock_resp.json.return_value)\n if not is_unique:\n scout_failed_job_id = jp['failed_job']['job_id']\n false_count += 1\n\n self.assertEqual(include_jobpair_count, 1)\n self.assertEqual(false_count, 1)\n self.assertEqual(scout_failed_job_id,\n artifact_mock_resp.json.return_value[str(scout_failed_job_id)]['failed_job']['job_id'])\n\n # simulates repo: ImmobilienScout24/deadcode4j's failed job ID: 131735009 and passed job ID: 131741120\n # to be included for reproducing and will not be filtered out due to it's association with it's\n # Artifact: ImmobilienScout24-deadcode4j-131735009\n true_count = 0\n include_jobpair_count = 0\n include_projects_jobpair_count = 0\n for jp in immobilien_mock_resp.json.return_value['jobpairs']:\n # simulates total # of jobpairs for project for reproducing\n include_jobpair = should_include_jobpair(jp, None, None)\n if include_jobpair:\n include_projects_jobpair_count += 1\n\n # simulates the jobpair for reproducing\n include_jobpair = should_include_jobpair(jp, 131735009, 131741120)\n if include_jobpair:\n include_jobpair_count += 1\n\n is_unique = is_jp_unique('ImmobilienScout24/deadcode4j', jp, artifact_mock_resp.json.return_value)\n if is_unique:\n true_count += 1\n\n self.assertEqual(include_projects_jobpair_count, 15)\n self.assertEqual(include_jobpair_count, 1)\n self.assertEqual(true_count, len(scout_mock_resp.json.return_value['jobpairs']))\n","sub_path":"travis-reproducer/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467975381","text":"from django.conf.urls import patterns, url\nfrom . import views\nfrom endless_pagination.decorators import (\n page_template,\n page_templates,\n)\n\nurlpatterns = patterns('',\n url(r'^test/$', views.test, name='test'),\n url(r'^index/$', views.index, name='index'),\n url(r'^login/$', views.login, name='login'),\n url(r'^logout/$',views.logout,name='logout'),\n url(r'^register/$',views.register,name='register'),\n)\n","sub_path":"fw/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"281928489","text":"from marionette_driver import By\nfrom marionette_driver.errors import MarionetteException\n\nfrom marionette_harness import MarionetteTestCase\n\n# expected values for navigation properties\nnav_props = {\"appCodeName\": \"Mozilla\",\n\"appName\": \"Netscape\",\n\"appVersion\": \"5.0 (Windows)\",\n\"language\": \"en-US\",\n\"mimeTypes\": \"[object MimeTypeArray]\",\n\"platform\": \"Win32\",\n\"oscpu\": \"Windows NT 6.1\",\n\"vendor\": \"\",\n\"vendorSub\": \"\",\n\"product\": \"Gecko\",\n\"productSub\": \"20100101\",\n\"plugins\": \"[object PluginArray]\",\n\"userAgent\": \"Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0\",\n\"cookieEnabled\": \"true\",\n\"onLine\": \"true\",\n\"buildID\": \"20100101\",\n\"doNotTrack\": \"unspecified\",\n\"javaEnabled\": \"\"\"function javaEnabled() {\n [native code]\n}\"\"\",\n\"taintEnabled\": \"\"\"function taintEnabled() {\n [native code]\n}\"\"\",\n\"vibrate\": \"\"\"function vibrate() {\n [native code]\n}\"\"\",\n\"registerContentHandler\": \"\"\"function registerContentHandler() {\n [native code]\n}\"\"\",\n\"registerProtocolHandler\": \"\"\"function registerProtocolHandler() {\n [native code]\n}\"\"\",\n\"mozIsLocallyAvailable\": \"undefined\",\n\"mozId\": \"undefined\",\n\"mozPay\": \"undefined\",\n\"mozAlarms\": \"undefined\",\n\"mozContacts\": \"undefined\",\n\"mozPhoneNumberService\": \"undefined\",\n\"mozApps\": \"undefined\",\n\"mozTCPSocket\": \"undefined\",\n}\n\n\nclass Test(MarionetteTestCase):\n def test_navigator(self):\n with self.marionette.using_context('content'):\n self.marionette.navigate('about:robots')\n js = self.marionette.execute_script\n for nav_prop, expected_value in nav_props.iteritems():\n # cast to string on the JS side, otherwise we have issues\n # that raise from Python/JS type disparity\n self.marionette.set_context(self.marionette.CONTEXT_CONTENT)\n current_value = js(\"return ''+navigator['%s']\" % nav_prop)\n self.assertEqual(expected_value, current_value, \"Navigator property mismatch %s [%s != %s]\" % (nav_prop, current_value, expected_value))\n","sub_path":"marionette/tor_browser_tests/test_fp_navigator.py","file_name":"test_fp_navigator.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"662630","text":"import wx\n \nclass MyForm(wx.Frame):\n \n def __init__(self):\n wx.Frame.__init__(self, None, wx.ID_ANY, 'Image Extractor')\n \n # Add a panel so it looks the correct on all platforms\n self.panel = wx.Panel(self, wx.ID_ANY)\n \n ico = wx.Icon('resources/icons/myIcon.ico', wx.BITMAP_TYPE_ICO)\n self.SetIcon(ico)\n \n \n# Run the program\nif __name__ == '__main__':\n app = wx.App()\n frame = MyForm().Show()\n app.MainLoop()","sub_path":"wxIconExample.py","file_name":"wxIconExample.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"321655347","text":"from __future__ import division, print_function\nimport numpy as np\nfrom xmitgcm import open_mdsdataset as mitgcmds\nfrom os.path import join, isfile\nfrom time import sleep\n\n\nclass tmsim(object):\n \"\"\"\n A class that deals with tracmass.\n Tracmass must be compiled manually (at least for now),\n then tmsim can configure and run a simulation.\n \"\"\"\n _empty = np.array([], int)\n\n def __init__(self, basedir, projdir, ptemplate, inname, mitgcmdir):\n \"\"\"\n Define a tmsim object.\n basedir: base directory, where the \"runtrm\" executable\n and the \"projects\" directory are found.\n projdir: directory of tracmass project template,\n containing namelist, radgrid, etc.\n (to be found inside the \"projects\" subdirectory)\n ptemplate: template file name with namelist for tracmass,\n this will be edited to split the computation\n over multiple cpus.\n inname: filename of the tracmass namelist, which will be\n fed to the executable\n mitgcmdir: Path to MITgcm data\n \"\"\"\n \n tmexe = join(basedir, \"runtrm\")\n if not isfile(tmexe):\n raise ValueError(\"Cannot find 'runtrm' executable.\")\n self.exepath = tmexe\n\n with open(join(basedir, \"projects\", projdir, ptemplate), 'r') as f:\n self._infile = f.readlines()\n self.project = projdir\n self.projdir = join(basedir, \"projects\", projdir)\n\n inname = inname.rstrip()\n if inname.endswith(\".in\"):\n self.nmlname = inname\n else:\n self.nmlname = inname + \".in\"\n \n if not mitgcmdir.endswith(\"/\"):\n mitgcmdir += \"/\"\n self.mitgcmdir = mitgcmdir\n\n self.ii = None\n self.jj = None\n self.kk = None\n self.indlist = None\n\n def ijklims(self, ii=_empty, jj=_empty, kk=_empty,\n inds=True, geometry=\"curvilinear\"):\n \"\"\"\n Define the ii, jj, kk indices from which particles will be\n released.\n ii, jj, kk: list, array, or scalar with indices (i, j, k) from which\n particles will be released (must be integers).\n inds: if True (default), ii, jj and kk are interpreted\n as indices, otherwise they are interpreted as lists of\n exact release positions\n geometry: only used when inds=False, it describes the MITgcm\n grid geometry. At the moment, only \"curvilinear\" and\n \"cartesian\" have been implemented.\n \"\"\"\n self.seed_inds = inds\n\n if inds:\n if not np.issubdtype(self.ii.dtype, np.integer):\n raise TypeError(\"Indices must be integers (i-indices).\")\n self.ii = np.atleast_1d(np.squeeze(ii))\n if not np.issubdtype(self.jj.dtype, np.integer):\n raise TypeError(\"Indices must be integers (j-indices).\")\n self.jj = np.atleast_1d(np.squeeze(jj))\n if not np.issubdtype(self.kk.dtype, np.integer):\n raise TypeError(\"Indices must be integers (k-indices).\")\n self.kk = np.atleast_1d(np.squeeze(kk))\n else:\n # if MITgcm coordinates are passed, we have to load the model grid\n # and then translate into the \"normalised\" index coordinates of\n # tracmass\n from . import _get_geometry, _xy2grid\n from matplotlib.path import Path\n from itertools import product\n\n ii = np.atleast_1d(np.squeeze(ii))\n jj = np.atleast_1d(np.squeeze(jj))\n kk = np.atleast_1d(np.squeeze(kk))\n\n if (ii.size != jj.size) or (ii.size != kk.size):\n raise ValueError(\"If inds=False, ii, jj and kk must have \"\n \"all the same dimension.\")\n \n grid = mitgcmds(self.mitgcmdir, read_grid=True,\n iters=[], prefix=[\"UVEL\"], swap_dims=False,\n geometry=geometry)\n xG, yG = _get_geometry(grid, geometry)\n dX = grid.dxG\n dY = grid.dyG\n cs = grid.CS\n sn = grid.SN\n dZ = (grid.drF * grid.hFacC).to_masked_array()\n zG = np.zeros((dZ.shape[0] + 1, dZ.shape[1], dZ.shape[2]))\n zG[1:, ...] = np.cumsum(dZ, axis=0).filled(0)\n # tracmass has opposite Z order\n zG = zG[::-1, ...]\n self.ii = np.zeros(ii.size) * np.nan\n self.jj = np.zeros(ii.size) * np.nan\n self.kk = np.zeros(ii.size) * np.nan\n trials = ([-1, -1],\n [-1, 0],\n [-1, 1],\n [ 0, -1],\n [ 0, 1],\n [ 1, -1],\n [ 1, 0],\n [ 1, 1])\n for nn, (xx, yy, zz) in enumerate(zip(ii, jj, kk)):\n for jj, ii in product(range(xG.shape[0]-1), range(xG.shape[1]-1)):\n bbPath = Path([[xG[jj, ii], yG[jj, ii]],\n [xG[jj, ii+1], yG[jj, ii+1]],\n [xG[jj+1, ii+1], yG[jj+1, ii+1]],\n [xG[jj+1, ii], yG[jj+1, ii]]])\n if bbPath.contains_point((xx, yy)):\n nx, ny = _xy2grid(xx - xG[jj, ii], yy - yG[jj, ii],\n dX[jj, ii], dY[jj, ii],\n cs[jj, ii], sn[jj, ii])\n # since some corner points are approximate, we must\n # check the computed nx and ny, and in case seek in\n # nearby cell\n if (nx < 0) or (nx > 1) or (ny < 0) or (ny > 1):\n for ijtry in trials:\n ii = ii - ijtry[0]\n jj = jj - ijtry[1]\n nx, ny = _xy2grid(xx - xG[jj, ii], yy - yG[jj, ii],\n dX[jj, ii], dY[jj, ii],\n cs[jj, ii], sn[jj, ii])\n if (nx >= 0) and (nx < 1) and (ny >=0) and (ny < 1):\n break\n else:\n raise ValueError(\"Could not find the point (x=%f, y=%f)\" \n % xx, yy)\n z_here = zG[:, jj, ii]\n if (zz > z_here.max()) or (zz <= z_here.min()):\n print(\"Point outside vertical bounds at x,y,z=%.2f,%.2f,%.2f\" %\n (xx, yy, zz))\n break\n kk = np.where(z_here > zz)[0][-1]\n nz = (zz - z_here[kk]) / (z_here[kk+1] - z_here[kk])\n self.ii[nn] = ii + nx\n self.jj[nn] = jj + ny\n self.kk[nn] = kk + nz\n self.ii = self.ii[np.isfinite(self.ii)]\n self.jj = self.jj[np.isfinite(self.jj)]\n self.kk = self.kk[np.isfinite(self.kk)]\n\n\n def _decompose(self, ncpu):\n if (self.ii is None) or (self.jj is None) or (self.kk is None):\n raise ValueError(\"To perform a domain decomposition, first \"\n \" define the indices from where the particles\"\n \" will be released.\")\n if self.seed_inds:\n ii, ji, ki = np.meshgrid(self.ii, self.jj, self.kk)\n self.indlist = zip(ii.ravel(), ji.ravel(), ki.ravel())\n else:\n self.indlist = zip(self.ii, self.jj, self.kk)\n #nsplit = len(indlist) // ncpu\n #self.mpinds = []\n #for nc in range(ncpu-1):\n # self.mpinds.append(indlist[nc*nsplit:(nc+1)*nsplit])\n #self.mpinds.append(indlist[(nc+1)*nsplit:])\n\n def run(self, ncpu=1, ni0=None, ni1=None):\n \"\"\"\n Run simulation on ncpu cores. Each realese grid cell is run separately.\n ni0, ni1: if given, run simulations numbered from ni0 to ni1 included only.\n Useful to repeat some simulations, etc.\n \"\"\"\n if not np.issubdtype(type(ncpu), np.integer):\n raise TypeError(\"Number of cpus must be an integer.\")\n\n from subprocess32 import Popen\n\n def check_active(procs):\n # check which processes are running\n active = []\n for p in procs:\n if p.poll() is None:\n active.append(p)\n return active, len(active)\n\n self._decompose(ncpu)\n\n procs = []\n ijkproc = []\n if ni0 is None:\n ni0 = 0\n if ni1 is None:\n ni1 = len(self.indlist) - 1\n outf = [open(join(self.projdir, (\"output_%.6d.txt\" % nproc)), 'w')\n if (nproc >= ni0) & (nproc <= ni1) else None\n for nproc, _ in enumerate(self.indlist)]\n for nproc, ijk in enumerate(self.indlist):\n if (nproc < ni0) or (nproc > ni1):\n continue\n # generate namelist for the grid point\n if self.seed_inds:\n nml = self._make_namelist(i1=ijk[0], i2=ijk[0],\n j1=ijk[1], j2=ijk[1],\n k1=ijk[2], k2=ijk[2],\n cn=nproc,\n ddir=self.mitgcmdir)\n else:\n nml = self._make_namelist(cn=nproc,\n ddir=self.mitgcmdir)\n f = open(join(self.projdir, \"seed.txt\"), 'w')\n f.write((3*\"%10.2f\" + 2*\"%6i\" + \"%12i\\n\") %\n (ijk[0], ijk[1], ijk[2], 5, 0, 1))\n f.close()\n\n\n # write nml to file\n f = open(join(self.projdir, self.nmlname), 'w')\n f.writelines(nml)\n f.close()\n # start tracmass\n procs.append(Popen([self.exepath, self.project,\n self.nmlname[:-3]],\n stdout=outf[nproc], stderr=outf[nproc]))\n ijkproc.append(ijk)\n # sleep to let the process start and read the namelist\n # this is a poor trick, but as long as we dont want to use\n # a direct interface between python and fortran, it does the job\n if ncpu > 1:\n sleep(0.5)\n # check which processes are running\n active, na = check_active(procs)\n while na >= ncpu:\n # if we wait for a specific process to finish,\n # we may leave one or more CPUs empty even for\n # long time. This is certainly not professional\n # but works.\n sleep(5)\n active, na = check_active(procs)\n\n # wait for all to finish and store exit code\n self.exit = {}\n for n, (ijk, p) in enumerate(zip(ijkproc, procs)):\n self.exit[ijk] = p.wait()\n outf[n].close()\n\n def _make_namelist(self, **kwargs):\n\n from string import Template\n outfile = []\n for l in self._infile:\n t = Template(l)\n outfile.append(t.safe_substitute(kwargs))\n return outfile\n","sub_path":"tmpyui/tmsim.py","file_name":"tmsim.py","file_ext":"py","file_size_in_byte":11500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"633778522","text":"class Solution:\r\n def findContinuousSequence(self, target: int):\r\n i, j = 1, 1\r\n res = []\r\n while j < (target + 1) // 2 + 1:\r\n summ = sum(list(range(i, j + 1)))\r\n if summ < target: # 若和小于目标,右指针向右移动,扩大窗口\r\n j += 1\r\n elif summ == target: # 相等就把指针形成的窗口添加进输出列表中\r\n res.append(list(range(i, j + 1)))\r\n i += 1\r\n j += 1\r\n else: # 若和大于目标,左指针向右移动,减小窗口\r\n i += 1\r\n return res\r\n\r\n\r\nprint(Solution().findContinuousSequence(9))","sub_path":"LeetCode practice/First/57-2.findContinuousSequence.py","file_name":"57-2.findContinuousSequence.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492307371","text":"from python.component.pagepart.CreateEditExpenseBasicComponent import CreateEditExpenseBasicComponent\n\nclass CreateEditExpenseBasicReportComponent(CreateEditExpenseBasicComponent):\n\n selectors = {\n \"detail_project_input\": \"id=project\",\n \"detail_client_input\": \"id=client\",\n \"detail_attendees_input\": \"xpath=.//div[contains(@class,'c6')]//input\",\n \"detail_note_input\": \"xpath=.//div[contains(@class,'c7 cell_note')]//input\",\n \"detail_note_input_textarea\": \"id=noteContent\",\n \"creating_mode_recipt\" : \"id=receipt_\"\n }\n\n def input_client(self, client):\n self.logger.info(\"Input client\")\n locator_client = self.resolve_selector(\"detail_client_input\")\n self.input_text(locator_client, client)\n self.wait_until_element_is_not_visible(\"id=gridLoadingDiv\", 30)\n return self\n\n def input_attendees(self, attendees):\n self.logger.info(\"Input attendees\")\n self.input_text(\"detail_attendees_input\", attendees)\n return self\n\n def input_note(self, note):\n self.logger.info(\"Click note input to show note textarea\")\n self.click_element(\"detail_note_input\")\n self.logger.info(\"Input note to textarea\")\n self.input_text(\"detail_note_input_textarea\", note)\n return self\n\n def input_project(self, project):\n self.logger.info(\"Input project\")\n locator_project = self.resolve_selector(\"detail_project_input\")\n self.input_text(locator_project, project)\n return self\n \n def client_value_should_be(self, client):\n self.logger.info(\"Verify client\")\n self.textfield_value_should_be(\"detail_client_input\", client)\n return self\n\n def attendees_value_should_be(self, attendees):\n self.logger.info(\"Verify attendees\")\n self.textfield_value_should_be(\"detail_attendees_input\", attendees)\n return self\n\n def note_value_should_be(self, note):\n self.logger.info(\"Verify note\")\n self.textfield_value_should_be(\"detail_note_input\", note)\n return self\n\n def project_value_should_be(self, project):\n self.logger.info(\"Verify project\")\n self.textfield_value_should_be(\"detail_project_input\", project)\n return self\n\n def report_table_basic_editor_should_be_displayed(self):\n self.table_basic_editor_should_be_displayed()\n self.element_should_be_visible(\"detail_project_input\")\n self.element_should_be_visible(\"detail_client_input\")\n self.element_should_be_visible(\"detail_attendees_input\")\n self.element_should_be_visible(\"detail_note_input\")\n return self\n \n def report_expense_table_basic_editor_should_be_displayed(self, currentdate, default_currency):\n self.new_expense_row_should_be_displayed()\n self.date_value_should_be(currentdate)\n self.amount_unit_should_be(default_currency)\n self.receipt_should_be_shown_in_create_mode\n self.element_should_be_visible(\"show_detail_panel_button\")\n return self\n \n def receipt_should_be_shown_in_create_mode(self):\n webElements = self.get_webelements(\"creating_mode_recipt\")\n for el in webElements:\n style_value = el.get_attribute('style')\n if \"display: none;\" in style_value:\n return True\n return False","sub_path":"expense-ui-robot-tests/PythonExpenseAutomationTest/python/component/pagepart/report/CreateEditExpenseBasicReportComponent.py","file_name":"CreateEditExpenseBasicReportComponent.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"368090567","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 1 11:49:19 2018\r\n\r\n@author: fmuret\r\n\"\"\"\r\n\r\nimport win32api, win32con, time, random, numpy\r\nfrom PIL.Image import Image\r\nimport PIL.Image\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport scipy.ndimage\r\nimport scipy\r\nimport numpy as np\r\nfrom resizeimage import resizeimage\r\nimport random\r\nfrom time import sleep\r\nimport threading\r\nfrom pynput import keyboard\r\nimport threading, msvcrt\r\nimport sys\r\nimport cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom PIL import ImageGrab\r\nimport os.path\r\n\r\n\r\ndef click(x,y):\r\n win32api.SetCursorPos((x,y))\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)\r\n \r\n\r\n\r\n\r\n\r\ndef securite(porte,max,min):\r\n while porte < min or porte > max: \r\n porte=int(input(\"valeur de range entre 1 et 4 ? \"))\r\n print( porte ) \r\n return porte\r\n\r\n\r\n\r\n# #---------------- filtre ---------------------- \r\ndef filtrer():\r\n lena = PIL.Image.open(\"map.jpg\") #image\r\n img = np.asarray(lena) \r\n img_modified = scipy.ndimage.filters.gaussian_filter(img, sigma=0.7) #filtre\r\n reverse=PIL.Image.fromarray(img_modified,'RGB')\r\n im=reverse\r\n Image.show(im)\r\n \r\n \r\n \r\ndef decision(pos_x,pos_y):\r\n actualx=pos_x\r\n actualy=pos_y\r\n \r\n direction = random.randint(1,4)\r\n \r\n if direction == 1: # ==>\r\n actualx=pos_x+1\r\n elif direction==2: # <==\r\n actualx=pos_x-1\r\n elif direction==3: # ^\r\n actualy=pos_y+1\r\n elif direction==4: # v\r\n actualy=pos_y-1\r\n return (actualy, actualx,direction)\r\n \r\n\r\n\r\ndef directions(direction):\r\n if direction==1: # ==>\r\n click(2309, 33)\r\n elif direction==2: # <==\r\n click(2959, 509)\r\n elif direction==3: # ^\r\n click(2299 ,1021)\r\n else : # v\r\n click(1701, 446)\r\n print(pos_x,pos_y)\r\n\r\n\r\n\r\ndef interupt(timer):\r\n s=timer\r\n for k in range(0,s):\r\n n = win32api.GetAsyncKeyState(win32con.VK_F2 )\r\n if n==-32767:\r\n return False\r\n break\r\n time.sleep(0.1)\r\n return True\r\n\r\n\r\n\r\n\r\ndef capture_frame():\r\n img = ImageGrab.grab(bbox=(0, 0, 1678, 1043)) #x, y, w, h a adapter\r\n img_np = np.array(img)\r\n frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)\r\n return frame\r\n #----------USEFULL FOR DEBUG\r\n \r\n #cv2.imshow(\"frame\", frame)\r\n #cv2.waitKey(0)\r\n #cv2.destroyAllWindows()\r\n \r\n\r\n\r\n\r\ndef treatment_nvgris(seuil,img):\r\n seuil_gris=seuil\r\n #img = cv2.imread('map5.jpg',0)\r\n \r\n kernel = np.ones((5,5),np.float32)/25\r\n dst = cv2.filter2D(img,-1,kernel)\r\n \r\n #cv2.imshow('smotthing2',img)\r\n #cv2.waitKey(0)\r\n #cv2.destroyAllWindows()\r\n \r\n height = np.size(dst, 0)\r\n width = np.size(dst, 1)\r\n #print(height,width)\r\n \r\n \r\n for x in range (width-1):\r\n for y in range (height-1):\r\n px = dst[y,x]\r\n if px>seuil_gris:\r\n dst[y,x]=255\r\n \r\n #cv2.imshow('smotthing2',dst)\r\n #cv2.waitKey(0)\r\n #cv2.destroyAllWindows()\r\n \r\n return dst\r\n \r\n\r\n\r\n\r\ndef treatment_localisation(frame,thresdown,threshold):\r\n Found=[]\r\n somme=0\r\n compteur=0\r\n for x in range (0,780,20): #800, par pas de 20 noyaux de 40 par 130 \r\n for y in range (0,408,17):\r\n somme=0\r\n \r\n compteur=compteur+1\r\n \r\n \r\n for x_current in range (x,x+40,1):\r\n for y_current in range (y,130+y,1):\r\n poid=frame[y_current,x_current]\r\n somme=somme+poid\r\n \r\n if thresdown Observable:\n x = sentence_to_vec(sentences, word_index, model_config)\n\n start = time.clock()\n preds = model.predict(x, batch_size=1024)\n print(\"Predict cost time {} s\".format(time.clock() - start))\n tags_encode = np.argmax(preds, axis=2)\n tags_decode = Observable.of(*tags_encode)\n\n if parallel:\n return Observable.zip(Observable.of(*sentences), tags_decode, lambda s, i: (s, i)) \\\n .flat_map(lambda v: Observable.just(v)\n .subscribe_on(pool_scheduler)\n .map(lambda v: (v[0], v[1][-len(v[0]):]))\n .map(lambda v: (v[0], list(map(lambda i: index_chunk[i], v[1]))))\n .map(lambda v: cut_sentence_str(*v)))\n else:\n return Observable.zip(Observable.of(*sentences), tags_decode, lambda s, i: (s, i)) \\\n .map(lambda v: (v[0], v[1][-len(v[0]):])) \\\n .map(lambda v: (v[0], list(map(lambda i: index_chunk[i], v[1])))) \\\n .map(lambda v: cut_sentence_str(*v))\n\n\ndef cut_sentence(sentence, tags):\n words = list(sentence)\n cuts, t1 = [], []\n for i, tag in enumerate(tags):\n if tag == 'B':\n if len(t1) != 0:\n cuts.append(t1)\n t1 = [words[i]]\n elif tag == 'I':\n t1.append(words[i])\n elif tag == 'S':\n if len(t1) != 0:\n cuts.append(t1)\n cuts.append([words[i]])\n t1 = []\n if i == len(tags) - 1 and len(t1) != 0:\n cuts.append(t1)\n return cuts\n\n\ndef cut_sentence_str(sentence, tags):\n cuts = cut_sentence(sentence, tags)\n words = list(map(lambda word_cuts: ''.join(word_cuts), cuts))\n return words\n\n\ndef _load_sentences(text_file, max_sentence_len):\n with open(text_file, \"r\", encoding=\"UTF-8\") as f:\n return list(map(lambda line: line[:min(len(line), max_sentence_len)], f.readlines()))\n\n\ndef _save_pred(pred, pred_file_path):\n stream = pred.reduce(lambda a, b: a + b)\n with open(pred_file_path, \"a\", encoding=\"UTF-8\") as f:\n stream.subscribe(lambda text: f.write(' '.join(text)))\n\n\nif __name__ == '__main__':\n optimal_thread_count = multiprocessing.cpu_count()\n pool_scheduler = ThreadPoolScheduler(optimal_thread_count)\n\n parser = argparse.ArgumentParser(description=\"分割一段或几段文本,每段文本不超过150词,否则会截断。\")\n parser.add_argument(\"-m\", \"--model_dir\", help=\"指定模型目录\", default=\"./model\")\n parser.add_argument(\"-pf\", \"--pref_file_path\", help=\"将分词结果保存到指定文件中\", default=None)\n\n parser.add_mutually_exclusive_group()\n parser.add_argument(\"-s\", \"--sentence\", help=\"指定要分词的语句,以空格' '分割多句\")\n parser.add_argument(\"-tf\", \"--text_file_path\", help=\"要分割的文本文件的路径,文本中每一行为一句话。\")\n\n args = parser.parse_args()\n\n model_base_dir = args.model_dir\n config = load_model_config(os.path.join(model_base_dir, \"model.cfg\"))\n word_index, chunk_index = load_dict(os.path.join(model_base_dir, \"model.dict\"))\n model = config.build_model()\n model.load_weights(os.path.join(model_base_dir, \"model.final.h5\"))\n\n index_chunk = {i: c for c, i in chunk_index.items()}\n\n if args.sentence:\n sentences = args.sentence.split()\n elif args.text_file_path:\n sentences = _load_sentences(args.text_file_path, config.max_sequence_len)\n else:\n raise RuntimeError(\"你必须通过-s 获 -tf 选项指定要进行分词的文本。\")\n\n # sentences = [\n # \"Multi-tasklearning (多任务学习)是和single-task learning (单任务学习)相对的一种机器学习方法。\",\n # \"拿大家经常使用的school data做个简单的对比,school data是用来预测学生成绩的回归问题的数据集,总共有139个中学的15362个学生,其中每一个中学都可以看作是一个预测任务。\",\n # \"单任务学习就是忽略任务之间可能存在的关系分别学习139个回归函数进行分数的预测,或者直接将139个学校的所有数据放到一起学习一个回归函数进行预测。\"]\n\n result = predict(sentences, word_index, index_chunk, model, config)\n\n if args.pref_file_path:\n _save_pred(result, args.pref_file_path)\n else:\n result.subscribe(lambda v: print(v))\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508395411","text":"from queue import Queue\n\nclass Map:\n def __init__(self, *node_list):\n map = {}\n tmp = {}\n for i in node_list:\n tmp[i] = None\n for i in node_list:\n map[i] = tmp.copy()\n self.map = map\n self.node_list = node_list\n return\n\n def append(self, node_from, node_to, distance):\n assert distance > 0\n assert node_from in self.node_list\n assert node_to in self.node_list\n self.map[node_from][node_to] = distance\n return\n\n def distance(self, node_from, node_to):\n return self.map[node_from][node_to]\n\n\n def dijkstra(self, node_from, node_to):\n founded = [node_from]\n shortest = {}\n for i in self.node_list:\n shortest[i] = None\n shortest[node_from] = 0\n\n while True:\n tmp_node = None\n tmp_mid_node = None\n tmp_distance = None\n for i in founded:\n for j in self.node_list:\n if j in founded:\n continue\n distance = self.distance(i, j)\n if distance is None:\n continue\n if tmp_distance is None or distance < tmp_distance:\n tmp_distance = distance\n tmp_mid_node = i\n tmp_node = j\n if tmp_node is None:\n break\n founded.append(tmp_node)\n shortest[tmp_node] = shortest[tmp_mid_node] + tmp_distance\n for i in self.node_list:\n if i in founded:\n continue\n if self.distance(tmp_node, i) is not None:\n if shortest[i] is None or shortest[i] > shortest[tmp_node] + self.distance(tmp_node, i):\n shortest[i] = shortest[tmp_node] + self.distance(tmp_node, i)\n\n if shortest[node_to] is None:\n return 'NO SUCH ROUTE'\n return shortest[node_to]\n\n\n def sum_distance(self, *node_list):\n sum = 0\n while True:\n if 1 == len(node_list):\n return sum\n distance = self.distance(node_list[0], node_list[1])\n if distance is None:\n return 'NO SUCH ROUTE'\n sum += distance\n node_list = node_list[1:]\n\n def shortest_route(self, node_from, node_to):\n shortest = -1\n queue = Queue()\n\n def put_in(node, route):\n for i in self.node_list:\n distance = self.distance(node, i)\n if distance is not None:\n queue.put((i, route + distance))\n return\n\n put_in(node_from, 0)\n\n while not queue.is_empty():\n node, route = queue.get()\n if route > shortest > 0:\n continue\n if node == node_to:\n if -1 == shortest or route < shortest:\n shortest = route\n continue\n put_in(node, route)\n\n return shortest\n\n def all_trips(self, node_from, node_to, accept_func, trim_func):\n number = 0\n queue = Queue()\n\n def put_in(node, step, route):\n for i in self.node_list:\n distance = self.distance(node, i)\n if distance is not None:\n queue.put((i, step + 1, route + distance))\n return\n\n put_in(node_from, 0, 0)\n\n while not queue.is_empty():\n node, step, route = queue.get()\n if node == node_to and accept_func(step, route):\n number += 1\n if trim_func(step, route):\n continue\n\n put_in(node, step, route)\n\n return number\n","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"418390140","text":"\"\"\" Terminal view module \"\"\"\n\ndef sum_position(table):\n sum_pos = 0\n for i in range(len(table)):\n sum_pos += float(table[i])\n\n return sum_pos\n\ndef print_table(table, title_list):\n \"\"\"\n Prints table with data.\n\n Example:\n /-----------------------------------\\\n | id | title | type |\n |--------|----------------|---------|\n | 0 | Counter strike | fps |\n |--------|----------------|---------|\n | 1 | fo | fps |\n \\-----------------------------------/\n\n Args:\n table (list): list of lists - table to display\n title_list (list): list containing table headers\n\n Returns:\n None: This function doesn't return anything it only prints to console.\n \"\"\"\n\n # your goes code\n title_list.insert(0,'NUMBER')\n\n count = 0\n\n for row in table:\n count += 1\n row.insert(0, str(count))\n\n table.insert(0, title_list)\n\n\n len_col = []\n index = 0\n for row in table:\n len_col.append([])\n for number in range(len(row)):\n longest_name = len(row[number])\n len_col[index].append(longest_name)\n index += 1\n\n max_line_len = []\n for number in range(len(title_list)):\n max_line_len.append([])\n for col in len_col:\n max_line_len[number].append(col[number])\n\n max_line_len = [(max(line)) for line in max_line_len]\n max_line = sum_position(max_line_len)\n\n dashed_line = (\"═\" * int(max_line + 1 + len(title_list)))\n head = [(title_list[index].rjust(max_line_len[index])+'│') for index in range(len(title_list))]\n header = '│' + ''.join(head)\n table.pop(0)\n print(dashed_line)\n print(header)\n print(dashed_line)\n \n \n for row in table:\n body_list = [(row[index].rjust(max_line_len[index])+'│') for index in range(len(row))]\n body = '│' + ''.join(body_list)\n print(body)\n print(dashed_line)\n\n\n for row in table:\n row.pop(0)\n\n title_list.pop(0)\n\ndef print_result(result, label):\n \"\"\"\n Displays results of the special functions.\n\n Args:\n result: result of the special function (string, list or dict)\n label (str): label of the result\n\n Returns:\n None: This function doesn't return anything it only prints to console.\n \"\"\"\n \n # your code\n\n if isinstance(result, dict):\n print('{0:>35}'.format(label))\n to_print_a = [[item[0], item[1]] for item in result.items()]\n to_print_b = [('{0:>35} : {1:>1}'.format(item[0], item[1])) for item in to_print_a]\n [print(element) for element in to_print_b]\n elif isinstance(result, list):\n if isinstance(result[0], list):\n print('{0:>20}'.format(label))\n for i in range(len(result)):\n for j in range(len(result[i])):\n result[i][j] = str(result[i][j])\n for i in result:\n body_list = [('{0:^21}-'.format(i[q])) for q in range(len(i))]\n body = '-' + ''.join(body_list)\n print(body)\n else:\n print('{0:>20}'.format(label))\n [print('{0:>20}'.format(item)) for item in result]\n\n elif isinstance(result, str):\n print('{} : {}'.format(label, result))\n\n \n \n\ndef print_menu(title, list_options, exit_message):\n \"\"\"\n Displays a menu. Sample output:\n Main menu:\n (1) Store manager\n (2) Human resources manager\n (3) Inventory manager\n (4) Accounting manager\n (5) Sales manager\n (6) Customer relationship management (CRM)\n (0) Exit program\n\n Args:\n title (str): menu title\n list_options (list): list of strings - options that will be shown in menu\n exit_message (str): the last option with (0) (example: \"Back to main menu\")\n\n Returns:\n None: This function doesn't return anything it only prints to console.\n \"\"\"\n\n print(\"{}:\".format(title))\n for list_index in range(len(list_options)):\n print(\"\\t({}) {}\".format(list_index+1, list_options[list_index]))\n print(\"\\t(0) {}\".format(exit_message))\n\n\ndef get_inputs(list_labels, title):\n \"\"\"\n Gets list of inputs from the user.\n Sample call:\n get_inputs([\"Name\",\"Surname\",\"Age\"],\"Please provide your personal information\")\n Sample display:\n Please provide your personal information\n Name \n Surname \n Age \n\n Args:\n list_labels (list): labels of inputs\n title (string): title of the \"input section\"\n\n Returns:\n list: List of data given by the user. Sample return:\n [, , ]\n \"\"\"\n # your code\n inputs = []\n\n print(title)\n for label in list_labels:\n data_user = input(label + \" \")\n inputs.append(data_user)\n\n return inputs\n\n\ndef get_choice(options, exit_message):\n print_menu(\"Main menu\", options, exit_message)\n inputs = get_inputs([\"Please enter a number: \"], \"\")\n return inputs[0]\n\n\ndef print_error_message(message):\n \"\"\"\n Displays an error message (example: ``Error: @message``)\n\n Args:\n message (str): error message to be displayed\n\n Returns:\n None: This function doesn't return anything it only prints to console.\n \"\"\"\n\n print(\"``Error: @{}``\".format(message))\n","sub_path":"view/terminal_view.py","file_name":"terminal_view.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265875211","text":"#!/usr/bin/python3\nimport math, operator, random, sys\n\ndef get_lower_hull(concave_function, X):\n Y = list(map(int, map(concave_function, X)))\n min_value = min(Y)\n return list(map(lambda x: x - min_value, Y))\n\n\ndef get_lower_hull_2(concave_function_1, concave_function_2, X, q):\n cusp = min(len(X) - 1, int(q * len(X)))\n Y1 = get_lower_hull(concave_function_1, X[:cusp+1])\n Y2 = get_lower_hull(concave_function_2, X[cusp:])\n return join_hulls(Y1, Y2)\n\n\ndef convert_to_upper_hull(lower_Y, t):\n return list(map(lambda y: t - y, lower_Y))\n\n\ndef join_hulls(increasing, decreasing):\n max_value = max(increasing[-1], decreasing[0])\n diff_increasing = max_value - increasing[-1]\n diff_decreasing = max_value - decreasing[0]\n return list(map(lambda x: x + diff_increasing, increasing)) + list(map(lambda x: x + diff_decreasing, decreasing[1:]))\n\n\ndef get_distance(lower_X, lower_Y, upper_X, upper_Y):\n def neg(A):\n return list(map(operator.neg, A))\n\n def aux(points, hull_X, hull_Y):\n res = float('inf')\n j = 0\n for x, y in points:\n while hull_X[j] < x:\n j += 1\n if hull_X[j] == x:\n res = min(res, hull_Y[j] - y)\n else:\n q = (x - hull_X[j - 1]) / (hull_X[j] - hull_X[j - 1])\n yu = q * hull_Y[j] + (1 - q) * hull_Y[j - 1]\n res = min(res, yu - y)\n return res\n\n assert lower_X[0] == upper_X[0] and lower_X[-1] == upper_X[-1]\n return min(aux(zip(lower_X, lower_Y), upper_X, upper_Y),\n aux(zip(upper_X, neg(upper_Y)), lower_X, neg(lower_Y)))\n\n\ndef add_dummy_points(X, hull_X, hull_Y):\n assert X[0] == hull_X[0] and X[-1] == hull_X[-1]\n j = 0\n Y = []\n for x in X:\n while hull_X[j] < x:\n j += 1\n ax, ay = 2 * hull_X[j - 1] - hull_X[j], 2 * hull_Y[j - 1] - hull_Y[j]\n bx, by = hull_X[j - 1], hull_Y[j - 1]\n if hull_X[j] == x:\n Y.append(hull_Y[j])\n else:\n q = (x - ax) / (bx - ax)\n y = max(0, int(q * by + (1 - q) * ay) - random.randint(1, 5))\n Y.append(y)\n ax, ay = bx, by\n bx, by = x, y\n return Y\n\n\ndef get_sample(X, q):\n return [X[0]] + sorted(random.sample(X[1:-1], min(len(X) - 2, int(q * len(X))))) + [X[-1]]\n\n\ndef bring_closer(lower_Y, upper_Y, d):\n assert len(lower_Y) == len(upper_Y)\n lower_d = d // 2\n upper_d = (d + 1) // 2\n for i in range(len(lower_Y)):\n lower_Y[i] += lower_d\n upper_Y[i] -= upper_d\n\n\ndef generate(n, t, lower_coeff, upper_coeff, lower_f1, lower_f2, lower_cusp, upper_f1, upper_f2, upper_cusp, strategy):\n X = sorted(random.sample(range(t), n))\n lower_X = get_sample(X, lower_coeff)\n upper_X = get_sample(X, upper_coeff)\n lower_Y = get_lower_hull_2(lower_f1, lower_f2, lower_X, lower_cusp)\n upper_Y = get_lower_hull_2(upper_f1, upper_f2, upper_X, upper_cusp)\n\n d = get_distance(lower_X, lower_Y, upper_X, convert_to_upper_hull(upper_Y, t))\n print(d, file=sys.stderr)\n assert d >= 0\n\n lower_Y = add_dummy_points(X, lower_X, lower_Y)\n upper_Y = convert_to_upper_hull(add_dummy_points(X, upper_X, upper_Y), t)\n bring_closer(lower_Y, upper_Y, strategy(d))\n\n return (X, lower_Y, upper_Y)\n\n\nclass Writer:\n def __init__(self):\n self.current_set = 0\n self.current_case = 0\n\n def next_case(self):\n self.current_case += 1\n\n def next_set(self):\n self.current_set += 1\n self.current_case = 0\n\n def write(self, X, lower_Y, upper_Y):\n assert len(X) == len(lower_Y) and len(X) == len(upper_Y)\n P = list(range(len(X)))\n random.shuffle(P)\n with open('{}.{}.in'.format(self.current_set, chr(self.current_case + ord('a'))), 'w') as f:\n print(len(X), file=f)\n for i in P:\n assert lower_Y[i] <= upper_Y[i]\n print(X[i], lower_Y[i], upper_Y[i], file=f)\n self.next_case()\n\n\ndef get_raiser(k):\n return lambda x: pow(x, k)\n\n\ndef scale(function, a):\n return lambda x: a * function(x)\n\n\ndef slow_down(function, k):\n return lambda x: function(x) / pow(math.log(x + 2), k)\n\n\ndef reflect(function, t):\n return lambda x: function(t - x)\n\n\ndef impossible_strategy(x):\n return math.ceil(x)\n\n\ndef tight_strategy(x):\n return math.floor(x)\n\n\ndef get_coeff_strategy(coeff):\n return lambda x: int((1 - coeff) * x)\n\n\nrandom.seed(0x25367c61)\nW = Writer()\n\nW.next_set()\nt = 100\nn = 10\nf = scale(get_raiser(0.9), 1)\ns = get_coeff_strategy(0.2)\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0.3, f, reflect(f, t), 0.6, s))\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 1, f, reflect(f, t), 1, s))\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0, f, reflect(f, t), 1, s))\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 1, f, reflect(f, t), 0, s))\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0, f, scale(reflect(f, t), 0.5), 0, s))\nW.write([4], [20], [30])\nt = 10**9\ns = get_coeff_strategy(1 / 10**6)\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0.7, f, reflect(f, t), 0.6, s))\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0.1, f, reflect(f, t), 0.3, tight_strategy))\nn = 10**3\nW.write(*generate(n, t, 0.9, 0.9, f, reflect(f, t), 0.4, f, reflect(f, t), 0.6, s))\nW.write(*generate(n, t, 0.2, 0.9, f, reflect(f, t), 0.1, f, reflect(f, t), 0.2, tight_strategy))\nf = reflect(scale(get_raiser(1.05), -0.1), t)\nW.write(*generate(n, t, 0.5, 0.5, f, reflect(f, t), 0.9, f, reflect(f, t), 1, s))\nW.write(*generate(n, t, 0.5, 0.5, f, reflect(f, t), 0.9, f, reflect(f, t), 0.8, impossible_strategy))\nW.write(*generate(n, t, 0.5, 0.2, f, reflect(f, t), 0.4, slow_down(f, 1), reflect(f, t), 0.5, tight_strategy))\n\nW.next_set()\nt = 10**9\nn = 10**5\nf = scale(get_raiser(0.9), 7)\ns = get_coeff_strategy(1 / 10**6)\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0.5, f, reflect(f, t), 0.5, s))\nW.write(*generate(n, t, 0.8, 0.8, f, reflect(f, t), 0.3, f, reflect(f, t), 0.8, tight_strategy))\nW.write(*generate(n, t, 0.7, 0.7, f, reflect(f, t), 0.9, scale(f, 0.2), reflect(f, t), 0.8, impossible_strategy))\nW.write(*generate(n, t, 0.4, 0.4, f, reflect(f, t), 0, f, reflect(f, t), 1, s))\nW.write(*generate(n, t, 0.4, 0.4, f, slow_down(reflect(f, t), 0.5), 0, f, scale(reflect(f, t), 0.1), 0, s))\nW.write(*generate(n, t, 0.1, 0.2, f, reflect(f, t), 0.3, f, slow_down(reflect(f, t), 1), 0.3, tight_strategy))\n\nW.next_set()\nt = 10**9\nn = 10**5\nf = reflect(scale(get_raiser(1.05), -0.3), t)\ns = get_coeff_strategy(1 / 10**6)\nW.write(*generate(n, t, 1, 1, f, reflect(f, t), 0.5, f, reflect(f, t), 0.5, s))\nW.write(*generate(n, t, 0.8, 0.8, f, reflect(f, t), 0.3, f, reflect(f, t), 0.8, impossible_strategy))\nW.write(*generate(n, t, 0.7, 0.7, f, reflect(f, t), 0.9, scale(f, 0.2), reflect(f, t), 0.8, tight_strategy))\nf = scale(f, 0.4)\nW.write(*generate(n, t, 0.4, 0.4, f, reflect(f, t), 0.2, f, reflect(f, t), 0.3, get_coeff_strategy(0.5)))\nW.write(*generate(n, t, 0.4, 0.4, f, slow_down(reflect(f, t), 0.5), 0.8, f, scale(reflect(f, t), 0.1), 0.8, s))\nW.write(*generate(n, t, 0.05, 0.05, f, reflect(f, t), 0.3, f, slow_down(reflect(f, t), 1), 0.3, tight_strategy))\n","sub_path":"tester/day-mix2/slalom/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":7184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277410178","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom new import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.index, name=\"index\"),\n path('about/', views.about, name=\"about\"),\n path('courses/', views.courses, name=\"courses\"),\n path('team/', views.team, name=\"team\"),\n path('contact/', views.contact, name=\"contact\"),\n path('pricing/', views.pricing, name=\"pricing\"),\n path('reviews/', views.reviews, name=\"reviews\"),\n path('signin/', views.signin, name=\"signin\"),\n path('signup/', views.signup, name=\"signup\"),\n path('logout/', views.logoutUser, name=\"logoutUser\"),\n path('new_course/', views.new_course, name=\"new_course\"),\n]\n\nurlpatterns+=static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"559395752","text":"from __future__ import print_function\n\nimport os\n\nimport numpy as np\nimport scipy.misc\nfrom PIL import Image, ImageOps\n\n\ndef get_resized_image(img_path, height, width, save=True):\n image = Image.open(img_path)\n # it's because PIL is column major so you have to change place of width and height\n # this is stupid, i know\n image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)\n if save:\n image_dirs = img_path.split('/')\n image_dirs[-1] = 'resized_' + image_dirs[-1]\n out_path = '/'.join(image_dirs)\n if not os.path.exists(out_path):\n image.save(out_path)\n image = np.asarray(image, np.float32)\n return np.expand_dims(image, 0)\n\n\ndef generate_noise_image(content_image, height, width, noise_ratio=0.6):\n noise_image = np.random.uniform(-20, 20,\n (1, height, width, 3)).astype(np.float32)\n return noise_image * noise_ratio + content_image * (1 - noise_ratio)\n\n\ndef save_image(path, image):\n # Output should add back the mean pixels we subtracted at the beginning\n image = image[0] # the image\n image = np.clip(image, 0, 255).astype('uint8')\n scipy.misc.imsave(path, image)\n\n\ndef rgb2gray(rgb):\n return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])\n\n\ndef gray2rgb(gray):\n _, w, h = gray.shape\n rgb = np.empty((w, h, 3), dtype=np.float32)\n rgb[:, :, 2] = rgb[:, :, 1] = rgb[:, :, 0] = gray\n return rgb\n\n\ndef recreate_img(content, img_out):\n original_image = np.clip(content, 0, 255)\n styled_image = np.clip(img_out, 0, 255)\n\n # Luminosity transfer steps:\n # 1. Convert stylized RGB->grayscale accoriding to Rec.601 luma (0.299, 0.587, 0.114)\n # 2. Convert stylized grayscale into YUV (YCbCr)\n # 3. Convert original image into YUV (YCbCr)\n # 4. Recombine (stylizedYUV.Y, originalYUV.U, originalYUV.V)\n # 5. Convert recombined image from YUV back to RGB\n\n # 1\n styled_grayscale = rgb2gray(styled_image)\n styled_grayscale_rgb = gray2rgb(styled_grayscale)\n\n # 2\n styled_grayscale_yuv = np.array(Image.fromarray(styled_grayscale_rgb.astype(np.uint8)).convert('YCbCr'))\n\n # 3\n _, w, h, _ = original_image.shape\n original_yuv = np.array(Image.fromarray(original_image.astype(np.uint8)[0]).convert('YCbCr'))\n\n # 4\n combined_yuv = np.empty((w, h, 3), dtype=np.uint8)\n combined_yuv[..., 0] = styled_grayscale_yuv[..., 0]\n combined_yuv[..., 1] = original_yuv[..., 1]\n combined_yuv[..., 2] = original_yuv[..., 2]\n\n # 5\n img_out = np.array(Image.fromarray(combined_yuv, 'YCbCr').convert('RGB'))\n return img_out.reshape([1, w, h, 3])\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176394389","text":"# coding:utf-8\n# author:zhangyanni\nimport pkg_resources\nfrom gitRepo import ExerciseRepo\nfrom conf import Config\nfrom lib_util import Util\nfrom xblock.core import XBlock\nfrom xblock.fields import Scope, Integer\nfrom xblock.fragment import Fragment\nimport urllib2\nimport json\nimport base64\n\n\nclass PeerAssessemntXBlock(XBlock):\n \"\"\"\n TO-DO: document what your XBlock does.\n \"\"\"\n\n # Fields are defined on the class. You can access them in your code as\n # self..\n\n # TO-DO: delete count, and define your own fields.\n count = Integer(\n default=0, scope=Scope.user_state,\n help=\"A simple counter, to show something happening\",\n )\n logger = Util.custom_logger({\n 'logFile': Config.logFile,\n 'logFmt': Config.logFmt,\n 'logName': 'PeerAssessmentXBlockLog'\n })\n\n # 当前block保存的题题号\n qNo = Integer(default=0, scope=Scope.content)\n\n def resource_string(self, path):\n \"\"\"Handy helper for getting resources from our kit.\"\"\"\n data = pkg_resources.resource_string(__name__, path)\n return data.decode(\"utf8\")\n\n # TO-DO: change this view to display your data your own way.\n def student_view(self, context=None):\n \"\"\"\n The primary view of the PeerAssessemntXBlock, shown to students\n when viewing courses.\n \"\"\"\n html = self.resource_string(\"static/html/peerassessment.html\")\n frag = Fragment(html.format(self=self))\n frag.add_css(self.resource_string(\"static/css/peerassessment.css\"))\n frag.add_javascript_url('//cdn.bootcss.com/handlebars.js/4.0.5/handlebars.min.js')\n frag.add_javascript_url('//cdn.bootcss.com/showdown/1.3.0/showdown.min.js')\n frag.add_javascript(self.resource_string(\"static/js/src/peerassessment.js\"))\n frag.initialize_js('PeerAssessemntXBlock')\n return frag\n\n # TO-DO: change this handler to perform your own actions. You may need more\n # than one handler, or you may not need any handlers at all.\n\n @XBlock.json_handler\n def getQuestionJson(self, data, suffix=''):\n q_number = int(data['q_number'])\n url = Config.questionJsonUrl % {\n 'qDir': ((q_number - 1) / 100) + 1,\n 'qNo': q_number,\n }\n try:\n #req = urllib2.Request(url)\n res_data = urllib2.urlopen(url)\n res = res_data.read()\n res = json.loads(res)\n if 'content' in res:\n content = json.loads(base64.b64decode(res['content']))\n self.logger.info('getQuestionJson [qNo=%d] [url=%s]' % (q_number, url))\n return {'code': 0, 'desc': 'ok', 'res': content}\n elif res['message'] == 'Not Found':\n self.logger.info('ERROR getQuestionJson [qNo=%d] [msg=%s] [url=%s]' % (q_number, res['message'], url))\n return {'code': 1, 'type': 'error', 'desc': u'题号为%d的题目不存在' % q_number}\n else:\n self.logger.info('ERROR getQuestionJson [qNo=%d] [msg=%s] [url=%s]' % (q_number, res['message'], url))\n return {'code': 1, 'error': 'error', 'dese': 'Error occurs when loading %d.json message: %s' % (q_number, res['message'])}\n except Exception as e:\n self.logger.exception('ERROR getQuestionJson [qNo=%d] [desc=%s] [url=%s]' % (q_number, str(e), url))\n return {\n 'code': 1,\n 'type': 'error',\n 'desc': str(e),\n }\n\n @XBlock.json_handler\n def setQuestionJson(self, data, suffix=''):\n try:\n repo = ExerciseRepo(Config.localRepoDir)\n repo.setUser({'email': Config.commitEmail, 'name': Config.commitName})\n # 简单检查题目是否合理\n lenOfAnswer = len(data['answer'].strip())\n questionType = data['type']\n if lenOfAnswer == 0:\n return {'code': 2, 'type': 'warning', 'desc': '答案不能为空'}\n if questionType == 'single_answer' and lenOfAnswer != 1:\n return {'code': 2, 'type': 'warning', 'desc': '单选题的答案个数仅有一个'}\n\n data['status'] = 'ok'\n\n if not data['q_number']:\n data['q_number'] = repo.getMaxQNo() + 1\n repo.setExercise(data)\n self.logger.info('setQuestionJson [qNo=%d] [%s]' % (data['q_number'], json.dumps(data)))\n return {'code': 0, 'q_number': data['q_number']}\n except Exception as e:\n self.logger.exception('ERROR setQuestionJson [qNo=%d] [desc=%s] [%s]' % (data['q_number'], str(e), json.dumps(data)))\n return {'code': 1, 'type': 'error', 'desc': '发生错误, %s' % str(e)}\n \n @XBlock.json_handler\n def onLoad(self,data,suffix=''):\n \"\"\"\n 页面加载时,判断用户类型。\n \"\"\"\n student = self.runtime.get_real_user(self.runtime.anonymous_student_id)\n studentEmail = student.email\n if(student.is_staff):\n return {\"userType\":\"staff\",\"email\":studentEmail}\n else:\n return {\"userType\":\"student\",\"email\":studentEmail}\n\n @XBlock.json_handler\n def questionInitLoad(self,data,suffix=''):\n \"\"\"\n 题目布置页面,初始加载,检查是否己经布置过题目\n \"\"\"\n if(self.qNo==0):\n return {\"qNo\":0,\"type\":\"info\",\"desc\":\"尙未布置题目\"}\n else:\n qDir=((self.qNo - 1) / 100) + 1\n q_number=self.qNo\n try:\n APIUrl = Config.activitiAPIUrl+ \"getQAContent?qDir=%(qDir)s,qNo=%(qNo)s\" % {'qDir':qDir,'qNo':self.qNo}\n res_data = urllib2.urlopen(APIUrl)\n res = res_data.read()\n res = json.loads(res)\n if 'content' in res:\n content = json.loads(base64.b64decode(res['content']))\n self.logger.info('getQuestionJson [qNo=%d] [url=%s]' % (q_number, APIUrl))\n return {'code': 0, 'desc': 'ok', 'res': content}\n elif res['message'] == 'Not Found':\n self.logger.info('ERROR getQuestionJson [qNo=%d] [msg=%s] [url=%s]' % (q_number, res['message'], APIUrl))\n return {'code': 1, 'type': 'error', 'desc': u'题号为%d的题目不存在' % q_number}\n else:\n self.logger.info('ERROR getQuestionJson [qNo=%d] [msg=%s] [url=%s]' % (q_number, res['message'], APIUrl))\n return {'code': 1, 'error': 'error', 'dese': 'Error occurs when loading %d.json message: %s' % (q_number, res['message'])}\n except Exception as e:\n self.logger.exception('ERROR questionInitLoad [desc=%s] [%s]' % ( str(e), json.dumps(data)))\n return {'success': 0, 'type': 'error', 'desc': '发生错误, %s' % str(e)}\n\n @XBlock.json_handler\n def getStudentStatus(self,data,suffix=''):\n \"\"\"\n 获得学生状态,及要显示的数据\n \"\"\"\n curStatus = {\"title\": \"作业提交阶段\",\"question\": \"下面是SFS的磁盘索引节点数据结构定义。\\n```\\nstruct sfs_disk_inode {\\n uint32_t size;\\n uint16_t type;\\n uint16_t nlinks;\\n uint32_t blocks;\\n uint32_t direct[SFS_NDIRECT];\\n uint32_t indirect;\\n};\\n```\\n假定ucore 里 SFS_NDIRECT的取值是16,而磁盘上数据块大小为1KB。请计算这时ucore支持的最大文件大小。请给出计算过程。(这样可给步骤分)\"}\n student = self.runtime.get_real_user(self.runtime.anonymous_student_id)\n \n try:\n #APIUrl = Config.activitiAPIUrl+ \"getStudentStatus?email=%(email)s\" % {'email':student.email}\n url='http://192.168.1.137:8000/workFlow/common/getQAContent?qDir=16&qNo=1570'\n res_data = urllib2.urlopen(url)\n res = res_data.read()\n res = json.loads(res)\n return {\"success\":1,\"result\":json.dumps(res)}\n #return {\"success\":1,\"result\":json.dumps(curStatus)}\n except Exception as e:\n self.logger.exception('ERROR getStudentStatus [desc=%s] [%s]' % ( str(e), json.dumps(data)))\n return {'success': 0, 'type': 'error', 'desc': '发生错误, %s' % str(e)}\n\n @XBlock.json_handler\n def getTimeJson(self,data,suffix=''):\n \"\"\"\n Get Time Setting From API\n \"\"\" \n try: \n data[\"courseName\"]=\"os_course\"\n data[\"courseCode\"]=\"course-v1:Tsinghua+OS101+2016_T1\"\n #url = Config.activitiAPIUrl+ \"getScheduleTime?schedule=%(schedule)s\" % {'schedule':json.dumps(data)}\n #url='http://192.168.1.137:8000/workFlow/common/getQAContent?qDir=16&qNo=1570'\n url = 'http://192.168.1.137:8000/workFlow/common/selectScheduleTime?courseCode=%(courseCode)s' % {'courseCode':data[\"courseCode\"]}\n res_data = urllib2.urlopen(url)\n res = res_data.read()\n res = json.loads(res)\n return {\"result\": json.dumps(res),\"url\":url}\n #return {\"hasTimeSetting\":0,\"result\":url} \n except Exception as e:\n self.logger.exception('ERROR getTimeJson [desc=%s] [%s]' % ( str(e), json.dumps(data)))\n return {'success': 0, 'type': 'error', 'desc': '发生错误, %s' % str(e)}\n @XBlock.json_handler\n def setTimeJson(self,data,suffix=''):\n \"\"\"\n Set Time \n \"\"\"\n try:\n data[\"courseName\"]=\"os_course\"\n data[\"courseCode\"]=\"course-v1:Tsinghua+OS101+2016_T1\"\n url = \"http://192.168.1.137:8000/workFlow/common/insertScheduleTime?schedule=%(schedule)s\" % {'schedule':json.dumps(data)} \n res_data = urllib2.urlopen(url)\n res = res_data.read()\n res = json.loads(res)\n return {\"success\": json.dumps(res)}\n #return {\"success\":1,\"result\":url} \n except Exception as e:\n self.logger.exception('ERROR setTimeJson [desc=%s] [%s]' % ( str(e), json.dumps(data)))\n return {'success': 0, 'url':url,'type': 'error', 'desc': '发生错误, %s' % str(e)} \n @XBlock.json_handler\n def commitPhase(self,data,suffix=''):\n \"\"\"\n commit excercise\n \"\"\"\n student = self.runtime.get_real_user(self.runtime.anonymous_student_id)\n data[\"email\"]=student.email\n try:\n url = Config.activitiAPIUrl + \"commitExercise?...\"\n # res_data = urllib2.urlopen(url)\n # res = res_data.read()\n # res = json.loads(res)\n # return {\"success\":1,\"result\":res}\n return {\"success\":1,\"result\":data}\n except Exception as e:\n self.logger.exception('ERROR setTimeJson [desc=%s] [%s]' % ( str(e), json.dumps(data)))\n return {'success': 0, 'type': 'error', 'desc': '发生错误, %s' % str(e)}\n\n @XBlock.json_handler\n def teacher_settings(self, data, suffix=''):\n \"\"\"\n An example handler, which increments the data.\n \"\"\"\n # Just to show data coming in...\n data[\"courseName\"]=\"os_course\"\n data[\"courseCode\"] =\"course-v1:Tsinghua+OS101+2016_T1\"\n\n url = Config.activitiAPIUrl+ \"insertScheduleTime?schedule=%(schedule)s\" % {'schedule':json.dumps(data)}\n res_data = urllib2.urlopen(url)\n res = res_data.read()\n res = json.loads(res)\n return {\"success\": json.dumps(res)}\n\n # TO-DO: change this to create the scenarios you'd like to see in the\n # workbench while developing your XBlock.\n @staticmethod\n def workbench_scenarios():\n \"\"\"A canned scenario for display in the workbench.\"\"\"\n return [\n (\"PeerAssessemntXBlock\",\n \"\"\"\n \"\"\"),\n (\"Multiple PeerAssessemntXBlock\",\n \"\"\"\n \n \n \n \n \"\"\"),\n ]\n","sub_path":"backup/peerassessment/peerassessment.py","file_name":"peerassessment.py","file_ext":"py","file_size_in_byte":11988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"615614113","text":"# Servo Controller\n# Sets a UART Controller on specified UART device with baud of 9600\n\nimport serial\n\nclass UART:\n\n # Constants for maximum angle deflection from 90 degrees\n MAX_DEFLECTION = 20\n X_ANGLE_TUNER = 0 * 2 # Values for ANGLE_TUNER is [desired angle] * 2\n Y_ANGLE_TUNER = 0 * 2\n\n def __init__(self, uartDevicePath):\n ''' Constructor which sets the Serial Port and flushes any pending data '''\n global serialPort\n serialPort = serial.Serial(uartDevicePath, 9600, timeout=1)\n serialPort.flush()\n\n @staticmethod\n def sendXServo(servoXAngle):\n ''' Transmits the Servo Angle for the X Rotation Axis over UART '''\n xAngleBits = UART.__convertAngle__(servoXAngle + UART.X_ANGLE_TUNER)\n xByte = UART.__generateUARTData__(xAngleBits, 1)\n UART.__uartTX__(xByte)\n\n @staticmethod \n def sendYServo(servoYAngle):\n ''' Transmits the Servo Angle for the Y Rotation Axis over UART '''\n yAngleBits = UART.__convertAngle__(servoYAngle + UART.Y_ANGLE_TUNER)\n yByte = UART.__generateUARTData__(yAngleBits, 0)\n UART.__uartTX__(yByte)\n \n @staticmethod \n def __convertAngle__(angle):\n\n ''' Converts a Given Angle into the 7-bit value required by the FPGA '''\n\n # Check if angle is a number between 0 to 180 deg, otherwise throw exception\n try:\n angle = int(angle)\n except ValueError:\n raise ValueError(\"The angle specified is not a valid numerical value.\")\n\n if (angle > 180 or angle < 0):\n raise ValueError(\"The angle specified is outside the scope of this servo.\")\n\n # If angle is greater than bound, then set to the maximum\n if (abs(angle - 90) < UART.MAX_DEFLECTION):\n angle = angle / abs(angle) * UART.MAX_DEFLECTION\n\n # If value is okay, then convert into closest binary representation\n binaryPos = ((angle - 70) / 0.5)\n binaryPos = int(binaryPos)\n return binaryPos\n\n @staticmethod \n def __generateUARTData__(binaryPosition, isYServo):\n ''' Takes the Binary Position Data and Servo Select and generates the 8-bit value '''\n # Assembles the byte\n if (isYServo == 1):\n byteInt = binaryPosition + 128\n else:\n byteInt = binaryPosition\n \n byte = [byteInt]\n\n return bytearray(byte)\n\n @staticmethod\n def __uartTX__(data):\n ''' Performs the UART TX for some given data '''\n global serialPort\n size = serialPort.write(data)","sub_path":"Main Application/Backend/UART.py","file_name":"UART.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59575975","text":"import numpy as np\nimport pandas as pd\n\n\nf = open('glz_hg_highfire.txt', 'r')\nlines = f.readlines()\nf.close\n\ncolumns = ['Graze name', 'Cone', 'Color', 'Testing', 'Surface', 'Firing', 'Transparency', 'Recipe1', 'Recipe2', 'Recipe3', 'Recipe4', 'Recipe5', 'Recipe6', 'Recipe7', 'Recipe8', 'Recipe9', 'Recipe10']\nind_list = []\nfor i in range(len(columns)):\n ind_list.append('hogehoge')\nall_list = []\n\n# for iline, line in enumerate(lines):\nfor iline, line in enumerate(lines):\n # print(iline, line)\n # print(ind_list)\n if 'Glaze name:' in line:\n ind_list[0] = line[12:-1]\n elif 'Cone:' in line:\n ind_list[1] = line[6:-1]\n elif 'Color:' in line:\n ind_list[2] = line[7:-1]\n elif 'Testing:' in line:\n ind_list[3] = line[9:-1]\n elif 'Surface:' in line:\n ind_list[4] = line[9:-1]\n elif 'Firing:' in line:\n ind_list[5] = line[8:-1]\n elif 'Transparency:' in line:\n ind_list[6] = line[14:-1]\n elif 'Recipe:' in line:\n for i in range(1, 11):\n line = lines[iline+i]\n print(iline+i, line)\n print(ind_list)\n if 'Comments:' in line:\n for j in range(i, 11):\n ind_list[6+j] = 'nothing'\n break\n else:\n ind_list[6+i] = line[:-1]\n all_list.append(ind_list[:])\n for i in range(17):\n ind_list[i] = 'hogehoge'\n else:\n pass\n\n\ndf = pd.DataFrame(all_list)\ndf.columns = columns\nprint(df)\n","sub_path":"database/GlazChem/trash/txt2csv.py","file_name":"txt2csv.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340954509","text":"import pygame\n\n# === CONSTANTS === (UPPER_CASE names)\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nSCREEN_WIDTH = 600\nSCREEN_HEIGHT = 400\n\n\n\nclass Button():\n\n def __init__(self, text, x=0, y=0, width=50, height=50, command=None):\n\n self.text = text\n self.command = command\n self.image_normal = pygame.Surface((width, height))\n color = pygame.Color('bisque4')\n self.image_normal.fill(color)\n self.image_hovered = pygame.Surface((width, height))\n color2 = pygame.Color(\"burlywood3\")\n self.image_hovered.fill(color2)\n self.image = self.image_normal\n self.rect = self.image.get_rect()\n self.font = pygame.font.Font('assets/pixel_font.ttf', 30)\n self.font2 = pygame.font.Font('assets/pixel_font.ttf', 26)\n text_image = self.font.render(text, True, WHITE)\n text_rect = text_image.get_rect(center=self.rect.center)\n self.image_normal.blit(text_image, text_rect)\n self.image_hovered.blit(text_image, text_rect)\n # you can't use it before `blit`\n self.rect.topleft = (x, y)\n self.hovered = False\n self.clicked = False\n\n def update(self):\n if self.hovered:\n self.image = self.image_hovered\n else:\n self.image = self.image_normal\n\n def draw(self, surface):\n surface.blit(self.image, self.rect)\n self.show_text_box(surface)\n\n\n def handle_event(self, event):\n if event.type == pygame.MOUSEMOTION:\n self.hovered = self.rect.collidepoint(event.pos)\n #print(\"currenlty aimed\") # the player is hovering over the button\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if self.clicked:\n print('Clicked:', self.text) # we can tell him 'now shoot'\n if self.command:\n self.command()\n\n def show_text_box(self,surface):\n\n test = pygame.draw.rect(surface, (255, 255, 255), (514,540,250,80), 2)\n textTitle = self.font2.render(\"\", True, WHITE)\n rectTitle = textTitle.get_rect(center=surface.get_rect().center)\n surface.blit(textTitle, test)\n\n text = self.font2.render(\"PLace cursor above enemy to attack!\", True, WHITE)\n text_rect = text.get_rect(center=(514 + 130, 540 + 40))\n surface.blit(text, text_rect)\n\n\n\n","sub_path":"tutorial.py","file_name":"tutorial.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"305183194","text":"import os\nimport sys\nimport logging\nsys.path.append('../lib')\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(levelname)s: %(message)s',\n filemode='w')\n\n\nclass ConfigFileManager:\n # Manages the writing and reading of configuration files.\n def __init__(self, delim=','):\n self.delim = delim\n self.comment_ch = '#'\n\n def read(self, filename):\n # Read Method manages the reading of configuration file\n config = {}\n fp = None\n try:\n fp = open(filename, 'r')\n for line in fp:\n if line[0] == self.comment_ch:\n # commented line, skip\n continue\n parts = line.strip('\\n').split(self.delim)\n # line = attribute_type,attribute_name,example\n if len(parts) < 2:\n # skip ill-formatted lines\n continue\n [attr_type, attr_name] = parts[:2]\n config.setdefault(attr_type, []).append(attr_name)\n except:\n logging.warning('Unable to parse file:' + self.filename)\n finally:\n if fp:\n fp.close()\n return config\n\n def write(self, filename, data_dict, attr_set=None):\n # Manages the writing of configuration file\n fp = open(filename, 'w')\n for attr_type, attr_vals in data_dict.iteritems():\n fp.write('# %s INFORMATION\\n' % attr_type.upper())\n attr_names = sorted(attr_vals.keys())\n for attr_name in attr_names:\n attr_data = attr_vals[attr_name]\n if attr_set and attr_name not in attr_set:\n # Not an attribute we want to dump out\n continue\n for ind_block, val in attr_data.iteritems():\n fp.write('%s%s%s%sExample: %s\\n' % (attr_name.upper(),\n self.delim, ind_block, self.delim, val))\n","sub_path":"lib/config_file_manager.py","file_name":"config_file_manager.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"624698247","text":"from enum import Enum\r\nimport time\r\nimport math\r\n\r\nclass PythonBot():\r\n \r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.moveList = []\r\n self.matrix = []\r\n self.found = False\r\n \r\n for pos in board.maze:\r\n print(str(pos))\r\n \r\n def primarySearch(self, dest, goal):\r\n \r\n self.found = False\r\n \r\n if board.maze[dest.y][dest.x - 1] != \"#\" and board.maze[dest.y][dest.x - 1]!= \"*\":\r\n self.moveList.append(\"0 L\") #need to go Right \r\n newDest = Point(dest.x - 1, dest.y)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n self.moveList = []\r\n \r\n if board.maze[dest.y][dest.x + 1] != \"#\"and board.maze[dest.y][dest.x + 1]!= \"*\":\r\n #print(\"0 R\") \r\n self.moveList.append(\"0 R\") #need to go Left\r\n newDest = Point(dest.x + 1, dest.y)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n self.moveList = []\r\n \r\n if board.maze[dest.y + 1][dest.x] != \"#\" and board.maze[dest.y + 1][dest.x]!= \"*\":\r\n #print(\"0 D\") \r\n self.moveList.append(\"0 D\") #need to go Up\r\n newDest = Point(dest.x, dest.y + 1)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n self.moveList = []\r\n \r\n if board.maze[dest.y - 1][dest.x] != \"#\" and board.maze[dest.y - 1][dest.x]!= \"*\":\r\n #print(\"0 U\") \r\n self.moveList.append(\"0 U\") #need to go Down\r\n newDest = Point(dest.x, dest.y - 1)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n \r\n print(\"Done !!!\")\r\n \r\n def secondarySearch(self, dest, goal):\r\n #print(len(self.matrix)) \r\n \r\n right = False\r\n left = False\r\n up = False\r\n down = False\r\n \r\n if board.maze[dest.y][dest.x] == \"!\":\r\n #print(\"I find a way : \" + str(self.moveList))\r\n self.found = True\r\n self.matrix.append(self.moveList.copy())\r\n return True\r\n \r\n else:\r\n board.maze[dest.y][dest.x]= \"*\"\r\n \r\n if self.found == False:\r\n \r\n #print(\"Searching : \" + board.maze[dest.y][dest.x] + \" / \" + str(dest.x) + \",\" + str(dest.y))\r\n \r\n #print(\"len : \" + str(len(self.moveList))) \r\n distances = [] \r\n \r\n distanceLeftPoint = calculateDistance(Point(dest.x - 1, dest.y), goal)\r\n distanceRightPoint = calculateDistance(Point(dest.x + 1, dest.y), goal)\r\n distanceDownPoint = calculateDistance(Point(dest.x, dest.y + 1), goal)\r\n distanceUpPoint = calculateDistance(Point(dest.x, dest.y - 1),goal)\r\n \r\n \r\n distances.append(distanceLeftPoint)\r\n distances.append(distanceRightPoint)\r\n distances.append(distanceDownPoint)\r\n distances.append(distanceUpPoint)\r\n \r\n distances.sort()\r\n \r\n #print(distances)\r\n \r\n for w in range(0, len(distances)):\r\n \r\n if distances[w] == distanceLeftPoint: #left point est plus proche\r\n #print(\"left short\")\r\n try:\r\n if board.maze[dest.y][dest.x - 1] != \"#\" and board.maze[dest.y][dest.x - 1]!= \"*\" and left == False:\r\n self.moveList.append(\"0 L\") \r\n newDest = Point(dest.x - 1, dest.y)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n # print(\"Remove : \" + str(self.moveList.pop(len(self.moveList)-1)))\r\n left = True\r\n self.removePreviousGraphicMove(newDest);\r\n except:\r\n pass\r\n\r\n elif distances[w] == distanceRightPoint: #right point est plus proche\r\n # print(\"right short\")\r\n try:\r\n if board.maze[dest.y][dest.x + 1] != \"#\"and board.maze[dest.y][dest.x + 1]!= \"*\" and right == False:\r\n self.moveList.append(\"0 R\")\r\n newDest = Point(dest.x + 1, dest.y)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n \r\n # print(\"Remove : \" + str(self.moveList.pop(len(self.moveList)-1)))\r\n right = True\r\n self.removePreviousGraphicMove(newDest);\r\n\r\n except:\r\n pass\r\n \r\n elif distances[w] == distanceDownPoint: #down point est plus proche\r\n #print(\"down short\")\r\n try: \r\n if board.maze[dest.y + 1][dest.x] != \"#\" and board.maze[dest.y + 1][dest.x]!= \"*\" and down == False:\r\n self.moveList.append(\"0 D\") #need to go down\r\n newDest = Point(dest.x, dest.y + 1)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n #print(\"Remove : \" + str(self.moveList.pop(len(self.moveList)-1)))\r\n down = True\r\n self.removePreviousGraphicMove(newDest);\r\n \r\n except:\r\n pass\r\n \r\n elif distances[w] == distanceUpPoint: #up point est plus proche\r\n #print(\"up short\") \r\n try: \r\n if board.maze[dest.y - 1][dest.x] != \"#\" and board.maze[dest.y - 1][dest.x]!= \"*\" and up == False:\r\n self.moveList.append(\"0 U\") #need to go up\r\n newDest = Point(dest.x, dest.y - 1)\r\n \r\n if self.secondarySearch(newDest, goal) == True:\r\n return\r\n \r\n #print(\"Remove : \" + str(self.moveList.pop(len(self.moveList)-1)))\r\n up = True\r\n self.removePreviousGraphicMove(newDest);\r\n except:\r\n pass\r\n \r\n #self.removePreviousGraphicMove(dest);\r\n \r\n def removePreviousGraphicMove(self,dest):\r\n if board.maze[dest.y][dest.x]== \"*\":\r\n board.maze[dest.y][dest.x]= \" \"\r\n\r\n \r\n def showMoves(self):\r\n for listE in self.matrix:\r\n print(str(listE))\r\n \r\n\r\nclass Point:\r\n\tdef __init__(self, x, y):\r\n\t\tself.x = x\r\n\t\tself.y = y\r\n\t\t\r\n\tdef __repr__(self):\r\n\t\treturn self.__str__();\r\n\t\t\r\n\tdef __str__(self):\r\n\t\treturn \"Point: { x: \" + str(self.x) + \" y: \" + str(self.y) + \" }\"\r\n\t\t\r\nclass Direction(Enum):\r\n\tUp, Down, Left, Right = range(4)\r\n\t\r\n\tdef __str__(self):\r\n\t\treturn self.name[0]\r\n\t\t\r\nclass Board:\r\n\tdef __init__(self, robots, maze):\r\n\t\tself.robots = robots\r\n\t\tself.maze = maze\r\n\t\t\r\n\tdef __str__(self):\r\n\t\ts = \"\"\r\n\t\tfor i in range(len(maze[0])):\r\n\t\t\tfor j in range(len(maze)):\r\n\t\t\t\ts += maze[j][i]\r\n\t\t\ts += \"\\n\"\r\n\t\treturn s\r\n\t\t\r\nEMPTY_CHAR = ' '\r\nWALL_CHAR = '#'\r\nGOAL_CHAR = '!'\r\nBOT_CHAR = \"0\"\r\n\r\ngoal = None\r\n# Switches and the walls, which they affect\r\ntoggle_switches = {}\r\nhold_switches = {}\r\n\r\nboard = None\r\n\r\ndef compute_solution(Matrix):\r\n\t# TODO: Implement really clever stuff here!\r\n\t# For now - just output a couple of moves:\r\n for list_ in Matrix:\r\n print(str(list_))\r\n \r\nclass Node():\r\n def __init__(self, pos, parent, nexts):\r\n self.pos = pos\r\n self.parent = parent\r\n self.nexts = nexts\r\n\r\n\r\ndef calculateDistance(A,B):\r\n result = math.sqrt(((B.x - A.x)**2) + ((B.y - A.y)**2))\r\n return result\r\n\r\ndef parse():\r\n\t# TODO:\r\n\t# This template was intended for Python 2.\r\n\t# If using Python 3, simply change raw_input() to input()\r\n\t\r\n\t#dims = input().split(' ')\r\n #dims = \"7 7\".split(' ')\r\n dims = \"10 10\".split(' ')\r\n\t#width = int(dims[0])\r\n width = int(dims[0])\r\n #height = int(dims[1])\r\n height = int(dims[1])\r\n\t\r\n #no_of_Robots = int(input())\r\n no_of_Robots = int(1)\r\n \r\n robots = [None] * no_of_Robots\r\n\t\t\r\n\t#switches = input().split(' ')\r\n switches = \"0 0\".split(' ')\r\n no_of_toggle_switches = int(switches[0])\r\n no_of_hold_switches = int(switches[1])\r\n \r\n maze = []\r\n for i in range(0,height):\r\n #line = input()\r\n \r\n if i == 0:\r\n line = \"# # \"\r\n \r\n elif i == 1:\r\n line = \"#0 #!#\"\r\n \r\n elif i == 2:\r\n line = \"# ## #\"\r\n \r\n elif i == 3:\r\n line = \"# ## # #\"\r\n \r\n elif i == 4:\r\n line = \"# ##### \"\r\n elif i == 5:\r\n line = \"# #\"\r\n elif i == 6:\r\n line = \"# #\"\r\n elif i == 7:\r\n line = \"# #\"\r\n elif i == 8:\r\n line = \"# # #\"\r\n elif i == 9:\r\n line = \"##########\"\r\n \r\n row = []\r\n for j in range(width):\r\n if line[j] == GOAL_CHAR:\r\n goal = Point(j, i)\r\n elif line[j].isdigit():\r\n robots[int(line[j])] = Point(j, i)\r\n if line[j] == BOT_CHAR:\r\n global bot\r\n bot= Point(j, i)\r\n \r\n if line[j] != EMPTY_CHAR and line[j] != WALL_CHAR and not line[j].isalpha() and line[j] != BOT_CHAR and line[j] != GOAL_CHAR:\r\n print (\"Error: Unknown character '\" + str(line[j]) + \"' on line \" + str(i+1) + \", column \" + str(j+1))\r\n\t\t\t\r\n row.append(line[j])\r\n\t\t\t\r\n maze.append(row)\r\n\t\t\t\r\n for i in range(no_of_toggle_switches):\r\n switch = raw_input().split(' ')\r\n toggle_switches[switch[0]] = Point(int(switch[1]), int(switch[2]))\r\n\t\t\t\r\n for i in range(no_of_hold_switches):\r\n switch = raw_input().split(' ')\r\n hold_switches[switch[0]] = Point(int(switch[1]), int(switch[2]))\r\n\t\t\r\n if goal is None:\r\n print (\"Error: No goal found on board\")\r\n \r\n global board\r\n\t\t\r\n \r\n board = Board(robots, maze)\r\n \r\n return goal\r\n \r\nstart = time.time()\r\n\r\ndest = parse()\r\n \r\n\"\"\"\r\nMy bot\r\n\"\"\"\r\nprint(str(bot.x) + \" \" + str(bot.y))\r\n\r\nprint(str(board.maze[bot.y][bot.x]))\r\n\r\nprint(str(board.maze[bot.y - 1][bot.x]))\r\n\r\nprint(\"GOAL : \" + str(dest.x) + \", \" + str(dest.y))\r\n\r\nmyBot = PythonBot(bot.x, bot.y)\r\n\r\nmyBot.primarySearch(Point(bot.x, bot.y), dest)\r\n\r\n#myBot.showMoves()\r\n\r\ncompute_solution(myBot.matrix)\r\n\r\nend = time.time()\r\nprint (\"Finished in \" + str(end) + \" - \" + str(start) + \" = \" + str(end-start) + \" sec\")\r\n","sub_path":"MazeRunner.py","file_name":"MazeRunner.py","file_ext":"py","file_size_in_byte":11733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"447087035","text":"import datetime\nimport random\nfrom django.test import TestCase\nfrom django.test import Client\nfrom unittest import TestCase as tc\nimport urllib.parse\nfrom ..models import *\nfrom ..consts import *\nfrom ..forms import *\nfrom ..views import *\n\n\nclass InquiryStudentViewTest(TestCase):\n\n def test_get_initial_display(self):\n \"\"\" 初期表示 \"\"\"\n c = Client()\n response = c.get('/inquiry_student/', follow=True)\n # View\n self.assertEqual(response.resolver_match.func.__name__, InquiryStudentView.as_view().__name__)\n # 表示成功\n self.assertEqual(200, response.status_code, 'ページが取得できません。')\n # context\n self.assertEqual('問い合わせ', response.context['menu_title'], 'メニュー名エラー')\n self.assertEqual([{'url': '', \"title\": '問い合わせ'}]\n , response.context['breads'], 'パンくずリストエラー')\n self.assertEqual(User.objects.get(id=DEMONSTRATION_USER_ID)\n , response.context['demo_user'], 'デモユーザエラー')\n self.assertQuerysetEqual(Inquiry.objects.filter(student=User.objects.get(id=DEMONSTRATION_USER_ID)),\n response.context['inquiry_list'], '結果データエラー')\n # session\n full_url = c.session.get(SESSION_INQUIRY_STUDENT_SUCCESS_URL)\n self.assertEqual('/inquiry_student/', full_url, '戻りurl格納エラー')\n # cookie\n\n # print(response.request)\n \"\"\"\n 参考 response.requestの中身。\n {'PATH_INFO': '/inquiry_student/', 'REQUEST_METHOD': 'GET', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'QUERY_STRING': '', 'format': True}\n \"\"\"\n # # form\n # form = response.context['form']\n # self.assertContains(form['is_resolved'][0], 'checked')\n\n def test_get_search_by_lesson_date(self):\n \"\"\" 日付検索後表示 \"\"\"\n c = Client()\n time_start = datetime.time(hour=0)\n time_end = datetime.time(hour=23, minute=59, second=59)\n inquiry_datetime_from = datetime.date(year=2019, month=4, day=1)\n inquiry_datetime_to = datetime.date(year=2019, month=5, day=30)\n ### fromのみ。\n data = {'inquiry_datetime_from': inquiry_datetime_from}\n response = c.get('/inquiry_student/', data=data, follow=True)\n # 表示成功\n self.assertEqual(200, response.status_code, 'ページが取得できません。')\n # context\n self.assertQuerysetEqual(\n Inquiry.objects.filter(student=User.objects.get(id=DEMONSTRATION_USER_ID),\n inquiry_datetime__gte=datetime.datetime.combine(\n inquiry_datetime_from, time_start)),\n response.context['inquiry_list'], '結果データエラー')\n full_url = c.session.get(SESSION_INQUIRY_STUDENT_SUCCESS_URL)\n self.assertEqual('/inquiry_student/?'+urllib.parse.urlencode(data), full_url, '戻りurl格納エラー')\n ### toのみ。\n data = {'inquiry_datetime_to': inquiry_datetime_to}\n response = c.get('/inquiry_student/', data=data)\n # 表示成功\n self.assertEqual(200, response.status_code, 'ページが取得できません。')\n # context\n self.assertQuerysetEqual(\n Inquiry.objects.filter(student=User.objects.get(id=DEMONSTRATION_USER_ID),\n inquiry_datetime__lte=datetime.datetime.combine(\n inquiry_datetime_to, time_end)),\n response.context['inquiry_list'], '結果データエラー')\n full_url = c.session.get(SESSION_INQUIRY_STUDENT_SUCCESS_URL)\n self.assertEqual('/inquiry_student/?'+urllib.parse.urlencode(data), full_url, '戻りurl格納エラー')\n\n def test_get_search_by_xxx(self):\n \"\"\" 関連レッスン・関連教科検索表示 \"\"\"\n pass\n \"\"\" などなど。検索系のテスト \"\"\"\n\n","sub_path":"onlclass/tests/test_InquiryStudentView.py","file_name":"test_InquiryStudentView.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486436872","text":"import os\nimport time\n\nattente = 3\n\ndef my_type(text):\n for c in text:\n if c == \" \":\n key = \"KP_Space\"\n elif c == \"\\n\":\n key = \"KP_Enter\"\n else:\n key = c\n #\n cmd = \"xdotool key {}\".format(key)\n os.system(cmd)\n\ndef main():\n print(\"Vous avez {} secondes avant que le programme de ne se lance\".format(attente))\n time.sleep(attente)\n text = \"test\\n\"\n my_type(text)\n\nmain()\n","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"360005162","text":"# QDesktopWidget\nimport sys\nfrom PyQt5.QtWidgets import QPushButton, QHBoxLayout, QWidget, QMainWindow, QApplication, QDesktopWidget\nfrom PyQt5.QtGui import QIcon\n\nclass QuitApp(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle('QuitApp')\n self.resize(400, 300)\n\n # 添加Button\n self.button = QPushButton('退出')\n self.button.clicked.connect(self.onClickButton)\n\n layout = QHBoxLayout()\n layout.addWidget(self.button)\n\n mainframe = QWidget()\n mainframe.setLayout(layout)\n\n # setCentralWidget(self, mainWidget)\n self.setCentralWidget(mainframe)\n\n # 按钮单击事件的方法(自定义的slot)\n def onClickButton(self):\n # sender = self.sender()\n # print(sender.text()+'被按下')\n # app = QApplication.instance()\n app.quit()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main = QuitApp()\n main.show()\n sys.exit(app.exec_())\n","sub_path":"QuitApp(退出程序).py","file_name":"QuitApp(退出程序).py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"605028982","text":"\r\nimport io\r\nimport os\r\nfrom datetime import datetime\r\n\r\nimport cv2\r\nfrom google.cloud import vision_v1p3beta1 as vision\r\n\r\n# Setup google authen client key\r\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'client_key.json'\r\n\r\n# Source path content all images\r\nSOURCE_PATH = \"C:/Users/vmironov/Fruit/\"\r\nOUTPUT_PATH = \"C:/Users/vmironov/Fruit_res3/\"\r\n\r\nFOOD_TYPE = 'Fruit'\r\n\r\n\r\ndef recognize_food(img_path):\r\n\r\n # Read image with opencv\r\n img = cv2.imread(img_path)\r\n\r\n # Get image size\r\n height, width = img.shape[:2]\r\n\r\n # Scale image\r\n img = cv2.resize(img, (800, int((height * 800) / width)))\r\n #Image cutting\r\n # height, width = img.shape[:2]\r\n # height = int(height/2)\r\n # width = int(width/2)\r\n # img = img[height:2*height, 0:width]\r\n\r\n # Save the image to temp file\r\n cv2.imwrite(SOURCE_PATH + \"output.jpg\", img)\r\n\r\n # Create new img path for google vision\r\n img_path = SOURCE_PATH + \"output.jpg\"\r\n\r\n # Create google vision client\r\n client = vision.ImageAnnotatorClient()\r\n\r\n # Read image file\r\n with io.open(img_path, 'rb') as image_file:\r\n content = image_file.read()\r\n\r\n image = vision.types.Image(content=content)\r\n\r\n #Segmentation\r\n objects = client.object_localization(image=image).localized_object_annotations\r\n # print('Number of objects found: {}'.format(len(objects)))\r\n for object_ in objects:\r\n # print('\\n{} (confidence: {})'.format(object_.name, object_.score))\r\n # print('Normalized bounding polygon vertices: ')\r\n # print(object_.bounding_poly.normalized_vertices)\r\n\r\n #writing rectangle\r\n height, width = img.shape[:2]\r\n a = int(800*object_.bounding_poly.normalized_vertices[0].x)\r\n b = int(height*object_.bounding_poly.normalized_vertices[0].y)\r\n c = int(800*object_.bounding_poly.normalized_vertices[2].x)\r\n d = int(height*object_.bounding_poly.normalized_vertices[2].y)\r\n cv2.rectangle(img,(a,b),(c,d),(50,50,200),2)\r\n # print(object_.name)\r\n\r\n # if (object_.name == 'Tableware'):\r\n # print('hello')\r\n\r\n #first option to recognize\r\n # cv2.putText(img,object_.name,(int((a+c)/2),int((b+d)/2)),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(0,0,0),2)\r\n\r\n #second option to recognize (NOT PRODUCTIVE IN TIME)\r\n segment = img[b:d,a:c]\r\n # cv2.imshow('Recognize & Draw', segment)\r\n # cv2.waitKey(0)\r\n cv2.imwrite(SOURCE_PATH + \"peace.jpg\", segment)\r\n img_path = SOURCE_PATH + \"peace.jpg\"\r\n client = vision.ImageAnnotatorClient()\r\n with io.open(img_path, 'rb') as image_file:\r\n content = image_file.read()\r\n segment = vision.types.Image(content=content)\r\n objects_new = client.object_localization(image=segment).localized_object_annotations\r\n # print(objects_new)\r\n for object_ in objects_new:\r\n q = int((c-a) * object_.bounding_poly.normalized_vertices[0].x)\r\n w = int((d-b) * object_.bounding_poly.normalized_vertices[0].y)\r\n e = int((c-a)* object_.bounding_poly.normalized_vertices[2].x)\r\n r = int((d-b) * object_.bounding_poly.normalized_vertices[2].y)\r\n # print(c-a,e-q)\r\n # if ((5*(e-q))<=(4*(c-a))):\r\n # cv2.rectangle(img, (a+q, b+w), (a+e, b+r), (50, 50, 200), 2)\r\n if (q!=0 and w!=0 and e!=(c-a) and r!=(d-b) and 10*(e-q)<=9*(c-a)):\r\n cv2.rectangle(img, (a+q, b+w), (a+e, b+r), (50, 50, 200), 2)\r\n # print(e-q,c-a)\r\n # cv2.imshow('Recognize & Draw', img)\r\n # cv2.waitKey(0)\r\n # cv2.putText(img, desc, (a, int((b + d) / 2)), cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (255, 255, 255), 2)\r\n # break\r\n\r\n #third option to recognize(NOT PRODUCTIVE IN TIME, DOESNT CORRECTLY WORKS)\r\n # segment = img[b:d, a:c]\r\n # cv2.imwrite(SOURCE_PATH + \"peace.jpg\", segment)\r\n # img_path = SOURCE_PATH + \"peace.jpg\"\r\n # client = vision.ImageAnnotatorClient()\r\n # with io.open(img_path, 'rb') as image_file:\r\n # content = image_file.read()\r\n # segment = vision.types.Image(content=content)\r\n # response = client.label_detection(image=segment)\r\n # labels = response.label_annotations\r\n # for label in labels:\r\n # desc = label.description.lower()\r\n # break\r\n # cv2.putText(img, desc, (a, int((b + d) / 2)), cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (255, 255, 255),2)\r\n\r\n cv2.imshow('Recognize & Draw', img)\r\n cv2.waitKey(0)\r\n return img\r\n\r\n\r\nprint('---------- Start FOOD Recognition --------')\r\nstart_time = datetime.now()\r\nfor k in range(3,9):\r\n path = SOURCE_PATH + '{id}.jpg'.format(id=k)\r\n res = recognize_food(path)\r\n cv2.imwrite(OUTPUT_PATH + \"{id}.jpg\".format(id=k), res)\r\nprint('Total time: {}'.format(datetime.now() - start_time))\r\nprint('---------- End ----------')","sub_path":"FoodGV.py","file_name":"FoodGV.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349882310","text":"#!/usr/bin/env python3.5\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom scipy.special import erf\nimport sys\n\nplt.style.use('bmh')\n\nxaxis=np.arange(49)\nfilename=\"ThresholdScan_200323_131753.dat\"\n\ngraphic_output_single = False\ngraphic_output_landau = True\n\ndef step_func(x,a,b):\n return 1/(1+np.exp(a*(x-b)))\n\ndef gerf(x,mu,sig):\n return 1/2*(1+erf((x-mu)/(np.sqrt(2)*sig)))\n\ndef scurve_fit(steps, ninj):\n dvs=sorted(steps.keys())\n m=0\n s=0\n den=0\n for dv1,dv2 in zip(dvs[:-1],dvs[1:]):\n ddv=dv2-dv1\n mdv=0.5*(dv2+dv1)\n n1=1.0*steps[dv1]/ninj\n n2=1.0*steps[dv2]/ninj\n dn=n2-n1\n den+=dn/ddv\n m+=mdv*dn/ddv\n s+=mdv**2*dn/ddv\n if den>0:\n if s>m*m:\n s=(s-m*m)**0.5\n m/=den\n s/=den\n return m,s\n\nthresholds = []\nrmss = []\nthresholds_scipy = []\nrmss_scipy = []\nwith open(filename) as f:\n prevr = prevc = -1\n for line in f:\n r,c,dv,hits = [int(i) for i in line.strip().split()]\n if not (prevr==r and prevc==c):\n #Once one set is done, fit\n if (prevr>=0 and prevc>=0):\n m,s=scurve_fit(steps,50)\n thresholds.append(m)\n rmss.append(s)\n #write from dictionary to array\n y = np.ndarray((49))\n for i in range(1,50):\n y[i-1] = steps[i]/50\n #Fit Function to data #################################\n p0 = [18,0.5]\n popt, pcov = curve_fit(gerf, xaxis, y, method='dogbox',\n bounds=([0., 0.],[100., 10.]))\n thresholds_scipy.append(popt[0])\n rmss_scipy.append(popt[1])\n ####################################### PLOTTING\n if graphic_output_single:\n plt.figure()\n plt.scatter(xaxis,y, label=\"Data\",marker='.')\n x = np.linspace(0,49,500)\n plt.plot(x, gerf(x,*popt),label=\"Scipy Fit\")\n plt.plot(x, np.heaviside(x-m,0.5),label=\"Quick Fit\")\n plt.legend()\n steps={}\n else:\n steps[dv]=hits\n prevr=r\n prevc=c\n\n #if c == 256: break print(thresholds)\n print(np.mean(thresholds))\n print(np.mean(rmss))\n print(np.mean(thresholds_scipy))\n print(np.mean(rmss_scipy))\n\nif graphic_output_landau:\n plt.figure()\n plt.xlabel('Threshold in DAC')\n plt.ylabel('Frequency')\n plt.title('Whole ALPIDE')\n plt.hist(thresholds,range=(0,30), bins=30)\n plt.show()\n\n plt.figure()\n plt.xlabel('RMS in DAC')\n plt.ylabel('Frequency')\n plt.title('Whole ALPIDE')\n plt.hist(rmss,range=(0,1), bins=50)\n plt.show()\n\n plt.figure()\n plt.xlabel('Threshold in DAC')\n plt.ylabel('Frequency')\n plt.title('Whole ALPIDE')\n plt.hist(thresholds_scipy,range=(0,30), bins=30)\n plt.show()\n\n plt.figure()\n plt.xlabel('RMS in DAC')\n plt.ylabel('Frequency')\n plt.title('Whole ALPIDE')\n plt.hist(rmss_scipy,range=(0,1), bins=50)\n plt.show()\n","sub_path":"mdonner/07-09-Tracking/scripts/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383159739","text":"class Queue:\n class Point:\n def __init__(self, y, x, c):\n self.y = y\n self.x = x\n self.c = c\n\n def __init__(self, capacity):\n self.queue = [0] * capacity\n self.head = self.rear = 0\n\n def isEmpty(self):\n return self.head <= self.rear\n\n def enQueue(self, y, x, c):\n self.queue[self.head] = self.Point(y, x, c)\n self.head = self.head + 1\n\n def deQueue(self):\n if self.isEmpty():\n return None\n self.rear = self.rear + 1\n return self.queue[self.rear - 1]\n\n\ndef breadthFirstSearch():\n queue = Queue(row * column)\n queue.enQueue(0, 0, 0)\n MAP[0][0] = 0\n\n while queue.isEmpty() == False:\n p = queue.deQueue()\n\n if p.y == row - 1 and p.x == column - 1:\n return p.c\n\n if p.y + 1 < row and MAP[p.y + 1][p.x]:\n queue.enQueue(p.y + 1, p.x, p.c + 1)\n MAP[p.y + 1][p.x] = 0\n if p.x + 1 < column and MAP[p.y][p.x + 1]:\n queue.enQueue(p.y, p.x + 1, p.c + 1)\n MAP[p.y][p.x + 1] = 0\n if p.y - 1 >= 0 and MAP[p.y - 1][p.x] != 0:\n queue.enQueue(p.y - 1, p.x, p.c + 1)\n MAP[p.y - 1][p.x] = 0\n if p.x - 1 > 0 and MAP[p.y][p.x - 1] != 0:\n queue.enQueue(p.y, p.x - 1, p.c + 1)\n MAP[p.y][p.x - 1] = 0\n\n return -1\n\n\ndef main():\n global MAP, row, column\n T = int(input())\n\n for test_case in range(1, T + 1):\n row, column = map(int, input().split())\n MAP = [[int(num) for num in input().split()] for _ in range(row)]\n print(\"#%d %d\" % (test_case, breadthFirstSearch()))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Algorithm/scs/bfs_ex.py","file_name":"bfs_ex.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"131625645","text":"\n\n#calss header\nclass _MISDIRECT():\n\tdef __init__(self,): \n\t\tself.name = \"MISDIRECT\"\n\t\tself.definitions = [u'to send something to the wrong place or aim something in the wrong direction: ', u'to use something in a way that is not suitable or right: ', u'to be wrong in how you feel or act in a situation: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_misdirect.py","file_name":"_misdirect.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155684944","text":"#-------------------------------------------------------------------------------\n# Name: Maleficium Game Logic\n# Made for Maleficium: The Demon Scrolls\n# malificiumgame.com\n#\n# Author: Thomas Gull\n#\n# Created: 29/12/2011\n#-------------------------------------------------------------------------------\n\nDEBUG = False\n\nDWARF = 'dwarf'\nELF = 'elf'\nGRIMVALKIN = 'grimvalkin'\nCONSTRUCT = 'construct'\nHUMAN = 'human'\n\nraces = [DWARF, ELF, GRIMVALKIN, CONSTRUCT, HUMAN]\n\nlevels = []\nfor i in range(1,21):\n levels.append(i)\n\nexp_medium = [0, 2000, 5000, 9000, 15000, 23000, 35000, \\\n 51000, 75000, 105000, 155000, 220000, 315000, 445000, \\\n 635000, 890000, 1300000, 1800000, 2550000, 3600000]\n\nSTRENGTH = 'strength'\nARMOR = 'armor'\nMAGIC = 'magic'\n\nWEAPON = 'weapon'\nARMOR = 'armor'\n\nbase_abilities = [STRENGTH, ARMOR, MAGIC]\nbase_abilities_dictionary = {STRENGTH:STRENGTH, ARMOR:ARMOR, MAGIC:MAGIC}\n","sub_path":"game_logic/base_vars.py","file_name":"base_vars.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"498676454","text":"import os\n\nstart = '601'\nend = '900'\n\nwith open('plot_CDFs.plt','w') as f_out:\n with open('gnuplot_CDF_template.plt') as template:\n f_out.write(template.read())\n\n f_out.write('plot ')\n\n for i in range(1,26):\n if(not i == 1):\n f_out.write(',\\\\\\n')\n\n f_out.write(\"'<(sed -n \\\"\" + start + \",\" + end + \"p\\\" config-\" + str(i) + \"-all-medians.dat)' using 3:((1.0/300)) smooth cumulative title 'Config \" + str(i) + \"'\")\n if(i == 1 or i == 2 or i == 3 or i == 4):\n f_out.write(' ls ' + str(i))\n i = i + 1\n\nos.system('gnuplot plot_CDFs.plt')\nos.system('gnome-open CDFs.pdf')\n","sub_path":"EAX/old-PSMs/project/full_results/plotCDF.py","file_name":"plotCDF.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544252103","text":"#!/usr/bin/env python2.7\nimport matplotlib.pyplot as plt\n\n\nclass stat_plot:\n def __init__(self, idx, taus, all_scores):\n self.n = sorted(all_scores.keys())\n self.taus = taus\n self.scores = all_scores\n self.index = 0\n self.fig = plt.figure()\n self.fig.canvas.mpl_connect('key_release_event', self.on_key)\n self.draw_plot()\n plt.show()\n\n def draw_plot(self):\n title = str(self.n[self.index]) + \" proposals\"\n self.fig.clf()\n plt.plot(taus, self.scores[self.n[self.index]])\n plt.title(title)\n self.fig.canvas.draw()\n\n def on_key(self, event):\n if event.key == 'left':\n self.left_release()\n elif event.key == 'right':\n self.right_release()\n\n def left_release(self):\n if self.index == 0:\n self.index = len(self.n)\n self.index -= 1\n self.draw_plot()\n\n def right_release(self):\n if self.index == len(self.n) - 1:\n self.index = -1\n self.index += 1\n self.draw_plot()\n\nresults = open(\"result_stats.txt\")\ntaus_line = results.readline()\ntaus_string = taus_line.strip().split('\\t')\ntaus = []\nall_scores = dict()\nfor tau in taus_string:\n taus.append(float(tau))\nfor line in results:\n n = int(line.split(':')[0])\n scores_string = line.split(':')[1].strip()\n scores_list = scores_string.split('\\t')\n scores = []\n for s in scores_list:\n scores.append(float(s))\n all_scores[n] = scores\nidx = all_scores.keys()\nprint('\\t'),\nfor t in taus:\n print('%.2g\\t' % t),\nprint('')\nfor i in sorted(idx):\n print('%d:\\t' % i),\n for score in all_scores[i]:\n print(\"%.3g\\t\" % score),\n print('')\nstats = stat_plot(idx, taus, all_scores)\n","sub_path":"plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"368843270","text":"# import the necessary packages\nimport argparse\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom rib_counting import compute_rib_gap\n\n# initialize the list of reference points and boolean indicating\n# whether cropping is being performed or not\nrefPt = []\nisShow = False\nglobal annotated_original_img\n\n#input\nimg_src = '../data/sample_image/sample_rib8.jpg'\n\nimage = cv2.imread(img_src)\nimage = cv2.resize(image, (0,0), fx=1.0, fy=1.0)\nheight, width = image.shape[:2]\ncurrent_x = 0\ncurrent_y = 0\n\n#Trackbar callback function\ndef onTrackbarChange(trackbarValue):\n global annotated_original_img\n if(isShow):\n annotated_original_img = clone.copy()\n show_count(cv2.EVENT_LBUTTONDOWN, current_x, current_y, True, 0)\n print(\"Set gap distance = \"+str(trackbarValue))\n\ndef show_count(event, x, y, flags, param):\n # grab references to the global variables\n global refPt, isShow, annotated_original_img, current_x, current_y\n # annotated_original_img = clone.copy()\n count_width = 15 # The length between the vertebra line and x-position which we count rib\n spacing_height = 4 # the moving down length when annotated the original image\n gap_threshold = 10\n # gap = 17 #get from programming\n gap = cv2.getTrackbarPos('gap', 'RibCounting')\n count = 12\n tmp_height = height\n # if the left mouse button was clicked, start count the first rib from that (x, y) coordinates\n if event == cv2.EVENT_LBUTTONDOWN:\n if(isShow):\n annotated_original_img = clone.copy()\n refPt = [(x, y)]\n current_x = x\n current_y = y\n gap_list = compute_rib_gap(img_src,current_x,current_y)\n gap = cv2.getTrackbarPos('gap', 'RibCounting')\n isShow = True\n\n for i in range(len(gap_list)):\n if(y-i*spacing_height > 0):\n if(count % 2 == 0):\n cv2.putText(annotated_original_img, str(count), (x, y - i*gap-spacing_height),\n cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 0, 0), 1)\n if(x int:\n \"\"\"Calculates Internet Protocol checksum\n\n :param packet: packet to calculate checksum for\n :return: checksum value\n \"\"\"\n if len(packet) % 2 != 0:\n packet += b'\\0' # padding\n\n res = sum(array.array(\"H\", packet))\n res = (res >> 16) + (res & 0xffff)\n res += res >> 16\n res = ~res\n\n return res & 0xffff\n\n\nclass TCPPacket:\n def __init__(self,\n src_host: str,\n src_port: int,\n dst_host: str,\n dst_port: int,\n data: str = '',\n flags: list = None):\n if flags is None:\n flags = []\n\n self.src_host = src_host\n self.src_port = src_port\n self.dst_host = dst_host\n self.dst_port = dst_port\n self.data = bytes(data, encoding='utf-8') # TODO: encoding\n self.flags = [\n 1 if 'fin' in flags else 0, # FIN\n 1 if 'syn' in flags else 0, # SYN\n 1 if 'rst' in flags else 0, # Reset\n 1 if 'psh' in flags else 0, # Push\n 1 if 'ack' in flags else 0, # Acknowledgement\n 1 if 'urg' in flags else 0, # Urgent\n 1 if 'ecn' in flags else 0, # ECN-Echo\n 1 if 'cwr' in flags else 0, # CWR\n 1 if 'noc' in flags else 0, # Nonce\n 0, # Reserved\n ]\n\n self.raw = self._compile()\n\n def _get_tcp_header(self) -> bytes:\n tcp_src = self.src_port\n tcp_dst = self.dst_port\n tcp_seq = 0\n tcp_ack = 0\n tcp_header = (5 << 4) # Data offset\n tcp_flags = reduce(lambda a, b: a + b,\n [self.flags[idx] << idx for idx in\n range(len(self.flags))],\n 0)\n tcp_window = 8192\n tcp_checksum = 0 # Initial checksum\n tcp_urgent_ptr = 0\n\n return struct.pack(\n '!HHIIBBHHH',\n tcp_src,\n tcp_dst,\n tcp_seq,\n tcp_ack,\n tcp_header,\n tcp_flags,\n tcp_window,\n tcp_checksum,\n tcp_urgent_ptr\n )\n\n def _get_tcp_checksum(self, packet: bytes) -> int:\n pseudo = struct.pack(\n '!4s4sHH',\n socket.inet_aton(self.src_host),\n socket.inet_aton(self.dst_host),\n socket.IPPROTO_TCP,\n len(packet)\n )\n\n return chksum(pseudo + packet)\n\n def _compile(self) -> bytes:\n packet = bytes()\n packet += self._get_tcp_header()\n packet += self.data\n\n tcp_checksum = self._get_tcp_checksum(packet)\n packet = packet[:16] + struct.pack('H', tcp_checksum) + packet[18:]\n\n return packet\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('host',\n help='IP address or domain name of the receiving host',\n metavar='IP/DOMAIN')\n parser.add_argument('port',\n help='TCP port of the receiving host',\n type=int,\n metavar='PORT')\n\n flag_group = parser.add_mutually_exclusive_group(required=True)\n flag_group.add_argument('--syn',\n help='create TCP packet with only the SYN flag set',\n action='store_true')\n flag_group.add_argument('--xmas',\n help='create TCP packet with the FIN, URG and PSH flags set',\n action='store_true')\n flag_group.add_argument('--fin',\n help='create TCP packet with only the FIN flag set',\n action='store_true')\n flag_group.add_argument('--null',\n help='create TCP packet with no flags set',\n action='store_true')\n\n args = parser.parse_args()\n\n use_flags = []\n\n if args.syn:\n use_flags.append('syn')\n elif args.xmas:\n use_flags.append('fin')\n use_flags.append('urg')\n use_flags.append('psh')\n elif args.fin:\n use_flags.append('fin')\n\n pak = TCPPacket(\n socket.gethostbyname(socket.gethostname()),\n 20,\n socket.gethostbyname(args.host),\n args.port,\n '',\n use_flags\n )\n\n s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)\n\n s.sendto(pak.raw, (args.host, 0))\n","sub_path":"ex05/out/src/send_packet.py","file_name":"send_packet.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"43975574","text":"import datetime\n# 修改标题\ntitle=\"1034. 有理数四则运算(20)\"\n# 修改目录\ncategory=\"PAT乙题\"\n\n\nm1='''---\nlayout: post\ncategory: '''\nm2='''\ntitle: '''\nm3='''\n---'''\n# 获得代码内容 text\nf1=r\"D:\\Code_Projects\\c++\\vs2017\\Project1\\Project1\\code.cpp\"\nwith open(f1, \"rt\") as in_file:\n text = in_file.read()\n# print(text)\ntext1='''\n```c++\n'''+text+'''\n```'''\n# str 正文\nstr=m1+category+m2+\"PAT乙题 \"+title+m3+text1;\nprint(str)\n# 获取当前时间, 其中中包含了year, month, hour, 需要import datetime \ndef datetime_toString(dt):\n return dt.strftime(\"%Y-%m-%d-%H\")\ntoday = datetime.date.today() \nt2=today.strftime(\"%Y-%m-%d\")\n# print(t2)\n\n\nwith open(t2+\"-\"+title+\".md\", \"wt\") as out_file:\n out_file.write(str)\n","sub_path":"_posts/Algorithms/PAT/PAT_yi/newPATblog.py","file_name":"newPATblog.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"8228270","text":"from tkinter import Tk\nimport numpy as np\nimport pandas as pd\nimport logging\nfrom codecs import open as codecsopen\nfrom json import load as jsonload\nimport pickle\n\nfrom tkinter.filedialog import askopenfilename, askdirectory\n\nlog = logging.getLogger(__name__)\n\n\ndef _cast_parameters(parameters: dict) -> dict:\n \"\"\"Cast to Value.\n\n Take in a parameters dictionary and coverts to a dictionary with type converted\n and extranous information removed.\n \"\"\"\n new_parameters = {}\n for key, value in parameters.items():\n new_parameters[key] = cast_value(value)\n\n return new_parameters\n\n\ndef cast_value(value):\n \"\"\"Cast Value.\n\n Takes in a value with a desired type and attempts to cast it to that type.\n \"\"\"\n actual_value = str(value['value'])\n actual_type = value['type']\n\n try:\n if actual_type == 'int':\n new_value = int(actual_value)\n elif actual_type == 'float':\n new_value = float(actual_value)\n elif actual_type == 'bool':\n new_value = True if actual_value == 'true' else False\n elif actual_type == 'str' or 'path' in actual_type:\n new_value = str(actual_value)\n else:\n raise ValueError('Unrecognized value type')\n\n except Exception:\n raise ValueError(f'Could not cast {actual_value} to {actual_type}')\n\n return new_value\n\n\ndef load_json_parameters(path: str, value_cast: bool = False) -> dict:\n \"\"\"Load JSON Parameters.\n\n Given a path to a json of parameters, convert to a dictionary and optionally\n cast the type.\n\n Expects the following format:\n \"fake_data\": {\n \"value\": \"true\",\n \"section\": \"bci_config\",\n \"readableName\": \"Fake Data Sessions\",\n \"helpTip\": \"If true, fake data server used\",\n \"recommended_values\": \"\",\n \"type\": \"bool\"\n }\n\n PARAMETERS\n ----------\n :param: path: string path to the parameters file.\n :param: value_case: True/False cast values to specified type.\n \"\"\"\n # loads in json parameters and turns it into a dictionary\n try:\n with codecsopen(path, 'r', encoding='utf-8') as f:\n parameters = []\n try:\n parameters = jsonload(f)\n\n if value_cast:\n parameters = _cast_parameters(parameters)\n except ValueError:\n raise ValueError(\n \"Parameters file is formatted incorrectly!\")\n\n f.close()\n\n except IOError:\n raise IOError(\"Incorrect path to parameters given! Please try again.\")\n\n return parameters\n\n\ndef load_experimental_data() -> str:\n # use python's internal gui to call file explorers and get the filename\n try:\n Tk().withdraw() # we don't want a full GUI\n filename = askdirectory() # show dialog box and return the path\n\n except Exception as error:\n raise error\n\n log.debug(\"Loaded Experimental Data From: %s\" % filename)\n return filename\n\n\ndef load_signal_model(filename: str = None):\n # use python's internal gui to call file explorers and get the filename\n\n if not filename:\n try:\n Tk().withdraw() # we don't want a full GUI\n filename = askopenfilename() # show dialog box and return the path\n\n # except, raise error\n except Exception as error:\n raise error\n\n # load the signal_model with pickle\n signal_model = pickle.load(open(filename, 'rb'))\n\n return (signal_model, filename)\n\n\ndef load_csv_data(filename: str = None) -> str:\n if not filename:\n try:\n Tk().withdraw() # we don't want a full GUI\n filename = askopenfilename() # show dialog box and return the path\n\n except Exception as error:\n raise error\n\n # get the last part of the path to determine file type\n file_name = filename.split('/')[-1]\n\n if 'csv' not in file_name:\n raise Exception(\n 'File type unrecognized. Please use a supported csv type')\n\n return filename\n\n\ndef read_data_csv(folder: str, dat_first_row: int = 2,\n info_end_row: int = 1) -> tuple:\n \"\"\" Reads the data (.csv) provided by the data acquisition\n Arg:\n folder(str): file location for the data\n dat_first_row(int): row with channel names\n info_end_row(int): final row related with daq. info\n where first row idx is '0'\n Return:\n raw_dat(ndarray[float]): C x N numpy array with samples\n where C is number of channels N is number of time samples\n channels(list[str]): channels used in DAQ\n stamp_time(ndarray[float]): time stamps for each sample\n type_amp(str): type of the device used for DAQ\n fs(int): sampling frequency\n \"\"\"\n dat_file = pd.read_csv(folder, skiprows=dat_first_row)\n\n # Remove object columns (ex. BCI_Stimulus_Marker column)\n # TODO: might be better in use:\n # dat_file.select_dtypes(include=['float64'])\n numeric_dat_file = dat_file.select_dtypes(exclude=['object'])\n channels = list(numeric_dat_file.columns[1:]) # without timestamp column\n\n temp = pd.DataFrame.as_matrix(numeric_dat_file)\n stamp_time = temp[:, 0]\n raw_dat = temp[:, 1:temp.shape[1]].transpose()\n\n dat_file_2 = pd.read_csv(folder, nrows=info_end_row)\n type_amp = list(dat_file_2.axes[1])[1]\n fs = np.array(dat_file_2)[0][1]\n\n return raw_dat, stamp_time, channels, type_amp, fs\n\n\ndef load_txt_data() -> str:\n try:\n Tk().withdraw() # we don't want a full GUI\n filename = askopenfilename() # show dialog box and return the path\n except Exception as error:\n raise error\n\n file_name = filename.split('/')[-1]\n\n if 'txt' not in file_name:\n raise Exception(\n 'File type unrecognized. Please use a supported text type')\n\n return filename\n","sub_path":"bcipy/helpers/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"196518473","text":"__author__ = 'Russell J. Boag'\nimport pandas as pd\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plot\ntarget_url = (\"http://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data\")\n\n# read data\nabalone = pd.read_csv(target_url,header=None, prefix=\"V\")\nabalone.columns = ['Sex', 'Length', 'Diameter', 'Height', 'Whole Wt', 'Shucked Wt', 'Viscera Wt', 'Shell Wt', 'Rings']\n\n# calculate correlation matrix\ncorMat = DataFrame(abalone.iloc[:,1:9].corr())\n\n# print correlation matrix\nprint(corMat)\n\n# visualize correlations using heatmap\nplot.pcolor(corMat)\nplot.show()\n","sub_path":"ml.py/2.12.abaloneCorrHeat.py","file_name":"2.12.abaloneCorrHeat.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"533064609","text":"# -*- coding: utf-8 -*-\n\nif __name__ == '__main__':\n n = int( input() )\n tmp = input().split(' ')\n A = [int(i) for i in tmp]\n\n count = 0\n for i in range( len(A) ):\n for j in range( i, len(A) ):\n if A[i] > A[j]:\n count += 1\n\n print( count )\n","sub_path":"python/aizu/itaads/problem1_5D.py","file_name":"problem1_5D.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176046799","text":"import re\n#P = 20780029\nP = 144873962\nMIN = 20\ndef Splicing(inF):\n inFile = open(inF)\n ouFile = open(inF + '_Splicing', 'w')\n for line in inFile:\n line = line.strip()\n fields = line.split('\\t')\n cigar = fields[5]\n start = int(fields[3])\n s = re.search('(\\d+)M(\\d+)N(\\d+)M',cigar)\n if s:\n N = int(s.group(2))\n M1 = int(s.group(1))\n M2 = int(s.group(3))\n if M1 > MIN and M2 > MIN:\n if start + M1 < P:\n if start + M1 + N > P:\n print(start+M1+N)\n ouFile.write(line + '\\n')\n inFile.close()\n\n#Splicing('HG00096.1.M_111124_6_chr22')\nSplicing('x')\n","sub_path":"Projects/Splicing/02-Splicing.py","file_name":"02-Splicing.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"68878662","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\nfrom scipy.optimize import minimize\nfrom scipy.interpolate import interp1d\nimport sys\nimport warnings\n\n# Import data file\n# Column 1 = time (t)\n# Column 2 = input (u)\n# Column 3 = output (yp)\ndata_fan = pd.read_csv('a_Fan_step.csv', index_col=0)\nt = data_fan['Time'].to_numpy()\nu = data_fan['Fan'].to_numpy()\ny = data_fan['Tcpu'].to_numpy()\nq = data_fan['Q'].to_numpy()\nTa = data_fan['T_air'].to_numpy()\n\n# wait until steady state\ntsleep = 60\nt = t[tsleep:]\nu = u[tsleep:]\ny = y[tsleep:]\nq = q[tsleep:]\nTa = Ta[tsleep:]\nu0 = u[0]\ny0 = y[0]\nxp0 = [y0, 0.0]\nyp = y\n\n\n# specify number of steps\nns = len(t)\ndelta_t = t[1]-t[0]\n# create linear interpolation of the u data versus time\nuf = interp1d(t, u)\n\n# define first-order plus dead-time approximation\ndef fopdt(y,t,uf,Km,taum,thetam):\n # arguments\n # y = output\n # t = time\n # uf = input linear function (for time shift)\n # Km = model gain\n # taum = model time constant\n # thetam = model time constant\n # time-shift u\n try:\n if (t-thetam) <= 0:\n um = uf(0.0)\n else:\n um = uf(t-thetam)\n except:\n #print('Error with time extrapolation: ' + str(t))\n um = u0\n # calculate derivative\n dydt = (-(y-yp[0]) + Km * (um-u0))/taum\n return dydt\n\n# simulate FOPDT model with x=[Km,taum,thetam]\ndef sim_model(x):\n # input arguments\n Km = x[0]\n taum = x[1]\n thetam = x[2]\n # storage for model values\n ym = np.zeros(ns) # model\n # initial condition\n ym[0] = yp[0]\n # loop through time steps\n for i in range(0,ns-1):\n ts = [t[i],t[i+1]]\n y1 = odeint(fopdt,ym[i],ts,args=(uf,Km,taum,thetam))\n ym[i+1] = y1[-1]\n return ym\n\n# define objective\ndef objective(x):\n # simulate model\n ym = sim_model(x)\n # calculate objective\n obj = 0.0\n for k in range(len(ym)):\n obj = obj + (ym[k]-yp[k])**2\n # return result\n return obj\n\n# initial guesses\nx0 = np.zeros(3)\nx0[0] = -801.4 # Km\nx0[1] = .24 # taum\nx0[2] = 1 # thetam\n\n#show initial objective\nprint('Initial SSE Objective: ' + str(objective(x0)))\n\n# theta = np.linspace(0, 100, 100)\n# results = []\n# j = 1\n# for b in theta:\n# x0 = [-802, 1, b]\n# results.append(objective(x0))\n# sys.stdout.write(\"\\rDoing Test %d\" % j)\n# sys.stdout.flush()\n# j += 1\n#\n# plt.figure(figsize=(10, 7))\n# plt.plot(theta, results)\n# plt.xlabel('Theta Value')\n# plt.ylabel('SSE Error')\n# min_err = min(results)\n# Kp_best = theta[results.index(min_err)]\n# plt.show()\n# x = int(input('x Coordinate of text'))\n# y = int(input('Y coordinate of string'))\n#\n#\n# plt.figure(figsize=(10, 7))\n# plt.plot(theta, results)\n# plt.xlabel('Tau Value')\n# plt.ylabel('SSE Error')\n# min_err = min(results)\n# Kp_best = theta[results.index(min_err)]\n# plt.text(x,y, f'Min Err: {min_err}\\nBest Theta: {Kp_best}')\n# plt.savefig(input('What should this be named?'))\n# plt.show()\n\n\n# optimize Km, taum, thetam\nsolution = minimize(objective,x0)\n\n# Another way to solve: with bounds on variables\n#bnds = ((0.4, 0.6), (1.0, 10.0), (0.0, 30.0))\n#solution = minimize(objective,x0,bounds=bnds,method='SLSQP')\nx = solution.x\n\n# show final objective\nprint('Final SSE Objective: ' + str(objective(x)))\n\nprint('Kp: ' + str(x[0]))\nprint('taup: ' + str(x[1]))\nprint('thetap: ' + str(x[2]))\n\n# calculate model with updated parameters\nym1 = sim_model(x0)\nym2 = sim_model(x)\n# plot results\nplt.figure()\nplt.subplot(2,1,1)\nplt.plot(t,yp,'kx-',linewidth=2,label='Process Data')\nplt.plot(t,ym1,'b-',linewidth=2,label='Initial Guess')\nplt.plot(t,ym2,'r--',linewidth=3,label='Optimized FOPDT')\nplt.ylabel('Temperature')\nplt.legend(loc='best')\nplt.subplot(2,1,2)\nplt.plot(t,u,'bx-',linewidth=2)\nplt.plot(t,uf(t),'r--',linewidth=3)\nplt.legend(['Measured','Interpolated'],loc='best')\nplt.text(3100, .025, f'SSE: {round(objective(x), 2)}\\nKp: {round(x[0])}\\nTauP: {round(x[1],2)}\\n\\\nThetaP: {round(x[2],2)}')\nplt.ylabel('Fan Rate (m^3/sec)')\nplt.savefig('FanOptParam_step.png')\nplt.show()","sub_path":"Air/FOPDTfitAir.py","file_name":"FOPDTfitAir.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"483924472","text":"#To get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.\n\ndef both_end_string (s):\n ch1 = ' '\n ch2 = ' '\n a = len(s)\n if a > 1:\n print('Method 2 ',str( s[0:2] + s[-2:] ) )\n\n for i in range(2):\n ch1 += s[i]\n a -= 2\n ch2 += s[a]\n a += 3\n \n return(ch1 + ch2)\n else:\n return('empty string')\n\nprint('Method 1', both_end_string('w3scaol'))\n","sub_path":"str_6.py","file_name":"str_6.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"4773236","text":"\nimport os \n\nAPP_ANDROID_ROOT = '../../Client/trunk/proj.android'\n\nAPP_NAME = 'Dota-debug.apk'\n\nif __name__ == '__main__':\n\n SDK_ROOT = os.environ['ANDROID_SDK_ROOT']\n adbTool = os.path.join(SDK_ROOT, 'platform-tools/adb')\n apkFile = os.path.join(APP_ANDROID_ROOT, 'bin', APP_NAME)\n\n command = '%s devices' % (adbTool)\n os.system(command)\n\n command = '%s install -l -r %s' % (adbTool, apkFile)\n os.system(command)\n","sub_path":"android_build/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182197791","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport re\nfrom typing import Any\n\nimport pytest\nfrom _pytest.python_api import RaisesContext\nfrom omegaconf import DictConfig, OmegaConf\n\nfrom hydra._internal import utils\nfrom hydra._internal.utils import _locate\nfrom hydra.types import ObjectConf\nfrom tests import AClass, Adam, AnotherClass, ASubclass, NestingClass, Parameters\n\n\n@pytest.mark.parametrize( # type: ignore\n \"matrix,expected\",\n [\n ([[\"a\"]], [1]),\n ([[\"a\", \"bb\"]], [1, 2]),\n ([[\"a\", \"bb\"], [\"aa\", \"b\"]], [2, 2]),\n ([[\"a\"], [\"aa\", \"b\"]], [2, 1]),\n ([[\"a\", \"aa\"], [\"bb\"]], [2, 2]),\n ([[\"a\"]], [1]),\n ([[\"a\"]], [1]),\n ([[\"a\"]], [1]),\n ],\n)\ndef test_get_column_widths(matrix: Any, expected: Any) -> None:\n assert utils.get_column_widths(matrix) == expected\n\n\n@pytest.mark.parametrize( # type: ignore\n \"config, expected, warning\",\n [\n pytest.param(\n OmegaConf.create({\"_target_\": \"foo\"}), \"foo\", False, id=\"ObjectConf:target\"\n ),\n pytest.param(\n OmegaConf.create({\"cls\": \"foo\"}), \"foo\", \"cls\", id=\"DictConfig:cls\"\n ),\n pytest.param(\n OmegaConf.create({\"class\": \"foo\"}), \"foo\", \"class\", id=\"DictConfig:class\"\n ),\n pytest.param(\n OmegaConf.create({\"target\": \"foo\"}),\n \"foo\",\n \"target\",\n id=\"DictConfig:target\",\n ),\n pytest.param(\n OmegaConf.create({\"cls\": \"foo\", \"_target_\": \"bar\"}),\n \"bar\",\n False,\n id=\"DictConfig:cls_target\",\n ),\n pytest.param(\n OmegaConf.create({\"class\": \"foo\", \"_target_\": \"bar\"}),\n \"bar\",\n \"class\",\n id=\"DictConfig:class_target\",\n ),\n # check that `target` is prioritized over `cls`/`class`.\n pytest.param(\n OmegaConf.create({\"cls\": \"foo\", \"_target_\": \"bar\"}),\n \"bar\",\n \"cls\",\n id=\"DictConfig:pri_cls\",\n ),\n pytest.param(\n OmegaConf.create({\"class\": \"foo\", \"_target_\": \"bar\"}),\n \"bar\",\n \"class\",\n id=\"DictConfig:pri_class\",\n ),\n pytest.param(\n OmegaConf.create({\"target\": \"foo\", \"_target_\": \"bar\"}),\n \"bar\",\n \"target\",\n id=\"DictConfig:pri_target\",\n ),\n ],\n)\ndef test_get_class_name(\n config: DictConfig, expected: Any, warning: Any, recwarn: Any\n) -> None:\n assert utils._get_cls_name(config) == expected\n\n target_field_deprecated = (\n \"\\nConfig key '{key}' is deprecated since Hydra 1.0 and will be removed in Hydra 1.1.\"\n \"\\nUse '_target_' instead of '{field}'.\"\n \"\\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/object_instantiation_changes\"\n )\n\n if warning is not False:\n assert recwarn[0].category == UserWarning\n assert recwarn[0].message.args[0] == target_field_deprecated.format(\n key=warning, field=warning\n )\n\n\n# TODO: why?\n# @pytest.mark.skipif( # type: ignore\n# sys.version_info < (3, 7), reason=\"requires python3.7\"\n# )\n@pytest.mark.parametrize( # type: ignore\n \"name,expected\",\n [\n (\"tests.Adam\", Adam),\n (\"tests.Parameters\", Parameters),\n (\"tests.AClass\", AClass),\n (\"tests.ASubclass\", ASubclass),\n (\"tests.NestingClass\", NestingClass),\n (\"tests.AnotherClass\", AnotherClass),\n (\"\", pytest.raises(ImportError, match=re.escape(\"Empty path\"))),\n (\n \"not_found\",\n pytest.raises(\n ImportError, match=re.escape(\"Error loading module 'not_found'\")\n ),\n ),\n (\n \"tests.b.c.Door\",\n pytest.raises(ImportError, match=re.escape(\"No module named 'tests.b'\")),\n ),\n ],\n)\ndef test_locate(name: str, expected: Any) -> None:\n if isinstance(expected, RaisesContext):\n with expected:\n _locate(name)\n else:\n assert _locate(name) == expected\n\n\ndef test_object_conf_deprecated() -> None:\n msg = (\n \"\\nObjectConf is deprecated in favor of TargetConf since Hydra 1.0.0rc3 and will be removed in Hydra 1.1.\"\n \"\\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/object_instantiation_changes\"\n )\n\n with pytest.warns(expected_warning=UserWarning, match=msg):\n ObjectConf(target=\"foo\")\n","sub_path":"tests/test_internal_utils.py","file_name":"test_internal_utils.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"281704930","text":"# modulo trapper\n\nclass Trapper:\n\n def __init__(\n self, \n width, \n height, \n horizontal_speed, \n vertical_speed,\n gravity\n ):\n self.y = height/2\n self.x = width/2\n self.horizontal_speed = horizontal_speed\n self.vertical_speed = vertical_speed\n self.up = 0\n self.size = 10\n self.gravity = gravity\n\n def moveUp(self):\n if (self.up > 0):\n self.up -= 1\n self.y -= self.vertical_speed\n\n def moveDown(self):\n if (self.up == 0):\n self.y += self.gravity","sub_path":"entities/trapper.py","file_name":"trapper.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613984132","text":"import sys\nimport re\nimport os\nimport numpy as np\n\ndef createInput(ffname, gfname, yfname, dir):\n f = []\n g = []\n y = []\n ycenter = []\n ffname = os.path.join(dir, ffname)\n gfname = os.path.join(dir, gfname)\n yfname = os.path.join(dir, yfname) \n with open(ffname) as rf:\n rf.readline()\n for line in rf.readlines():\n ary = re.split(\",\", line.strip())\n f.append(float(ary[1]))\n with open(gfname) as rf:\n rf.readline()\n for line in rf.readlines():\n ary = re.split(\",\", line.strip())\n g.append(float(ary[2]))\n y.append(float(ary[3]))\n with open(yfname) as rf:\n rf.readline()\n for line in rf.readlines():\n ary = re.split(\",\", line.strip())\n ycenter.append(float(ary[1]))\n f = np.array(f)\n g = np.array(g)\n y = np.array(y)\n ycenter = np.array(ycenter)\n g = np.reshape(g, (len(f), len(ycenter)))\n y = np.reshape(y, (len(f), len(ycenter)))\n return (f, g, y, ycenter)\n\ndef calcIntercept(f, g, y):\n b = f - np.diag(np.dot(g, y.T))\n return b\n\n# - Lambda_k ||g^t d||^2 t + at t = 0\ndef calcDualDerivative0(Lambda, theta, g, d, b, ycenter):\n gtTheta = np.dot(g.T, theta)\n xdash = ycenter - Lambda * gtTheta\n gxPlusB = np.dot(g, xdash) + b\n return np.dot(d, gxPlusB)\n\ndef exactLineSearch(Lambda, gtdSquared, d_0):\n return d_0/(gtdSquared*Lambda)\n\ndef calcDual(Lambda, theta, ycenter, g, b):\n gtTheta = np.dot(g.T, theta)\n ret = - 0.5*Lambda*np.dot(gtTheta, gtTheta)\n gxPlusB = np.dot(g, ycenter) + b\n ret += np.dot(theta, gxPlusB)\n return ret\n\ndef calcPDgap(Lambda, theta, ycenter, g, b):\n gtTheta = np.dot(g.T, theta)\n xdash = ycenter - Lambda * gtTheta\n affines = np.dot(g, xdash) + b\n diff = max(affines) - affines\n ret = np.dot(theta, diff)\n return ret\n\ndef coordinateDescent(N, itrmax, Lambda, g, b, ycenter, gamma, logger):\n theta = np.ones(N)/float(N)\n for itr in range(itrmax):\n i = itr % N\n e_i = np.zeros(N)\n e_i[i] = 1.0\n d = e_i - theta\n d_0 = calcDualDerivative0(Lambda, theta, g, d, b, ycenter)\n if np.absolute(d_0) <= 1.0e-8:\n continue\n if d_0 < 0 and np.absolute(theta[i]) <= 1.0e-8:\n continue\n gtd = np.dot(g.T, d)\n gtdSquared = np.dot(gtd, gtd)\n if np.absolute(gtdSquared) <= 1.0e-12:\n continue\n else:\n tmax = 1.0\n tmin = - theta[i]/(1.0 - theta[i])\n t = exactLineSearch(Lambda, gtdSquared, d_0)\n if t >= tmax:\n t = tmax\n if t <= tmin:\n t = tmin\n theta += t*d\n gap = calcPDgap(Lambda, theta, ycenter, g, b)\n if gap <= gamma:\n logger.debug(\"reach the gap! \" + str(itr))\n break\n gap = calcPDgap(Lambda, theta, ycenter, g, b)\n gtTheta = np.dot(g.T, theta)\n xdash = ycenter - Lambda * gtTheta\n affines = np.dot(g, xdash) + b\n mnext = np.dot(theta, affines)\n logger.debug(\"gap = \" + str(gap) + \" gamma = \" + str(gamma))\n return(xdash, mnext, gtTheta)\n \nif __name__ == \"__main__\":\n Lambda = 1.0\n (f, g, y, ycenter) = createInput(\"f.csv\", \"gy.csv\", \"ycenter.csv\", sys.argv[1])\n N = len(f)\n b = calcIntercept(f, g, y)\n (theta, gap) = coordinateDescent(N, Lambda, g, b, ycenter)\n print(theta)\n print(gap)\n \n","sub_path":"dualCoordinate.py","file_name":"dualCoordinate.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97377587","text":"import os\r\nimport functools\r\nimport operator\r\nimport gzip\r\nimport struct\r\nimport array\r\nimport tempfile\r\nimport numpy as np\r\n\r\ntry:\r\n from urllib.request import urlretrieve\r\nexcept ImportError:\r\n from urllib import urlretrieve # py2\r\ntry:\r\n from urllib.parse import urljoin\r\nexcept ImportError:\r\n from urlparse import urljoin\r\n\r\n# the url can be changed by the users of the library (not a constant)\r\ndatasets_url = 'http://yann.lecun.com/exdb/mnist/'\r\n\r\n\r\nclass IdxDecodeError(ValueError):\r\n \"\"\"Raised when an invalid idx file is parsed.\"\"\"\r\n pass\r\n\r\n\r\ndef download_file(fname, target_dir=None, force=False):\r\n \"\"\"Download fname from the datasets_url, and save it to target_dir,\r\n unless the file already exists, and force is False.\r\n Parameters\r\n ----------\r\n fname : str\r\n Name of the file to download\r\n target_dir : str\r\n Directory where to store the file\r\n force : bool\r\n Force downloading the file, if it already exists\r\n Returns\r\n -------\r\n fname : str\r\n Full path of the downloaded file\r\n \"\"\"\r\n if not target_dir:\r\n target_dir = tempfile.gettempdir()\r\n target_fname = os.path.join(target_dir, fname)\r\n\r\n if force or not os.path.isfile(target_fname):\r\n url = urljoin(datasets_url, fname)\r\n urlretrieve(url, target_fname)\r\n\r\n return target_fname\r\n\r\n\r\ndef parse_idx(fd):\r\n \"\"\"Parse an IDX file, and return it as a numpy array.\r\n Parameters\r\n ----------\r\n fd : file\r\n File descriptor of the IDX file to parse\r\n endian : str\r\n Byte order of the IDX file. See [1] for available options\r\n Returns\r\n -------\r\n data : numpy.ndarray\r\n Numpy array with the dimensions and the data in the IDX file\r\n 1. https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment\r\n \"\"\"\r\n DATA_TYPES = {0x08: 'B', # unsigned byte\r\n 0x09: 'b', # signed byte\r\n 0x0b: 'h', # short (2 bytes)\r\n 0x0c: 'i', # int (4 bytes)\r\n 0x0d: 'f', # float (4 bytes)\r\n 0x0e: 'd'} # double (8 bytes)\r\n\r\n header = fd.read(4)\r\n if len(header) != 4:\r\n raise IdxDecodeError('Invalid IDX file, file empty or does not contain a full header.')\r\n\r\n zeros, data_type, num_dimensions = struct.unpack('>HBB', header)\r\n\r\n if zeros != 0:\r\n raise IdxDecodeError('Invalid IDX file, file must start with two zero bytes. '\r\n 'Found 0x%02x' % zeros)\r\n\r\n try:\r\n data_type = DATA_TYPES[data_type]\r\n except KeyError:\r\n raise IdxDecodeError('Unknown data type 0x%02x in IDX file' % data_type)\r\n\r\n dimension_sizes = struct.unpack('>' + 'I' * num_dimensions,\r\n fd.read(4 * num_dimensions))\r\n\r\n data = array.array(data_type, fd.read())\r\n data.byteswap() # looks like array.array reads data as little endian\r\n\r\n expected_items = functools.reduce(operator.mul, dimension_sizes)\r\n if len(data) != expected_items:\r\n raise IdxDecodeError('IDX file has wrong number of items. '\r\n 'Expected: %d. Found: %d' % (expected_items, len(data)))\r\n\r\n return np.array(data).reshape(dimension_sizes)\r\n\r\n\r\ndef download_and_parse_mnist_file(fname, target_dir=None, force=False):\r\n \"\"\"Download the IDX file named fname from the URL specified in dataset_url\r\n and return it as a numpy array.\r\n Parameters\r\n ----------\r\n fname : str\r\n File name to download and parse\r\n target_dir : str\r\n Directory where to store the file\r\n force : bool\r\n Force downloading the file, if it already exists\r\n Returns\r\n -------\r\n data : numpy.ndarray\r\n Numpy array with the dimensions and the data in the IDX file\r\n \"\"\"\r\n fname = download_file(fname, target_dir=target_dir, force=force)\r\n fopen = gzip.open if os.path.splitext(fname)[1] == '.gz' else open\r\n with fopen(fname, 'rb') as fd:\r\n return parse_idx(fd)\r\n\r\n\r\ndef train_images():\r\n \"\"\"Return train images from Yann LeCun MNIST database as a numpy array.\r\n Download the file, if not already found in the temporary directory of\r\n the system.\r\n Returns\r\n -------\r\n train_images : numpy.ndarray\r\n Numpy array with the images in the train MNIST database. The first\r\n dimension indexes each sample, while the other two index rows and\r\n columns of the image\r\n \"\"\"\r\n return download_and_parse_mnist_file('train-images-idx3-ubyte.gz')\r\n\r\n\r\ndef test_images():\r\n \"\"\"Return test images from Yann LeCun MNIST database as a numpy array.\r\n Download the file, if not already found in the temporary directory of\r\n the system.\r\n Returns\r\n -------\r\n test_images : numpy.ndarray\r\n Numpy array with the images in the train MNIST database. The first\r\n dimension indexes each sample, while the other two index rows and\r\n columns of the image\r\n \"\"\"\r\n return download_and_parse_mnist_file('t10k-images-idx3-ubyte.gz')\r\n\r\n\r\ndef train_labels():\r\n \"\"\"Return train labels from Yann LeCun MNIST database as a numpy array.\r\n Download the file, if not already found in the temporary directory of\r\n the system.\r\n Returns\r\n -------\r\n train_labels : numpy.ndarray\r\n Numpy array with the labels 0 to 9 in the train MNIST database.\r\n \"\"\"\r\n return download_and_parse_mnist_file('train-labels-idx1-ubyte.gz')\r\n\r\n\r\ndef test_labels():\r\n \"\"\"Return test labels from Yann LeCun MNIST database as a numpy array.\r\n Download the file, if not already found in the temporary directory of\r\n the system.\r\n Returns\r\n -------\r\n test_labels : numpy.ndarray\r\n Numpy array with the labels 0 to 9 in the train MNIST database.\r\n \"\"\"\r\n return download_and_parse_mnist_file('t10k-labels-idx1-ubyte.gz')\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\ndef show(array, index):\r\n plt.imshow(array[index], cmap=plt.get_cmap('gray_r'))\r\n plt.show()\r\n\r\ndef sig(m):\r\n return (np.exp(m))/(1+np.exp(m))\r\n\r\ndef dsig(m):\r\n return sig(m)*(1-sig(m))\r\n\r\ndef accuracy(sL1, B3, B2, W3, W2, Y):\r\n L2 = sL1.dot(W2)+B2\r\n sL2 = sig(L2)\r\n\r\n L3 = sL2.dot(W3)+B3\r\n sL3 = sig(L3)\r\n\r\n labels = np.argmax(sL3, axis=1)\r\n\r\n return np.sum(labels == Y)\r\n\r\ndef cost(sL1, B3, B2, W3, W2, Y):\r\n L2 = sL1.dot(W2)+B2\r\n sL2 = sig(L2)\r\n\r\n L3 = sL2.dot(W3)+B3\r\n sL3 = sig(L3)\r\n\r\n return np.sum(0.5*(sL3-Y)*(sL3-Y))\r\n\r\n# hyperparameters\r\nbatch = 10\r\nnumEpochs = 10;\r\nepochTime = 60000/batch\r\nlearningRate = 3/batch\r\n\r\ndef train(Labels, Data, B3, B2, W3, W2):\r\n for i in range(numEpochs):\r\n print(accuracy(Data, B3, B2, W3, W2, train_labels()))\r\n for j in range(int(epochTime)):\r\n\r\n nums = np.arange(60000)\r\n np.random.shuffle(nums)\r\n shuffle = nums[:batch]\r\n\r\n Y = Labels[shuffle]\r\n sL1 = Data[shuffle]\r\n\r\n # neural network\r\n\r\n L2 = sL1.dot(W2)+B2\r\n sL2 = sig(L2)\r\n\r\n L3 = sL2.dot(W3)+B3\r\n sL3 = sig(L3)\r\n\r\n # gradients\r\n\r\n dB3 = (sL3-Y)*dsig(L3)\r\n dB2 = dB3.dot(W3.T)*dsig(L2)\r\n\r\n dW3 = (sL2.T).dot(dB3)\r\n dW2 = (sL1.T).dot(dB2)\r\n\r\n # update\r\n\r\n B3 -= learningRate*dB3.sum(axis=0)\r\n B2 -= learningRate*dB2.sum(axis=0)\r\n\r\n W3 -= learningRate*dW3\r\n W2 -= learningRate*dW2\r\n\r\nW12 = np.random.normal(0, 1/np.sqrt(784), (784,150))\r\nW25 = np.random.normal(0, 1/np.sqrt(150), (150,10))\r\n\r\nW23 = np.random.normal(0, 1/np.sqrt(150), (150,100))\r\nW35 = np.random.normal(0, 1/np.sqrt(100), (100,10))\r\n\r\nW34 = np.random.normal(0, 1/np.sqrt(100), (100,50))\r\nW45 = np.random.normal(0, 1/np.sqrt(50), (50,10))\r\n\r\n\r\nB12 = np.random.normal(0, 1, (150))\r\nB25 = np.random.normal(0, 1, (10))\r\n\r\nB23 = np.random.normal(0, 1, (100))\r\nB35 = np.random.normal(0, 1, (10))\r\n\r\nB34 = np.random.normal(0, 1, (50))\r\nB45 = np.random.normal(0, 1, (10))\r\n\r\n\r\nY = np.zeros((60000,10))\r\nY[np.arange(60000), train_labels()] = 1\r\n\r\nsL1 = train_images().reshape(60000,784)/256\r\ntrain(Y, sL1, B25, B12, W25, W12)\r\nprint(accuracy(sL1, B25, B12, W25, W12, train_labels()))\r\n\r\nsL2 = sig(sL1.dot(W12) + B12)\r\ntrain(Y, sL2, B35, B23, W35, W23)\r\nprint(accuracy(sL2, B35, B23, W35, W23, train_labels()))\r\n\r\nsL3 = sig(sL2.dot(W23) + B23)\r\ntrain(Y, sL3, B45, B34, W45, W34)\r\nprint(accuracy(sL3, B45, B34, W45, W34, train_labels()))\r\n\r\n# label\r\ntestLabels = np.zeros((10000,10))\r\ntestLabels[np.arange(10000), test_labels()] = 1\r\n\r\n# input\r\ntestImages = test_images().reshape(10000,784)/256\r\n\r\naccuracy(testImages, B23, B12, W23, W12, test_labels())\r\n\r\nplt.imshow(trainImages[0].reshape(28,28),cmap=plt.get_cmap('gray_r'))\r\n","sub_path":"ForwardThinking.py","file_name":"ForwardThinking.py","file_ext":"py","file_size_in_byte":8759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"466795895","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC COPYRIGHT: Columbia Sportswear 2020
    \n# MAGIC DESCRIPTION: This notebook exports US and CAN Order Promotions data for Dynamic Action\n# MAGIC \n# MAGIC -----------------------------------------------------------------\n# MAGIC ###### MODIFICATION LOG\n# MAGIC | Programmmer | Change Request | Date | Change Description |\n# MAGIC |----------------------|-----------------|------------|--------------------------------------------------------------------|\n# MAGIC | Bob Socolich | X1 | 7/14/2020 |Initial Version | \n\n# COMMAND ----------\n\ndbutils.widgets.text(\"schmNm\", \"\", \"\")\ndbutils.widgets.text(\"tblNm\", \"\", \"\")\n\ndbutils.widgets.text(\"deltaTS\", \"\", \"\")\ndbutils.widgets.text(\"initFlg\", \"\", \"\")\n\ndbutils.widgets.get(\"deltaTS\")\ndeltaTS = getArgument(\"deltaTS\")\n\ndbutils.widgets.get(\"initFlg\")\ninitFlg = getArgument(\"initFlg\")\n\ndbutils.widgets.get(\"schmNm\")\nschmNm = getArgument(\"schmNm\")\n\ndbutils.widgets.get(\"tblNm\")\ntblNm = getArgument(\"tblNm\")\n\n#Update the Timestamp to remove T\ndeltaTS = deltaTS.replace('T',' ')\n#get region from table name, will be used later in the notebook\nregion = tblNm[-2:].lower()\n\n\n# COMMAND ----------\n\n# Import functions\nfrom datetime import datetime, timedelta\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\nimport glob\nimport shutil\nimport os\nimport time\nimport pyspark\nfrom zipfile import ZipFile, ZIP_DEFLATED\nfrom calendar import monthrange\n\n\n# COMMAND ----------\n\n#Initialize variables \ncurrent_date = deltaTS[0:10] #get date portion of deltaTS with current date following YYYY-MM-DD syntax\n\nfilepath = \"/mnt/entadls/curated/internal/merchandising/dynamic_action/columbiainternalorderpromos/\" + region + \"/\"\narchiveFilePath = \"/mnt/entadls/curated/internal/merchandising/dynamic_action/columbiainternalorderpromos/\" + region + \"_archive/\"\nfilename = \"Columbia-\" + region.upper() + \"_OrderPromos_OD_\" + current_date + \"_daily.csv\"\n\nif region.upper() == 'US':\n salesOrg = '1001'\nelse:\n salesOrg = '2001'\n\n# COMMAND ----------\n\n#Retrieve data to export\nsqlStmt = \"\"\"select ohd.OmsOrderNumber as JDAOrderNbr, ohd.SFCCOrderNumber as SFCCOrderNumber,from_utc_timestamp(ohd.OrderDateTime,\"PST\") as OrderDate, ohd.Type as PromotionType, ohd.DiscountAmount as DiscountAmt,\n ohd.PromotionID as PromotionName,ohd.Description as CampaignDescription\n from edw_lnd_oms_view.order_header_discounts ohd\n where ohd.salesorg = '{1}'\n and ohd.SFCCOrderNumber is not null\n and substring(from_utc_timestamp(ohd.OrderDateTime,\"PST\"),1,10) = '{0}'\"\"\".format(current_date, salesOrg)\n\ndf_product = spark.sql(sqlStmt)\ndf_product.persist()\ndf_product.createOrReplaceTempView(\"planning_product\")\n\n# COMMAND ----------\n\n#Export data as .csv file\ndf_product.coalesce(1).write.format(\"com.databricks.spark.csv\") \\\n .mode(\"overwrite\") \\\n .option(\"delimiter\", \",\") \\\n .option(\"emptyValue\",None) \\\n .option(\"nullValue\",None) \\\n .option('encoding',\"cp1252\") \\\n .save(filepath, header=\"true\")\n\n# COMMAND ----------\n\n#Create Archive Directory if not exists\ndbutils.fs.mkdirs(archiveFilePath)\n\n# COMMAND ----------\n\n#Rename exported .csv file from path*.csv to the defined filename syntax\n\n#get list of files in export directory\nfile_list = dbutils.fs.ls(filepath)\n\n#loop through file list and capture the name of the .csv file\nfor list in file_list:\n if list.name.endswith(\".csv\") == True:\n oldfFile = filepath + list.name\n else:\n dbutils.fs.rm(filepath + list.name) #remove non-csv files \n\n#process csv file if one is found\nif oldfFile != '':\n newFileName = filepath + filename\n archiveFile = archiveFilePath + filename\n dbutils.fs.cp(oldfFile, newFileName) #copy old file to create a new one with the correct naming standard\n dbutils.fs.cp(newFileName, archiveFile) #archive today's file\n dbutils.fs.rm(oldfFile) #remove the old .csv file \n \n#cleanup non-csv files in archive directory\nfile_list = dbutils.fs.ls(archiveFilePath)\n#loop through file list and capture the name of the .csv file\nfor list in file_list:\n if list.name.endswith(\".csv\") == False:\n dbutils.fs.rm(archiveFilePath + list.name)\n\n# COMMAND ----------\n\n# Delete Files from Archive Folder older than 90 days\nnow = time.time()\nfiles = [os.path.join(\"/dbfs\" + archiveFilePath, filename) for filename in os.listdir(\"/dbfs\" + archiveFilePath)]\nfor filename in files:\n if (now - os.stat(filename).st_mtime) > 7776000:\n command = \"rm {0}\".format(filename)\n subprocess.call(command, shell=True)\n\n# COMMAND ----------\n\ndf_product.unpersist()\n","sub_path":"Dev/entpr_merchandising/dna_order_promotions.py","file_name":"dna_order_promotions.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"377440902","text":"import csv\n\ncsvpath = r\"Resources/budget_data.csv\"\n\ntotalMonths = 0 \nprofitLosses = 0 \nlastMonthProfit = 0 \nfirstRow = True\nchangeDict = {}\n\nwith open(csvpath, \"r\") as csvfile: \n csvreader = csv.reader(csvfile, delimiter = ',')\n\n csv_header = next(csvreader)\n print(f\"CSV Header: {csv_header}\")\n \n for row in csvreader:\n totalMonths += 1 \n profitLosses += int(row[1])\n \n if firstRow: \n lastMonthProfit = row[1] \n firstRow = False\n else: \n change = int(row[1]) - int(lastMonthProfit)\n changeDict[row[0]] = change \n lastMonthProfit = int(row[1])\n\nfor key in changeDict.keys():\n averageChange = (sum(changeDict.values())) / (totalMonths-1)\n\nmaxChange = max(changeDict,key=changeDict.get)\nmaxChangeValue = changeDict[maxChange]\nminChange = min(changeDict, key=changeDict.get)\nminChangeValue = changeDict[minChange]\n\n#print(totalMonths)\n#print(profitLosses)\n#print(changeDict)\n#print(averageChange)\n#print(maxChange)\n#print(minChange)\n\n\nsummary = f\"\"\" Financial Analysis \n---------------------------------\nTotal Months : {totalMonths}\nTotal: ${profitLosses}\nAverage Change: %{averageChange}\nGreatest Increase in Profits: {maxChange}(${maxChangeValue})\nGreatest Decrease in Profits: {minChange}(${minChangeValue})\"\"\"\n\nprint(summary)\n\nwith open(\"Financial_AnalysisResults.txt\", \"w\") as file1:\n file1.write(summary)\n\n\n\n\n \n\n\n \n","sub_path":"03-Python/PyBank/pyBank_Lane copy.py","file_name":"pyBank_Lane copy.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"285938324","text":"import os\nimport random\nimport sys\nimport time\nimport pygame\n\ndef image_from_url(url):\n try:\n from urllib2 import urlopen\n from cStringIO import StringIO as inout\n except ImportError:\n from urllib.request import urlopen\n from io import BytesIO as inout\n myurl = urlopen(url)\n return inout(myurl.read())\n\nbackground_URL = ('http://i1315.photobucket.com/albums/t600/11roadkills/space_zpsec971d2c.png')\nmeteor_URL = ('http://i1315.photobucket.com/albums/t600/11roadkills/f3252a21-352d-49ca-a7ae-eac85c18b4b7_zpsd97af755.png?t=1387696943')\nmeteor2_URL = ('http://i1315.photobucket.com/albums/t600/11roadkills/097c706e-bb42-4400-8f79-78d805d685e5_zps629c6efa.png?t=1387696885')\nSpaceship_URL = ('http://i1315.photobucket.com/albums/t600/11roadkills/a1c54686-2e35-442d-85a9-20ae135db85b_zps406f61d7.png?t=1387696835')\nexplosion_URL = ('http://i1315.photobucket.com/albums/t600/11roadkills/explosion_zpsbbc7bb55.png')\n\nBLACK = (0,0,0)\nRED = (255,0,0)\nGREEN = (0,255,0)\n\npa = False\npygame.init()\nDISPLAYSURF = pygame.display.set_mode((900,700),0,32)\npygame.display.set_caption('Astroid feild')\nclock = pygame.time.Clock()\nu = True\nd = False\nt = True\nspaceship_img = pygame.image.load(image_from_url(Spaceship_URL))\nspaceship = pygame.transform.scale(spaceship_img, (150,90))\nmeteor = pygame.image.load(image_from_url(meteor_URL))\nbackground_img = pygame.image.load(image_from_url(background_URL))\nbackground = pygame.transform.scale(background_img, (800,800))\nmeteor2 = pygame.image.load(image_from_url(meteor2_URL))\nmyfont = pygame.font.SysFont(\"Lucida Console\", 30)\nmyfont2 = pygame.font.SysFont(\"Lucida Console\", 100)\nmyfont3 = pygame.font.SysFont(\"Lucida Console\", 80)\nplace = [(800,298) , (800,200) , (800,80) , (800,500)]\nsetplace = random.choice(place)\nplace2 = [(800,256) , (800,90) , (800,180) , (800,500)]\nsetplace2 = random.choice(place)\nexplosion_img = pygame.image.load(image_from_url(explosion_URL))\nexplosion = pygame.transform.scale(explosion_img, (170,110))\nlevel = 5\ndistance = 0\ni = 255\nf = True\nlabel2 = myfont2.render(\"GAME OVER\", 1, RED)\nlabel3 = myfont3.render(\"Asteroid Field\", 1, GREEN)\nlabel4 = myfont.render(\"Play\", 1, GREEN)\nlabel5 = myfont.render(\"Quit\", 1, GREEN)\nbackgroundrect = background.get_rect(topleft=(1,1))\nbackgroundrect2 = background.get_rect(topleft=(800,1))\nmeteorrect = meteor.get_rect(topleft=(setplace))\nmeteorrect2 = meteor.get_rect(topleft=(setplace2))\nmeteorrect3 = meteor.get_rect(topleft=(setplace))\nmeteorrect4 = meteor.get_rect(topleft=(setplace2))\nspaceshiprect = spaceship.get_rect(topleft= (1,100))\nl = True\np = False\nhit = False\nwhile True:\n DISPLAYSURF.fill(BLACK)\n key = pygame.key.get_pressed()\n if l and key[pygame.K_UP] and not hit and l:\n spaceshiprect.y -= level\n if l and key[pygame.K_DOWN] and not hit:\n spaceshiprect.y += level \n if l and key[pygame.K_RIGHT] and not hit:\n spaceshiprect.x += level - 3\n if l and key[pygame.K_LEFT] and not hit:\n spaceshiprect.x -= level - 3\n\n\n if backgroundrect.x < -800:\n backgroundrect.x = 800\n if backgroundrect2.x < -800:\n backgroundrect2.x = 800\n\n\n DISPLAYSURF.blit(background, backgroundrect)\n DISPLAYSURF.blit(background, backgroundrect2)\n DISPLAYSURF.blit(spaceship, spaceshiprect)\n DISPLAYSURF.blit(meteor, meteorrect)\n DISPLAYSURF.blit(meteor2, meteorrect2)\n DISPLAYSURF.blit(meteor, meteorrect3)\n\n if p == False:\n spaceship = pygame.transform.scale(spaceship, (300, 240))\n DISPLAYSURF.fill((119,136,153))\n DISPLAYSURF.blit(label3, (150,100))\n DISPLAYSURF.blit(spaceship, (250,200))\n pygame.draw.rect(DISPLAYSURF, BLACK, (300, 450, 200, 200,))\n DISPLAYSURF.blit(label4, (360,550))\n DISPLAYSURF.blit(label5, (360,580))\n if key[pygame.K_UP]:\n u = True\n d = False\n if u:\n pygame.draw.rect(DISPLAYSURF, GREEN, (350, 550, 85, 35,), 10)\n if key[pygame.K_RETURN]:\n spaceship = pygame.transform.scale(spaceship_img, (150,90))\n p = True\n l = True\n distance = 0\n \n if key[pygame.K_DOWN]:\n d = True\n u = False\n if d:\n pygame.draw.rect(DISPLAYSURF, GREEN, (350, 580, 80, 30,), 10)\n if key[pygame.K_RETURN]:\n pygame.quit()\n \n if spaceshiprect.colliderect(meteorrect) or spaceshiprect.colliderect(meteorrect2) or spaceshiprect.colliderect(meteorrect3):\n hit = True\n\n if hit:\n l = False\n\n if l == False:\n label4 = myfont.render(\"Play again\", 1, GREEN)\n explosionrect = explosion.get_rect(topleft=(spaceshiprect.x, spaceshiprect.y))\n DISPLAYSURF.blit(explosion, explosionrect)\n DISPLAYSURF.blit(label2, (200,200))\n DISPLAYSURF.blit(label4, (370,550))\n DISPLAYSURF.blit(label5, (430,580))\n if key[pygame.K_UP]:\n u = True\n d = False \n if u:\n pygame.draw.rect(DISPLAYSURF, GREEN, (360, 550, 220, 30,), 10)\n if key[pygame.K_RETURN]:\n p = True\n l = True\n hit = False\n level = 5\n distance = -1\n meteorrect.x = -26\n meteorrect2.x = -26\n meteorrect3.x = -26\n spaceshiprect = spaceship.get_rect(topleft= (1,100))\n \n\n\n\n \n if key[pygame.K_DOWN]:\n d = True\n u = False\n if d:\n pygame.draw.rect(DISPLAYSURF, GREEN, (430, 580, 80, 30,), 10)\n if key[pygame.K_RETURN]:\n pygame.quit()\n\n\n\n \n \n if meteorrect.x <= -25:\n place = [(800,spaceshiprect.y) , (850,80) , (800,spaceshiprect.y) , (800,298) , (950,spaceshiprect.y) , (950,80) , (900,spaceshiprect.y) , (900,298)]\n setplace = random.choice(place)\n place2 = [(800,256) , (800,spaceshiprect.y) , (850,30) , (800,spaceshiprect.y) , (950,500) , (900,spaceshiprect.y) , (900,200) , (900,spaceshiprect.y)]\n setplace2 = random.choice(place2)\n meteorrect = meteor.get_rect(topleft=(setplace))\n meteorrect2 = meteor2.get_rect(topleft=(setplace2))\n DISPLAYSURF.blit(meteor, meteorrect)\n DISPLAYSURF.blit(meteor2, meteorrect2)\n level += 1\n distance += 1\n if p:\n distanceboard = myfont.render('Distance: {} Killometers'.format(distance), 1 , GREEN)\n DISPLAYSURF.blit(distanceboard, (10,10))\n\n\n if p and not hit:\n meteorrect.x -= level\n meteorrect2.x -= level\n meteorrect3.x -= level\n backgroundrect.x -= level - 3\n backgroundrect2.x -= level - 3\n \n if meteorrect3.x <= -25:\n place3 = [(1050,200) , (1050,spaceshiprect.y) , (1200,40) , (1200,spaceshiprect.y) , (1050,600) , (1080,spaceshiprect.y) , (1050,300) , (1200,spaceshiprect.y)]\n setplace3 = random.choice(place3)\n meteorrect3 = meteor.get_rect(topleft=(setplace3))\n DISPLAYSURF.blit(meteor, meteorrect3)\n \n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n pygame.display.update()\n clock.tick(60)\n","sub_path":"Asteroid Field.py","file_name":"Asteroid Field.py","file_ext":"py","file_size_in_byte":7301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577212617","text":"import time\n\nstart_time = time.time()\n\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nduplicates = [] # Return the list of duplicates in this data structure\n\nclass BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value):\n if value < self.value:\n if self.left:\n self.left.insert(value)\n else:\n self.left = BinarySearchTree(value)\n else:\n if self.right:\n self.right.insert(value)\n else:\n self.right = BinarySearchTree(value)\n\n def contains(self, target):\n if self.value == target:\n return True\n if self.value < target:\n if self.right:\n return self.right.contains(target)\n else:\n return False\n else:\n if self.left:\n return self.left.contains(target)\n else:\n return False\n\n\ntree = BinarySearchTree(names_1[0])\nfor name in names_1:\n tree.insert(name)\nfor name in names_2:\n if tree.contains(name):\n duplicates.append(name)\n \n\n# Replace the nested for loops below with your improvements\n# for name_1 in names_1:\n# for name_2 in names_2:\n# if name_1 == name_2:\n# duplicates.append(name_1)\n# n^2\n\n# for name in names_2:\n# if name in names_1:\n# duplicates.append(name) \n# n?\n\n#https://www.geeksforgeeks.org/python-print-common-elements-two-lists/\n\n# names_1 = set(names_1)\n# names_2 = set(names_2)\n# duplicates = list(names_1.intersection(names_2)) \n#average = O(min(len(s), len(t))\t worst = O(len(s) * len(t))\n\nend_time = time.time()\nprint(f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint(f\"runtime: {end_time - start_time} seconds\")\n\n# ---------- Stretch Goal -----------\n# Python has built-in tools that allow for a very efficient approach to this problem\n# What's the best time you can accomplish? Thare are no restrictions on techniques or data\n# structures, but you may not import any additional libraries that you did not write yourself.\n","sub_path":"names/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316382869","text":"#!/usr/bin/env python\n\nfrom gluon.custom_import import track_changes\n\nimport collections\nimport json\nimport datetime\nfrom urllib.parse import urlparse, urlunparse\nfrom markdown import markdown\n\nfrom render import (\n Verses,\n Verse,\n verse_simple,\n Viewsettings,\n legend,\n colorpicker,\n h_esc,\n get_request_val,\n get_fields,\n style,\n tp_labels,\n tab_views,\n tr_info,\n tr_labels,\n iid_encode,\n iid_decode,\n nt_statclass,\n booklangs,\n booknames,\n booktrans,\n from_cache,\n clear_cache,\n get_books\n)\nfrom mql import mql\nfrom get_db_config import emdros_versions\n\n\ntrack_changes(True)\n\nRESULT_PAGE_SIZE = 20\nBLOCK_SIZE = 500\nPUBLISH_FREEZE = datetime.timedelta(weeks=1)\nPUBLISH_FREEZE_MSG = \"1 week\"\nNULLDT = \"____-__-__ __:__:__\"\n\n\ndef books():\n session.forget(response)\n jsinit = \"\"\"\nvar bookla = {bookla};\nvar booktrans = {booktrans};\nvar booklangs = {booklangs};\n\"\"\".format(\n bookla=json.dumps(booknames[\"Hebrew\"][\"la\"]),\n booktrans=json.dumps(booktrans),\n booklangs=json.dumps(booklangs[\"Hebrew\"]),\n )\n return dict(jsinit=jsinit)\n\n\ndef text():\n session.forget(response)\n\n return dict(\n viewsettings=Viewsettings(cache, passage_dbs, URL, versions),\n colorpicker=colorpicker,\n legend=legend,\n tp_labels=tp_labels,\n tab_views=tab_views,\n tr_labels=tr_labels,\n tr_info=tr_info,\n )\n\n\ndef get_clause_atom_fmonad(vr):\n (books, books_order, book_id, book_name) = from_cache(\n cache, \"books_{}_\".format(vr), lambda: get_books(passage_dbs, vr), None\n )\n sql = \"\"\"\nselect book_id, ca_num, first_m\nfrom clause_atom\n;\n\"\"\"\n ca_data = passage_dbs[vr].executesql(sql) if vr in passage_dbs else []\n clause_atom_first = {}\n for (bid, can, fm) in ca_data:\n bnm = book_name[bid]\n clause_atom_first.setdefault(bnm, {})[can] = fm\n return clause_atom_first\n\n\ndef get_clause_atoms(vr, bk, ch, vs): # get clauseatoms for each verse\n clause_atoms = []\n ca_data = (\n passage_dbs[vr].executesql(\n \"\"\"\nselect\n distinct word.clause_atom_number\nfrom\n verse\ninner join\n word_verse on verse.id = word_verse.verse_id\ninner join\n word on word.word_number = word_verse.anchor\ninner join\n chapter on chapter.id = verse.chapter_id\ninner join\n book on book.id = chapter.book_id\nwhere\n book.name = '{}' and chapter.chapter_num = {} and verse.verse_num = {}\norder by\n word.clause_atom_number\n;\n\"\"\".format(\n bk, ch, vs\n )\n )\n if vr in passage_dbs\n else []\n )\n\n for (can,) in ca_data:\n clause_atoms.append(can)\n return clause_atoms\n\n\ndef get_blocks(\n vr,\n):\n \"\"\"get block info\n For each monad: to which block it belongs,\n for each block: book and chapter number of first word.\n Possibly there are gaps between books.\n \"\"\"\n if vr not in passage_dbs:\n return ([], {})\n book_monads = passage_dbs[vr].executesql(\n \"\"\"\nselect name, first_m, last_m from book\n;\n\"\"\"\n )\n chapter_monads = passage_dbs[vr].executesql(\n \"\"\"\nselect chapter_num, first_m, last_m from chapter\n;\n\"\"\"\n )\n m = -1\n cur_blk_f = None\n cur_blk_size = 0\n cur_bk_index = 0\n cur_ch_index = 0\n (cur_bk, cur_bk_f, cur_bk_l) = book_monads[cur_bk_index]\n (cur_ch, cur_ch_f, cur_ch_l) = chapter_monads[cur_ch_index]\n blocks = []\n block_mapping = {}\n\n def get_curpos_info(n):\n (cur_ch, cur_ch_f, cur_ch_l) = chapter_monads[cur_ch_index]\n chapter_len = cur_ch_l - cur_ch_f + 1\n fraction = float(n - cur_ch_f) / chapter_len\n rep = (\n \"{}.Z\".format(cur_ch)\n if n == cur_ch_l\n else \"{}.z\".format(cur_ch)\n if round(10 * fraction) == 10\n else \"{:0.1f}\".format(cur_ch + fraction)\n )\n return (cur_ch, rep)\n\n while True:\n m += 1\n if m > cur_bk_l:\n size = round((float(cur_blk_size) / BLOCK_SIZE) * 100)\n blocks.append((cur_bk, cur_blk_f, get_curpos_info(m - 1), size))\n cur_blk_size = 0\n cur_bk_index += 1\n if cur_bk_index >= len(book_monads):\n break\n else:\n (cur_bk, cur_bk_f, cur_bk_l) = book_monads[cur_bk_index]\n cur_ch_index += 1\n (cur_ch, cur_ch_f, cur_ch_l) = chapter_monads[cur_ch_index]\n cur_blk_f = get_curpos_info(m)\n if cur_blk_size == BLOCK_SIZE:\n blocks.append((cur_bk, cur_blk_f, get_curpos_info(m - 1), 100))\n cur_blk_size = 0\n if m > cur_ch_l:\n cur_ch_index += 1\n if cur_ch_index >= len(chapter_monads):\n break\n else:\n (cur_ch, cur_ch_f, cur_ch_l) = chapter_monads[cur_ch_index]\n if m < cur_bk_f:\n continue\n if m < cur_ch_f:\n continue\n if cur_blk_size == 0:\n cur_blk_f = get_curpos_info(m)\n block_mapping[m] = len(blocks)\n cur_blk_size += 1\n return (blocks, block_mapping)\n\n\ndef material():\n session.forget(response)\n mr = get_request_val(\"material\", \"\", \"mr\")\n qw = get_request_val(\"material\", \"\", \"qw\")\n vr = get_request_val(\"material\", \"\", \"version\")\n bk = get_request_val(\"material\", \"\", \"book\")\n ch = get_request_val(\"material\", \"\", \"chapter\")\n tp = get_request_val(\"material\", \"\", \"tp\")\n tr = get_request_val(\"material\", \"\", \"tr\")\n lang = get_request_val(\"material\", \"\", \"lang\")\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n (authorized, msg) = item_access_read(iidrep=iidrep)\n if not authorized:\n return dict(\n version=vr,\n mr=mr,\n qw=qw,\n msg=msg,\n hits=0,\n results=0,\n pages=0,\n page=0,\n pagelist=json.dumps([]),\n material=None,\n monads=json.dumps([]),\n )\n page = get_request_val(\"material\", \"\", \"page\")\n mrrep = \"m\" if mr == \"m\" else qw\n return from_cache(\n cache,\n \"verses_{}_{}_{}_{}_{}_{}_{}_\".format(\n vr,\n mrrep,\n bk if mr == \"m\" else iidrep,\n ch if mr == \"m\" else page,\n tp,\n tr,\n lang,\n ),\n lambda: material_c(vr, mr, qw, bk, iidrep, ch, page, tp, tr, lang),\n None,\n )\n\n\ndef material_c(vr, mr, qw, bk, iidrep, ch, page, tp, tr, lang):\n if mr == \"m\":\n (book, chapter) = getpassage()\n material = (\n Verses(passage_dbs, vr, mr, chapter=chapter[\"id\"], tp=tp, tr=tr, lang=lang)\n if chapter\n else None\n )\n result = dict(\n mr=mr,\n qw=qw,\n hits=0,\n msg=\"{} {} does not exist\".format(bk, ch) if not chapter else None,\n results=len(material.verses) if material else 0,\n pages=1,\n material=material,\n monads=json.dumps([]),\n )\n elif mr == \"r\":\n (iid, kw) = (None, None)\n if iidrep is not None:\n (iid, kw) = iid_decode(qw, iidrep)\n if iid is None:\n msg = \"No {} selected\".format(\n \"query\" if qw == \"q\" else \"word\" if qw == \"w\" else \"note set\"\n )\n result = dict(\n mr=mr,\n qw=qw,\n msg=msg,\n hits=0,\n results=0,\n pages=0,\n page=0,\n pagelist=json.dumps([]),\n material=None,\n monads=json.dumps([]),\n )\n else:\n (nmonads, monad_sets) = (\n load_q_hits(vr, iid)\n if qw == \"q\"\n else load_w_occs(vr, iid)\n if qw == \"w\"\n else load_n_notes(vr, iid, kw)\n )\n (nresults, npages, verses, monads) = get_pagination(vr, page, monad_sets)\n material = Verses(passage_dbs, vr, mr, verses, tp=tp, tr=tr, lang=lang)\n result = dict(\n mr=mr,\n qw=qw,\n msg=None,\n hits=nmonads,\n results=nresults,\n pages=npages,\n page=page,\n pagelist=json.dumps(pagelist(page, npages, 10)),\n material=material,\n monads=json.dumps(monads),\n )\n else:\n result = dict()\n return result\n\n\ndef verse():\n session.forget(response)\n msgs = []\n vr = get_request_val(\"material\", \"\", \"version\")\n bk = get_request_val(\"material\", \"\", \"book\")\n ch = get_request_val(\"material\", \"\", \"chapter\")\n vs = get_request_val(\"material\", \"\", \"verse\")\n tr = get_request_val(\"material\", \"\", \"tr\")\n\n if request.extension == \"json\":\n return from_cache(\n cache,\n \"versej_{}_{}_{}_{}_\".format(vr, bk, ch, vs),\n lambda: verse_simple(passage_dbs, vr, bk, ch, vs),\n None,\n )\n\n if vs is None:\n return dict(good=False, msgs=msgs)\n return from_cache(\n cache,\n \"verse_{}_{}_{}_{}_{}_\".format(vr, bk, ch, vs, tr),\n lambda: verse_c(vr, bk, ch, vs, tr, msgs),\n None,\n )\n\n\ndef verse_c(vr, bk, ch, vs, tr, msgs):\n material = Verse(\n passage_dbs,\n vr,\n bk,\n ch,\n vs,\n xml=None,\n word_data=None,\n tp=\"txt_il\",\n tr=tr,\n mr=None,\n )\n good = True\n if len(material.word_data) == 0:\n msgs.append((\"error\", \"{} {}:{} does not exist\".format(bk, ch, vs)))\n good = False\n result = dict(\n good=good,\n msgs=msgs,\n material=material,\n )\n return result\n\n\ndef cnotes():\n session.forget(response)\n myid = None\n msgs = []\n if auth.user:\n myid = auth.user.id\n logged_in = myid is not None\n vr = get_request_val(\"material\", \"\", \"version\")\n bk = get_request_val(\"material\", \"\", \"book\")\n ch = get_request_val(\"material\", \"\", \"chapter\")\n vs = get_request_val(\"material\", \"\", \"verse\")\n edit = check_bool(\"edit\")\n save = check_bool(\"save\")\n clause_atoms = from_cache(\n cache,\n \"clause_atoms_{}_{}_{}_{}_\".format(vr, bk, ch, vs),\n lambda: get_clause_atoms(vr, bk, ch, vs),\n None,\n )\n changed = False\n if save:\n changed = note_save(myid, vr, bk, ch, vs, clause_atoms, msgs)\n return cnotes_c(vr, bk, ch, vs, myid, clause_atoms, changed, msgs, logged_in, edit)\n\n\ndef cnotes_c(vr, bk, ch, vs, myid, clause_atoms, changed, msgs, logged_in, edit):\n condition = \"\"\"note.is_shared = 'T' or note.is_published = 'T' \"\"\"\n if myid is not None:\n condition += \"\"\" or note.created_by = {} \"\"\".format(myid)\n\n note_sql = \"\"\"\nselect\n note.id,\n note.created_by as uid,\n shebanq_web.auth_user.first_name as ufname,\n shebanq_web.auth_user.last_name as ulname,\n note.clause_atom,\n note.is_shared,\n note.is_published,\n note.published_on,\n note.status,\n note.keywords,\n note.ntext\nfrom note inner join shebanq_web.auth_user\non note.created_by = shebanq_web.auth_user.id\nwhere\n ({cond})\nand\n note.version = '{vr}'\nand\n note.book ='{bk}'\nand\n note.chapter = {ch}\nand\n note.verse = {vs}\norder by\n modified_on desc\n;\n\"\"\".format(\n cond=condition,\n vr=vr,\n bk=bk,\n ch=ch,\n vs=vs,\n )\n\n records = note_db.executesql(note_sql)\n users = {}\n nkey_index = {}\n notes_proto = collections.defaultdict(lambda: {})\n ca_users = collections.defaultdict(lambda: collections.OrderedDict())\n if myid is not None and edit:\n users[myid] = \"me\"\n for ca in clause_atoms:\n notes_proto[ca][myid] = [\n dict(\n uid=myid, nid=0, shared=True, pub=False, stat=\"o\", kw=\"\", ntxt=\"\"\n )\n ]\n ca_users[ca][myid] = None\n good = True\n if records is None:\n msgs.append(\n (\n \"error\",\n \"Cannot lookup notes for {} {}:{} in version {}\".format(\n bk, ch, vs, vr\n ),\n )\n )\n good = False\n elif len(records) == 0:\n msgs.append((\"warning\", \"No notes\"))\n else:\n for (\n nid,\n uid,\n ufname,\n ulname,\n ca,\n shared,\n pub,\n pub_on,\n status,\n keywords,\n ntext,\n ) in records:\n if (myid is None or (uid != myid) or not edit) and uid not in users:\n users[uid] = \"{} {}\".format(ufname, ulname)\n if uid not in ca_users[ca]:\n ca_users[ca][uid] = None\n pub = pub == \"T\"\n shared = pub or shared == \"T\"\n ro = (\n myid is None\n or uid != myid\n or not edit\n or (\n pub\n and pub_on is not None\n and (pub_on <= request.utcnow - PUBLISH_FREEZE)\n )\n )\n kws = keywords.strip().split()\n for k in kws:\n nkey_index[\"{} {}\".format(uid, k)] = iid_encode(\"n\", uid, kw=k)\n notes_proto.setdefault(ca, {}).setdefault(uid, []).append(\n dict(\n uid=uid,\n nid=nid,\n ro=ro,\n shared=shared,\n pub=pub,\n stat=status,\n kw=keywords,\n ntxt=ntext,\n )\n )\n notes = {}\n for ca in notes_proto:\n for uid in ca_users[ca]:\n notes.setdefault(ca, []).extend(notes_proto[ca][uid])\n\n return json.dumps(\n dict(\n good=good,\n changed=changed,\n msgs=msgs,\n users=users,\n notes=notes,\n nkey_index=nkey_index,\n logged_in=logged_in,\n )\n )\n\n\ndef note_save(myid, vr, bk, ch, vs, these_clause_atoms, msgs):\n if myid is None:\n msgs.append((\"error\", \"You have to be logged in when you save notes\"))\n return\n notes = (\n json.loads(request.post_vars.notes)\n if request.post_vars and request.post_vars.notes\n else []\n )\n (good, old_notes, upd_notes, new_notes, del_notes) = note_filter_notes(\n myid, notes, these_clause_atoms, msgs\n )\n\n updated = 0\n for nid in upd_notes:\n (shared, pub, stat, kw, ntxt) = upd_notes[nid]\n (o_shared, o_pub, o_stat, o_kw, o_ntxt) = old_notes[nid]\n extrafields = []\n if shared and not o_shared:\n extrafields.append(\",\\n\\tshared_on = '{}'\".format(request.utcnow))\n if not shared and o_shared:\n extrafields.append(\",\\n\\tshared_on = null\")\n if pub and not o_pub:\n extrafields.append(\",\\n\\tpublished_on = '{}'\".format(request.utcnow))\n if (not pub and o_pub):\n extrafields.append(\",\\n\\tpublished_on = null\")\n shared = \"'T'\" if shared else \"null\"\n pub = \"'T'\" if pub else \"null\"\n stat = \"o\" if stat not in {\"o\", \"*\", \"+\", \"?\", \"-\", \"!\"} else stat\n update_sql = \"\"\"\nupdate note\n set modified_on = '{}',\n is_shared = {},\n is_published = {},\n status = '{}',\n keywords = '{}',\n ntext = '{}'{}\nwhere id = {}\n;\n\"\"\".format(\n request.utcnow,\n shared,\n pub,\n stat,\n kw.replace(\"'\", \"''\"),\n ntxt.replace(\"'\", \"''\"),\n \"\".join(extrafields),\n nid,\n )\n note_db.executesql(update_sql)\n updated += 1\n if len(del_notes) > 0:\n del_sql = \"\"\"\ndelete from note where id in ({})\n;\n\"\"\".format(\n \",\".join(str(x) for x in del_notes)\n )\n note_db.executesql(del_sql)\n for canr in new_notes:\n (shared, pub, stat, kw, ntxt) = new_notes[canr]\n insert_sql = \"\"\"\ninsert into note\n(version, book, chapter, verse, clause_atom,\ncreated_by, created_on, modified_on,\nis_shared, shared_on, is_published, published_on,\nstatus, keywords, ntext)\nvalues\n('{}', '{}', {}, {}, {}, {}, '{}', '{}', {}, {}, {}, {}, '{}', '{}', '{}')\n;\n\"\"\".format(\n vr,\n bk,\n ch,\n vs,\n canr,\n myid,\n request.utcnow,\n request.utcnow,\n \"'T'\" if shared else \"null\",\n \"'{}'\".format(request.utcnow) if shared else \"null\",\n \"'T'\" if pub else \"null\",\n \"'{}'\".format(request.utcnow) if pub else \"null\",\n \"o\" if stat not in {\"o\", \"*\", \"+\", \"?\", \"-\", \"!\"} else stat,\n kw.replace(\"'\", \"''\"),\n ntxt.replace(\"'\", \"''\"),\n )\n note_db.executesql(insert_sql)\n\n changed = False\n if len(del_notes) > 0:\n msgs.append((\"special\", \"Deleted notes: {}\".format(len(del_notes))))\n if updated > 0:\n msgs.append((\"special\", \"Updated notes: {}\".format(updated)))\n if len(new_notes) > 0:\n msgs.append((\"special\", \"Added notes: {}\".format(len(new_notes))))\n if len(del_notes) + len(new_notes) + updated == 0:\n msgs.append((\"warning\", \"No changes\"))\n else:\n changed = True\n clear_cache(cache, r\"^items_n_{}_{}_{}_\".format(vr, bk, ch))\n if len(new_notes):\n for kw in {new_notes[canr][3] for canr in new_notes}:\n clear_cache(\n cache,\n r\"^verses_{}_{}_{}_\".format(vr, \"n\", iid_encode(\"n\", myid, kw=kw))\n )\n if len(del_notes):\n for nid in del_notes:\n if nid in old_notes:\n kw = old_notes[nid][3]\n clear_cache(\n cache,\n r\"^verses_{}_{}_{}_\".format(\n vr, \"n\", iid_encode(\"n\", myid, kw=kw)\n )\n )\n return changed\n\n\ndef note_filter_notes(myid, notes, these_clause_atoms, msgs):\n good = True\n other_user_notes = set()\n missing_notes = set()\n extra_notes = set()\n same_notes = set()\n clause_errors = set()\n emptynew = 0\n old_notes = {}\n upd_notes = {}\n new_notes = {}\n del_notes = set()\n for fields in notes:\n nid = int(fields[\"nid\"])\n uid = int(fields[\"uid\"])\n canr = int(fields[\"canr\"])\n if uid != myid:\n other_user_notes.add(nid)\n good = False\n continue\n if canr not in these_clause_atoms:\n clause_errors.add(nid)\n good = False\n continue\n kw = \"\".join(\" \" + k + \" \" for k in fields[\"kw\"].strip().split())\n ntxt = fields[\"ntxt\"].strip()\n if kw == \"\" and ntxt == \"\":\n if nid == 0:\n emptynew += 1\n else:\n del_notes.add(nid)\n continue\n if nid != 0:\n upd_notes[nid] = (fields[\"shared\"], fields[\"pub\"], fields[\"stat\"], kw, ntxt)\n else:\n new_notes[fields[\"canr\"]] = (\n fields[\"shared\"],\n fields[\"pub\"],\n fields[\"stat\"],\n kw,\n ntxt,\n )\n if len(upd_notes) > 0 or len(del_notes) > 0:\n old_sql = \"\"\"\nselect id, created_by, is_shared, is_published, status, keywords, ntext\nfrom note where id in ({})\n;\n\"\"\".format(\n \",\".join(str(x) for x in (set(upd_notes.keys()) | del_notes))\n )\n cresult = note_db.executesql(old_sql)\n if cresult is not None:\n for (nid, uid, o_shared, o_pub, o_stat, o_kw, o_ntxt) in cresult:\n remove = False\n if uid != myid:\n other_user_notes.add(nid)\n remove = True\n elif nid not in upd_notes and nid not in del_notes:\n extra_notes.add(nid)\n remove = True\n elif nid in upd_notes:\n (shared, pub, stat, kw, ntxt) = upd_notes[nid]\n if not shared:\n shared = None\n if not pub:\n pub = None\n if (\n o_stat == stat\n and o_kw == kw\n and o_ntxt == ntxt\n and o_shared == shared\n and o_pub == pub\n ):\n same_notes.add(nid)\n if nid not in del_notes:\n remove = True\n if remove:\n if nid in upd_notes:\n del upd_notes[nid]\n if nid in del_notes:\n del_notes.remove(nid)\n else:\n old_notes[nid] = (o_shared, o_pub, o_stat, o_kw, o_ntxt)\n to_remove = set()\n for nid in upd_notes:\n if nid not in old_notes:\n if nid not in other_user_notes:\n missing_notes.add(nid)\n to_remove.add(nid)\n for nid in to_remove:\n del upd_notes[nid]\n to_remove = set()\n for nid in del_notes:\n if nid not in old_notes:\n if nid not in other_user_notes:\n missing_notes.add(nid)\n to_remove.add(nid)\n for nid in to_remove:\n del_notes.remove(nid)\n if len(other_user_notes) > 0:\n msgs.append(\n (\"error\", \"Notes of other users skipped: {}\".format(len(other_user_notes)))\n )\n if len(missing_notes) > 0:\n msgs.append((\"error\", \"Non-existing notes: {}\".format(len(missing_notes))))\n if len(extra_notes) > 0:\n msgs.append((\"error\", \"Notes not shown: {}\".format(len(extra_notes))))\n if len(clause_errors) > 0:\n msgs.append(\n (\"error\", \"Notes referring to wrong clause: {}\".format(len(clause_errors)))\n )\n if len(same_notes) > 0:\n pass\n # msgs.append(('info', 'Unchanged notes: {}'.format(len(same_notes))))\n if emptynew > 0:\n pass\n # msgs.append(('info', 'Skipped empty new notes: {}'.format(emptynew)))\n return (good, old_notes, upd_notes, new_notes, del_notes)\n\n\ndef sidem():\n session.forget(response)\n vr = get_request_val(\"material\", \"\", \"version\")\n qw = get_request_val(\"material\", \"\", \"qw\")\n bk = get_request_val(\"material\", \"\", \"book\")\n ch = get_request_val(\"material\", \"\", \"chapter\")\n pub = get_request_val(\"highlights\", qw, \"pub\") if qw != \"w\" else \"\"\n return from_cache(\n cache,\n \"items_{}_{}_{}_{}_{}_\".format(qw, vr, bk, ch, pub),\n lambda: sidem_c(vr, qw, bk, ch, pub),\n None,\n )\n\n\ndef sidem_c(vr, qw, bk, ch, pub):\n (book, chapter) = getpassage()\n if not chapter:\n result = dict(\n colorpicker=colorpicker,\n side_items=[],\n qw=qw,\n )\n else:\n if qw == \"q\":\n monad_sets = get_q_hits(vr, chapter, pub)\n side_items = groupq(vr, monad_sets)\n elif qw == \"w\":\n monad_sets = get_w_occs(vr, chapter)\n side_items = groupw(vr, monad_sets)\n elif qw == \"n\":\n side_items = get_notes(vr, book, chapter, pub)\n else:\n side_items = []\n result = dict(\n colorpicker=colorpicker,\n side_items=side_items,\n qw=qw,\n )\n return result\n\n\ndef query():\n session.forget(response)\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n request.vars[\"mr\"] = \"r\"\n request.vars[\"qw\"] = \"q\"\n if request.extension == \"json\":\n (authorized, msg) = item_access_read(iidrep=iidrep)\n if not authorized:\n result = dict(good=False, msg=[msg], data={})\n else:\n vr = get_request_val(\"material\", \"\", \"version\")\n msgs = []\n (iid, kw) = iid_decode(\"q\", iidrep)\n qrecord = get_query_info(\n False, iid, vr, msgs, with_ids=False, single_version=False, po=True\n )\n result = dict(good=qrecord is not None, msg=msgs, data=qrecord)\n return dict(data=json.dumps(result))\n else:\n request.vars[\"page\"] = 1\n return text()\n\n\ndef word():\n session.forget(response)\n request.vars[\"mr\"] = \"r\"\n request.vars[\"qw\"] = \"w\"\n request.vars[\"page\"] = 1\n return text()\n\n\ndef note():\n session.forget(response)\n request.vars[\"mr\"] = \"r\"\n request.vars[\"qw\"] = \"n\"\n request.vars[\"page\"] = 1\n return text()\n\n\ndef csv(\n data,\n):\n \"\"\"converts an data structure of rows and fields into a csv string.\n With proper quotations and escapes\n \"\"\"\n result = []\n if data is not None:\n for row in data:\n prow = [str(x) for x in row]\n trow = [\n '\"{}\"'.format(x.replace('\"', '\"\"')) if '\"' in x or \",\" in x else x\n for x in prow\n ]\n result.append(\n (\",\".join(trow)).replace(\"\\n\", \" \").replace(\"\\r\", \" \")\n ) # no newlines in fields, it is impractical\n return \"\\n\".join(result)\n\n\ndef item():\n \"\"\"controller to produce a csv file of query results or lexeme occurrences\n Where fields are specified in the current legend\n \"\"\"\n session.forget(response)\n vr = get_request_val(\"material\", \"\", \"version\")\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n qw = get_request_val(\"material\", \"\", \"qw\")\n tp = get_request_val(\"material\", \"\", \"tp\")\n extra = get_request_val(\"rest\", \"\", \"extra\")\n if extra:\n extra = \"_\" + extra\n if len(extra) > 64:\n extra = extra[0:64]\n (iid, kw) = iid_decode(qw, iidrep)\n iidrep2 = iid_decode(qw, iidrep, rsep=\" \")\n filename = \"{}_{}{}_{}{}.csv\".format(\n vr, style[qw][\"t\"], iidrep2, tp_labels[tp], extra\n )\n (authorized, msg) = item_access_read(iidrep=iidrep)\n if not authorized:\n return dict(filename=filename, data=msg)\n hfields = get_fields(tp, qw=qw)\n if qw != \"n\":\n head_row = [\"book\", \"chapter\", \"verse\"] + [hf[1] for hf in hfields]\n (nmonads, monad_sets) = (\n load_q_hits(vr, iid) if qw == \"q\" else load_w_occs(vr, iid)\n )\n monads = flatten(monad_sets)\n data = []\n if len(monads):\n sql = \"\"\"\nselect\n book.name, chapter.chapter_num, verse.verse_num,\n {hflist}\nfrom word\ninner join word_verse on\n word_verse.anchor = word.word_number\ninner join verse on\n verse.id = word_verse.verse_id\ninner join chapter on\n verse.chapter_id = chapter.id\ninner join book on\n chapter.book_id = book.id\nwhere\n word.word_number in ({monads})\norder by\n word.word_number\n;\n\"\"\".format(\n hflist=\", \".join(\"word.{}\".format(hf[0]) for hf in hfields),\n monads=\",\".join(str(x) for x in monads),\n )\n data = passage_dbs[vr].executesql(sql) if vr in passage_dbs else []\n else:\n head_row = [\"book\", \"chapter\", \"verse\"] + [hf[1] for hf in hfields]\n kw_sql = kw.replace(\"'\", \"''\")\n myid = auth.user.id if auth.user is not None else None\n extra = \"\"\" or created_by = {} \"\"\".format(uid) if myid == iid else \"\"\n sql = \"\"\"\nselect\n shebanq_note.note.book, shebanq_note.note.chapter, shebanq_note.note.verse,\n {hflist}\nfrom shebanq_note.note\ninner join book on shebanq_note.note.book = book.name\ninner join clause_atom on clause_atom.ca_num = shebanq_note.note.clause_atom\n and clause_atom.book_id = book.id\nwhere shebanq_note.note.keywords like '% {kw} %'\n and shebanq_note.note.version = '{vr}' and (shebanq_note.note.is_shared = 'T' {ex})\n;\n\"\"\".format(\n hflist=\", \".join(hf[0] for hf in hfields),\n kw=kw_sql,\n vr=vr,\n ex=extra,\n )\n data = passage_dbs[vr].executesql(sql) if vr in passage_dbs else []\n return dict(filename=filename, data=csv([head_row] + list(data)))\n\n\ndef chart(): # controller to produce a chart of query results or lexeme occurrences\n session.forget(response)\n vr = get_request_val(\"material\", \"\", \"version\")\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n qw = get_request_val(\"material\", \"\", \"qw\")\n (authorized, msg) = item_access_read(iidrep=iidrep)\n if not authorized:\n result = get_chart(vr, [])\n result.update(qw=qw)\n return result\n return from_cache(\n cache,\n \"chart_{}_{}_{}_\".format(vr, qw, iidrep),\n lambda: chart_c(vr, qw, iidrep),\n None,\n )\n\n\ndef chart_c(vr, qw, iidrep):\n (iid, kw) = iid_decode(qw, iidrep)\n (nmonads, monad_sets) = (\n load_q_hits(vr, iid)\n if qw == \"q\"\n else load_w_occs(vr, iid)\n if qw == \"w\"\n else load_n_notes(vr, iid, kw)\n )\n result = get_chart(vr, monad_sets)\n result.update(qw=qw)\n return result\n\n\ndef sideqm():\n session.forget(response)\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n vr = get_request_val(\"material\", \"\", \"version\")\n (authorized, msg) = item_access_read(iidrep=iidrep)\n if authorized:\n msg = \"fetching query\"\n return dict(\n load=LOAD(\n \"hebrew\",\n \"sideq\",\n extension=\"load\",\n vars=dict(mr=\"r\", qw=\"q\", version=vr, iid=iidrep),\n ajax=False,\n ajax_trap=True,\n target=\"querybody\",\n content=msg,\n )\n )\n\n\ndef sidewm():\n session.forget(response)\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n vr = get_request_val(\"material\", \"\", \"version\")\n (authorized, msg) = item_access_read(iidrep=iidrep)\n if authorized:\n msg = \"fetching word\"\n return dict(\n load=LOAD(\n \"hebrew\",\n \"sidew\",\n extension=\"load\",\n vars=dict(mr=\"r\", qw=\"w\", version=vr, iid=iidrep),\n ajax=False,\n ajax_trap=True,\n target=\"wordbody\",\n content=msg,\n )\n )\n\n\ndef sidenm():\n session.forget(response)\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n vr = get_request_val(\"material\", \"\", \"version\")\n msg = \"Not a valid id {}\".format(iidrep)\n if iidrep:\n msg = \"fetching note set\"\n return dict(\n load=LOAD(\n \"hebrew\",\n \"siden\",\n extension=\"load\",\n vars=dict(mr=\"r\", qw=\"n\", version=vr, iid=iidrep),\n ajax=False,\n ajax_trap=True,\n target=\"notebody\",\n content=msg,\n )\n )\n\n\ndef sideq():\n session.forget(response)\n if not request.ajax:\n redirect(URL(\"hebrew\", \"query\", extension=\"\", vars=request.vars))\n msgs = []\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n vr = get_request_val(\"material\", \"\", \"version\")\n (iid, kw) = iid_decode(\"q\", iidrep)\n (authorized, msg) = query_auth_read(iid)\n if iid == 0 or not authorized:\n msgs.append((\"error\", msg))\n return dict(\n writable=False,\n iidrep=iidrep,\n vr=vr,\n qr=dict(),\n q=json.dumps(dict()),\n msgs=json.dumps(msgs),\n oldeversions=set(emdros_versions[0:-1]),\n )\n q_record = get_query_info(\n auth.user is not None,\n iid,\n vr,\n msgs,\n with_ids=True,\n single_version=False,\n po=True,\n )\n if q_record is None:\n return dict(\n writable=True,\n iidrep=iidrep,\n vr=vr,\n qr=dict(),\n q=json.dumps(dict()),\n msgs=json.dumps(msgs),\n oldeversions=set(emdros_versions[0:-1]),\n )\n\n (authorized, msg) = query_auth_write(iid=iid)\n\n return dict(\n writable=authorized,\n iidrep=iidrep,\n vr=vr,\n qr=q_record,\n q=json.dumps(q_record),\n msgs=json.dumps(msgs),\n oldeversions=set(emdros_versions[0:-1]),\n )\n\n\ndef sidew():\n session.forget(response)\n if not request.ajax:\n redirect(URL(\"hebrew\", \"word\", extension=\"\", vars=request.vars))\n msgs = []\n vr = get_request_val(\"material\", \"\", \"version\")\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n (iid, kw) = iid_decode(\"w\", iidrep)\n (authorized, msg) = word_auth_read(vr, iid)\n if not authorized:\n msgs.append((\"error\", msg))\n return dict(\n wr=dict(),\n w=json.dumps(dict()),\n msgs=json.dumps(msgs),\n )\n w_record = get_word_info(iid, vr, msgs)\n return dict(\n vr=vr,\n wr=w_record,\n w=json.dumps(w_record),\n msgs=json.dumps(msgs),\n )\n\n\ndef siden():\n session.forget(response)\n if not request.ajax:\n redirect(URL(\"hebrew\", \"note\", extension=\"\", vars=request.vars))\n msgs = []\n vr = get_request_val(\"material\", \"\", \"version\")\n iidrep = get_request_val(\"material\", \"\", \"iid\")\n (iid, kw) = iid_decode(\"n\", iidrep)\n if not iid:\n msg = \"Not a valid id {}\".format(iid)\n msgs.append((\"error\", msg))\n return dict(\n nr=dict(),\n n=json.dumps(dict()),\n msgs=json.dumps(msgs),\n )\n n_record = get_note_info(iidrep, vr, msgs)\n return dict(\n vr=vr,\n nr=n_record,\n n=json.dumps(n_record),\n msgs=json.dumps(msgs),\n )\n\n\ndef words():\n session.forget(response)\n viewsettings = Viewsettings(cache, passage_dbs, URL, versions)\n vr = get_request_val(\"material\", \"\", \"version\", default=False)\n if not vr:\n vr = viewsettings.theversion()\n lan = get_request_val(\"rest\", \"\", \"lan\")\n letter = get_request_val(\"rest\", \"\", \"letter\")\n return from_cache(\n cache,\n \"words_page_{}_{}_{}_\".format(vr, lan, letter),\n lambda: words_page(viewsettings, vr, lan, letter),\n None,\n )\n\n\ndef queries():\n session.forget(response)\n msgs = []\n qid = check_id(\"goto\", \"q\", \"query\", msgs)\n if qid is not None:\n if not query_auth_read(qid):\n qid = 0\n return dict(\n viewsettings=Viewsettings(cache, passage_dbs, URL, versions),\n qid=qid,\n )\n\n\ndef notes():\n session.forget(response)\n msgs = []\n nkid = check_id(\"goto\", \"n\", \"note\", msgs)\n (may_upload, myid) = check_upload()\n return dict(\n viewsettings=Viewsettings(cache, passage_dbs, URL, versions),\n nkid=nkid, may_upload=may_upload, uid=myid\n )\n\n\ndef check_upload(no_controller=True):\n myid = None\n may_upload = False\n if auth.user:\n myid = auth.user.id\n if myid:\n sql = \"\"\"\nselect uid from uploaders where uid = {}\n \"\"\".format(\n myid\n )\n records = db.executesql(sql)\n may_upload = records is not None and len(records) == 1 and records[0][0] == myid\n return (may_upload, myid)\n\n\n@auth.requires_login()\ndef note_upload():\n session.forget(response)\n msgs = []\n good = True\n uid = request.vars.uid\n (may_upload, myid) = check_upload()\n if may_upload and str(myid) == uid:\n good = load_notes(myid, request.vars.file, msgs)\n else:\n good = False\n msgs.append([\"error\", \"you are not allowed to upload notes as csv files\"])\n return dict(data=json.dumps(dict(msgs=msgs, good=good)))\n\n\ndef load_notes(uid, filetext, msgs):\n my_versions = set()\n book_info = {}\n for vr in versions:\n if versions[vr][\"present\"]:\n my_versions.add(vr)\n book_info[vr] = from_cache(\n cache,\n \"books_{}_\".format(vr), lambda: get_books(passage_dbs, vr), None\n )[0]\n normative_fields = \"\\t\".join(\n \"\"\"\n version\n book\n chapter\n verse\n clause_atom\n is_shared\n is_published\n status\n keywords\n ntext\n \"\"\".strip().split()\n )\n good = True\n fieldnames = normative_fields.split(\"\\t\")\n nfields = len(fieldnames)\n errors = {}\n allKeywords = set()\n allVersions = set()\n now = request.utcnow\n created_on = now\n modified_on = now\n\n nerrors = 0\n chunks = []\n chunksize = 100\n sqlhead = \"\"\"\ninsert into note\n({}, created_by, created_on, modified_on, shared_on, published_on, bulk) values\n\"\"\".format(\n \", \".join(fieldnames)\n )\n\n this_chunk = []\n this_i = 0\n # for (i, linenl) in enumerate(str(filetext.value, encoding=\"utf8\").split(\"\\n\")):\n # for (i, linenl) in enumerate(filetext.value.split(\"\\n\")):\n for (i, linenl) in enumerate(filetext.value.decode(\"utf8\").split(\"\\n\")):\n line = linenl.rstrip()\n if line == \"\":\n continue\n if i == 0:\n if line != normative_fields:\n msgs.append(\n [\n \"error\",\n \"Wrong fields: {}. Required fields are {}\".format(\n line, normative_fields\n ),\n ]\n )\n good = False\n break\n continue\n fields = line.replace(\"'\", \"''\").split(\"\\t\")\n if len(fields) != nfields:\n nerrors += 1\n errors.setdefault(\"wrong number of fields\", []).append(i + 1)\n continue\n (\n version,\n book,\n chapter,\n verse,\n clause_atom,\n is_shared,\n is_published,\n status,\n keywords,\n ntext,\n ) = fields\n published_on = \"NULL\"\n shared_on = \"NULL\"\n if version not in my_versions:\n nerrors += 1\n errors.setdefault(\"unrecognized version\", []).append(\n \"{}:{}\".format(i + 1, version)\n )\n continue\n books = book_info[version]\n if book not in books:\n nerrors += 1\n errors.setdefault(\"unrecognized book\", []).append(\n \"{}:{}\".format(i + 1, book)\n )\n continue\n max_chapter = books[book]\n if not chapter.isdigit() or int(chapter) > max_chapter:\n nerrors += 1\n errors.setdefault(\"unrecognized chapter\", []).append(\n \"{}:{}\".format(i + 1, chapter)\n )\n continue\n if not verse.isdigit() or int(verse) > 200:\n nerrors += 1\n errors.setdefault(\"unrecognized verse\", []).append(\n \"{}:{}\".format(i + 1, verse)\n )\n continue\n if not clause_atom.isdigit() or int(clause_atom) > 100000:\n nerrors += 1\n errors.setdefault(\"unrecognized clause_atom\", []).append(\n \"{}:{}\".format(i + 1, clause_atom)\n )\n continue\n if is_shared not in {\"T\", \"\"}:\n nerrors += 1\n errors.setdefault(\"unrecognized shared field\", []).append(\n \"{}:{}\".format(i + 1, is_shared)\n )\n continue\n if is_published not in {\"T\", \"\"}:\n nerrors += 1\n errors.setdefault(\"unrecognized published field\", []).append(\n \"{}:{}\".format(i + 1, is_published)\n )\n continue\n if status not in nt_statclass:\n nerrors += 1\n errors.setdefault(\"unrecognized status\", []).append(\n \"{}:{}\".format(i + 1, status)\n )\n continue\n if len(keywords) >= 128:\n nerrors += 1\n errors.setdefault(\"keywords length over 128\", []).append(\n \"{}:{}\".format(i + 1, len(keywords))\n )\n continue\n if len(ntext) >= 1024:\n nerrors += 1\n errors.setdefault(\"note text length over 1024\", []).append(\n \"{}:{}\".format(i + 1, len(ntext))\n )\n continue\n if nerrors > 20:\n msgs.append([\"error\", \"too many errors, aborting\"])\n break\n if is_shared == \"T\":\n shared_on = \"'{}'\".format(now)\n if is_published == \"T\":\n published_on = \"'{}'\".format(now)\n keywordList = keywords.split()\n if len(keywordList) == 0:\n errors.setdefault(\"empty keyword\", []).append(\n '{}:\"{}\"'.format(i + 1, keywords)\n )\n continue\n allKeywords |= set(keywordList)\n keywords = \"\".join(\" {} \".format(x) for x in keywordList)\n allVersions.add(version)\n this_chunk.append(\n (\n \"('{}','{}',{},{},{},'{}','{}','{}',\"\n \"'{}','{}',{},'{}','{}',{},{},'b')\"\n ).format(\n version,\n book,\n chapter,\n verse,\n clause_atom,\n is_shared,\n is_published,\n status,\n keywords,\n ntext,\n uid,\n created_on,\n modified_on,\n shared_on,\n published_on,\n )\n )\n this_i += 1\n if this_i >= chunksize:\n chunks.append(this_chunk)\n this_chunk = []\n this_i = 0\n if len(this_chunk):\n chunks.append(this_chunk)\n\n # with open('/tmp/xxx.txt', 'w') as fh:\n # for line in filetext.value:\n # fh.write(line)\n if errors or nerrors:\n good = False\n else:\n whereVersion = \"version in ('{}')\".format(\"', '\".join(allVersions))\n whereKeywords = \" or \".join(\n \" keywords like '% {} %' \".format(keyword) for keyword in keywordList\n )\n # first delete previously bulk uploaded notes by this author\n # and with these keywords and these versions\n delSql = \"\"\"delete from note\n where bulk = 'b' and created_by = {} and {} and {};\"\"\".format(\n uid, whereVersion, whereKeywords\n )\n note_db.executesql(delSql)\n for chunk in chunks:\n sql = \"{} {};\".format(sqlhead, \",\\n\".join(chunk))\n note_db.executesql(sql)\n clear_cache(cache, r\"^items_n_\")\n for vr in my_versions:\n clear_cache(cache, r\"^verses_{}_n_\".format(vr))\n for msg in sorted(errors):\n msgs.append(\n [\"error\", \"{}: {}\".format(msg, \",\".join(str(i) for i in errors[msg]))]\n )\n msgs.append([\"good\" if good else \"error\", \"Done\"])\n return True\n\n\ndef words_page(viewsettings, vr, lan=None, letter=None):\n (letters, words) = from_cache(\n cache,\n \"words_data_{}_\".format(vr), lambda: get_words_data(vr), None\n )\n version = viewsettings.versionstate()\n\n return dict(\n version=version,\n viewsettings=viewsettings,\n lan=lan,\n letter=letter,\n letters=letters,\n words=words.get(lan, {}).get(letter, []),\n )\n\n\n# the query was:\n#\n# select id, entry_heb, entryid_heb, lan, gloss from lexicon order by lan, entryid_heb\n#\n# normal sorting is not good enough: the pointed shin and sin turn out after the tav\n# I will sort with key entryid_heb where every pointed shin/sin\n# is preceded by an unpointed one.\n# The unpointed one does turn up in the right place.\n\n\ndef heb_key(x):\n return x.replace(\"שׁ\", \"ששׁ\").replace(\"שׂ\", \"ששׂ\")\n\n\ndef get_words_data(vr):\n if vr not in passage_dbs:\n return ({}, {})\n ddata = sorted(\n passage_dbs[vr].executesql(\n \"\"\"\nselect id, entry_heb, entryid_heb, lan, gloss from lexicon\n;\n\"\"\"\n ),\n key=lambda x: (x[3], heb_key(x[2])),\n )\n letters = dict(arc=[], hbo=[])\n words = dict(arc={}, hbo={})\n for (wid, e, eid, lan, gloss) in ddata:\n letter = ord(e[0])\n if letter not in words[lan]:\n letters[lan].append(letter)\n words[lan][letter] = []\n words[lan][letter].append((e, wid, eid, gloss))\n return (letters, words)\n\n\ndef get_word_info(iid, vr, msgs):\n sql = \"\"\"\nselect * from lexicon where id = '{}'\n;\n\"\"\".format(\n iid\n )\n w_record = dict(id=iid, versions={})\n for v in versions:\n if not versions[v][\"present\"]:\n continue\n records = passage_dbs[v].executesql(sql, as_dict=True)\n if records is None:\n msgs.append(\n (\"error\", \"Cannot lookup word with id {} in version {}\".format(iid, v))\n )\n elif len(records) == 0:\n msgs.append((\"warning\", \"No word with id {} in version {}\".format(iid, v)))\n else:\n w_record[\"versions\"][v] = records[0]\n return w_record\n\n\ndef get_note_info(iidrep, vr, msgs):\n (iid, kw) = iid_decode(\"n\", iidrep)\n if iid is None:\n return {}\n n_record = dict(id=iidrep, uid=iid, ufname=\"N?\", ulname=\"N?\", kw=kw, versions={})\n n_record[\"versions\"] = count_n_notes(iid, kw)\n sql = \"\"\"\nselect first_name, last_name from auth_user where id = '{}'\n;\n\"\"\".format(\n iid\n )\n uinfo = db.executesql(sql)\n if uinfo is not None and len(uinfo) > 0:\n n_record[\"ufname\"] = uinfo[0][0]\n n_record[\"ulname\"] = uinfo[0][1]\n return n_record\n\n\ndef get_query_info(\n show_private_fields, iid, vr, msgs, single_version=False, with_ids=True, po=False\n):\n sqli = (\n \"\"\",\n query.created_by as uid,\n project.id as pid,\n organization.id as oid\n\"\"\"\n if with_ids and po\n else \"\"\n )\n\n sqlx = (\n \"\"\",\n query_exe.id as xid,\n query_exe.mql as mql,\n query_exe.version as version,\n query_exe.eversion as eversion,\n query_exe.resultmonads as resultmonads,\n query_exe.results as results,\n query_exe.executed_on as executed_on,\n query_exe.modified_on as xmodified_on,\n query_exe.is_published as is_published,\n query_exe.published_on as published_on\n\"\"\"\n if single_version\n else \"\"\n )\n\n sqlp = (\n \"\"\",\n project.name as pname,\n project.website as pwebsite,\n organization.name as oname,\n organization.website as owebsite\n\"\"\"\n if po\n else \"\"\n )\n\n sqlb = (\n \"\"\",\n auth_user.email as uemail\n\"\"\"\n if show_private_fields\n else \"\"\",\n 'n.n@not.disclosed' as uemail\n\"\"\"\n )\n\n sqlm = \"\"\"\n query.id as id,\n query.name as name,\n query.description as description,\n query.created_on as created_on,\n query.modified_on as modified_on,\n query.is_shared as is_shared,\n query.shared_on as shared_on,\n auth_user.first_name as ufname,\n auth_user.last_name as ulname\n {}{}{}{}\n\"\"\".format(\n sqlb, sqli, sqlp, sqlx\n )\n\n sqlr = (\n \"\"\"\ninner join query_exe on query_exe.query_id = query.id and query_exe.version = '{}'\n\"\"\".format(\n vr\n )\n if single_version\n else \"\"\n )\n\n sqlpr = (\n \"\"\"\ninner join organization on query.organization = organization.id\ninner join project on query.project = project.id\n\"\"\"\n if po\n else \"\"\n )\n\n sqlc = (\n \"\"\"\nwhere query.id in ({})\n\"\"\".format(\n \",\".join(iid)\n )\n if single_version\n else \"\"\"\nwhere query.id = {}\n\"\"\".format(\n iid\n )\n )\n\n sqlo = (\n \"\"\"\norder by auth_user.last_name, query.name\n\"\"\"\n if single_version\n else \"\"\n )\n\n sql = \"\"\"\nselect{} from query inner join auth_user on query.created_by = auth_user.id {}{}{}{}\n;\n\"\"\".format(\n sqlm, sqlr, sqlpr, sqlc, sqlo\n )\n records = db.executesql(sql, as_dict=True)\n if records is None:\n msgs.append((\"error\", \"Cannot lookup query(ies)\"))\n return None\n if single_version:\n for q_record in records:\n query_fields(vr, q_record, [], single_version=True)\n return records\n else:\n if len(records) == 0:\n msgs.append((\"error\", \"No query with id {}\".format(iid)))\n return None\n q_record = records[0]\n q_record[\"description_md\"] = markdown(\n q_record[\"description\"] or \"\", output_format=\"xhtml5\"\n )\n sql = \"\"\"\nselect\n id as xid,\n mql,\n version,\n eversion,\n resultmonads,\n results,\n executed_on,\n modified_on as xmodified_on,\n is_published,\n published_on\nfrom query_exe\nwhere query_id = {}\n;\n\"\"\".format(\n iid\n )\n recordx = db.executesql(sql, as_dict=True)\n query_fields(vr, q_record, recordx, single_version=False)\n return q_record\n\n\ndef pagelist(page, pages, spread):\n factor = 1\n filtered_pages = {1, page, pages}\n while factor <= pages:\n page_base = factor * int(page / factor)\n filtered_pages |= {\n page_base + int((i - spread / 2) * factor)\n for i in range(2 * int(spread / 2) + 1)\n }\n factor *= spread\n return sorted(i for i in filtered_pages if i > 0 and i <= pages)\n\n\nRECENT_LIMIT = 50\n\n\ndef queriesr():\n session.forget(response)\n\n # The next query contains a clever idea from\n # http://stackoverflow.com/a/5657514\n # (http://stackoverflow.com/questions/5657446/mysql-query-max-group-by)\n # We want to find the most recent mql queries.\n # Queries may have multiple executions.\n # We want to have the queries with the most recent executions.\n # From such queries, we only want to have that one most recent executions.\n # This idea can be obtained by left outer joining the query_exe table\n # with itself (qe1 with qe2) # on the condition that the rows are combined\n # where qe1 and qe2 belong to the same query, and qe2 is more recent.\n # Rows in the combined table where qe2 is null, are such that qe1 is most recent.\n # This is the basic idea.\n # We then have to refine it: we only want shared queries.\n # That is an easy where condition on the final result.\n # We only want to have up-to-date queries.\n # So the join condition is not that qe2 is more recent,\n # but that qe2 is up-to-date and more recent.\n # And we need to add a where to express that qe1 is up to date.\n\n pqueryx_sql = \"\"\"\nselect\n query.id as qid,\n auth_user.first_name as ufname,\n auth_user.last_name as ulname,\n query.name as qname,\n qe.executed_on as qexe,\n qe.version as qver\nfrom query inner join\n (\n select qe1.query_id, qe1.executed_on, qe1.version\n from query_exe qe1\n left outer join query_exe qe2\n on (\n qe1.query_id = qe2.query_id and\n qe1.executed_on < qe2.executed_on and\n qe2.executed_on >= qe2.modified_on\n )\n where\n (qe1.executed_on is not null and qe1.executed_on >= qe1.modified_on) and\n qe2.query_id is null\n ) as qe\non qe.query_id = query.id\ninner join auth_user on query.created_by = auth_user.id\nwhere query.is_shared = 'T'\norder by qe.executed_on desc, auth_user.last_name\nlimit {};\n\"\"\".format(\n RECENT_LIMIT\n )\n\n pqueryx = db.executesql(pqueryx_sql)\n pqueries = []\n for (qid, ufname, ulname, qname, qexe, qver) in pqueryx:\n text = h_esc(\"{} {}: {}\".format(ufname[0], ulname[0:9], qname[0:20]))\n title = h_esc(\"{} {}: {}\".format(ufname, ulname, qname))\n pqueries.append(dict(id=qid, text=text, title=title, version=qver))\n\n return dict(data=json.dumps(dict(queries=pqueries, msgs=[], good=True)))\n\n\ndef query_tree():\n session.forget(response)\n myid = None\n if auth.user:\n myid = auth.user.id\n linfo = collections.defaultdict(lambda: {})\n\n def title_badge(lid, ltype, publ, good, num, tot):\n name = linfo[ltype][lid] if ltype is not None else \"Shared Queries\"\n nums = []\n if publ != 0:\n nums.append(\n ' {}'.format(publ)\n )\n if good != 0:\n nums.append(' {}'.format(good))\n badge = \"\"\n if len(nums) == 0:\n if tot == num:\n badge = '{}'.format(\", \".join(nums))\n else:\n badge = '{} of {}'.format(\n \", \".join(nums), tot\n )\n else:\n if tot == num:\n badge = '{} of {}'.format(\n \", \".join(nums), num\n )\n else:\n badge = '{} of {} of all {}'.format(\n \", \".join(nums), num, tot\n )\n rename = \"\"\n select = \"\"\n if ltype in {\"o\", \"p\"}:\n if myid is not None:\n if lid:\n rename = ''.format(\n ltype, lid\n )\n select = ''.format(\n ltype, lid\n )\n else:\n if lid:\n rename = ''.format(\n ltype, lid\n )\n return '{} {}({}) {}'.format(\n select, h_esc(name), badge, rename\n )\n\n condition = (\n \"\"\"\nwhere query.is_shared = 'T'\n\"\"\"\n if myid is None\n else \"\"\"\nwhere query.is_shared = 'T' or query.created_by = {}\n\"\"\".format(\n myid\n )\n )\n\n pqueryx_sql = \"\"\"\nselect\n query_exe.query_id,\n query_exe.version,\n query_exe.is_published,\n query_exe.published_on,\n query_exe.modified_on,\n query_exe.executed_on\nfrom query_exe\ninner join query on query.id = query_exe.query_id\n{};\n\"\"\".format(\n condition\n )\n\n pquery_sql = \"\"\"\nselect\n query.id as qid,\n organization.name as oname, organization.id as oid,\n project.name as pname, project.id as pid,\n concat(auth_user.first_name, ' ', auth_user.last_name) as uname,\n auth_user.id as uid,\n query.name as qname, query.is_shared as is_shared\nfrom query\ninner join organization on query.organization = organization.id\ninner join project on query.project = project.id\ninner join auth_user on query.created_by = auth_user.id\n{}\norder by organization.name,\nproject.name,\nauth_user.last_name,\nauth_user.first_name,\nquery.name\n;\n\"\"\".format(\n condition\n )\n\n pquery = db.executesql(pquery_sql)\n pqueryx = db.executesql(pqueryx_sql)\n pqueries = collections.OrderedDict()\n rversion_order = [v for v in version_order if versions[v][\"present\"]]\n rversion_index = dict((x[1], x[0]) for x in enumerate(rversion_order))\n for (qid, oname, oid, pname, pid, uname, uid, qname, qshared) in pquery:\n qsharedstatus = qshared == \"T\"\n qownstatus = uid == myid\n pqueries[qid] = {\n \"\": (oname, oid, pname, pid, uname, uid, qname, qsharedstatus, qownstatus),\n \"publ\": False,\n \"good\": False,\n \"v\": [4 for v in rversion_order],\n }\n for (qid, vr, qispub, qpub, qmod, qexe) in pqueryx:\n if vr not in rversion_index:\n continue\n qinfo = pqueries[qid]\n qexestatus = None\n if qexe:\n qexestatus = qexe >= qmod\n qpubstatus = (\n False\n if qispub != \"T\"\n else None\n if qpub > request.utcnow - PUBLISH_FREEZE\n else True\n )\n qstatus = (\n 1\n if qpubstatus\n else 2\n if qpubstatus is None\n else 3\n if qexestatus\n else 4\n if qexestatus is None\n else 5\n )\n qinfo[\"v\"][rversion_index[vr]] = qstatus\n if qpubstatus or qpubstatus is None:\n qinfo[\"publ\"] = True\n if qexestatus:\n qinfo[\"good\"] = True\n\n porg_sql = \"\"\"\nselect name, id from organization order by name\n;\n\"\"\"\n porg = db.executesql(porg_sql)\n\n pproj_sql = \"\"\"\nselect name, id from project order by name\n;\n\"\"\"\n pproj = db.executesql(pproj_sql)\n\n tree = collections.OrderedDict()\n countset = collections.defaultdict(lambda: set())\n counto = collections.defaultdict(lambda: 0)\n counto_publ = collections.defaultdict(lambda: 0)\n counto_good = collections.defaultdict(lambda: 0)\n counto_tot = collections.defaultdict(lambda: 0)\n countp = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\n countp_publ = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\n countp_good = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\n countp_tot = collections.defaultdict(lambda: 0)\n countu = collections.defaultdict(\n lambda: collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\n )\n countu_publ = collections.defaultdict(\n lambda: collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\n )\n countu_good = collections.defaultdict(\n lambda: collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\n )\n countu_tot = collections.defaultdict(lambda: 0)\n count = 0\n count_publ = 0\n count_good = 0\n for qid in pqueries:\n pqinfo = pqueries[qid]\n (oname, oid, pname, pid, uname, uid, qname, qshared, qown) = pqinfo[\"\"]\n qpubl = pqinfo[\"publ\"]\n qgood = pqinfo[\"good\"]\n countset[\"o\"].add(oid)\n countset[\"p\"].add(pid)\n countset[\"u\"].add(uid)\n countset[\"q\"].add(qid)\n linfo[\"o\"][oid] = oname\n linfo[\"p\"][pid] = pname\n linfo[\"u\"][uid] = uname\n if qown:\n countset[\"m\"].add(qid)\n if not qshared:\n countset[\"r\"].add(qid)\n if qpubl:\n countu_publ[oid][pid][uid] += 1\n countp_publ[oid][pid] += 1\n counto_publ[oid] += 1\n count_publ += 1\n if qgood:\n countu_good[oid][pid][uid] += 1\n countp_good[oid][pid] += 1\n counto_good[oid] += 1\n count_good += 1\n tree.setdefault(oid, collections.OrderedDict()).setdefault(\n pid, collections.OrderedDict()\n ).setdefault(uid, []).append(qid)\n count += 1\n counto[oid] += 1\n countp[oid][pid] += 1\n countu[oid][pid][uid] += 1\n counto_tot[oid] += 1\n countp_tot[pid] += 1\n countu_tot[uid] += 1\n\n linfo[\"o\"][0] = \"Projects without Queries\"\n linfo[\"p\"][0] = \"New Project\"\n linfo[\"u\"][0] = \"\"\n linfo[\"q\"] = pqueries\n counto[0] = 0\n countp[0][0] = 0\n for (oname, oid) in porg:\n if oid in linfo[\"o\"]:\n continue\n countset[\"o\"].add(oid)\n linfo[\"o\"][oid] = oname\n tree[oid] = collections.OrderedDict()\n\n for (pname, pid) in pproj:\n if pid in linfo[\"p\"]:\n continue\n countset[\"o\"].add(0)\n countset[\"p\"].add(pid)\n linfo[\"p\"][pid] = pname\n tree.setdefault(0, collections.OrderedDict())[pid] = collections.OrderedDict()\n\n ccount = dict((x[0], len(x[1])) for x in countset.items())\n ccount[\"uid\"] = myid\n title = title_badge(None, None, count_publ, count_good, count, count)\n dest = [dict(title=\"{}\".format(title), folder=True, children=[], data=ccount)]\n curdest = dest[-1][\"children\"]\n cursource = tree\n for oid in cursource:\n onum = counto[oid]\n opubl = counto_publ[oid]\n ogood = counto_good[oid]\n otot = counto_tot[oid]\n otitle = title_badge(oid, \"o\", opubl, ogood, onum, otot)\n curdest.append(dict(title=\"{}\".format(otitle), folder=True, children=[]))\n curodest = curdest[-1][\"children\"]\n curosource = cursource[oid]\n for pid in curosource:\n pnum = countp[oid][pid]\n ppubl = countp_publ[oid][pid]\n pgood = countp_good[oid][pid]\n ptot = countp_tot[pid]\n ptitle = title_badge(pid, \"p\", ppubl, pgood, pnum, ptot)\n curodest.append(dict(title=\"{}\".format(ptitle), folder=True, children=[]))\n curpdest = curodest[-1][\"children\"]\n curpsource = curosource[pid]\n for uid in curpsource:\n unum = countu[oid][pid][uid]\n upubl = countu_publ[oid][pid][uid]\n ugood = countu_good[oid][pid][uid]\n utot = countu_tot[uid]\n utitle = title_badge(uid, \"u\", upubl, ugood, unum, utot)\n curpdest.append(\n dict(title=\"{}\".format(utitle), folder=True, children=[])\n )\n curudest = curpdest[-1][\"children\"]\n curusource = curpsource[uid]\n for qid in curusource:\n pqinfo = linfo[\"q\"][qid]\n (oname, oid, pname, pid, uname, uid, qname, qshared, qown) = pqinfo[\n \"\"\n ]\n qpubl = pqinfo[\"publ\"]\n qgood = pqinfo[\"good\"]\n qversions = pqinfo[\"v\"]\n rename = ''.format(\n \"r\" if qown else \"v\", \"q\", qid\n )\n curudest.append(\n dict(\n title=(\n '{} '\n '{} {}'\n ).format(\n \" \".join(\n formatversion(\n \"q\", qid, v, qversions[rversion_index[v]]\n )\n for v in rversion_order\n if v in rversion_index\n ),\n \"qmy\" if qown else \"\",\n \"\" if qshared else \"qpriv\",\n iid_encode(\"q\", qid),\n h_esc(qname),\n rename,\n ),\n key=\"q{}\".format(qid),\n folder=False,\n )\n )\n return dict(data=json.dumps(dest))\n\n\ndef note_tree():\n session.forget(response)\n myid = None\n if auth.user:\n myid = auth.user.id\n linfo = collections.defaultdict(lambda: {})\n\n def title_badge(lid, ltype, tot):\n name = linfo[ltype][lid] if ltype is not None else \"Shared Notes\"\n badge = \"\"\n if tot != 0:\n badge = ' {}'.format(tot)\n return '{}({})'.format(\n h_esc(name), badge\n )\n\n condition = (\n \"\"\"\nwhere note.is_shared = 'T'\n\"\"\"\n if myid is None\n else \"\"\"\nwhere note.is_shared = 'T' or note.created_by = {}\n\"\"\".format(\n myid\n )\n )\n\n pnote_sql = \"\"\"\nselect\n count(note.id) as amount,\n note.version,\n note.keywords,\n concat(auth_user.first_name, ' ', auth_user.last_name) as uname, auth_user.id as uid\nfrom note\ninner join shebanq_web.auth_user on note.created_by = shebanq_web.auth_user.id\n{}\ngroup by auth_user.id, note.keywords, note.version\norder by shebanq_web.auth_user.last_name,\nshebanq_web.auth_user.first_name, note.keywords\n;\n\"\"\".format(\n condition\n )\n\n pnote = note_db.executesql(pnote_sql)\n pnotes = collections.OrderedDict()\n rversion_order = [v for v in version_order if versions[v][\"present\"]]\n rversion_index = dict((x[1], x[0]) for x in enumerate(rversion_order))\n for (amount, nvr, kws, uname, uid) in pnote:\n if nvr not in rversion_index:\n continue\n for kw in set(kws.strip().split()):\n nkid = iid_encode(\"n\", uid, kw=kw)\n if nkid not in pnotes:\n pnotes[nkid] = {\"\": (uname, uid, kw), \"v\": [0 for v in rversion_order]}\n pnotes[nkid][\"v\"][rversion_index[nvr]] = amount\n\n tree = collections.OrderedDict()\n countset = collections.defaultdict(lambda: set())\n countu = collections.defaultdict(lambda: 0)\n count = 0\n for nkid in pnotes:\n pninfo = pnotes[nkid]\n (uname, uid, nname) = pninfo[\"\"]\n countset[\"u\"].add(uid)\n countset[\"n\"].add(nkid)\n linfo[\"u\"][uid] = uname\n tree.setdefault(uid, []).append(nkid)\n count += 1\n countu[uid] += 1\n\n linfo[\"u\"][0] = \"\"\n linfo[\"n\"] = pnotes\n\n ccount = dict((x[0], len(x[1])) for x in countset.items())\n ccount[\"uid\"] = myid\n title = title_badge(None, None, count)\n dest = [dict(title=\"{}\".format(title), folder=True, children=[], data=ccount)]\n curdest = dest[-1][\"children\"]\n cursource = tree\n for uid in cursource:\n utot = countu[uid]\n utitle = title_badge(uid, \"u\", utot)\n curdest.append(dict(title=\"{}\".format(utitle), folder=True, children=[]))\n curudest = curdest[-1][\"children\"]\n curusource = cursource[uid]\n for nkid in curusource:\n pninfo = linfo[\"n\"][nkid]\n (uname, uid, nname) = pninfo[\"\"]\n nversions = pninfo[\"v\"]\n curudest.append(\n dict(\n title=(\n '{} '\n '{} '\n ).format(\n \" \".join(\n formatversion(\"n\", nkid, v, nversions[rversion_index[v]])\n for v in rversion_order\n if v in rversion_index\n ),\n nkid,\n h_esc(nname),\n ),\n key=\"n{}\".format(nkid),\n folder=False,\n ),\n )\n return dict(data=json.dumps(dest))\n\n\ndef formatversion(qw, lid, vr, st):\n if qw == \"q\":\n if st == 1:\n icon = \"quote-right\"\n cls = \"special\"\n elif st == 2:\n icon = \"quote-right\"\n cls = \"\"\n elif st == 3:\n icon = \"gears\"\n cls = \"good\"\n elif st == 4:\n icon = \"circle-o\"\n cls = \"warning\"\n elif st == 5:\n icon = \"clock-o\"\n cls = \"error\"\n return (\n ''.format(\n qw, cls, icon, qw, lid, vr\n )\n )\n else:\n return '{}'.format(\n qw, lid, vr, st if st else \"-\"\n )\n\n\ntps = dict(\n o=(\"organization\", \"organization\"), p=(\"project\", \"project\"), q=(\"query\", \"query\")\n)\n\n\ndef check_unique(tp, lid, val, myid, msgs):\n result = False\n (label, table) = tps[tp]\n for x in [1]:\n if tp == \"q\":\n check_sql = \"\"\"\nselect id from query where name = '{}' and query.created_by = {}\n;\n\"\"\".format(\n val, myid\n )\n else:\n check_sql = \"\"\"\nselect id from {} where name = '{}'\n;\n\"\"\".format(\n table, val\n )\n try:\n ids = db.executesql(check_sql)\n except Exception:\n msgs.append(\n (\"error\", \"cannot check the unicity of {} as {}!\".format(val, label))\n )\n break\n if len(ids) and (lid == 0 or ids[0][0] != int(lid)):\n msgs.append((\"error\", \"the {} name is already taken!\".format(label)))\n break\n result = True\n return result\n\n\ndef check_name(tp, lid, myid, val, msgs):\n label = tps[tp][0]\n result = None\n for x in [1]:\n if len(val) > 64:\n msgs.append(\n (\n \"error\",\n \"{label} name is longer than 64 characters!\".format(label=label),\n )\n )\n break\n val = val.strip()\n if val == \"\":\n msgs.append(\n (\n \"error\",\n \"{label} name consists completely of white space!\".format(\n label=label\n ),\n )\n )\n break\n val = val.replace(\"'\", \"''\")\n if not check_unique(tp, lid, val, myid, msgs):\n break\n result = val\n return result\n\n\ndef check_description(tp, val, msgs):\n label = tps[tp][0]\n result = None\n for x in [1]:\n if len(val) > 8192:\n msgs.append(\n (\n \"error\",\n \"{label} description is longer than 8192 characters!\".format(\n label=label\n ),\n )\n )\n break\n result = val.replace(\"'\", \"''\")\n return result\n\n\ndef check_mql(tp, val, msgs):\n label = tps[tp][0]\n result = None\n for x in [1]:\n if len(val) > 8192:\n msgs.append(\n (\n \"error\",\n \"{label} mql is longer than 8192 characters!\".format(label=label),\n )\n )\n break\n result = val.replace(\"'\", \"''\")\n return result\n\n\ndef check_published(tp, val, msgs):\n label = tps[tp][0]\n result = None\n for x in [1]:\n if len(val) > 10 or (len(val) > 0 and not val.isalnum()):\n msgs.append(\n (\n \"error\",\n \"{} published status has an invalid value {}\".format(label, val),\n )\n )\n break\n result = \"T\" if val == \"T\" else \"\"\n return result\n\n\ndef check_website(tp, val, msgs):\n label = tps[tp][0]\n result = None\n for x in [1]:\n if len(val) > 512:\n msgs.append(\n (\n \"error\",\n \"{label} website is longer than 512 characters!\".format(\n label=label\n ),\n )\n )\n break\n val = val.strip()\n if val == \"\":\n msgs.append(\n (\n \"error\",\n \"{label} website consists completely of white space!\".format(\n label=label\n ),\n )\n )\n break\n try:\n url_comps = urlparse(val)\n except ValueError:\n msgs.append(\n (\"error\", \"invalid syntax in {label} website !\".format(label=label))\n )\n break\n scheme = url_comps.scheme\n if scheme not in {\"http\", \"https\"}:\n msgs.append(\n (\n \"error\",\n \"{label} website does not start with http(s)://\".format(\n label=label\n ),\n )\n )\n break\n netloc = url_comps.netloc\n if \".\" not in netloc:\n msgs.append(\n (\"error\", \"no location in {label} website\".format(label=label))\n )\n break\n result = urlunparse(url_comps).replace(\"'\", \"''\")\n return result\n\n\ndef check_int(var, label, msgs):\n val = request.vars[var]\n if val is None:\n msgs.append((\"error\", \"No {} number given\".format(label)))\n return None\n if len(val) > 10 or not val.isdigit():\n msgs.append((\"error\", \"Not a valid {} verse\".format(label)))\n return None\n return int(val)\n\n\ndef check_bool(var):\n val = request.vars[var]\n if (\n val is None\n or len(val) > 10\n or not val.isalpha()\n or val not in {\"true\", \"false\"}\n or val == \"false\"\n ):\n return False\n return True\n\n\ndef check_id(var, tp, label, msgs, valrep=None):\n if valrep is None:\n valrep = request.vars[var]\n if valrep is None:\n msgs.append((\"error\", \"No {} id given\".format(label)))\n return None\n if tp in {\"w\", \"q\", \"n\"}:\n (val, kw) = iid_decode(tp, valrep)\n else:\n val = valrep\n if len(valrep) > 10 or not valrep.isdigit():\n msgs.append((\"error\", \"Not a valid {} id\".format(label)))\n return None\n val = int(valrep)\n if tp == \"n\":\n return valrep\n return val\n\n\ndef check_rel(tp, val, msgs):\n (label, table) = tps[tp]\n result = None\n for x in [1]:\n check_sql = \"\"\"\nselect count(*) as occurs from {} where id = {}\n;\n\"\"\".format(\n table, val\n )\n try:\n occurs = db.executesql(check_sql)[0][0]\n except Exception:\n msgs.append(\n (\n \"error\",\n \"cannot check the occurrence of {} id {}!\".format(label, val),\n )\n )\n break\n if not occurs:\n if val == 0:\n msgs.append((\"error\", \"No {} chosen!\".format(label)))\n else:\n msgs.append((\"error\", \"There is no {} {}!\".format(label, val)))\n break\n result = val\n return result\n\n\ndef record():\n session.forget(response)\n msgs = []\n record = {}\n orecord = {}\n precord = {}\n good = False\n ogood = False\n pgood = False\n myid = auth.user.id if auth.user is not None else None\n for x in [1]:\n tp = request.vars.tp\n if tp not in tps:\n msgs.append((\"error\", \"unknown type {}!\".format(tp)))\n break\n (label, table) = tps[tp]\n lid = check_id(\"lid\", tp, label, msgs)\n upd = request.vars.upd\n if lid is None:\n break\n if upd not in {\"true\", \"false\"}:\n msgs.append((\"error\", \"invalid instruction {}!\".format(upd)))\n break\n upd = True if upd == \"true\" else False\n if upd and not myid:\n msgs.append((\"error\", \"for updating you have to be logged in!\"))\n break\n fields = [\"name\"]\n if tp == \"q\":\n fields.append(\"organization\")\n fields.append(\"project\")\n else:\n fields.append(\"website\")\n if upd:\n (authorized, msg) = (\n query_auth_write(lid) if tp == \"q\" else auth_write(label)\n )\n else:\n (authorized, msg) = query_auth_read(lid) if tp == \"q\" else auth_read(label)\n if not authorized:\n msgs.append((\"error\", msg))\n break\n if upd:\n fvalues = None\n if tp == \"q\":\n subfields = [\"name\", \"website\"]\n fvalues = [request.vars.name]\n do_new_o = request.vars.do_new_o\n do_new_p = request.vars.do_new_p\n if do_new_o not in {\"true\", \"false\"}:\n msgs.append(\n (\n \"error\",\n \"invalid instruction for organization {}!\".format(\n do_new_o\n ),\n )\n )\n break\n do_new_o = do_new_o == \"true\"\n if do_new_p not in {\"true\", \"false\"}:\n msgs.append(\n (\n \"error\",\n \"invalid instruction for project {}!\".format(do_new_p),\n )\n )\n break\n do_new_p = do_new_p == \"true\"\n ogood = True\n if do_new_o:\n (ogood, oid) = upd_record(\n \"o\",\n 0,\n myid,\n subfields,\n msgs,\n fvalues=[request.vars.oname, request.vars.owebsite],\n )\n if ogood:\n orecord = dict(\n id=oid,\n name=request.vars.oname,\n website=request.vars.owebsite,\n )\n else:\n oid = check_id(\"oid\", \"o\", tps[\"o\"][0], msgs)\n pgood = True\n if do_new_p:\n (pgood, pid) = upd_record(\n \"p\",\n 0,\n myid,\n subfields,\n msgs,\n fvalues=[request.vars.pname, request.vars.pwebsite],\n )\n if pgood:\n precord = dict(\n id=pid,\n name=request.vars.pname,\n website=request.vars.pwebsite,\n )\n else:\n pid = check_id(\"pid\", \"p\", tps[\"o\"][0], msgs)\n if not ogood or not pgood:\n break\n if oid is None or pid is None:\n break\n fvalues.extend([oid, pid])\n (good, new_lid) = upd_record(tp, lid, myid, fields, msgs, fvalues=fvalues)\n if not good:\n break\n lid = new_lid\n else:\n good = True\n dbrecord = None\n if tp == \"q\":\n if lid == 0:\n dbrecord = [0, \"\", 0, \"\", \"\", 0, \"\", \"\"]\n else:\n dbrecord = db.executesql(\n \"\"\"\nselect\nquery.id as id,\nquery.name as name,\norganization.id as oid,\norganization.name as oname,\norganization.website as owebsite,\nproject.id as pid,\nproject.name as pname,\nproject.website as pwebsite\nfrom query\ninner join organization on query.organization = organization.id\ninner join project on query.project = project.id\nwhere query.id = {}\n;\n\"\"\".format(\n lid\n ),\n as_dict=True,\n )\n else:\n if lid == 0:\n dbrecord = [0, \"\", \"\"]\n else:\n dbrecord = db.executesql(\n \"\"\"\nselect {} from {} where id = {}\n;\n\"\"\".format(\n \",\".join(fields), table, lid\n ),\n as_dict=True,\n )\n if not dbrecord:\n msgs.append((\"error\", \"No {} with id {}\".format(label, lid)))\n break\n record = dbrecord[0]\n return dict(\n data=json.dumps(\n dict(\n record=record,\n orecord=orecord,\n precord=precord,\n msgs=msgs,\n good=good,\n ogood=ogood,\n pgood=pgood,\n )\n )\n )\n\n\ndef upd_record(tp, lid, myid, fields, msgs, fvalues=None):\n updrecord = {}\n good = False\n (label, table) = tps[tp]\n use_values = {}\n for i in range(len(fields)):\n field = fields[i]\n value = fvalues[i] if fvalues is not None else request.vars[field]\n use_values[field] = value\n\n for x in [1]:\n valsql = check_name(\n # tp, lid, myid, str(use_values[\"name\"], encoding=\"utf-8\"), msgs\n tp, lid, myid, use_values[\"name\"], msgs\n )\n if valsql is None:\n break\n updrecord[\"name\"] = valsql\n if tp == \"q\":\n val = check_id(\n \"oid\", \"o\", tps[\"o\"][0], msgs, valrep=str(use_values[\"organization\"])\n )\n if val is None:\n break\n valsql = check_rel(\"o\", val, msgs)\n if valsql is None:\n break\n updrecord[\"organization\"] = valsql\n val = check_id(\n \"pid\", \"p\", tps[\"p\"][0], msgs, valrep=str(use_values[\"project\"])\n )\n valsql = check_rel(\"p\", val, msgs)\n if valsql is None:\n break\n updrecord[\"project\"] = valsql\n fld = \"modified_on\"\n updrecord[fld] = request.utcnow\n fields.append(fld)\n if lid == 0:\n fld = \"created_on\"\n updrecord[fld] = request.utcnow\n fields.append(fld)\n fld = \"created_by\"\n updrecord[fld] = myid\n fields.append(fld)\n else:\n valsql = check_website(tp, use_values[\"website\"], msgs)\n if valsql is None:\n break\n updrecord[\"website\"] = valsql\n good = True\n if good:\n if lid:\n fieldvals = [\" {} = '{}'\".format(f, updrecord[f]) for f in fields]\n sql = \"\"\"update {} set{} where id = {};\"\"\".format(\n table, \",\".join(fieldvals), lid\n )\n thismsg = \"updated\"\n else:\n fieldvals = [\"'{}'\".format(updrecord[f]) for f in fields]\n sql = \"\"\"\ninsert into {} ({}) values ({})\n;\n\"\"\".format(\n table, \",\".join(fields), \",\".join(fieldvals)\n )\n thismsg = \"{} added\".format(label)\n db.executesql(sql)\n if lid == 0:\n lid = db.executesql(\n \"\"\"\nselect last_insert_id() as x\n;\n\"\"\"\n )[0][0]\n\n msgs.append((\"good\", thismsg))\n return (good, lid)\n\n\ndef field():\n session.forget(response)\n msgs = []\n good = False\n mod_dates = {}\n mod_cls = \"\"\n extra = {}\n for x in [1]:\n qid = check_id(\"qid\", \"q\", \"query\", msgs)\n if qid is None:\n break\n fname = request.vars.fname\n val = request.vars.val\n vr = request.vars.version\n if fname is None or fname not in {\"is_shared\", \"is_published\"}:\n msgs.append(\"error\", \"Illegal field name {}\")\n break\n (authorized, msg) = query_auth_write(qid)\n if not authorized:\n msgs.append((\"error\", msg))\n break\n (good, mod_dates, mod_cls, extra) = upd_field(vr, qid, fname, val, msgs)\n return dict(\n data=json.dumps(\n dict(\n msgs=msgs, good=good, mod_dates=mod_dates, mod_cls=mod_cls, extra=extra\n )\n )\n )\n\n\ndef upd_shared(myid, qid, valsql, msgs):\n mod_date = None\n mod_date_fld = \"shared_on\"\n table = \"query\"\n fname = \"is_shared\"\n clear_cache(cache, r\"^items_q_\")\n fieldval = \" {} = '{}'\".format(fname, valsql)\n mod_date = request.utcnow.replace(microsecond=0) if valsql == \"T\" else None\n mod_date_sql = \"null\" if mod_date is None else \"'{}'\".format(mod_date)\n fieldval += \", {} = {} \".format(mod_date_fld, mod_date_sql)\n sql = \"\"\"\nupdate {} set{} where id = {}\n;\n\"\"\".format(\n table, fieldval, qid\n )\n db.executesql(sql)\n thismsg = \"modified\"\n thismsg = \"shared\" if valsql == \"T\" else \"UNshared\"\n msgs.append((\"good\", thismsg))\n return (mod_date_fld, str(mod_date) if mod_date else NULLDT)\n\n\ndef upd_published(myid, vr, qid, valsql, msgs):\n mod_date = None\n mod_date_fld = \"published_on\"\n table = \"query_exe\"\n fname = \"is_published\"\n clear_cache(cache, r\"^items_q_{}_\".format(vr))\n verify_version(qid, vr)\n fieldval = \" {} = '{}'\".format(fname, valsql)\n mod_date = request.utcnow.replace(microsecond=0) if valsql == \"T\" else None\n mod_date_sql = \"null\" if mod_date is None else \"'{}'\".format(mod_date)\n fieldval += \", {} = {} \".format(mod_date_fld, mod_date_sql)\n sql = \"\"\"\nupdate {} set{} where query_id = {} and version = '{}'\n;\n\"\"\".format(\n table, fieldval, qid, vr\n )\n db.executesql(sql)\n thismsg = \"modified\"\n thismsg = \"published\" if valsql == \"T\" else \"UNpublished\"\n msgs.append((\"good\", thismsg))\n return (mod_date_fld, str(mod_date) if mod_date else NULLDT)\n\n\ndef upd_field(vr, qid, fname, val, msgs):\n good = False\n myid = None\n mod_dates = {}\n mod_cls = {}\n extra = {}\n if auth.user:\n myid = auth.user.id\n for x in [1]:\n # valsql = check_published(\"q\", str(val, encoding=\"utf-8\"), msgs)\n valsql = check_published(\"q\", val, msgs)\n if valsql is None:\n break\n if fname == \"is_shared\" and valsql == \"\":\n sql = \"\"\"\nselect count(*) from query_exe where query_id = {} and is_published = 'T'\n;\n\"\"\".format(\n qid\n )\n pv = db.executesql(sql)\n has_public_versions = pv is not None and len(pv) == 1 and pv[0][0] > 0\n if has_public_versions:\n msgs.append(\n (\n \"error\",\n (\n \"You cannot UNshare this query because there is\"\n \"a published execution record\"\n ),\n )\n )\n break\n if fname == \"is_published\":\n mod_cls[\"#is_pub_ro\"] = \"fa-{}\".format(\n \"check\" if valsql == \"T\" else \"close\"\n )\n mod_cls['div[version=\"{}\"]'.format(vr)] = (\n \"published\" if valsql == \"T\" else \"unpublished\"\n )\n extra[\"execq\"] = (\"show\", valsql != \"T\")\n if valsql == \"T\":\n sql = \"\"\"\nselect executed_on, modified_on as xmodified_on\nfrom query_exe where query_id = {} and version = '{}'\n;\n\"\"\".format(\n qid, vr\n )\n pv = db.executesql(sql, as_dict=True)\n if pv is None or len(pv) != 1:\n msgs.append(\n (\n \"error\",\n \"cannot determine whether query results are up to date\",\n )\n )\n break\n uptodate = qstatus(pv[0])\n if uptodate != \"good\":\n msgs.append(\n (\n \"error\",\n \"You can only publish if the query results are up to date\",\n )\n )\n break\n sql = \"\"\"\nselect is_shared from query where id = {}\n;\n\"\"\".format(\n qid\n )\n pv = db.executesql(sql)\n is_shared = pv is not None and len(pv) == 1 and pv[0][0] == \"T\"\n if not is_shared:\n (mod_date_fld, mod_date) = upd_shared(myid, qid, \"T\", msgs)\n mod_dates[mod_date_fld] = mod_date\n extra[\"is_shared\"] = (\"checked\", True)\n else:\n sql = \"\"\"\nselect published_on from query_exe where query_id = {} and version = '{}'\n;\n\"\"\".format(\n qid, vr\n )\n pv = db.executesql(sql)\n pdate_ok = (\n pv is None\n or len(pv) != 1\n or pv[0][0] is None\n or pv[0][0] > request.utcnow - PUBLISH_FREEZE\n )\n if not pdate_ok:\n msgs.append(\n (\n \"error\",\n (\n \"You cannot UNpublish this query because\"\n \"it has been published more than {} ago\"\n ).format(PUBLISH_FREEZE_MSG),\n )\n )\n break\n\n good = True\n\n if good:\n if fname == \"is_shared\":\n (mod_date_fld, mod_date) = upd_shared(myid, qid, valsql, msgs)\n else:\n (mod_date_fld, mod_date) = upd_published(myid, vr, qid, valsql, msgs)\n mod_dates[mod_date_fld] = mod_date\n return (good, mod_dates, mod_cls, extra)\n\n\ndef verify_version(qid, vr):\n exist_version = db.executesql(\n \"\"\"\nselect id from query_exe where version = '{}' and query_id = {}\n;\n\"\"\".format(\n vr, qid\n )\n )\n if exist_version is None or len(exist_version) == 0:\n db.executesql(\n \"\"\"\ninsert into query_exe (id, version, query_id) values (null, '{}', {})\n;\n\"\"\".format(\n vr, qid\n )\n )\n\n\ndef fields():\n session.forget(response)\n msgs = []\n good = False\n myid = auth.user.id if auth.user is not None else None\n flds = {}\n fldx = {}\n vr = request.vars.version\n q_record = {}\n for x in [1]:\n qid = check_id(\"qid\", \"q\", \"query\", msgs)\n if qid is None:\n break\n (authorized, msg) = query_auth_write(qid)\n if not authorized:\n msgs.append((\"error\", msg))\n break\n\n verify_version(qid, vr)\n oldrecord = db.executesql(\n \"\"\"\nselect\n query.name as name,\n query.description as description,\n query_exe.mql as mql,\n query_exe.is_published as is_published\nfrom query inner join query_exe on\n query.id = query_exe.query_id and query_exe.version = '{}'\nwhere query.id = {}\n;\n\"\"\".format(\n vr, qid\n ),\n as_dict=True,\n )\n if oldrecord is None or len(oldrecord) == 0:\n msgs.append((\"error\", \"No query with id {}\".format(qid)))\n break\n oldvals = oldrecord[0]\n is_published = oldvals[\"is_published\"] == \"T\"\n if not is_published:\n # newname = str(request.vars.name, encoding=\"utf-8\")\n newname = request.vars.name\n if oldvals[\"name\"] != newname:\n valsql = check_name(\"q\", qid, myid, newname, msgs)\n if valsql is None:\n break\n flds[\"name\"] = valsql\n flds[\"modified_on\"] = request.utcnow\n newmql = request.vars.mql\n # newmql_u = str(newmql, encoding=\"utf-8\")\n newmql_u = newmql\n if oldvals[\"mql\"] != newmql_u:\n msgs.append((\"warning\", \"query body modified\"))\n valsql = check_mql(\"q\", newmql_u, msgs)\n if valsql is None:\n break\n fldx[\"mql\"] = valsql\n fldx[\"modified_on\"] = request.utcnow\n else:\n msgs.append((\"good\", \"same query body\"))\n else:\n msgs.append(\n (\n \"warning\",\n (\n \"only the description can been saved\"\n \"because this is a published query execution\"\n ),\n )\n )\n # newdesc = str(request.vars.description, encoding=\"utf-8\")\n newdesc = request.vars.description\n if oldvals[\"description\"] != newdesc:\n valsql = check_description(\"q\", newdesc, msgs)\n if valsql is None:\n break\n flds[\"description\"] = valsql\n flds[\"modified_on\"] = request.utcnow\n good = True\n if good:\n execute = not is_published and request.vars.execute\n xgood = True\n if execute == \"true\":\n (xgood, limit_exceeded, nresults, xmonads, this_msgs, eversion) = mql(\n vr, newmql\n )\n if xgood and not limit_exceeded:\n store_monad_sets(vr, qid, xmonads)\n fldx[\"executed_on\"] = request.utcnow\n fldx[\"eversion\"] = eversion\n nresultmonads = count_monads(xmonads)\n fldx[\"results\"] = nresults\n fldx[\"resultmonads\"] = nresultmonads\n msgs.append((\"good\", \"Query executed\"))\n else:\n store_monad_sets(vr, qid, [])\n msgs.extend(this_msgs)\n if len(flds):\n sql = \"\"\"\nupdate {} set{} where id = {}\n;\n\"\"\".format(\n \"query\",\n \", \".join(\n \" {} = '{}'\".format(f, flds[f]) for f in flds if f != \"status\"\n ),\n qid,\n )\n db.executesql(sql)\n clear_cache(cache, r\"^items_q_\")\n if len(fldx):\n sql = \"\"\"\nupdate {} set{} where query_id = {} and version = '{}'\n;\n\"\"\".format(\n \"query_exe\",\n \", \".join(\n \" {} = '{}'\".format(f, fldx[f]) for f in fldx if f != \"status\"\n ),\n qid,\n vr,\n )\n db.executesql(sql)\n clear_cache(cache, r\"^items_q_{}_\".format(vr))\n q_record = get_query_info(\n auth.user is not None,\n qid,\n vr,\n msgs,\n with_ids=False,\n single_version=False,\n po=True,\n )\n\n oldeversions = dict((x, 1) for x in emdros_versions[0:-1])\n return dict(\n data=json.dumps(\n dict(msgs=msgs, good=good and xgood, q=q_record, oldeversions=oldeversions)\n )\n )\n\n\ndef datetime_str(fields):\n for f in (\n \"created_on\",\n \"modified_on\",\n \"shared_on\",\n \"xmodified_on\",\n \"executed_on\",\n \"published_on\",\n ):\n if f in fields:\n ov = fields[f]\n fields[f] = str(ov) if ov else NULLDT\n for f in (\"is_shared\", \"is_published\"):\n if f in fields:\n fields[f] = fields[f] == \"T\"\n\n\ndef qstatus(qx_record):\n if not qx_record[\"executed_on\"]:\n return \"warning\"\n if qx_record[\"executed_on\"] < qx_record[\"xmodified_on\"]:\n return \"error\"\n return \"good\"\n\n\ndef query_fields(vr, q_record, recordx, single_version=False):\n datetime_str(q_record)\n if not single_version:\n q_record[\"versions\"] = dict(\n (\n v,\n dict(\n xid=None,\n mql=None,\n status=\"warning\",\n is_published=None,\n results=None,\n resultmonads=None,\n xmodified_on=None,\n executed_on=None,\n eversion=None,\n published_on=None,\n ),\n )\n for v in versions\n if versions[v][\"present\"]\n )\n for rx in recordx:\n vx = rx[\"version\"]\n dest = q_record[\"versions\"][vx]\n dest.update(rx)\n dest[\"status\"] = qstatus(dest)\n datetime_str(dest)\n\n\ndef flatten(msets):\n result = set()\n for (b, e) in msets:\n for m in range(b, e + 1):\n result.add(m)\n return list(sorted(result))\n\n\ndef getpassage(no_controller=True):\n vr = get_request_val(\"material\", \"\", \"version\")\n bookname = get_request_val(\"material\", \"\", \"book\")\n chapternum = get_request_val(\"material\", \"\", \"chapter\")\n if bookname is None or chapternum is None or vr not in passage_dbs:\n return ({}, {})\n bookrecords = passage_dbs[vr].executesql(\n \"\"\"\nselect * from book where name = '{}'\n;\n\"\"\".format(\n bookname\n ),\n as_dict=True,\n )\n book = bookrecords[0] if bookrecords else {}\n if book and \"id\" in book:\n chapterrecords = passage_dbs[vr].executesql(\n \"\"\"\nselect * from chapter where chapter_num = {} and book_id = {}\n;\n\"\"\".format(\n chapternum, book[\"id\"]\n ),\n as_dict=True,\n )\n chapter = chapterrecords[0] if chapterrecords else {}\n else:\n chapter = {}\n return (book, chapter)\n\n\ndef groupq(vr, input):\n monads = collections.defaultdict(lambda: set())\n for (qid, b, e) in input:\n monads[qid] |= set(range(b, e + 1))\n r = []\n if len(monads):\n msgs = []\n queryrecords = get_query_info(\n False,\n (str(q) for q in monads),\n vr,\n msgs,\n with_ids=False,\n single_version=True,\n po=False,\n )\n for q in queryrecords:\n r.append({\"item\": q, \"monads\": json.dumps(sorted(list(monads[q[\"id\"]])))})\n return r\n\n\n# select * from lexicon where id in ({}) order by entryid_heb\n# again: modify the sorting because of shin and sin\n# (see comments to function words_page)\n\n\ndef groupw(vr, input):\n if vr not in passage_dbs:\n return []\n wids = collections.defaultdict(lambda: [])\n for x in input:\n wids[x[1]].append(x[0])\n r = []\n if len(wids):\n wsql = \"\"\"\nselect * from lexicon where id in ({})\n;\n\"\"\".format(\n \",\".join(\"'{}'\".format(str(x)) for x in wids)\n )\n wordrecords = sorted(\n passage_dbs[vr].executesql(wsql, as_dict=True),\n key=lambda x: heb_key(x[\"entryid_heb\"]),\n )\n for w in wordrecords:\n r.append({\"item\": w, \"monads\": json.dumps(wids[w[\"id\"]])})\n return r\n\n\ndef get_notes(vr, book, chapter, pub):\n bk = book[\"name\"]\n ch = chapter[\"chapter_num\"]\n if pub == \"x\":\n pubv = \"\"\n else:\n pubv = \" and is_published = 'T'\"\n sql = \"\"\"\nselect\n note.created_by,\n shebanq_web.auth_user.first_name,\n shebanq_web.auth_user.last_name,\n note.keywords,\n note.verse,\n note.is_published\nfrom note\ninner join shebanq_web.auth_user on shebanq_web.auth_user.id = created_by\nwhere version = '{}' and book = '{}' and chapter = {} {}\norder by note.verse\n;\n\"\"\".format(\n vr, bk, ch, pubv\n )\n records = note_db.executesql(sql)\n user = {}\n npub = collections.Counter()\n nnotes = collections.Counter()\n nverses = {}\n for (uid, ufname, ulname, kw, v, pub) in records:\n if uid not in user:\n user[uid] = (ufname, ulname)\n for k in set(kw.strip().split()):\n if pub == \"T\":\n npub[(uid, k)] += 1\n nnotes[(uid, k)] += 1\n nverses.setdefault((uid, k), set()).add(v)\n r = []\n for (uid, k) in nnotes:\n (ufname, ulname) = user[uid]\n this_npub = npub[(uid, k)]\n this_nnotes = nnotes[(uid, k)]\n this_nverses = len(nverses[(uid, k)])\n r.append(\n {\n \"item\": dict(\n id=iid_encode(\"n\", uid, k),\n ufname=ufname,\n ulname=ulname,\n kw=k,\n is_published=this_npub > 0,\n nnotes=this_nnotes,\n nverses=this_nverses,\n ),\n \"monads\": json.dumps([]),\n }\n )\n return r\n\n\ndef get_q_hits(vr, chapter, pub):\n if pub == \"x\":\n pubv = \"\"\n pubx = \"\"\"inner join query on\n query.id = query_exe.query_id and query.is_shared = 'T'\"\"\"\n else:\n pubv = \" and query_exe.is_published = 'T'\"\n pubx = \"\"\n return db.executesql(\n \"\"\"\nselect DISTINCT\n query_exe.query_id as query_id,\n GREATEST(first_m, {chapter_first_m}) as first_m,\n LEAST(last_m, {chapter_last_m}) as last_m\nfrom monads\ninner join query_exe on\n monads.query_exe_id = query_exe.id and query_exe.version = '{vr}' and\n query_exe.executed_on >= query_exe.modified_on {pubv}\n{pubx}\nwhere\n (first_m BETWEEN {chapter_first_m} AND {chapter_last_m}) OR\n (last_m BETWEEN {chapter_first_m} AND {chapter_last_m}) OR\n ({chapter_first_m} BETWEEN first_m AND last_m)\n;\n\"\"\".format(\n chapter_last_m=chapter[\"last_m\"],\n chapter_first_m=chapter[\"first_m\"],\n vr=vr,\n pubv=pubv,\n pubx=pubx,\n )\n )\n\n\ndef get_w_occs(vr, chapter):\n return (\n passage_dbs[vr].executesql(\n \"\"\"\nselect anchor, lexicon_id\nfrom word_verse\nwhere anchor BETWEEN {chapter_first_m} AND {chapter_last_m}\n;\n\"\"\".format(\n chapter_last_m=chapter[\"last_m\"],\n chapter_first_m=chapter[\"first_m\"],\n )\n )\n if vr in passage_dbs\n else []\n )\n\n\ndef to_ascii(x):\n return x.encode(\"ascii\", \"replace\")\n\n\ndef item_access_read(iidrep=get_request_val(\"material\", \"\", \"iid\")):\n mr = get_request_val(\"material\", \"\", \"mr\")\n qw = get_request_val(\"material\", \"\", \"qw\")\n if mr == \"m\":\n return (True, \"\")\n if qw == \"w\":\n return (True, \"\")\n if qw == \"n\":\n return (True, \"\")\n if qw == \"q\":\n if iidrep is not None:\n (iid, kw) = iid_decode(qw, iidrep)\n if iid > 0:\n return query_auth_read(iid)\n return (None, \"Not a valid id {}\".format(iidrep))\n\n\ndef query_auth_read(iid):\n authorized = None\n if iid == 0:\n authorized = auth.user is not None\n else:\n q_records = db.executesql(\n \"\"\"\nselect * from query where id = {}\n;\n\"\"\".format(\n iid\n ),\n as_dict=True,\n )\n q_record = q_records[0] if q_records else {}\n if q_record:\n authorized = q_record[\"is_shared\"] or (\n auth.user is not None and q_record[\"created_by\"] == auth.user.id\n )\n msg = (\n \"No query with id {}\".format(iid)\n if authorized is None\n else \"You have no access to item with id {}\".format(iid)\n )\n return (authorized, msg)\n\n\ndef word_auth_read(vr, iid):\n authorized = None\n if not iid or vr not in passage_dbs:\n authorized = False\n else:\n words = passage_dbs[vr].executesql(\n \"\"\"\nselect * from lexicon where id = '{}'\n;\n\"\"\".format(\n iid\n ),\n as_dict=True,\n )\n word = words[0] if words else {}\n if word:\n authorized = True\n msg = (\n \"No word with id {}\".format(iid)\n if authorized is None\n else \"No data version {}\".format(vr)\n if vr not in passage_dbs\n else \"\"\n )\n return (authorized, msg)\n\n\ndef query_auth_write(iid):\n authorized = None\n if iid == 0:\n authorized = auth.user is not None\n else:\n q_records = db.executesql(\n \"\"\"\nselect * from query where id = {}\n;\n\"\"\".format(\n iid\n ),\n as_dict=True,\n )\n q_record = q_records[0] if q_records else {}\n if q_record is not None:\n authorized = (\n auth.user is not None and q_record[\"created_by\"] == auth.user.id\n )\n msg = (\n \"No item with id {}\".format(iid)\n if authorized is None\n else \"You have no access to create/modify item with id {}\".format(iid)\n )\n return (authorized, msg)\n\n\n@auth.requires_login()\ndef auth_write(label):\n authorized = auth.user is not None\n msg = \"You have no access to create/modify a {}\".format(label)\n return (authorized, msg)\n\n\ndef auth_read(label):\n authorized = True\n msg = \"You have no access to create/modify a {}\".format(label)\n return (authorized, msg)\n\n\ndef get_qx(vr, iid):\n recordx = db.executesql(\n \"\"\"\nselect id from query_exe where query_id = {} and version = '{}'\n;\n\"\"\".format(\n iid, vr\n )\n )\n if recordx is None or len(recordx) != 1:\n return None\n return recordx[0][0]\n\n\ndef count_monads(rows):\n covered = set()\n for (b, e) in rows:\n covered |= set(range(b, e + 1))\n return len(covered)\n\n\ndef store_monad_sets(vr, iid, rows):\n xid = get_qx(vr, iid)\n if xid is None:\n return\n db.executesql(\n \"\"\"\ndelete from monads where query_exe_id={}\n;\n\"\"\".format(\n xid\n )\n )\n # Here we clear stuff that will become invalid because of a (re)execution of a query\n # and the deleting of previous results and the storing of new results.\n clear_cache(cache, r\"^verses_{}_q_{}_\".format(vr, iid))\n clear_cache(cache, r\"^items_q_{}_\".format(vr))\n clear_cache(cache, r\"^chart_{}_q_{}_\".format(vr, iid))\n nrows = len(rows)\n if nrows == 0:\n return\n\n limit_row = 10000\n start = \"\"\"\ninsert into monads (query_exe_id, first_m, last_m) values\n\"\"\"\n query = \"\"\n r = 0\n while r < nrows:\n if query != \"\":\n db.executesql(query)\n query = \"\"\n query += start\n s = min(r + limit_row, len(rows))\n row = rows[r]\n query += \"({},{},{})\".format(xid, row[0], row[1])\n if r + 1 < nrows:\n for row in rows[r + 1:s]:\n query += \",({},{},{})\".format(xid, row[0], row[1])\n r = s\n if query != \"\":\n db.executesql(query)\n query = \"\"\n\n\ndef load_q_hits(vr, iid):\n xid = get_qx(vr, iid)\n if xid is None:\n return normalize_ranges([])\n monad_sets = db.executesql(\n \"\"\"\nselect first_m, last_m from monads where query_exe_id = {} order by first_m\n;\n\"\"\".format(\n xid\n )\n )\n return normalize_ranges(monad_sets)\n\n\ndef load_w_occs(vr, lexeme_id):\n monads = (\n passage_dbs[vr].executesql(\n \"\"\"\nselect anchor from word_verse where lexicon_id = '{}' order by anchor\n;\n\"\"\".format(\n lexeme_id\n )\n )\n if vr in passage_dbs\n else []\n )\n return collapse_into_ranges(monads)\n\n\ndef count_n_notes(uid, kw):\n kw_sql = kw.replace(\"'\", \"''\")\n myid = auth.user.id if auth.user is not None else None\n extra = \"\"\" or created_by = {} \"\"\".format(uid) if myid == uid else \"\"\n sql = \"\"\"\nselect\n version,\n count(id) as amount\nfrom note\nwhere keywords like '% {} %' and (is_shared = 'T' {})\ngroup by version\n;\"\"\".format(\n kw_sql, extra\n )\n records = note_db.executesql(sql)\n vrs = set()\n versions_info = {}\n for (vr, amount) in records:\n vrs.add(vr)\n versions_info[vr] = dict(n=amount)\n return versions_info\n\n\ndef load_n_notes(vr, iid, kw):\n clause_atom_first = from_cache(\n cache,\n \"clause_atom_f_{}_\".format(vr), lambda: get_clause_atom_fmonad(vr), None\n )\n kw_sql = kw.replace(\"'\", \"''\")\n myid = auth.user.id if auth.user is not None else None\n extra = \"\"\" or created_by = {} \"\"\".format(uid) if myid == iid else \"\"\n sql = \"\"\"\nselect book, clause_atom from note\nwhere keywords like '% {} %' and version = '{}' and (is_shared = 'T' {})\n;\n\"\"\".format(\n kw_sql, vr, extra\n )\n clause_atoms = note_db.executesql(sql)\n monads = {clause_atom_first[x[0]][x[1]] for x in clause_atoms}\n return normalize_ranges(None, fromset=monads)\n\n\ndef collapse_into_ranges(monads):\n covered = set()\n for (start,) in monads:\n covered.add(start)\n return normalize_ranges(None, fromset=covered)\n\n\ndef normalize_ranges(ranges, fromset=None):\n covered = set()\n if fromset is not None:\n covered = fromset\n else:\n for (start, end) in ranges:\n for i in range(start, end + 1):\n covered.add(i)\n cur_start = None\n cur_end = None\n result = []\n for i in sorted(covered):\n if i not in covered:\n if cur_end is not None:\n result.append((cur_start, cur_end - 1))\n cur_start = None\n cur_end = None\n elif cur_end is None or i > cur_end:\n if cur_end is not None:\n result.append((cur_start, cur_end - 1))\n cur_start = i\n cur_end = i + 1\n else:\n cur_end = i + 1\n if cur_end is not None:\n result.append((cur_start, cur_end - 1))\n return (len(covered), result)\n\n\ndef get_pagination(vr, p, monad_sets):\n verse_boundaries = (\n from_cache(\n cache,\n \"verse_boundaries_{}_\".format(vr),\n lambda: passage_dbs[vr].executesql(\n \"\"\"\nselect first_m, last_m from verse order by id\n;\n\"\"\"\n ),\n None,\n )\n if vr in passage_dbs\n else []\n )\n m = 0 # monad range index, walking through monad_sets\n v = 0 # verse id, walking through verse_boundaries\n nvp = 0 # number of verses added to current page\n nvt = 0 # number of verses added in total\n lm = len(monad_sets)\n lv = len(verse_boundaries)\n cur_page = 1 # current page\n verse_ids = []\n verse_monads = set()\n last_v = -1\n while m < lm and v < lv:\n if nvp == RESULT_PAGE_SIZE:\n nvp = 0\n cur_page += 1\n (v_b, v_e) = verse_boundaries[v]\n (m_b, m_e) = monad_sets[m]\n if v_e < m_b:\n v += 1\n continue\n if m_e < v_b:\n m += 1\n continue\n # now v_e >= m_b and m_e >= v_b so one of the following holds\n # vvvvvv\n # mmmmm\n # mmmmmmmmmmmmmmm\n # mmm\n # mmmmmmmmmmmmm\n # so (v_b, v_e) and (m_b, m_e) overlap\n # so add v to the result pages and go to the next verse\n # and add p to the highlight list if on the selected page\n if v != last_v:\n if cur_page == p:\n verse_ids.append(v)\n last_v = v\n nvp += 1\n nvt += 1\n if last_v == v:\n clipped_m = set(range(max(v_b, m_b), min(v_e, m_e) + 1))\n verse_monads |= clipped_m\n if cur_page != p:\n v += 1\n else:\n if m_e < v_e:\n m += 1\n else:\n v += 1\n\n verses = verse_ids if p <= cur_page and len(verse_ids) else None\n return (nvt, cur_page if nvt else 0, verses, list(verse_monads))\n\n\ndef get_chart(\n vr, monad_sets\n): # get data for a chart of the monadset: organized by book and block\n # return a dict keyed by book, with values lists of blocks\n # (chapter num, start point, end point, number of results, size)\n\n monads = flatten(monad_sets)\n chart = {}\n chart_order = []\n if len(monads):\n (books, books_order, book_id, book_name) = from_cache(\n cache,\n \"books_{}_\".format(vr), lambda: get_books(passage_dbs, vr), None\n )\n (blocks, block_mapping) = from_cache(\n cache,\n \"blocks_{}_\".format(vr), lambda: get_blocks(vr), None\n )\n results = {}\n\n for bl in range(len(blocks)):\n results[bl] = 0\n for bk in books_order:\n chart[bk] = []\n chart_order.append(bk)\n for m in monads:\n results[block_mapping[m]] += 1\n for bl in range(len(blocks)):\n (bk, ch_start, ch_end, size) = blocks[bl]\n r = results[bl]\n chart[bk].append((ch_start[0], ch_start[1], ch_end[1], r, size))\n\n return dict(chart=json.dumps(chart), chart_order=json.dumps(chart_order))\n","sub_path":"controllers/hebrew.py","file_name":"hebrew.py","file_ext":"py","file_size_in_byte":109894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"518173384","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom exp_weibull import phase_pdf\nfrom exp_weibull import phase_hist\n\nOmega = 1.0\nalpha = 1.0\nK = 1000000\nt1 = np.linspace(0, 2 * np.pi / alpha, 1000)\n\ngraph = plt.gca(projection='polar')\ngraph.axes.get_yaxis().set_ticks([])\n\nfor m in [1.0, 1.25, 1.5, 1.8, 2.3, 3.0, 4.0]:\n p = phase_pdf(t1, alpha, m, Omega)\n plt.plot(t1, p, 'k-')\n\nfor m in [1.0, 3.0, 4.0, 5.0]:\n x, y = phase_hist(alpha, m, Omega, K, 50)\n plt.plot(x, y, 'ko', mfc='none')\n\np = phase_pdf(t1,alpha,5.0,Omega)\nplt.plot(t1,p,'k-',label=r'$\\alpha=1,~\\mu \\geq 1$')\n\nalpha = 2.0\nt1 = np.linspace((np.pi/2000),(1-np.pi/2000)*np.pi/alpha,1000)\nt2 = np.linspace(np.pi/alpha,np.pi,1000)\nt3 = np.linspace(np.pi,3*np.pi/2,1000)\nt4 = np.linspace(3*np.pi/2,2*np.pi,1000)\n\ntset = [t1, t2, t3, t4]\n\nmuset = [0.7, 0.8, 0.9]\nfor m in muset:\n p = phase_pdf(t1,alpha,m,Omega)\n for t in tset:\n plt.plot(t,p,'k-',color='.75')\n\np = phase_pdf(t1,alpha,0.95,Omega)\nplt.plot(t1,p,'k-',color='.75')\nplt.plot(t2,p,'k-',color='.75')\nplt.plot(t3,p,'k-',color='.75')\nplt.plot(t4,p,'k-',color='.75',label=r'$\\alpha=2,~\\mu < 1$')\n\nplt.rc('text',usetex=True)\nplt.rc('font',**{'family':'serif','serif':['Times'],'size':16})\nplt.ylim([0,0.25])\nplt.legend(shadow=True,fontsize=14,loc=(0.55,0.925))\nplt.show()\n","sub_path":"_exp_weibull_phase_plots.py","file_name":"_exp_weibull_phase_plots.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"386413911","text":"from django.core.exceptions import ValidationError\nfrom django.test import TestCase\n\nfrom rss.models import DataSource, DataFromSource\n\n\nclass DataSourceModelTest(TestCase):\n \"\"\"\n Demonstration realisation of simple tests\n \"\"\"\n def create_source(self, url):\n DataSource.objects.create(url=url)\n\n def create_data(self, data):\n \"\"\"\n :param data: dict\n :return: str\n \"\"\"\n # date example: Sat, 14 Jul 2018 21:20:42 -0400\n xml = \"\"\"\n \n \n {channel_title}\n https://www.example.com\n ru\n copyright\n \n {item_title}\n {item_pub_date}\n {item_link}\n {item_description}\n {item_author}\n \n \n \n \"\"\".format(\n channel_title=data['channel_title'],\n item_title=data['item_title'],\n item_pub_date=data['item_pub_date'],\n item_link=data['item_link'],\n item_description=data['item_description'],\n item_author=data['item_author'],\n )\n return xml\n\n def test_model_good_source(self):\n self.create_source('https://www.djangoproject.com/rss/weblog/')\n feed = DataSource.objects.get(url='https://www.djangoproject.com/rss/weblog/')\n self.assertTrue(isinstance(feed, DataSource))\n self.assertEqual(feed.__str__(), feed.source_head)\n self.assertEqual(feed.__repr__(), feed.source_head)\n\n def test_model_bad_source(self):\n ds = DataSource(url='https://www.google.com')\n self.assertRaises(ValidationError, ds.clean)\n\n def test_model_non_url_source(self):\n ds = DataSource(url='1')\n self.assertRaises(ValidationError, ds.clean)\n\n def test_for_exists_data_from_source(self):\n self.create_source('https://www.djangoproject.com/rss/weblog/')\n source = DataSource.objects.get(url='https://www.djangoproject.com/rss/weblog/')\n source_data = DataFromSource.objects.filter(source=source).exists()\n self.assertTrue(source_data)\n\n def test_data_without_date(self):\n data = {\n 'channel_title': 'Channel example',\n 'item_title': 'Title Example',\n 'item_pub_date': '',\n 'item_link': 'https://www.example.com',\n 'item_description': 'DESCRIPTION',\n 'item_author': 'Roberto',\n }\n self.create_source(self.create_data(data))\n source = DataSource.objects.get(source_head='Channel example')\n self.assertEqual(source.__str__(), source.source_head)\n data_source = DataFromSource.objects.get(source=source)\n\n self.assertEqual(data_source.source, source)\n self.assertEqual(data_source.source_event, 'Title Example')\n self.assertEqual(data_source.summary, 'DESCRIPTION')\n self.assertIsNone(data_source.pub_date)\n self.assertEqual(data_source.link, 'https://www.example.com')\n self.assertEqual(data_source.author, 'Roberto')\n\n","sub_path":"rss/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"141938651","text":"\"\"\"\n\n\"\"\"\nimport requests\n\n_public_url_base = \"https://api.bithumb.com/public\"\n\n\nclass Bithumb(object):\n\n @classmethod\n def get_relative_price(cls, order_currency, payment_currency):\n buy_order, sell_order = cls.get_price(order_currency)\n buy_payment, sell_payment = cls.get_price(payment_currency)\n return buy_order / sell_payment, sell_order / buy_payment\n\n @classmethod\n def get_price(cls, symbol):\n r = requests.get(\"{0}/ticker/{1}\".format(_public_url_base, symbol))\n assert (r.status_code == 200)\n data = r.json()['data']\n return float(data[\"buy_price\"]), float(data[\"sell_price\"])\n","sub_path":"watcher/bithumb.py","file_name":"bithumb.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"79297972","text":"#!/usr/bin/env python\n\nCONFIGURATION_FILENAME = \"wbezScraperConfig.txt\"\n\nfrom bs4 import BeautifulSoup, Comment\nimport feedparser\nimport httplib\nimport scraper\nimport sys\nimport os\nimport re\nimport time\nimport urllib2\n\nscraper.setPathToDjango(__file__)\n\nfrom django.db import transaction\nimport cjp.newsarticles.models as models\n\nclass WBEZScraper(scraper.FeedScraper):\n def __init__(self, configFile):\n super(WBEZScraper, self).__init__(models.FEED_WBEZ,\n configFile, models)\n \n def run(self):\n self.logInfo(\"START WBEZ Feed Scraper\")\n \n feedUrl = self.getConfig('config', 'feed_url')\n feed = feedparser.parse(feedUrl)\n\n if 'channel' not in feed:\n self.logError(\"Expected channel missing in RSS Feed\")\n return\n \n channel = feed['channel']\n if 'title' not in channel.keys() or channel['title'] != 'WBEZ | Criminal Justice':\n self.logError(\"Expected channel title missing\")\n return\n\n if 'link' not in channel.keys() or channel['link'] != 'http://www.wbez.org/news/criminal-justice':\n self.logError(\"Expected channel link missing\")\n return\n\n if len(feed.entries) == 0:\n self.logError(\"No entries in RSS feed\")\n return\n \n self.processFeed(feed)\n \n self.logInfo(\"END WBEZ Feed Scraper\")\n \n def processFeed(self, feed):\n insertCount = 0\n \n sleepTime = int(self.getConfig('config', 'seconds_between_queries'))\n\n for item in feed.entries:\n if len(item.guid) == 0:\n self.logError(\"Item guid is empty, skipping entry : %s\" % item)\n continue\n\n if len(item.link) == 0:\n self.logError(\"Item link is empty, skipping entry : %s\" % item)\n continue\n\n if len(item.description) == 0:\n self.logError(\"Item description is empty, skipping entry : %s\" % item)\n continue\n \n html = item.description\n \n self.saveStory(item.link, item.title, html, html)\n \n insertCount += 1\n\n time.sleep(sleepTime)\n\n self.logInfo(\"Inserted/updated %d WBEZ articles\" % insertCount)\n \n def parseResponse(self, url, content):\n \"\"\" Not called because the text is contained in the URL feed.\"\"\"\n pass\n \n\ndef main():\n configurationLocation = os.path.dirname(__file__)\n configPath = os.path.join(configurationLocation, CONFIGURATION_FILENAME)\n scraper = WBEZScraper(configPath)\n scraper.run() \n\nif __name__ == '__main__':\n main()\n","sub_path":"cjp/scripts/wbezScraper.py","file_name":"wbezScraper.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"8586016","text":"from sys import argv\n\nteam_id = argv[1]\nmetric_id = argv[2]\n\nfrom origami.common.core.context import TeamContext\nTeamContext().team_id = team_id\n\nfrom origami.common import services\n\nobject_service = services.Factory.create('Object')\nmetric_service = services.Factory.create('Metric')\n\nmetric = metric_service.get(metric_id)\nobject_service.add_metric_instance(team_id=metric.get('team_id'),\n object_type=metric.get('metric_owner_object_type'),\n metric_id=metric_id,\n name=metric.get('name'),\n granularity=metric.get('granularity'),\n owner_object_id=metric.get('owner_object_id'))\n\n","sub_path":"paperlaser/local/add_metric_instance_object_metadata.py","file_name":"add_metric_instance_object_metadata.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416074714","text":"import random\nimport numpy as np\nfrom scipy.spatial.distance import *\n\n'''\nA=0\nB=1\nC=2\nD=3\nE=4\nF=5\n'''\n\n\ndef main():\n n=6\n m=np.zeros(shape=(n,n))\n for i in range(n):\n for j in range(n):\n m[i][j]=-1\n\n m[0][1]=1\n m[1][0]=1\n m[1][4]=2\n m[4][1]=2\n m[4][5]=2\n m[5][4]=2\n m[5][3]=1\n m[3][5]=1\n m[1][3]=1\n m[3][1]=1\n m[3][2]=2\n m[2][3]=2\n m[0][2]=2\n m[2][0]=2\n paths=suurballePaths(m,0,5,n,2)\n exit(1)\n\n\n\ndef suurballePaths(w,start,end,n,k):\n\t(d,path)=djikstraPathWDist(w,start,end,n)\n\tpaths=[[] for _ in range(k)]\n\tpaths[0]=path\n\tgraph=w\n\tfor i in range(1,k):\n\t\t(graph,d,paths[i])=suurballePath(graph,start,end,n,d,paths[i-1])\n\treturn mergePaths(paths)\n\ndef mergePaths(paths):\n return None\n\ndef suurballePath(w,start,end,n,d,path):\n\tw_prime=np.zeros(shape=(n,n))\n\tfor i in range(len(w)):\n\t\tfor j in range(len(w[i])):\n\t\t\tif(w[i][j]==-1):\n\t\t\t\tw_prime[i][j]=-1\n\t\t\telse:\n\t\t\t\tw_prime[i][j]=w[i][j]-d[j]+d[i]\n\tGt=createResidGraph(w_prime,path,start)\n\tw[3][4]\n\tw[4][3]\n\tw_prime[3][4]\n\tw_prime[4][3]\n\t(newd,newpath)=djikstraPathWDist(Gt,start,end,n)\n\treturn (Gt,newd,newpath)\n\n\ndef createResidGraph(w_prime,path,start):\n\tn=len(w_prime)\n\tresid_graph=np.zeros(shape=(n,n))\n\teasy_path=makeEasy(path)\n\tfor i in range(len(w_prime)):\n\t\tfor j in range(len(w_prime)):\n\t\t\tif j==start:\n\t\t\t\tresid_graph[i][j]=-1\n\t\t\tif((i,j) in easy_path):\n\t\t\t\tresid_graph[i][j]=-1\n\t\t\t\tresid_graph[j][i]=0\n\t\t\telse:\n\t\t\t\tresid_graph[i][j]=w_prime[i][j]\n\treturn resid_graph\n\n\n\ndef sortNeighbors(w,start):\n\tmylist=[]\n\tfor i in range(len(w[start])):\n\t\tif(not w[start][i]==-1):\n\t\t\tmylist.append((i,w[start][i]))\n\treturn sorted(mylist,key=lambda x:x[1])\n\ndef djikstraPath(w,start,end,n):\n\t(dist,priors)=djikstraGen(start,n)\n\tpath=[]\n\tnext=end\n\twhile next!=start:\n\t\tnext=priors[next]\n\t\tpath.append(next)\n\treturn (dist[end],path)\n\ndef djikstraPathWDist(w,start,end,n):\n\t(dist,prior)=djikstraGen(w,start,n)\n\tpath=[]\n\tnext=end\n\twhile next!=start:\n\t\tpath.append(next)\n\t\tnext=prior[next]\n\tpath.append(next)\n\tpath=list(reversed(path))\n\treturn (dist,path)\n\ndef djikstraGen(w,start,n):\n\tdist=[float('inf') for _ in range(n)]\n\tprior=[None for _ in range(n)]\n\tdist[start]=0\n\tS=set()\n\tQ=set([i for i in range(n)])\n\tu=start\n\twhile not len(Q)==0:\n\t\tS.add(u)\n\t\tfor v in neighbors(u,w):\n\t\t\ttemp=dist[u]+w[u][v]\n\t\t\tif dist[v]>temp:\n\t\t\t\tdist[v]=temp\n\t\t\t\tprior[v]=u\n\t\tQ.remove(u)\n\t\tu=minDist(Q,dist)\n\treturn (dist,prior)\n\ndef neighbors(element,graph):\n\tmylist=set()\n\tfor i in range(len(graph[element])):\n\t\tif not graph[element][i]==-1:\n\t\t\tmylist.add(i)\n\treturn mylist\n\ndef minDist(myset,dist):\n\tmymin=float('inf')\n\tminelement=0\n\tfor element in myset:\n\t\tif(dist[element])\n# See LICENSE file for full copyright and licensing details.\n# License URL : \n#\n##########################################################################\n\n# Attribute Sync Operation\n\nfrom odoo import api, models\n\nclass ConnectorSnippet(models.TransientModel):\n _inherit = \"connector.snippet\"\n\n def create_prestashop_product_attribute(self , name, odoo_id, connection, ecomm_attribute_code):\n prestashop = connection.get('prestashop', False)\n status = False\n ecomm_id = False\n add_data = False\n error = ''\n if prestashop:\n try:\n add_data = prestashop.get('product_options', options={'schema': 'blank'})\n except Exception as e:\n error = str(e)\n if add_data:\n add_data['product_option'].update({\n 'group_type': 'select',\n 'position':'0'\n })\n if type(add_data['product_option']['name']['language']) == list:\n for i in range(len(add_data['product_option']['name']['language'])):\n add_data['product_option']['name']['language'][i]['value'] = name\n add_data['product_option']['public_name']['language'][i]['value'] = name\n else:\n add_data['product_option']['name']['language']['value'] = name\n add_data['product_option']['public_name']['language']['value'] = name\n try:\n ecomm_id = prestashop.add('product_options', add_data)\n except Exception as e:\n error = str(e)\n if ecomm_id:\n status = True\n return {\n 'status' : status,\n 'ecomm_id':ecomm_id,\n 'error' : error\n }\n\n def create_prestashop_product_attribute_value(self, ecomm_id, attribute_obj, ecomm_attribute_code, instance_id, connection):\n prestashop = connection.get('prestashop', False)\n status = True\n add_value = False\n error = ''\n if prestashop:\n try:\n add_value = prestashop.get('product_option_values', options={'schema': 'blank'})\n except Exception as e:\n status = False\n error = str(e)\n if add_value:\n for attribute_value_id in attribute_obj.value_ids:\n if not self.env['connector.option.mapping'].search([('odoo_id', '=', attribute_value_id.id), ('instance_id','=',instance_id)]):\n add_value['product_option_value'].update({\n 'id_attribute_group': ecomm_id,\n 'position':'0'\n })\n if type(add_value['product_option_value']['name']['language']) == list:\n for i in range(len(add_value['product_option_value']['name']['language'])):\n add_value['product_option_value']['name']['language'][i]['value'] = attribute_value_id.name\n else:\n add_value['product_option_value']['name']['language']['value'] = attribute_value_id.name\n try:\n ecomm_attr_id = prestashop.add('product_option_values', add_value)\n except Exception as e:\n status = False\n error = str(e)\n if status:\n self.create_odoo_connector_mapping('connector.option.mapping', ecomm_attr_id, \n attribute_value_id.id, instance_id,\n ecomm_attr_id = ecomm_id ,\n odoo_attr_id = attribute_obj.id)\n\n self.create_ecomm_connector_mapping('connector.option.mapping', 'prestashop', \n {'ecomm_id':ecomm_attr_id,\n 'ecomm_attr_id':ecomm_id,\n 'odoo_id':attribute_value_id.id,\n 'odoo_attr_id':attribute_obj.id,\n 'name':attribute_value_id.name,\n 'created_by': 'odoo'}, connection)\n return {\n 'status': True,\n 'error':error\n }\n ","sub_path":"pob/models/attribute_sync.py","file_name":"attribute_sync.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176232659","text":"import json\nimport os\nimport sys\nimport time\nfrom multiprocessing import Process\nfrom vk_api_entities import GroupVK, UserVK\n\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n\n\ndef print_help():\n return \"\"\"\n Шпионские игры\n Выводит список групп в ВК в которых состоит пользователь, но не состоит никто из его друзей\n Результат сохраняет в виде фала JSON в текущую папку\n - параметр коммандной строки, где id имя пользователя или его id в ВК\n Если пропущен, скрипт запросит ввод id через консоль\n \"\"\"\n\n\ndef do_crossing(user_friends_, user_croups_):\n result_ = [[], []]\n\n for group_id in user_croups_:\n group = GroupVK(group_id)\n is_friends_not_in_group = set(group.members).isdisjoint(set(user_friends_))\n\n if is_friends_not_in_group:\n result_[0].append(f'{group}')\n result_[1].append(group.info)\n return result_\n\n\ndef set_timer(user_croups_):\n execute_step = 25000\n counter = 0\n\n for group_id in user_croups_:\n group = GroupVK(group_id)\n group_info = group.info\n if 'deactivated' not in group_info[0]:\n counter += group_info[0]['members_count']\n return counter / execute_step\n\n\ndef reduce_timer(user_croups_):\n msecs = int(set_timer(user_croups_))\n step = 1\n\n for i in range(0, msecs + 1, step):\n timer = time.strftime('%H:%M:%S', time.gmtime(msecs))\n print('', end='\\r', flush=True)\n print(f'Осталось: {timer}', end='', flush=True)\n time.sleep(step)\n msecs -= step\n\n\nif __name__ == \"__main__\":\n print(print_help())\n\n try:\n id_ = sys.argv[1]\n except IndexError:\n while True:\n id_ = input('Введите имя пользователя или его id в ВК: ')\n if id_:\n break\n\n print('Подождите! Обрабатываются запросы к API')\n\n user = UserVK(id_)\n user_croups = user.groups\n\n if 'error_code' in user_croups:\n print(user_croups['error_msg'])\n\n else:\n proc = Process(target=reduce_timer, args=(user_croups,))\n proc.start()\n\n user_friends = user.friends\n result = do_crossing(user_friends, user_croups)\n\n proc.join()\n\n print('\\nПользователь', user)\n print('Список групп в ВК в которых состоит пользователь, но не состоит никто из его друзей:')\n for item in result[0]:\n print(item)\n\n path_to_save = os.path.join(current_dir, f'{id_}-groups.json')\n with open(path_to_save, \"w\", encoding=\"utf-8\") as file:\n json.dump(result[1], file, indent=2, separators=(',', ': '), ensure_ascii=False)\n print(f'Данные сохранены в {path_to_save}')\n","sub_path":"spy_games.py","file_name":"spy_games.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"198814900","text":"import os\nfrom flask import Flask, flash, request, redirect, url_for, render_template\nfrom werkzeug.utils import secure_filename\nfrom flask import send_from_directory\nimport librosa\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport librosa.display\n\nUPLOAD_FOLDER = 'app/static/'\nALLOWED_EXTENSIONS = {'mp3', 'wav'}\n\napp = Flask(__name__, template_folder='templates/')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit an empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(url_for('draw_spectr',\n filename=filename))\n return render_template('index.html')\n\n@app.route('/uploads/')\ndef uploaded_file(filename):\n return send_from_directory(app.config['IMAGE_STORE_PATH'],\n filename)\n\n\n@app.route('/audio_features/')\ndef draw_spectr(filename):\n y, sr = librosa.load(f'app/static/{filename}')\n D = np.abs(librosa.stft(y))\n plt.figure(figsize=(14, 5))\n librosa.display.specshow(librosa.amplitude_to_db(D, ref=np.max), y_axis='log', x_axis='time')\n plt.title('Power spectrogram')\n plt.colorbar(format='%+2.0f dB')\n plt.tight_layout()\n plt.savefig(f'static/{filename}.png')\n return render_template('spectrogramm.html', filename=f'{filename}.png', audioname=filename)\n\n\n@app.route('/all_features/')\ndef extract_features(filename):\n y, sr = librosa.load(f'app/static/{filename}')\n plt.figure(figsize=(14, 5))\n librosa.display.waveplot(y, sr=sr)\n plt.savefig('static/waveplot.png')\n mfcc = librosa.feature.mfcc(y, sr=sr)\n mfcc_delta = librosa.feature.delta(mfcc)\n mfcc_delta2 = librosa.feature.delta(mfcc, order=2)\n plt.figure(figsize=(14, 5))\n librosa.display.specshow(mfcc, x_axis='time')\n plt.colorbar()\n plt.title('MFCC')\n plt.savefig('static/MFCC.png')\n plt.figure(figsize=(14, 5))\n librosa.display.specshow(mfcc_delta, x_axis='time')\n plt.colorbar()\n plt.title(r'MFCC-$\\Delta$')\n plt.savefig('static/MFCC_delta.png')\n plt.figure(figsize=(14, 5))\n librosa.display.specshow(mfcc_delta2, x_axis='time')\n plt.colorbar()\n plt.title(r'MFCC-$\\Delta^2$')\n plt.savefig('static/MFCC_delta2.png')\n S, phase = librosa.magphase(librosa.stft(y))\n rms = librosa.feature.rms(S=S)\n plt.figure(figsize=(14, 5))\n plt.semilogy(rms.T, label='RMS Energy')\n plt.xticks([])\n plt.xlim([0, rms.shape[-1]])\n plt.legend()\n plt.savefig('static/RMS.png')\n return render_template('all_features.html', waveplot='waveplot.png', mfcc='MFCC.png', mfcc_delta='MFCC_delta.png',\n mfcc_delta2='MFCC_delta2.png', rms='rms.png')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588904327","text":"# coding=UTF-8\n# ==============================================================================\n#\n# PROJECT REALITY ADMIN SETTINGS (formerly AD Framework)\n#\n# WARNING: If logging is enabled, a folder must be created under /admin/logs/, or they will not be recorded\n#\n# $Id: realityconfig_admin.py 20838 2013-06-24 02:41:19Z bloodydeed $\n#\n#\n# ==============================================================================\n# GLOBAL SETTINGS\n#\n# If false, the entire RealityAdmin is disabled.\n# Default is True\nRAEnabled = True\n#\n# Display a sponsor message.\n# Default is False\nsponsorMessageEnabled = True\n#\n# The \"sponsormessage\" will be displayed every [interval] seconds.\n# Default is 600 seconds\nsponsorMessage = \"§C1001***§C1001 This server is powered by §C1001RealityAdmin ***§C1001\"\nsponsorMessageInterval = 600\n#\n# Are admins alerted about game notifications? (E.g. FOB Destruction via radio).\n# Default is True\ngameNotificationsEnabled = True\n#\n#\n# ==============================================================================\n# Squads SETTINGS\n#\n# Seconds after round start until allowed to create squads. \n# sqd_noSquadsBefore is subtracted from the number of seconds set in 'PRROUNDSTARTDELAY' var via realityconfig_common.py in order to get the SquadCreationTime.\n# Default is 90\n\nsqd_noSquadsBefore = 90\n#\n# Resign early\n# Default is False\nsqd_resignEarly = False\n#\n# Amount of failed attempts before kick\n# Default is 0 (disabled)\nsqd_kickLimit = 0\n#\n# Kick squadless\n# Default is False (disabled)\nsqd_kickSquadLess = False\n#\n# Time until squadless players are kicked\n# Default is 30\nsqd_kickSquadLessTime = 30\n#\n#\n# ==============================================================================\n# SMARTBALANCE SETTINGS\n#\n# Enable/disable smartbalancing.\n# Default is True\nsmb_enabled = True\n#\n# Perform smart balance when the difference of the teams is x or more.\n# Default is 2\nsmb_difference = 2\n#\n# A list of (partial) playernames and/or (clan)tags that get excluded from smart balancing.\n# If tag is part of name, you need to define position (front/back) by using * as wild card.\n# E.g. to add [R-DEV]PRBot you need to add \"[R-DEV]*\"\nsmb_excludeList = [\n \"[R-DEV]*\",\n]\n# If set to True, it will teamswap everyone on round startup.\n# Some people don't (or can't) have modmanager to do this for them.\n# Default is True\nsmb_swapTeamsOnStart = True\n#\n# \n# If set to true, teams will be scrambled at the start of each round\nsmb_scrambleTeamsOnStart = False\n# If set to true, when a player joins the server they will join onto a random team.\n# Joining players will still be subject to any smartbalancing.\n# By default players always load in on blufor. Default is False.\nsmb_randomiseJoinTeam = False\n# If set to True, players might get teamswitched for balance when they go dead-dead\n# Might switch anyone who is not SL/CO or on switch list\n# Default is True\nsmb_balanceOnDeath = True\n\n# Keep same IP players on the same team\n# Default is False\nsmb_antiGhost = False\n#\n#\n# ==============================================================================\n# LOGS SETTINGS\n#\n# Date format for logging\n# Default is \"%Y%m%d_%H%M\"\nlog_date_format = \"%Y-%m-%d %H:%M\"\n#\n# Time format for logging\n# Default is \"%H:%M:S\"\nlog_time_format = \"%H:%M:%S\"\n#\n# Enable/disable chat logging\n# Default is True\nlog_chat = True\n#\n# Enable/disable player connect/disconnect logging. Written into chatlog\n# Default is True\nlog_connects = True\n#\n# Enable/disable player team switch logging. Written into chatlog\n# Default is False\nlog_changeTeam = False\n#\n# Chat log file name.\n# Default is \"chatlog_%Y-%m-%d_%H%Ms.txt\"\nlog_chat_file = \"chatlog_%Y-%m-%d_%H%M.txt\"\n#\n# Chat log file name.\n# Default is \"admin/logs\"\nlog_chat_path = \"admin/logs\"\n#\n# Enable/disable teamkill logging. Saved in chatlog\n# Default is True\nlog_teamkills = True\n#\n# Enable/Disable logging of players who play from the same IP at the same time.\n# Default is True\nlog_coincident_IPs = True\n#\n# Enable/disable kill logging. Saved in chatlog\n# Default is False\nlog_kills = False\n#\n# Enable/disable admin command logging. Saved in continues file.\n# Default is True\nlog_admins = True\n#\n# Enable/disable logging of bans. Saved in continues file.\n# Default is True\nlog_bans = True\n#\n# Enable/disable logging of tickets on round end. Saved in continues file.\n# Default is True\nlog_tickets = True\n\n\n#\n# Filename of the admin log file\n# Default is \"ra_adminlog.txt\"\nlog_admins_file = \"ra_adminlog.txt\"\n#\n# Path relative to PR root (not mod root) of admin log file\n# Default is \"admin/logs\"\nlog_admins_path = \"admin/logs\"\n#\n# Filename of the cd hash log file\n# Default is \"cdhash.log\"\nlog_hash_file = \"cdhash.log\"\n#\n# Path relative to PR root (not mod root) of cd hash log file\n# Default is \"admin/logs\"\nlog_hash_path = \"admin/logs\"\n#\n# Filename of the admin log file\n# Default is \"banlist_info.log\"\nlog_bans_file = \"banlist_info.log\"\n#\n# Path relative to PR root (not mod root) of ban log file. [MOD] gets replaced by current mod directory\n# Default is \"[MOD]/settings/\"\nlog_bans_path = \"[MOD]/settings/\"\n#\n# Filename of the coincident IP address file\n# default is \"IPcoincidences.log\"\nlog_IP_coincidence_file = \"IPcoincidences.log\"\n#\n# Path relative to PR root (not mod root) of IP coincidence log. [MOD] gets replaced by current mod directory\n# Default is \"[MOD]/settings/\"\nlog_IP_coincidence_path = \"[MOD]/settings/\"\n#\n# Filename of the tickets log file\n# Default is \"tickets.log\"\nlog_tickets_file = \"tickets.log\"\n# Path relative to PR root (not mod root) of tickets log file\n# Default is \"admin/logs\"\nlog_tickets_path = \"admin/logs\"\n#\n#\n#\n# ==============================================================================\n# ANNOUNCER SETTINGS\n#\n# Tip: Text preceded by §C1001 will make it orange. §3 makes it big. §C1001§3 makes it orange and big.\n# Enable/disable announcer.\n# Default is True\nann_enabled = True\n#\n# Enable/disable dislpaying a message when a player joins the server (spawns for the first time).\n# Default is True\nann_joinMessageEnabled = True\n#\n# Message to send to the player (this is a PM).\n# If you want the message to contain a name, make sure to insert [playername] somewhere.\nann_joinMessage = \"§C1001Welcome to the battlefield, [playername]!\"\n#\n# If True, a message is displayed when a player disconnects from the server.\n# Default is False\nann_disconnectMessageEnabled = False\n#\n# This message is displayed when a player disconnects from the server.\nann_disconnectMessage = \"[playername] has left the battlefield\"\n#\n# Enable/disable displaying timed messages.\n# Default is False\nann_timedMessagesEnabled = False\n#\n# Timed servermessages.\n# Usage: Interval: Message\nann_timedMessages = {\n 100: \"Message 1\",\n 200: \"Message 2\",\n 300: \"\"\"Very long message,\nOver multiple lines\"\"\"\n}\n#\n#\n# ==============================================================================\n# ADMIN SETTINGS\n#\n# Enable/disable admincommands.\n# Default is True\nadm_enabled = True\n#\n# Enable/disable to show PRISM users in !admins command.\n# Default is True\nadm_show_prism = True\n#\n# If true, as soon as the last admin leaves autoadmin will be activated.\n# Default is False\nadm_autoAdmin = False\n#\n# If true, admins will get notified about players switching teams.\n# Default is False\nadm_notifyChangeTeam = False\n#\n# If true, send a message on each teamkill containing\n# weapon and distance between the players\n# Default is True\nadm_sendTeamKillMessage = True\n#\n# If true, will notify all admins that a player has connected with\n# the same IP as another player currently on the server.\n# Default is True\nadm_notifySameIP = True\n#\n# Time in minutes a player is temp banned (if you use the temp-ban command, normal ban is forever!).\n# Note: if the server is restarted, the ban is lifted.\n# Default is 180\nadm_banTime = 180\n#\n# Admin command symbol.\n# Default is !\nadm_commandSymbol = \"!\"\n#\n# Symbol to indicate you want to target player ID instead of name.\n# Default is @\nadm_idPrefix = \"@\"\n#\n# Symbol to indicate you want to target a squad instead of name.\n# Default is #\nadm_squadPrefix = \"#\"\n#\n# Define the maximum altitude (used in the fly-command).\n# Default is 1000\nadm_maxAltitude = 1000\n#\n#\n# Time how long a mapvote will take.\n# Default is 60\nadm_mvoteDuration = 60\n#\n# Time between the !mvote message pops up in the upper left corner.\n# Default is 10\nadm_mvoteRecurrence = 10\n#\n# The maximum number of ropes a player can have active\n# Default is 10\nadm_maxRopes = 10\n#\n# If !givelead should work in coop\n# Default is true\nadm_coopGiveLead = True\n#\n# Array in which the names of the administrators will be saved.\n# Make sure there are NO duplicates!\nadm_adminHashes = {\n # \"ENTER_ADMIN_HASHES_HERE\": 0, # comment , Superadmin\n}\n#\n# Array in which the liteadmins are saved.\n# Leave it empty if you dont want to use this functionality.\nadm_liteAdminHashes = {\n # \"ENTER_LITE_ADMIN_HASHES_HERE\": 2, # comment , Liteadmin\n}\n#\n# Command aliases\n# Specify aliases for long commands here.\nadm_commandAliases = {\n \"k\": \"kick\",\n \"tb\": \"tempban\",\n \"b\": \"ban\",\n \"r\": \"report\",\n \"rp\": \"reportplayer\",\n \"w\": \"warn\",\n \"s\": \"say\",\n \"m\": \"message\",\n \"st\": \"sayteam\",\n \"ub\": \"unban\",\n \"mvote\": \"mapvote\",\n \"lastmap\": \"history\",\n \"lastmaps\": \"history\",\n \"ug\": \"ungrief\",\n}\n#\n# Rights management.\n# The lower the powerlevel, the more power one has.\n# Two powerlevels are defined by default, but you can define as many as you want.\nadm_adminPowerLevels = {\n # 0: Superadmin, can do everything.\n # 1: Moderator, can't do everything.\n # 2: Meant to use for liteadmins.\n # 777: used for commands that everyone can use.\n #\n # Reload the current map.\n # Default is 1\n \"reload\": 1,\n #\n # Run the next map.\n # Default is 2\n \"runnext\": 2,\n #\n # Set a next map.\n # Default is 2\n \"setnext\": 2,\n #\n # Initializes a global server mapvote between 2-3 maps.\n # People can then vote with either writing 1,2 or 3 in chat.\n # All admins will receive a message which map won after a configured time.\n # Default is 2\n \"mapvote\": 2,\n #\n # Sends a message to a specified player.\n # Similar to !warn but without the STOP DOING THAT and is private.\n \"message\": 2,\n #\n # Diplays the ticket count of both teams.\n \"tickets\": 0,\n #\n # Player control\n # Ban a player.\n # Default is 1\n \"ban\": 1,\n #\n # Ban a player for a specified amount of time.\n # Default is 1\n \"timeban\": 1,\n #\n # Unbans the latest banned player.\n # Default is 1\n \"unban\": 1,\n #\n # Send a player up in the air.\n # Default is 0\n \"fly\": 0,\n #\n # Retrieves the hash of certain player.\n # Default is 2\n \"hash\": 2,\n #\n # Kick a player.\n # Default is 2\n \"kick\": 2,\n #\n # Kill a player.\n # Default is 1\n \"kill\": 1,\n #\n # Resign a player from being squad leader or commander.\n # Default is 2\n \"resign\": 2,\n #\n # Resign a player from being squad leader or commander.\n # Default is 2\n \"resignall\": 2,\n #\n # Teamswitch a player.\n # Default is 2\n \"switch\": 2,\n #\n # Temporary ban a player (basically extended 'kick').\n # Default is 1\n \"tempban\": 1,\n #\n # Warn a player.\n # Default is 2\n \"warn\": 2,\n #\n # Text messages\n # Show help about commands.\n # Default is 2\n \"help\": 2,\n #\n # Send a message to everybody.\n # Default is 2\n \"say\": 2,\n #\n # Same as !s, but for one team only.\n # Default is 2\n \"sayteam\": 2,\n #\n # Server- and Pythoncommands\n # Enable/disable smart balancing (ab = autobalance, people call it that).\n # Default is 1\n \"ab\": 1,\n # Reload some settings.\n # Default is 2\n \"init\": 2,\n #\n #\n # Swap the teams.\n # Default is 0\n \"swapteams\": 0,\n #\n #\n # Scramble the teams.\n # Default is 0\n \"scramble\": 0,\n #\n #\n # Stops the server.\n # Default is 1\n \"stopserver\": 1,\n #\n # Enable/disable autoadmin.\n # Default is 1\n \"aa\": 1,\n # \n # Displays a list of the last n maps that were played on the server (Configurable count)\n # Default is 2\n \"history\": 2,\n #\n # Open commands\n # Please note that 777 is a fixed value for \"open\" commands!\n # This means everybody on the server can use them.\n # Returns a list of online admins.\n # Default is 777\n \"admins\": 777,\n #\n # Report a player.\n # Default is 777\n \"reportplayer\": 777,\n #\n # Send a message to the admins.\n # Default is 777\n \"report\": 777,\n #\n # Shows the serverrules.\n # Default is 777\n \"rules\": 777,\n #\n # Show the next map.\n # Default is 777\n \"shownext\": 777,\n #\n # Give squad lead to another player.\n # Default is 777\n \"givelead\": 777,\n #\n # shows if Battlerecorder is activated and which quality its running with.\n # Default is 777\n \"br\": 777,\n #\n # Displays a link to the server website.\n # Default is 777\n \"website\": 777,\n #\n # Random number utility, return a random int 0/1 by default\n # or in the range [0,m] if m is a supplied positive integer\n # Default is 777\n \"flip\": 777,\n # Ungrief (TODO)\n #\n #\n \"ungrief\": 1,\n #\n #\n # Reset squads - may fix squad bug\n \"resetsquads\": 1,\n #\n # Server Entrance control\n # handle whitelist and join permissions to the server\n \"ec\": 1,\n #\n # Player info\n # Print IP, Account ID (\"hash\"), level, and whitelist status of a player\n \"info\": 2,\n}\n#\n# This text will be sent to the player issueing !website.\nadm_website = \"§C1001http://www.realitymod.com\"\n#\n# Predefined reasons, so you only have to type a keyword as a reason.\n# The script will automatically replace it with the reason you enter below.\n# Note: only use lowercase in the reason \"keys\", you can use all cases in the reason itself.\nadm_reasons = {\n \"afk\": \"You were AFK!\",\n \"dis\": \"You're bringing the game into disrepute. Be gone, foul demon!\",\n \"fail\": \"You are a failure\",\n \"steal\": \"Asset stealing\",\n \"tk\": \"Stop teamkilling!\",\n \"lang\": \"Watch your language!\",\n \"language\": \"Keep your language clean!\",\n \"locked\": \" Open your locked squad!\",\n \"solo\": \"Your vehicle is not properly manned!\",\n \"spam\": \"Stop chat-spamming!\",\n}\n#\n# Enable displaying rules.\n# Default is False\nadm_rulesEnabled = False\n#\n# Array in which the rules of the server will be saved.\n# Five rules is the max, the player can't see more than five lines. Remove lines if desired.\nadm_rules = [\n \"Rule 1\",\n \"Rule 2\",\n \"Rule 3\",\n \"Rule 4\",\n \"Rule 5\",\n]\n#\n# Modify this if you want to add additional maps. You do NOT need to add official maps.\n# Example:\n# \"asad_khal|gpm_cq|inf\",\n# \"asad_khal|gpm_cq|alt\",\n# \"asad_khal|gpm_cq|std\",\n# \"asad_khal|gpm_cq|lrg\"\nadm_mapListCustom = [\n # \"mapname|gamemode|layer\",\n]\n\n# Give reserved slots for the following groups\n# available groups: [\"CON\", \"DEV\", \"RETIRED\", \"TESTER\"]\nadm_devReservedSlots = [\"CON\", \"DEV\", \"RETIRED\", \"TESTER\"]\n\n# PRISM: See realitymod.com/prism for help.\nrcon_enabled = False\n\n# Rcon welcome message\nrcon_welcome = 'Welcome to PRISM!'\n\n# Powerlevels for the commands\nrcon_commandPowerLevels = {\n # PRISM user management\n 'getusers': 0,\n 'adduser': 0,\n 'changeuser': 0,\n 'deleteuser': 0,\n # Game management\n 'mapplayers': 0,\n 'mapgameplay': 0,\n 'readbanlist': 0,\n 'setbanlist': 0,\n 'readmaplist': 777,\n 'setmaplist': 0,\n # Do not change these\n 'listplayers': 777,\n 'serverdetails': 777,\n 'gameplaydetails': 777,\n}\n\n\n# Prism TCP port to listen on\nrcon_port = 4712\n\n\n# Entrance control\n# Possible values are 0, 1, 2\n# 0 Means everyone\n# 1 Means some trust\n# 2 Means high trust\nec_minimumTrust = 0\n\n# Allow VAC banned users to join the server if they're not on whitelist\nec_allowVacBanned = True\n\n\n# Report this as your external IP to the master server.\n# Do not touch unless you have multiple interfaces\nsv_externalIP = \"\"\n","sub_path":"prbf2/realityconfig_admin.py","file_name":"realityconfig_admin.py","file_ext":"py","file_size_in_byte":16324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"422139377","text":"\n\nfrom xai.brain.wordbase.nouns._territory import _TERRITORY\n\n#calss header\nclass _TERRITORIES(_TERRITORY, ):\n\tdef __init__(self,): \n\t\t_TERRITORY.__init__(self)\n\t\tself.name = \"TERRITORIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"territory\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_territories.py","file_name":"_territories.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"331196986","text":"import discord\r\nfrom discord.ext import commands\r\nimport random\r\nimport asyncio\r\nfrom textblob import TextBlob\r\n\r\nclient = discord.Client()\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('Logged in as')\r\n print(client.user.name)\r\n \r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author == client.user:\r\n return\r\n \r\n if message.content.startswith('Greetings'):\r\n await client.send_message(message.channel, 'Greetings? Why not say \"hello\" like a normal person?')\r\n msg = await client.wait_for_message(author=message.author, content='hello')\r\n await client.send_message(message.channel, 'Hello.')\r\n\r\n if message.content.startswith('Hireling, hold'):\r\n msg = 'Yes, Master. *takes item from {0.author.display_name} and puts it in his pack.*'.format(message)\r\n await client.send_message(message.channel, msg)\r\n\r\n if message.content.startswith('Hireling, give'):\r\n msg = 'Right away! *takes item out of pack and hands it to {0.author.display_name}*'.format(message)\r\n await client.send_message(message.channel, msg)\r\n \r\n if message.content.startswith('Good'):\r\n msg = \"*mumbles* What's so good about it?\".format(message)\r\n await client.send_message(message.channel, msg)\r\n return\r\n\r\n\r\nclient.run()\r\n","sub_path":"replies.py","file_name":"replies.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191214129","text":"from multiprocessing import Manager, Process\r\n# import readchar\r\nimport time\r\nfrom datetime import datetime\r\nimport sys\r\nimport os\r\nsys.path.append(\"/kaiyo/test\")\r\n\r\nfrom char_test import move_test\r\n\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n with Manager() as manager:\r\n #センサーのdata\r\n data = manager.dict()\r\n #my_blanceの操作量\r\n MV = manager.Value(\"d\", 0.0)\r\n #my_blanceの目標値\r\n goal_yaw = manager.Value(\"i\", 0)\r\n\r\n process1 = Process(target=move_test, args=[])\r\n\r\n process1.start()\r\n\r\n # while True:\r\n # pass\r\n\r\n process1.join()\r\n # process2.join()\r\n except Exception as e:\r\n print(\"\\n------\")\r\n print(\"main.py : \",e)\r\n print(\"------\\n\")\r\n\r\n print(\"end\")\r\n exit()\r\n","sub_path":"test/Process_test.py","file_name":"Process_test.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"49645039","text":"import pandas as pd\nimport timeSync\n\ncsvpath =\"cr-sensor3-test\"\ndata = pd.read_csv(csvpath + \".csv\", names = ['rawTime','temp','humidity'])\n\nif len(data) > 0:\n\t#multiply to get time in seconds\n\tdata['rawTime'] = data['rawTime']*8\n\n\ttimeSeries = list(data['rawTime'])\n\n\tdata['rawTime'] = timeSync.checkResetOverflow(timeSeries)\n\n\ttimeSync.singleSync(data, 'rawTime')\n\n\tpd.DataFrame.to_csv(data,path_or_buf=csvpath+\"-clean.csv\")\n","sub_path":"timeTest.py","file_name":"timeTest.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82793310","text":"\"\"\"Class to convert from log linear model to MRF\"\"\"\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom .MarkovNet import MarkovNet\n\n\nclass LogLinearModel(MarkovNet):\n \"\"\"\n Log linear model class. Able to convert from log linear features to pairwise MRF.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize a LogLinearModel. Create a Markov net.\"\"\"\n super(LogLinearModel, self).__init__()\n self.unary_features = dict()\n self.unary_feature_weights = dict()\n self.edge_features = dict()\n self.num_features = dict()\n self.num_edge_features = dict()\n\n # matrix mode placeholders\n self.weight_dim = None\n self.max_states = None\n self.max_unary_features = None\n self.max_edge_features = None\n self.unary_weight_mat = None\n self.edge_weight_mat = None\n self.unary_feature_mat = None\n self.edge_feature_mat = None\n\n def set_edge_factor(self, edge, potential):\n \"\"\"\n Set a factor by inputting the involved variables then the potential function. \n The potential function should be a np matrix. \n \n This method implicitly creates a single-dimensional edge feature set to value 1.0.\n\n :param edge: 2-tuple of the variables in the edge. Can be in any order.\n :param potential: k1 by k2 matrix of potential values for the joint state of the two variables\n :return: None\n \"\"\"\n super(LogLinearModel, self).set_edge_factor(edge, potential)\n if edge not in self.edge_features:\n # set default edge feature\n self.set_edge_features(edge, np.array([1.0]))\n\n def set_unary_weights(self, var, weights):\n \"\"\"\n Set the log-linear weights for the unary features of var. Used for non-matrix mode only. \n \n :param var: variable whose weights to set.\n :param weights: ndarray weight matrix of shape (self.num_states[var], len(self.unary_features[var]))\n :return: None\n \"\"\"\n assert isinstance(weights, np.ndarray)\n assert weights.shape[0] == self.num_states[var]\n self.unary_feature_weights[var] = weights\n\n def set_unary_features(self, var, values):\n \"\"\"\n Set the log-linear features for a particular variable. Used for non-matrix mode only.\n :param var: variable whose features to set\n :param values: ndarray feature vector describing the unary variable of any length\n :return: None\n \"\"\"\n assert isinstance(values, np.ndarray)\n self.unary_features[var] = values\n\n self.num_features[var] = len(values)\n\n def set_edge_features(self, edge, values):\n \"\"\"\n Set the log-linear feature for a particular edge. Used for non-matrix mode only. Currently does not work.\n :param edge: pair of variables representing the edge being set\n :param values: ndarray of feature values describing the edge\n :return: None\n \"\"\"\n reversed_edge = (edge[1], edge[0])\n self.edge_features[edge] = values\n self.num_edge_features[edge] = len(values)\n\n self.edge_features[reversed_edge] = values\n self.num_edge_features[reversed_edge] = len(values)\n\n def set_all_unary_factors(self):\n \"\"\"\n Uses current weights and features to set the potential functions for all unary factors.\n Used for non-matrix mode only.\n \n :return: None\n \"\"\"\n for var in self.variables:\n self.set_unary_factor(var, self.unary_feature_weights[var].dot(self.unary_features[var]))\n\n def set_feature_matrix(self, feature_mat):\n \"\"\"\n Set matrix of features for all unary variables. Used for matrix mode.\n \n :param feature_mat: ndarray of shape (max_unary_features, len(variables)) with variables as ordered in self.variables.\n Each jth column is the jth variable's feature vector.\n :return: None\n \"\"\"\n assert (np.array_equal(self.unary_feature_mat.shape, feature_mat.shape))\n\n self.unary_feature_mat[:, :] = feature_mat\n\n def set_weights(self, weight_vector):\n \"\"\"\n Set the unary and edge weight matrices by splitting and reshaping a weight vector. Useful for optimization when\n the optimizer is searching for a vector value. Used for matrix mode.\n \n :param weight_vector: real vector of length self.max_unary_features * self.max_state + \n self.max_edge_features * self.max_states ** 2\n :return: None\n \"\"\"\n num_vars = len(self.variables)\n\n feature_size = self.max_unary_features * self.max_states\n feature_weights = weight_vector[:feature_size].reshape((self.max_unary_features, self.max_states))\n\n pairwise_weights = weight_vector[feature_size:].reshape((self.max_edge_features, self.max_states ** 2))\n\n self.set_unary_weight_matrix(feature_weights)\n self.set_edge_weight_matrix(pairwise_weights)\n\n self.update_unary_matrix()\n self.update_edge_tensor()\n\n def set_unary_weight_matrix(self, weight_mat):\n \"\"\"\n Set unary weight matrix. Convenience method that also checks the shape of the new matrix. Used for matrix mode.\n \n Developer note: this method may not be necessary. It's meant to copy the matrix into the original weight matrix,\n memory but that may create problems for autodiff software in the future.\n \n :param weight_mat: ndarray of shape (self.max_unary_features, self.max_states)\n :type weight_mat: ndarray\n :return: None\n \"\"\"\n assert (np.array_equal(self.unary_weight_mat.shape, weight_mat.shape))\n self.unary_weight_mat[:, :] = weight_mat\n\n def set_edge_weight_matrix(self, edge_weight_mat):\n \"\"\"\n Set edge weight matrix. Used for matrix mode.\n \n See developer note in set_unary_weight_matrix.\n \n :param edge_weight_mat: ndarray of shape (self.max_edge_features, self.max_states ** 2)\n :type edge_weight_mat: ndarray\n :return: None\n \"\"\"\n assert (np.array_equal(self.edge_weight_mat.shape, edge_weight_mat.shape))\n self.edge_weight_mat[:, :] = edge_weight_mat\n\n def update_unary_matrix(self):\n \"\"\"\n Set the unary potential matrix by multiplying the feature matrix by the weight matrix.\n :return: None\n \"\"\"\n self.set_unary_mat(self.unary_feature_mat.T.dot(self.unary_weight_mat).T)\n\n def update_edge_tensor(self):\n \"\"\"\n Set the edge potential tensor by multiplying the edge feature matrix by the edge weight matrix, reshaping, and\n duplicating (to allow the tensor to contain the appropriate values for forward and backward messages.\n \n Used for matrix mode.\n \n :return: None\n \"\"\"\n half_edge_tensor = self.edge_feature_mat.T.dot(self.edge_weight_mat).T.reshape(\n (self.max_states, self.max_states, self.num_edges))\n self.edge_pot_tensor[:, :, :] = np.concatenate((half_edge_tensor.transpose(1, 0, 2), half_edge_tensor), axis=2)\n\n def create_matrices(self):\n \"\"\"\n Create matrix representations of the MRF structure and log-linear model to allow inference to be done via \n matrix operations.\n :return: None\n \"\"\"\n super(LogLinearModel, self).create_matrices()\n\n # create unary matrices\n self.max_unary_features = max([x for x in self.num_features.values()])\n self.unary_weight_mat = np.zeros((self.max_unary_features, self.max_states))\n self.unary_feature_mat = np.zeros((self.max_unary_features, len(self.variables)))\n\n for var in self.variables:\n index = self.var_index[var]\n self.unary_feature_mat[:, index] = self.unary_features[var]\n\n # create edge matrices\n self.max_edge_features = max([x for x in self.num_edge_features.values()] or [0])\n self.edge_weight_mat = np.zeros((self.max_edge_features, self.max_states ** 2))\n self.edge_feature_mat = np.zeros((self.max_edge_features, self.num_edges))\n\n for edge, i in self.message_index.items():\n self.edge_feature_mat[:, i] = self.edge_features[edge]\n\n self.weight_dim = self.max_states * self.max_unary_features + self.max_edge_features * self.max_states ** 2\n\n def create_indicator_model(self, markov_net):\n \"\"\"\n Sets this object to be a log-linear model representation of a Markov Net to enable directly learning the \n potential values. Each feature vector is an indicator vector, such that each dimension of the weights \n corresponds to exactly one variable or edge.\n \n :param markov_net: Markov network to build the indicator model of\n :type markov_net: MarkovNet\n :return: None\n \"\"\"\n n = len(markov_net.variables)\n\n # set unary variables\n for i, var in enumerate(markov_net.variables):\n self.declare_variable(var, num_states=markov_net.num_states[var])\n self.set_unary_factor(var, markov_net.unary_potentials[var])\n indicator_features = np.zeros(n)\n indicator_features[i] = 1.0\n self.set_unary_features(var, indicator_features)\n\n # count edges\n num_edges = 0\n for var in markov_net.variables:\n for neighbor in markov_net.get_neighbors(var):\n if var < neighbor:\n num_edges += 1\n\n # create edge indicator features\n i = 0\n for var in markov_net.variables:\n for neighbor in markov_net.get_neighbors(var):\n if var < neighbor:\n edge = (var, neighbor)\n self.set_edge_factor(edge, markov_net.get_potential(edge))\n indicator_features = np.zeros(num_edges)\n indicator_features[i] = 1.0\n self.set_edge_features(edge, indicator_features)\n i += 1\n\n self.create_matrices()\n\n self.unary_feature_mat = csr_matrix(self.unary_feature_mat)\n self.edge_feature_mat = csr_matrix(self.edge_feature_mat)\n\n # load current unary potentials into unary_weight_mat\n for (var, i) in self.var_index.items():\n self.unary_weight_mat[i, :] = -np.inf\n potential = self.unary_potentials[var]\n self.unary_weight_mat[i, :len(potential)] = potential\n\n # load current edge potentials into edge_weight_mat\n for (edge, i) in self.message_index.items():\n padded_potential = -np.inf * np.ones((self.max_states, self.max_states))\n potential = self.get_potential(edge)\n padded_potential[:self.num_states[edge[0]], :self.num_states[edge[1]]] = potential\n self.edge_weight_mat[i, :] = padded_potential.ravel()\n\n def load_factors_from_matrices(self):\n \"\"\"\n Load dictionary-based factors from current matrices. Since learning is often done by updating the matrix\n form, it's important to call this method before using the dictionary-based views of the potentials. This\n method will also properly undo the padding that makes all potential vectors and matrices the same shape (with \n zero-probability states to pad the smaller cardinality variables).\n \n :return: None\n \"\"\"\n self.update_unary_matrix()\n self.update_edge_tensor()\n\n for (var, i) in self.var_index.items():\n self.set_unary_factor(var, self.unary_mat[:self.num_states[var], i].ravel())\n\n for edge, i in self.message_index.items():\n self.set_edge_factor(edge,\n self.edge_pot_tensor[:self.num_states[edge[1]], :self.num_states[edge[0]],\n i].squeeze().T)\n","sub_path":"mrftools/LogLinearModel.py","file_name":"LogLinearModel.py","file_ext":"py","file_size_in_byte":11889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11261158","text":"from django.http import JsonResponse\r\nimport pymongo\r\nimport json\r\nfrom bson import json_util, ObjectId\r\nfrom datetime import datetime\r\n\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom pymongo import MongoClient\r\nfrom rest_framework import status\r\nimport time\r\n\r\nimport threading\r\n# from threading import Thread\r\n\r\n\r\ntry:\r\n client: MongoClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\r\n print('connect database successful.')\r\nexcept Exception as e:\r\n print('connect database error.', e)\r\n\r\ndb = client[\"slatestdb\"]\r\n\r\ncol = db[\"slapolicies\"]\r\n\r\ncol_list = db.list_collection_names()\r\nif 'slapolicies' in col_list:\r\n print(\"The collection exist.\")\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/\r\ndef get_data_from_db(request):\r\n tmp_type = col.find()\r\n data = json.loads(json_util.dumps(tmp_type))\r\n return JsonResponse({\r\n 'data': data\r\n }, status=status.HTTP_200_OK)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/insert\r\ndef insert_data(request):\r\n try:\r\n # timestamp_created = datetime.timestamp(datetime.now())\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n working_time = request_body.get('working_time')\r\n created_time = request_body.get('created_time')\r\n SLA_name = request_body.get('name')\r\n SLA_time = request_body.get('SLA_time')\r\n start_time = request_body.get('start_time')\r\n end_time = request_body.get('end_time')\r\n department = request_body.get('department')\r\n ticket_status = request_body.get('status')\r\n response_time = request_body.get('response_time')\r\n escalate_time = request_body.get('escalate_time')\r\n process_time = request_body.get('process_time')\r\n result = request_body.get('result')\r\n\r\n data = {\r\n \"working_time\": working_time,\r\n \"created_time\": created_time,\r\n \"response_time\": response_time,\r\n \"department\": department,\r\n \"name\": SLA_name,\r\n \"status\": ticket_status,\r\n \"result\": result,\r\n \"process_time\": process_time,\r\n \"SLA_time\": SLA_time,\r\n \"start_time\": start_time,\r\n \"end_time\": end_time,\r\n \"escalate_time\": escalate_time,\r\n }\r\n col.insert_one(data)\r\n return JsonResponse({\r\n 'data': 'Create new element successful.'\r\n }, status=status.HTTP_201_CREATED)\r\n except Exception as err:\r\n print(\"error:\", err)\r\n return JsonResponse({\r\n 'message': 'Create unsuccessful.'\r\n }, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/update\r\ndef update_data(request, result, SLA_time, process_time, response_time):\r\n try:\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n _id = request_body.get('_id')\r\n\r\n col.update_one({'_id': ObjectId(_id)}, {\r\n \"$set\": {\r\n 'SLA_time': str(SLA_time),\r\n 'response_time': str(response_time),\r\n 'process_time': str(process_time),\r\n 'status': 'done',\r\n 'result': result,\r\n },\r\n })\r\n\r\n return JsonResponse({\r\n 'message': 'Update element successful.'\r\n }, status=status.HTTP_201_CREATED)\r\n except Exception as err:\r\n print(\"error:\", err)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/thread1\r\ndef get_sla_policy1(request):\r\n data = {\r\n 'start_time': datetime.now().time(),\r\n 'sla_name': {\r\n 'P1': 'SLA1',\r\n 'P2': 'SLA2',\r\n },\r\n 'response_time': {\r\n 'SLA1': '10', # %H:%M:%S\r\n 'SLA2': '20', # %H:%M:%S\r\n },\r\n 'result': {\r\n 'SLA1': '5',\r\n 'SLA2': '7',\r\n 're': ('Done', 'Overdue'),\r\n },\r\n }\r\n\r\n return JsonResponse({\r\n 'data': data['sla_name']\r\n }, status=status.HTTP_200_OK)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/threading\r\ndef threading_task(request):\r\n try:\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n ticket_status = request_body.get('status')\r\n SLA_time = request_body.get('SLA_time')\r\n process_time = request_body.get('process_time')\r\n department = request_body.get('department')\r\n thread_id = 0\r\n print('SLA_time1', SLA_time)\r\n print(type(SLA_time))\r\n\r\n SLA_time = HmstoSeconds(SLA_time) # SLA time (seconds)\r\n print('SLA_time2', SLA_time)\r\n print(type(SLA_time))\r\n process_time = HmstoSeconds(process_time) # process time (seconds)\r\n print('process_time1', process_time)\r\n print(type(process_time))\r\n # Apply threading to runtime timer() and show_result()\r\n if ticket_status == 'new':\r\n timer_data = check_created_time(request)\r\n elif ticket_status == 'done':\r\n # run async function show_result\r\n thread2 = threading.Thread(target=show_result,\r\n args=(request, SLA_time, process_time, department, ticket_status))\r\n thread2.setDaemon(True)\r\n thread2.start()\r\n thread_id = threading.get_ident()\r\n # thread2.is_alive()\r\n thread2.join()\r\n return JsonResponse({\r\n 'message': 'ok.'\r\n },status=status.HTTP_200_OK)\r\n\r\n except Exception as err:\r\n print('error: ', err)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/result\r\ndef show_result(request, *args, **kwargs):\r\n try:\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n SLA_time = request_body.get('SLA_time')\r\n department = request_body.get('department')\r\n SLA_name = request_body.get('name')\r\n response_time = request_body.get('response_time')\r\n response_time = HmstoSeconds(response_time) # response_time(seconds)\r\n\r\n SLA_time = HmstoSeconds(SLA_time) # SLA time (seconds)\r\n print('SLA_time2', SLA_time)\r\n\r\n process_time = request_body.get('process_time')\r\n process_time = HmstoSeconds(process_time) # process_time(seconds)\r\n print('process_time1', process_time)\r\n\r\n result = ''\r\n ticket_status = request_body.get('status')\r\n\r\n escalate_time = request_body.get('escalate_time')\r\n escalate_time = HmstoSeconds(escalate_time) # escalate_time(seconds)\r\n print('escalate_time', escalate_time)\r\n\r\n if ticket_status == 'done':\r\n if (response_time and department and SLA_name and SLA_time) is not None:\r\n if response_time < 0:\r\n result = result + 'Overdue'\r\n update_data(request, result, SLA_time, process_time, response_time)\r\n print(\"SLA name: \", SLA_name)\r\n print(\"mess: \", result)\r\n return JsonResponse({\r\n 'result': result\r\n },status=status.HTTP_200_OK)\r\n else:\r\n if 0 <= response_time <= escalate_time:\r\n result = result + 'Done and Escalated'\r\n update_data(request, result, SLA_time, process_time, response_time)\r\n print(\"SLA name: \", SLA_name)\r\n print(\"mess: \", result)\r\n return JsonResponse({\r\n 'result': result\r\n }, status=status.HTTP_200_OK)\r\n else:\r\n result = result + 'Done'\r\n update_data(request, result, SLA_time, process_time, response_time)\r\n print(\"SLA name: \", SLA_name)\r\n print(\"mess: \", result)\r\n return JsonResponse({\r\n 'result': result\r\n }, status=status.HTTP_200_OK)\r\n else:\r\n return JsonResponse({\r\n 'message': 'Oop! Missing something, please check your input again.'\r\n }, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n except Exception as err:\r\n print(\"error\", err)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/timer\r\ndef timer(request, *args, **kwargs):\r\n try:\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n SLA_name = request_body.get('name')\r\n SLA_time = request_body.get('SLA_time')\r\n process_time = request_body.get('process_time')\r\n department = request_body.get('department')\r\n escalate_time = request_body.get('escalate_time')\r\n escalate_time = HmstoSeconds(escalate_time)\r\n\r\n SLA_time = HmstoSeconds(SLA_time) # SLA time (seconds)\r\n process_time = HmstoSeconds(process_time) # process time (seconds)\r\n\r\n if (SLA_time and department and SLA_name and process_time) is not None:\r\n\r\n while SLA_time >= 0:\r\n SLA_time = SLA_time - 1\r\n process_time = process_time + 1\r\n time.sleep(1)\r\n print('SLA name: ', SLA_name)\r\n print('SLA time: ', SLA_time)\r\n print('process time: ', process_time)\r\n if 0 < SLA_time <= escalate_time:\r\n data = {\r\n 'message': 'Need to escalate.'\r\n }\r\n print('data:', data)\r\n continue\r\n # else:\r\n # ticket_status = request_body.get('status')\r\n # SLA_time = SLA_time - 1\r\n # process_time = process_time + 1\r\n # time.sleep(1)\r\n # print('SLA name: ', SLA_name)\r\n # print('SLA time: ', SLA_time)\r\n # print('process time: ', process_time)\r\n # if ticket_status == 'done':\r\n timer_data = {\r\n 'SLA_name': SLA_name,\r\n 'response_time': SLA_time,\r\n 'process_time': process_time\r\n }\r\n return timer_data\r\n # return JsonResponse({\r\n # 'timer_data': timer_data\r\n # },status=status.HTTP_200_OK)\r\n else:\r\n return JsonResponse({\r\n 'message': 'Oop! Missing something, please check your input again.'\r\n }, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n except Exception as err:\r\n print('error', err)\r\n\r\n\r\ndef HmstoSeconds(string):\r\n try:\r\n string = string\r\n stringH = int(int(string.split(\":\")[0]) * 3600)\r\n stringM = int(int(string.split(\":\")[1]) * 60)\r\n stringS = int(int(string.split(\":\")[2]))\r\n string = stringH + stringM + stringS # string(seconds)\r\n return string\r\n except Exception as err:\r\n print('error: ', err)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/checktime/\r\ndef check_created_time(request):\r\n try:\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n print(\"data: \", request_body)\r\n working_time = request_body.get('working_time')\r\n created_time = request_body.get('created_time')\r\n created_time = created_time.split(\" \")[1]\r\n created_time = HmstoSeconds(created_time) # created_time(seconds)\r\n print('created_time', created_time)\r\n\r\n SLA_time = request_body.get('SLA_time')\r\n SLA_time = HmstoSeconds(SLA_time) # SLA_time(seconds)\r\n print('SLA_time', SLA_time)\r\n\r\n department = request_body.get('department')\r\n process_time = request_body.get('process_time')\r\n process_time = HmstoSeconds(process_time) # process_time(seconds)\r\n\r\n escalate_time = request_body.get('escalate_time')\r\n escalate_time = HmstoSeconds(escalate_time) # escalate_time(seconds)\r\n print('escalate_time', escalate_time)\r\n\r\n thread_id = 0\r\n # Xử lý thời gian làm việc của một công ty (working time) để so sánh với created_time:\r\n # Nếu working time == weekly time (work 24/7) thì created_time là bất kỳ và SLA_time bắt đầu được đếm ngược.\r\n # Nếu working time == business time (sẽ cho user setting start_time va end_time --> get được 2 values này)\r\n # thì sẽ so sánh:\r\n # - start_time <= created_time < end_time --> SLA_time bắt đầu được đếm ngược.\r\n # - ngược lại thì SLA_time sẽ dừng đến khi điều kiện trên được thỏa.\r\n # - trường hợp created_time < end_time nhưng thời gian ko còn đủ cho SLA_time đếm ngược\r\n # Khi SLA time vẫn còn mà end_time đến thì timer() vẫn sẽ chạy đếm ngược\r\n # với SLA time và Escalate_time lúc này cộng dồn thời gian\r\n # từ end_time ngày hôm nay đến start_time của ngày tiếp theo để đ��m bảo vẫn escalate đúng thời gian.\r\n\r\n if working_time == 'weekly time':\r\n # Run async SLA time\r\n thread1 = threading.Thread(target=timer,\r\n args=(request, SLA_time, process_time, department, escalate_time))\r\n thread1.setDaemon(True)\r\n thread1.start()\r\n thread_id = threading.get_ident()\r\n # thread1.is_alive()\r\n thread1.join()\r\n data = {\r\n 'created_time': created_time,\r\n 'SLA_time': SLA_time,\r\n 'escalate_time': escalate_time,\r\n 'thread_id': thread_id,\r\n }\r\n return JsonResponse({\r\n 'data': data\r\n }, status=status.HTTP_200_OK)\r\n elif working_time == 'business time':\r\n start_time = request_body.get('start_time')\r\n end_time = request_body.get('end_time')\r\n\r\n start_time = HmstoSeconds(start_time) # start_time(seconds)\r\n print('start_time', start_time)\r\n\r\n end_time = HmstoSeconds(end_time) # end_time(seconds)\r\n print('end_time', end_time)\r\n\r\n BaseTime = '24:00:00'\r\n\r\n BaseTime = HmstoSeconds(BaseTime) # BaseTime(seconds)\r\n print('BaseTime', BaseTime)\r\n\r\n if start_time <= created_time < end_time:\r\n if SLA_time <= (end_time - created_time):\r\n # Run async SLA time\r\n thread1 = threading.Thread(target=timer,\r\n args=(request, SLA_time, process_time, department, escalate_time))\r\n thread1.setDaemon(True)\r\n thread1.start()\r\n thread_id = threading.get_ident()\r\n # thread1.is_alive()\r\n thread1.join()\r\n data = {\r\n 'created_time': created_time,\r\n 'SLA_time': SLA_time,\r\n 'escalate_time': escalate_time,\r\n 'thread_id': thread_id,\r\n }\r\n return JsonResponse({\r\n 'data': data\r\n }, status=status.HTTP_200_OK)\r\n else:\r\n SLA_time = SLA_time + ((BaseTime - end_time) + start_time)\r\n print('SLA_time_plus', SLA_time)\r\n escalate_time = escalate_time + ((BaseTime - end_time) + start_time)\r\n print('escalate_time_plus', escalate_time)\r\n # Run async SLA time\r\n thread1 = threading.Thread(target=timer, args=(request, SLA_time, process_time, department, escalate_time))\r\n thread1.setDaemon(True)\r\n thread1.start()\r\n thread_id = threading.get_ident()\r\n # thread1.is_alive()\r\n thread1.join()\r\n data = {\r\n 'created_time': created_time,\r\n 'SLA_time': SLA_time,\r\n 'escalate_time': escalate_time,\r\n 'thread_id': thread_id,\r\n }\r\n return JsonResponse({\r\n 'data': data\r\n }, status=status.HTTP_200_OK)\r\n else:\r\n print(\"Full time, please return at the next day!\")\r\n return JsonResponse({\r\n 'message': 'Oop!Full time, please return at the next day!'\r\n }, status=status.HTTP_200_OK)\r\n\r\n # data = {\r\n # 'created_time': created_time,\r\n # 'SLA_time': SLA_time,\r\n # 'escalate_time': escalate_time,\r\n # 'thread_id': thread_id,\r\n # }\r\n # return JsonResponse({\r\n # 'data': data\r\n # },status=status.HTTP_200_OK)\r\n except Exception as err:\r\n print(\"error: \", err)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/updateresult/\r\ndef update_result(request):\r\n try:\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n ticket_status = request_body.get('status')\r\n process_time = request_body.get('process_time')\r\n response_time = request_body.get('response_time')\r\n _id = request_body.get('_id')\r\n SLA_name = request_body.get('name')\r\n department = request_body.get('department')\r\n result = request_body.get('result')\r\n get_data = col.find({'_id': ObjectId(_id)})\r\n print('request_body', request_body)\r\n\r\n col.update_one({'_id': ObjectId(_id)}, {\r\n \"$set\": {\r\n \"status\": ticket_status,\r\n \"process_time\": process_time,\r\n \"response_time\": response_time,\r\n \"result\": result\r\n }\r\n })\r\n return JsonResponse({\r\n 'message': \"Ok\"\r\n }, status=status.HTTP_201_CREATED)\r\n\r\n except Exception as err:\r\n print(\"error: \", err)\r\n\r\n\r\ndef update_all_data(request):\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n _id = request_body.get('_id')\r\n working_time = request_body.get('working_time')\r\n created_time = request_body.get('created_time')\r\n SLA_name = request_body.get('name')\r\n SLA_time = request_body.get('SLA_time')\r\n start_time = request_body.get('start_time')\r\n end_time = request_body.get('end_time')\r\n department = request_body.get('department')\r\n ticket_status = request_body.get('status')\r\n response_time = request_body.get('response_time')\r\n escalate_time = request_body.get('escalate_time')\r\n process_time = request_body.get('process_time')\r\n result = request_body.get('result')\r\n\r\n col.update_one({'_id': ObjectId(_id)}, {\r\n \"$set\": {\r\n \"working_time\": working_time,\r\n \"created_time\": created_time,\r\n \"response_time\": SLA_name,\r\n \"department\": SLA_time,\r\n \"name\": start_time,\r\n \"status\": end_time,\r\n \"result\": department,\r\n \"process_time\": ticket_status,\r\n \"SLA_time\": response_time,\r\n \"start_time\": escalate_time,\r\n \"end_time\": process_time,\r\n \"escalate_time\": result,\r\n }\r\n })\r\n return JsonResponse({\r\n 'message': \"Update element successfully.\"\r\n }, status=status.HTTP_201_CREATED)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/resultbyID/\r\ndef get_data_byID(request):\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n _id = request_body.get('_id')\r\n tmp_type = col.find({'_id': ObjectId(_id)})\r\n data = json.loads(json_util.dumps(tmp_type))\r\n return JsonResponse({\r\n 'data': data\r\n }, status=status.HTTP_200_OK)\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/deleteone/\r\ndef delete_one(request):\r\n if request.method == 'POST':\r\n request_body = json.loads(request.body)\r\n _id = request_body.get('_id')\r\n col.delete_one({'_id': ObjectId(_id)})\r\n return JsonResponse({\r\n 'message': 'Delete one element.'\r\n })\r\n\r\n\r\n@csrf_exempt\r\n# http://localhost:8000/api/deleteall/\r\ndef delete_all(request):\r\n if request.method == 'POST':\r\n col.delete_many({})\r\n return JsonResponse({\r\n 'message': 'Delete all elements.'\r\n })\r\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"423507609","text":"import os\nimport sys\nimport glob\nfrom PIL import Image\n\ndef ResizeImage(file, width, height, type):\n img = Image.open(file)\n out = img.resize((width, height), Image.ANTIALIAS)\n out.save(file, type)\n\nif __name__ == \"__main__\":\n for pngfile in glob.glob(os.path.dirname(__file__) + '\\\\*.png'):\n width = 1280\n height = 720\n type = 'png'\n ResizeImage(pngfile, width, height, type)\n","sub_path":"img-resize.py","file_name":"img-resize.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"471410693","text":"from gazel.core_types import Source, PositionMapping, Position, Range, Snapshot, Token\nfrom gazel.common import create_position_index_mapping, Id\nfrom gazel.parsing import get_tokens\nfrom typing import Dict\n\n\ndef make_source(source: str, language: str) -> Source:\n itp, pti = create_position_index_mapping(source)\n\n return Source(source, PositionMapping(itp, pti), language)\n\n\ndef token_from_capture(\n capture, source: str, mapping: PositionMapping, token_id=None\n) -> Token:\n (start, end), syntax_node = capture\n start_point = mapping[start]\n end_point = mapping[end]\n token_range = Range(Position(start, start_point), Position(end, end_point))\n\n return Token(range=token_range, syntax_node=syntax_node, id=token_id, source=source)\n\n\ndef make_snapshot(source: str, language: str, index=0, next_id=Id(),) -> Snapshot:\n _source = make_source(source, language)\n captures = get_tokens(source, language, _source.mapping.point_to_index)\n tokens = tuple(\n token_from_capture(capture, source, _source.mapping, token_id=next_id())\n for capture in captures\n )\n token_by_range: Dict[Range, Token] = {}\n for token in tokens:\n token_by_range[token.range] = token\n\n return Snapshot(index, _source, tokens, _token_by_range=token_by_range)\n","sub_path":"gazel/core_constructors.py","file_name":"core_constructors.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"203720742","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 21 17:48:44 2021\n\n@author: Sukanta Sharma\nName: Sukanta Sharma\nStudent Id: A20472623\nCourse: CS 484 - Introduction to Machine Learning\nSemester: Splring 2021\n\"\"\"\n\nimport pandas\nimport numpy\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import apriori\nfrom mlxtend.frequent_patterns import association_rules\n\n\n# ------------------------ Question 2 ------------------------------------------------\nToyAssoc = pandas.read_csv('q2data.csv', delimiter=',')\n\n# Convert the Sale Receipt data to the Item List format\nListItem = ToyAssoc.groupby(['Friend'])['Item'].apply(list).values.tolist()\n\n# Convert the Item List format to the Item Indicator format\n\nte = TransactionEncoder()\nte_ary = te.fit(ListItem).transform(ListItem)\nItemIndicator = pandas.DataFrame(te_ary, columns=te.columns_)\n\n\n\n# Find the frequent itemsets\nfrequent_itemsets = apriori(ItemIndicator, min_support = 0.3, max_len = 3, use_colnames = True)\n\n# Discover the association rules\nassoc_rules = association_rules(frequent_itemsets, metric = \"confidence\", min_threshold = 0.5)\n\n# Show rules that have the 'CEREAL' consquent\n\nCereal_Consequent_Rule = assoc_rules[numpy.isin(assoc_rules[\"consequents\"].values, {\"Soda\"})]\n\n# Show rules that have the 'Oranges' antecedent\nantecedent = assoc_rules[\"antecedents\"]\nselectAntecedent = numpy.ones((assoc_rules.shape[0], 1), dtype=bool)\n\ni = 0\nfor f in antecedent:\n # selectAntecedent[i,0] = \"Oranges\" in f\n selectAntecedent[i,0] = f.issubset(set(['Cheese', 'Wings']))\n i = i + 1\n \nOrange_Antecedent_Rule = assoc_rules[selectAntecedent]\n\n\n\n# ------------------ Question 4 --------------------------------------\nclusters = [[-2, -1, 1, 2, 3], [4, 5, 7, 8]]\n\n# ------------------------- Question 4. a ----------------------------\nobservation = -1\na_ij = sum(abs(x - observation) for x in clusters[0]) / (len(clusters[0]) - 1)\nb_ij = sum(abs(x - observation) for x in clusters[1] if x != observation) / len(clusters[0])\ns = (b_ij - a_ij) / max(a_ij, b_ij)\nprint(\"Silhouette Width of the observation is : {0}\".format(s))\n\n\n# ---------------------- Question 4.b -------------------------- \ns_0 = sum(abs(x - numpy.mean(clusters[0])) for x in clusters[0]) / len(clusters[0])\ns_1 = sum(abs(x - numpy.mean(clusters[1])) for x in clusters[1]) / len(clusters[1])\nprint(\"Davies-Bouldin value of Cluster 0 : {0}\".format(s_0))\nprint(\"Davies-Bouldin value of Cluster 1 : {0}\".format(s_1))\n\n\n# -------------------- Question 4.c -------------------------\nm_01 = abs(numpy.mean(clusters[0]) - numpy.mean(clusters[1]))\nr_01 = (s_0 + s_1) / m_01\ndb = r_01 / len(clusters)\nprint(\"\\n\\n\\nDavies-Bouldin value of Cluster 0 : {0}\".format(db))","sub_path":"Assignments/AS02/CS484_Assignment2_Sharma_Sukanta/AS02_Q1-Q4.py","file_name":"AS02_Q1-Q4.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"136076868","text":"#coding: utf8\n\nimport rospy\nfrom clover import srv\nfrom std_srvs.srv import Trigger\nimport math\n\nrospy.init_node('flight')\n\nget_telemetry = rospy.ServiceProxy('get_telemetry', srv.GetTelemetry)\nnavigate = rospy.ServiceProxy('navigate', srv.Navigate)\nnavigate_global = rospy.ServiceProxy('navigate_global', srv.NavigateGlobal)\nset_position = rospy.ServiceProxy('set_position', srv.SetPosition)\nset_velocity = rospy.ServiceProxy('set_velocity', srv.SetVelocity)\nset_attitude = rospy.ServiceProxy('set_attitude', srv.SetAttitude)\nset_rates = rospy.ServiceProxy('set_rates', srv.SetRates)\nland = rospy.ServiceProxy('land', Trigger)\n\ndef navigate_wait(x=0, y=0, z=0, yaw=float('nan'), speed=0.5, frame_id='', auto_arm=False, tolerance=0.2):\n navigate(x=x, y=y, z=z, yaw=yaw, speed=speed, frame_id=frame_id, auto_arm=auto_arm)\n\n while not rospy.is_shutdown():\n telem = get_telemetry(frame_id='navigate_target')\n if math.sqrt(telem.x ** 2 + telem.y ** 2 + telem.z ** 2) < tolerance:\n break\n rospy.sleep(0.2)\n\ndef land_wait():\n land()\n while get_telemetry().armed:\n rospy.sleep(0.2)\n\ndef go_home():\n navigate_wait(x=0, y=0, z=1, frame_id='aruco_map', auto_arm=True, speed=10)\n\n\nnavigate_wait(x=0, y=0, z=2, frame_id='body', auto_arm=True, speed=3)\ni=0\nwhile i != 4:\n navigate(x=9, y=0, z=2.7, frame_id='aruco_map', speed=12)\n rospy.sleep(1)\n navigate(x=9, y=9, z=0.8, frame_id='aruco_map', speed=12)\n rospy.sleep(1)\n navigate(x=0, y=9, z=0.8, frame_id='aruco_map', speed=12)\n rospy.sleep(1)\n navigate(x=0, y=0, z=2.7, frame_id='aruco_map', speed=12)\n rospy.sleep(1)\n i = i +1\n\n\nnavigate_wait(x=0, y=0, z=2, frame_id='aruco_map', speed=8)\nland()\n","sub_path":"DEMO/demo_2/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"654284568","text":"\"\"\"\nreads info\n\"\"\"\n\nimport autoparse.pattern as app\nimport autoparse.find as apf\n\n\ndef lennard_jones(output_string):\n \"\"\" reads the lennard jones params from the output\n \"\"\"\n\n sigma_ptt = (app.SPACES + app.INTEGER + app.SPACES +\n app.capturing(app.FLOAT) + app.SPACES +\n app.FLOAT)\n epsilon_ptt = (app.SPACES + app.INTEGER + app.SPACES +\n app.FLOAT + app.SPACES +\n app.capturing(app.FLOAT))\n\n sigmas = apf.all_captures(sigma_ptt, output_string)\n epsilons = apf.all_captures(epsilon_ptt, output_string)\n if sigmas is not None:\n sigmas = [float(val) for val in sigmas]\n if epsilons is not None:\n epsilons = [float(val) for val in epsilons]\n\n return sigmas, epsilons\n\n\ndef combine_params(param1, param2, rule='default'):\n \"\"\" perform a combining rule for two parameters\n \"\"\"\n\n if rule == 'default':\n combined_param = (param1 + param2) / 2.0\n else:\n raise NotImplementedError\n\n return combined_param\n","sub_path":"py1dmin/interface/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"407719761","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\n\nimport astropy.units as u\nfrom astropy.cosmology import z_at_value\nfrom astropy.cosmology import WMAP9 as cosmo\n\nimport gwent\n\nmpl.rcParams['figure.dpi'] = 300\nmpl.rcParams['figure.figsize'] = [5,3]\nmpl.rcParams['text.usetex'] = True\nmpl.rc('font',**{'family':'serif','serif':['Times New Roman'],'size':14})\n\n# # Load Directory\n\nload_directory = gwent.__path__[0] + '/LoadFiles/InstrumentFiles/'\n\n\n# # Load Data Files\n\n# #### ESA LISA\n\nlisa_filedirectory = load_directory + 'LISA_ESA/SNRFiles/'\n\nlisa_SNR_filename = 'LISA_ESA_SNR_Matrix.dat'\nlisa_Samples_filename = 'LISA_ESA_Samples.dat'\nlisa_SNR_filelocation = lisa_filedirectory+lisa_SNR_filename\nlisa_Samples_filelocation = lisa_filedirectory+lisa_Samples_filename\n\n#load SNR from file\nlisa_SNR = np.loadtxt(lisa_SNR_filelocation)\n\n#z and M sample space corresponding to SNR height\n#First column is x-axis variable, second is y-axis variable\nlisa_Samples = np.loadtxt(lisa_Samples_filelocation)\n\n#Take log of variables and SNR for plotting\nlisa_logSamples = np.log10(lisa_Samples)\nlisa_logSNR = np.log10(lisa_SNR)\n\n\n# #### Einstein Telescope\n\net_filedirectory = load_directory + 'EinsteinTelescope/SNRFiles/'\n\net_SNR_filename = 'ET_SNR_Matrix.dat'\net_Samples_filename = 'ET_Samples.dat'\net_SNR_filelocation = et_filedirectory+et_SNR_filename\net_Samples_filelocation = et_filedirectory+et_Samples_filename\net_SNR = np.loadtxt(et_SNR_filelocation)\net_Samples = np.loadtxt(et_Samples_filelocation)\net_logSamples = np.log10(et_Samples)\net_logSNR = np.log10(et_SNR)\n\n\n# #### aLIGO\n\naLIGO_filedirectory = load_directory + 'aLIGO/SNRFiles/'\n\naLIGO_SNR_filename = 'aLIGO_SNR_Matrix.dat'\naLIGO_Samples_filename = 'aLIGO_Samples.dat'\naLIGO_SNR_filelocation = aLIGO_filedirectory+aLIGO_SNR_filename\naLIGO_Samples_filelocation = aLIGO_filedirectory+aLIGO_Samples_filename\naLIGO_SNR = np.loadtxt(aLIGO_SNR_filelocation)\naLIGO_Samples = np.loadtxt(aLIGO_Samples_filelocation)\naLIGO_logSNR = np.log10(aLIGO_SNR)\naLIGO_logSamples = np.log10(aLIGO_Samples)\n\n\n# #### NANOGrav\n\nnanograv_filedirectory = load_directory + 'NANOGrav/SNRFiles/'\n\nnanograv_SNR_filename = 'NANOGrav_SNR_Matrix.dat'\nnanograv_Samples_filename = 'NANOGrav_Samples.dat'\nnanograv_SNR_filelocation = nanograv_filedirectory+nanograv_SNR_filename\nnanograv_Samples_filelocation = nanograv_filedirectory+nanograv_Samples_filename\nnanograv_SNR = np.loadtxt(nanograv_SNR_filelocation)\nnanograv_Samples = np.loadtxt(nanograv_Samples_filelocation)\nnanograv_logSamples = np.log10(nanograv_Samples)\nnanograv_logSNR = np.log10(nanograv_SNR)\n\n\n# #### SKA\n\nSKA_filedirectory = load_directory + 'SKA/SNRFiles/'\n\nSKA_SNR_filename = 'SKA_SNR_Matrix.dat'\nSKA_Samples_filename = 'SKA_Samples.dat'\nSKA_SNR_filelocation = SKA_filedirectory+SKA_SNR_filename\nSKA_Samples_filelocation = SKA_filedirectory+SKA_Samples_filename\nSKA_SNR = np.loadtxt(SKA_SNR_filelocation)\nSKA_Samples = np.loadtxt(SKA_Samples_filelocation)\nSKA_logSamples = np.log10(SKA_Samples)\nSKA_logSNR = np.log10(SKA_SNR)\n\n\n# # Make Waterfall Plots\n\n#Selects contour levels to separate sections into\ncontLevels = np.array([5, 10, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7])\nlogLevels = np.log10(contLevels)\n\ncontourcolorPresent = 'plasma'\ntransparencyPresent = 1.0\ncontourcolorFuture = 'plasma'\ntransparencyFuture = 0.6\naxissize = 12\nlabelsize = 16\ntextsize = 14\ntextcolor1 = 'k'\ntextcolor2 = 'w'\nlinesize = 4\nfigsize=(10,6)\n\n###########################\n#Set pretty labels\nMlabel_min = 0\nMlabel_max = 11\nzlabel_min = -2.0\nzlabel_max = 3.0\nzlabels = np.logspace(zlabel_min,zlabel_max,zlabel_max-zlabel_min+1)\nMlabels = np.logspace(Mlabel_min,Mlabel_max,Mlabel_max-Mlabel_min+1)\n\nages1 = np.array([13.5,13,10,5,1])*u.Gyr\nages2 = np.array([500,100,10,1])*u.Myr\nages2 = ages2.to('Gyr')\nages = np.hstack((ages1.value,ages2.value))\nages = ages*u.Gyr\nageticks = [z_at_value(cosmo.age,age) for age in ages]\n\n#########################\n#Label positions for different GW detectors\n#########################\n#Label different GW detectors\nlabelaLIGO_text = 'aLIGO\\n(2016)'\nlabelaLIGO_xpos = 0.22\nlabelaLIGO_ypos = 0.125\n\nlabelnanograv_text = 'NANOGrav\\n(2018)'\nlabelnanograv_xpos = 0.91\nlabelnanograv_ypos = 0.175\n\nlabelet_text = 'ET\\n(~2030s)'\nlabelet_xpos = 0.175\nlabelet_ypos = 0.6\n#labelet_xpos = 0.1\n#labelet_ypos = 0.75\n\nlabelLisa_text = 'LISA\\n(~2030s)'\nlabelLisa_xpos = 0.6\nlabelLisa_ypos = 0.1\n\nlabelIpta_text = 'IPTA\\n(~2030s)'\nlabelIpta_xpos = 0.65\nlabelIpta_ypos = 0.85\n#labelIpta_xpos = 0.775\n#labelIpta_ypos = 0.75\n\nfig, ax1 = plt.subplots(figsize=figsize)\n###########################\n#Set other side y-axis for lookback time scalings\nax2 = ax1.twinx()\n\nCS1 = ax1.contourf(nanograv_logSamples[0],nanograv_logSamples[1],\n nanograv_logSNR,logLevels,\n cmap = contourcolorPresent, alpha = transparencyPresent)\n\nax2.contour(nanograv_logSamples[0],nanograv_logSamples[1],\n nanograv_logSNR,logLevels,colors = 'k')\n\nax1.contourf(aLIGO_logSamples[0],aLIGO_logSamples[1],aLIGO_logSNR,logLevels,\n cmap = contourcolorPresent, alpha = transparencyPresent)\n\nax1.contour(aLIGO_logSamples[0],aLIGO_logSamples[1],aLIGO_logSNR,\n logLevels,colors = 'k')\n\nax1.contourf(lisa_logSamples[0],lisa_logSamples[1],lisa_logSNR,logLevels,\n cmap=contourcolorFuture, alpha = transparencyFuture)\n\nax1.contourf(et_logSamples[0],et_logSamples[1],et_logSNR,logLevels,\n cmap = contourcolorFuture, alpha = transparencyFuture)\n\nax1.contourf(SKA_logSamples[0],SKA_logSamples[1],SKA_logSNR,logLevels,\n cmap = contourcolorFuture, alpha = transparencyFuture)\n\n#########################\n#Set axes limits\nax1.set_xlim(et_logSamples[0][0],11)\nax1.set_ylim(SKA_logSamples[1][0],SKA_logSamples[1][-1])\n\n#########################\n#Set ticks and labels\nax1.set_yticks(np.log10(zlabels))\nax1.set_xticks(np.log10(Mlabels))\nax1.set_xticklabels([r'$10^{%i}$' %x for x in np.log10(Mlabels)],\n fontsize = axissize)\nax1.set_yticklabels([x if int(x) < 1 else int(x) for x in zlabels],\n fontsize = axissize)\n\nax1.set_xlabel(r'$M_{\\rm tot}$ $[M_{\\odot}]$',fontsize = labelsize)\nax1.set_ylabel(r'${\\rm Redshift}$',fontsize = labelsize)\n#ax1.yaxis.set_label_coords(-.5,.5)\n\nax2.set_yticks(np.log10(ageticks))\n#ax2.set_yticklabels(['%f' %age for age in ageticks],fontsize = axissize)\nax2.set_yticklabels(['{:g}'.format(age) for age in ages.value],\n fontsize = axissize)\nax2.set_ylabel(r'$t_{\\rm cosmic}$ [Gyr]',fontsize=labelsize)\n\n\n#########################\n#Label different GW detectors\nplt.text(labelaLIGO_xpos,labelaLIGO_ypos,labelaLIGO_text,fontsize = textsize,\n horizontalalignment='center',verticalalignment='center',\n color = textcolor2,transform = ax1.transAxes)\n\nplt.text(labelnanograv_xpos,labelnanograv_ypos, labelnanograv_text,\n fontsize = textsize, horizontalalignment='center',\n verticalalignment='center', color = textcolor2,\n transform = ax1.transAxes, rotation=72)\n\nplt.text(labelet_xpos,labelet_ypos,labelet_text, fontsize = textsize,\n horizontalalignment='center', verticalalignment='center',\n color = textcolor1, transform = ax1.transAxes)\n\nplt.text(labelLisa_xpos,labelLisa_ypos,labelLisa_text,fontsize = textsize,\n horizontalalignment='center',verticalalignment='center',\n color = textcolor1,transform = ax1.transAxes)\n\nplt.text(labelIpta_xpos,labelIpta_ypos,labelIpta_text,fontsize = textsize,\n horizontalalignment='center',verticalalignment='center',\n color = textcolor1,transform = ax1.transAxes)\n\n#########################\n#Make colorbar\ncbar = fig.colorbar(CS1,ax=(ax1,ax2),pad=0.01)\n#cbar = fig.colorbar(CS1)\ncbar.set_label(r'$SNR$',fontsize = labelsize)\ncbar.ax.tick_params(labelsize = axissize)\ncbar.ax.set_yticklabels([r'$10^{%i}$' %x if int(x) > 1 else r'$%i$' %(10**x)\n for x in logLevels])\nplt.show()\n","sub_path":"docs/pyplot/waterfall.py","file_name":"waterfall.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416583553","text":"import pymysql\nimport configparser\nfrom config import HOST, PORT, USER, PASSWORD, DB, wtimeout\nfrom common.Util.logger import Lamp_Logger\n\n'''\nCONFIG 를 만들어 넣는다\nDB 정보 \nsmyucheck 여기 예외처리 모두 해야함\n\nhttps://code.tutsplus.com/ko/tutorials/professional-error-handling-with-python--cms-25950\ncursor.execute 의 param 에 대해서\nhttps://pymysql.readthedocs.io/en/latest/modules/cursors.html\n\nsmyucheck 커넥터를 클래스로 만들수있음 생성자에서 커넥트 소멸자에서 클로스\n'''\n#smyucheck raise!! \n#https://www.programcreek.com/python/example/68898/pymysql.Error\ndef Connect(host=HOST, port=PORT, user=USER, password=PASSWORD, db=DB):\n try:\n db = pymysql.connect(host=host, port=port, user=user, password=password, db=db, write_timeout=wtimeout)\n except pymysql.Error as e:\n return e\n return db\n\n#smyu200318\n# db conn이 살아있는지 검사하고 끊음\n'''\ndef dbConnectClose(conn):\n if conn is not None:\n conn.close()\n return None\n'''\ndef dbConnectClose(conn):\n if conn is not None:\n try: \n conn.close()\n except pymysql.Error as e:\n# return 'could not close connection error pymysql'\n return str(e)\n return 'connection closed successfully'\n\n#smyucheck 예외처리\ndef dbCursorClose(cursor):\n if cursor is not None:\n try:\n cursor.close()\n except pymysql.Error as e:\n return str(e)\n# return 'could not close connection error pymysql {}: {}'.format(e.args[0], e.args[1])\n return 'db cursor closeed sucessfully'\n\n#~smyu\n\n#smyu 200318 return 조정\ndef selectsql(sql, conn, param):\n cursor = conn.cursor()\n cursor.execute(sql, param)\n fetchreslist=cursor.fetchall()\n\n dbCursorClose(cursor)\n return fetchreslist\n\n#smyu\n# ex반환 말고deledtedKeys 반환, ex는 위 함수에서 로깅\ndef deletewithgmkeylist(conn, table, keyColName, gmkeySet):\n delCnt=0\n deledtedKeys = [] \n colname=list(keyColName.values()) \n\n try:\n cursor = conn.cursor()\n except pymysql.MySQLError as ex:\n return str(delCnt)+' rows deleted', ex\n\n for gmkey in gmkeySet:\n sql = 'DELETE FROM '+table+' WHERE '+colname[0]+'=\\''+ gmkey +'\\';'\n #print(\"sql\")\n #print(sql)\n\n try:\n delres = cursor.execute(sql)\n #print (delres)\n delCnt += 1\n deledtedKeys.append(gmkey) \n except Exception as ex:\n #print(ex)\n return str(delCnt)+' rows deleted', ex\n finally:\n conn.commit()\n dbCursorClose(cursor)\n\n return str(delCnt)+' rows deleted', deledtedKeys\n#~smyu\n\ndef insertUpdatesql2(columns, table, key):\n insertsql = InsertSql(columns, table)\n updatesql = UpdateSql(columns, table, key)\n return insertsql, updatesql\n\n#sql문 생성\ndef InsertSql(columns, table):\n\n placeholders = ', '.join(['%s'] * len(columns))\n columns = ', '.join(columns)\n\n return ''' INSERT INTO '''+table+''' (%s) VALUES (%s) ''' % (columns, placeholders)\n\n#sql문 생성\ndef UpdateSql(columns, table, key):\n\n # 업데이트 컬럼\n update = '=%s ,'.join(columns)\n update += '=%s' # 마지막 컬럼 까지 추가\n\n pk = [k for k in key]\n pk = '=%s AND '.join(pk)\n pk += '=%s' # 마지막 컬럼 까지 추가\n\n return ''' UPDATE '''+table+''' SET '''+ update +''' WHERE ''' + pk \n\n\n# def insertUpdatesql(columns, table):\n#\n#\n# # 업데이트 컬럼\n# update = '=%s ,'.join(columns)\n# update += '=%s' # 마지막 컬럼 까지 추가\n#\n#\n# columns = ', '.join(columns)\n#\n# # 내용 찾아보고 뒷부분 고민\n# return ''' INSERT INTO '''+table+''' (%s) VALUES (%s) on duplicate key update %s ;''' % (columns, placeholders, update)\n#\n\n\n'''\n*** parkjp 2.27\n특별한 값이 있으면 update 아니면 insert\n'''\ndef insertUpdatesql(columns, table):\n\n placeholders = ', '.join(['%s'] * len(columns))\n # 업데이트 컬럼\n update = '=%s ,'.join(columns)\n update += '=%s' # 마지막 컬럼 까지 추가\n\n\n columns = ', '.join(columns)\n\n # 내용 찾아보고 뒷부분 고민\n return ''' INSERT INTO '''+table+''' (%s) VALUES (%s) on duplicate key update %s ;''' % (columns, placeholders, update)\n\ndef DataInsert(sql, param, columns, conn):\n '''\n exception 확인 해서 관련 내용 보완 해야 함\n '''\n try :\n p = []\n cursor = conn.cursor()\n\n for col in columns:\n if param[col] == 'True':\n p.append(True)\n elif param[col] == 'False':\n p.append(False)\n else:\n p.append(param[col])\n\n # 업데이트문 떄문에 2번 넣는다\n for col in columns:\n if param[col] == 'True':\n p.append(True)\n elif param[col] == 'False':\n p.append(False)\n else:\n p.append(param[col])\n\n for col in columns :\n p.append(param[col])\n # 에러 나는 것에 ��한 로거를 찍는 부분\n # print (p)\n cursor.execute(sql, p)\n except Exception as ex:\n # 에러 나는 것에 대한 로거를 찍는 부분\n # 에러 나면 데이터 수집 종료를 선언하고 끝내야 한다\n raise ValueError\n finally:\n dbCursorClose(cursor)\n'''\nsmyu 200319 가비지 코드 정리\ndef DataUpdate(sql, param, columns, conn):\n #exception 확인 해서 관련 내용 보완 해야 함\n try:\n p = []\n cursor = conn.cursor()\n\n for col in columns:\n if param[col] == 'True':\n p.append(True)\n elif param[col] == 'False':\n p.append(False)\n else:\n p.append(param[col])\n\n # 업데이트문 떄문에 2번 넣는다\n for col in columns:\n if param[col] == 'True':\n p.append(True)\n elif param[col] == 'False':\n p.append(False)\n else:\n p.append(param[col])\n\n for col in columns:\n p.append(param[col])\n # 에러 나는 것에 대한 로거를 찍는 부분\n # print(p)\n cursor.execute(sql, p)\n except Exception as ex:\n # 에러 나는 것에 대한 로거를 찍는 부분\n return ex\n finally:\n closeres = dbCursorClose(cursor)\n'''\ndef DataInsertUpdate2(insertsql, updatesql, param, columns, conn, table, key, insertCnt, updateCnt):\n sql = \"\"\n '''\n exception 확인 해서 관련 내용 보완 해야 함\n '''\n try:\n p = []\n cursor = conn.cursor()\n for col in columns:\n if param[col] == 'True' : p.append(True)\n elif param[col] == 'False' : p.append(False)\n else : p.append(param[col])\n\n # 에러 나는 것에 대한 로거를 찍는 부분\n # 값이 없으면 insert\n\n if selectWithKey(conn, table, key, param) == 0:\n # print(\"insert\")\n sql = insertsql\n insertCnt = insertCnt + 1\n else :\n # print(\"update\")\n for k in key:\n p.append(param[key[k]])\n sql = updatesql\n updateCnt = updateCnt + 1\n\n # print (sql)\n # print (p)\n\n # 보완 #\n cursor.execute(sql, p) \n return insertCnt, updateCnt, None\n except Exception as ex:\n # 에러 나는 것에 대한 로거를 찍는 부분\n # 보완해 주세요\n return None, None, ex\n finally:\n closeres = dbCursorClose(cursor)\n \n\ndef DataInsertUpdate(sql, param, columns, conn):\n '''\n exception 확인 해서 관련 내용 보완 해야 함\n '''\n try:\n p = []\n cursor = conn.cursor()\n for col in columns:\n if param[col] == 'True' : p.append(True)\n elif param[col] == 'False' : p.append(False)\n else : p.append(param[col])\n\n # 업데이트문 떄문에 2번 넣는다\n for col in columns:\n if param[col] == 'True' : p.append(True)\n elif param[col] == 'False' : p.append(False)\n else : p.append(param[col])\n # 에러 나는 것에 대한 로거를 찍는 부분\n # print (sql)\n # print (p)\n cursor.execute(sql, p)\n except Exception as ex:\n # print (ex)\n return ex\n finally:\n closeres = dbCursorClose(cursor)\n \n\ndef InsertBatch(sql, params, columns, conn):\n for param in params :\n DataInsertUpdate(sql, param, columns, conn)\n # commit의 위치 확인\n conn.commit()\n\n#smyu 200317 api 데이터 삭제 버그\n#sql문을 만들자, 테이블에 있는 게임키들을 리스트로 가져옴\ndef selectFetchAllTableSQL(conn, table, gmkey, AmountOfDataToFetch):\n colname=list(gmkey.values()) \n\n sql = 'SELECT ' + colname[0] +' FROM '+table+' WHERE '+colname[0]+' LIKE \\''+ AmountOfDataToFetch +'%\\' '+';'\n \n try:\n keysInDB = selectFetchAllTable(conn, table, sql)\n except pymysql.MySQLError as ex:\n return '0 rows fetched ', ex\n finally:\n return str(len(keysInDB))+' rows fetched ', keysInDB\n\ndef selectFetchAllTable(conn, table, sql):\n #테이블에서 fetch 수행\n #smyucheck pymysql.에러 종류 조사해보자 \n try:\n curs=conn.cursor()\n curs.execute(sql)\n AllKeyInDBTable = curs.fetchall() \n except pymysql.MySQLError as ex:\n return ex\n finally:\n dbCursorClose(curs)\n return AllKeyInDBTable\n#~smyu\n\n'''\n*** parkjp 3.5\nidx가 있을 떄, \n특별한 값이 있으면 update 아니면 insert\n\nselect 로 한번 조회해옴\n느려짐\n'''\n\ndef selectWithKey(conn, table, key, param):\n p= []\n pk = []\n for k in key :\n pk.append(k)\n p.append(param[key[k]])\n pk = '=%s AND '.join(pk)\n pk += '=%s' # 마지막 컬럼 까지 추가\n \n sql = 'SELECT * FROM '+table+' WHERE '+ pk +' ;'\n\n return len(selectsql(sql, conn, p))\n\n\ndef insertUpdatesql(columns, table):\n\n placeholders = ', '.join(['%s'] * len(columns))\n # 업데이트 컬럼\n update = '=%s , '.join(columns)\n update += '=%s' # 마지막 컬럼 까지 추가\n\n columns = ', '.join(columns)\n\n # 내용 찾아보고 뒷부분 고민\n return ''' INSERT INTO '''+table+''' (%s) VALUES (%s) on duplicate key update %s ;''' % (columns, placeholders, update)\n\n'''\ninsert와 update sql 을 만든다\n'''\ndef InsertUpdateBatch2(insertsql, updatesql, params, columns, conn, table, key):\n\n insertCnt = 0\n updateCnt = 0\n\n for param in params:\n try :\n insertCnt, updateCnt, error = DataInsertUpdate2(insertsql, updatesql, param, columns, conn, table, key, insertCnt, updateCnt)\n\n if error:\n return 'Error, 0 rows inserted ', 'Error, 0 row updated', error\n\n except Exception as ex:\n return 'Error, 0 rows inserted ', 'Error, 0 row updated', ex\n # 데이터를 commit 하지 않습니다.\n # commit의 위치 확인\n \n try:\n conn.commit()\n except Exception as ex:\n return 'Error, 0 rows inserted ', 'Error, 0 row updated', ex\n\n return str(insertCnt)+' rows inserted ', str(updateCnt)+' row updated', None\n\n# if __name__ == \"__main__\":\n# conn = Connect()\n#\n# if selectWithKey(conn) == 0 :\n# # 값이 없으면 insert\n# print(\"insert\")\n# # DataInsert(sql, param, columns, conn)\n# else :\n# print(\"update\")\n# DataUpdate(sql, param, columns, conn)\n","sub_path":"common/DB/mysqlConnector.py","file_name":"mysqlConnector.py","file_ext":"py","file_size_in_byte":10661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282249869","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 10 15:47:04 2017\n\n@author: 17549\n\"\"\"\n\nfrom pyecharts import Line3D\nimport math\n_data=[]\nfor t in range(0,25000):\n _t=t/1000\n x=(1+0.25*math.cos(75*_t))*math.cos(_t)\n y=(1+0.25*math.cos(75*_t))*math.sin(_t)\n z=_t+2.0*math.sin(75*_t)\n _data.append([x,y,z])\nrange_color=['#313695','#4575b4','#74add1','#abd9e9','#e0f3f8','#ffffbf',\n '#fee090','#fdae61','#f46d43','#d73027','#a50026']\nline3d=Line3D(\"3D折线图\",width=1200,height=600)\nline3d.add(\"\",_data,is_visualmap=True,visual_range_color=range_color,\n visual_range=[0,30],grid3D_rotate_sensitivity=5)\nline3d.show_config()\nline3d.render(r\"E:\\6_3D折线图.html\")","sub_path":"Python/python数据学习/pyecharts/8_3D折线图.py","file_name":"8_3D折线图.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"329625571","text":"from scrapy.contrib.spiders import Rule, CrawlSpider\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom scrapy.selector import HtmlXPathSelector\n\nfrom kulturalnie.items import EventItem\n\nclass KulturalnieSpider(CrawlSpider):\n name = \"kulturalnie\"\n allowed_domains = [\"kulturalnie.waw.pl\"]\n start_urls = [\n \"http://kulturalnie.waw.pl/wydarzenia/2012/04/15/\",\n ]\n\n rules = (\n Rule(\n SgmlLinkExtractor(\n allow=\"/wydarzenia/2012/04/15/\\d+/$\",\n ),\n follow=True,\n callback='parse_event'\n ),\n )\n\n def parse_event(self, response):\n self.log('Hi, this is an event page! %s' % response.url)\n\n # hxs = HtmlXPathSelector(response)\n # item = EventItem()\n # item['id'] = hxs.select('//td[@id=\"item_id\"]/text()').re(r'ID: (\\d+)')\n # item['name'] = hxs.select('//td[@id=\"item_name\"]/text()').extract()\n # item['description'] = hxs.select('//td[@id=\"item_description\"]/text()').extract()\n # return item\n","sub_path":"citypulse/kulturalnie/kulturalnie/spiders/kulturalnie_spider.py","file_name":"kulturalnie_spider.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"406213399","text":"#!/usr/bin/python\n\"\"\"\nFunctions that call ANTs (UPenn's PICSL group) commands.\n\nMindboggle functions call the following ANTs functions ::\n\n ImageMath:\n 'PropagateLabelsThroughMask','m','MD','ME' options in thickinthehead()\n 'PropagateLabelsThroughMask' option in PropagateLabelsThroughMask()\n if modify_surface_labels set to True:\n PropagateLabelsThroughMask() called and '+' option in mindboggle\n\n ThresholdImage:\n thickinthehead()\n PropagateLabelsThroughMask()\n\n ResampleImageBySpacing:\n thickinthehead()\n\n antsApplyTransformsToPoints:\n write_shape_stats(), write_vertex_measures()\n\nAuthors:\nArno Klein, 2011-2014 . arno@mindboggle.info . www.binarybottle.com\n\nCopyright 2014, Mindboggle team (http://mindboggle.info), Apache v2.0 License\n\n\"\"\"\n\n\ndef fetch_ants_data(segmented_file, use_ants_transforms=True):\n \"\"\"\n Fetch antsCorticalThickness.sh output.\n\n The input argument \"segmented_file\" is one of the relevant\n antsCorticalThickness.sh output files called by Mindboggle\n (assume path and PREFIX=\"ants\"):\n ants_subjects/subject1/antsBrainExtractionMask.nii.gz\n ants_subjects/subject1/antsBrainSegmentation.nii.gz\n ants_subjects/subject1/antsSubjectToTemplate0GenericAffine.mat\n ants_subjects/subject1/antsSubjectToTemplate1Warp.nii.gz\n ants_subjects/subject1/antsTemplateToSubject0Warp.nii.gz\n ants_subjects/subject1/antsTemplateToSubject1GenericAffine.mat\n The existence of the transform files are checked only if\n use_ants_transforms == True. Transforms can only be included\n if they have been generated by antsCorticalThickness.sh\n with the -k argument.\n\n Parameters\n ----------\n segmented_file : string\n full path to a subject's antsCorticalThickness.sh segmented file\n use_ants_transforms : Boolean\n include antsCorticalThickness.sh-generated transforms?\n\n Returns\n -------\n mask : string\n antsBrainExtraction.sh brain volume mask for extracting brain volume\n segments : string\n Atropos-segmented brain volume\n affine_subject2template : string\n subject to template affine transform (antsRegistration)\n warp_subject2template : string\n subject to template nonlinear transform (antsRegistration)\n affine_template2subject : string\n template to subject affine transform (antsRegistration)\n warp_template2subject : string\n template to subject nonlinear transform (antsRegistration)\n\n Examples\n --------\n >>> from mindboggle.utils.ants import fetch_ants_data\n >>> segmented_file = 'ants_subjects/OASIS-TRT-20-1/tmpBrainSegmentation.nii.gz'\n >>> fetch_ants_data(segmented_file)\n\n \"\"\"\n import os\n\n prefix = segmented_file.strip('BrainSegmentation.nii.gz')\n\n mask = prefix + 'BrainExtractionMask.nii.gz'\n segments = segmented_file\n\n if use_ants_transforms:\n affine_subject2template = prefix + 'SubjectToTemplate0GenericAffine.mat'\n warp_subject2template = prefix + 'SubjectToTemplate1Warp.nii.gz'\n affine_template2subject = prefix + 'TemplateToSubject1GenericAffine.mat'\n warp_template2subject = prefix + 'TemplateToSubject0Warp.nii.gz'\n files = [mask, segments,\n affine_subject2template, warp_subject2template,\n affine_template2subject, warp_template2subject]\n else:\n affine_subject2template = ''\n warp_subject2template = ''\n affine_template2subject = ''\n warp_template2subject = ''\n files = [mask, segments]\n\n # The existence of the transform files are checked only if\n # use_ants_transforms == True. Transforms are generated by\n # antsCorticalThickness.sh when the -k argument is used.\n for s in files:\n if not os.path.exists(s):\n str1 = 'antsCorticalThickness.sh output ' + s + ' does not exist.'\n raise IOError(str1)\n\n return mask, segments, affine_subject2template, warp_subject2template, \\\n affine_template2subject, warp_template2subject\n\n\ndef antsApplyTransformsToPoints(points, transform_files, inverse_booleans=[0]):\n \"\"\"\n Run ANTs antsApplyTransformsToPoints function to transform points.\n (Creates pre- and post-transformed .csv points files for ANTs.)\n\n Parameters\n ----------\n points : list of lists of three integers\n point coordinate data\n transform_files : list\n transform file names\n inverse_booleans : list\n for each transform, one to apply inverse of transform (otherwise zero)\n\n Returns\n -------\n transformed_points : list of lists of three integers\n transformed point coordinate data\n\n Examples\n --------\n >>> from mindboggle.utils.ants import antsApplyTransformsToPoints\n >>> from mindboggle.utils.io_vtk import read_vtk\n >>> transform_files = ['/Users/arno/Data/antsCorticalThickness/Twins-2-1/antsTemplateToSubject1GenericAffine.mat','/Users/arno/Data/antsCorticalThickness/Twins-2-1/antsTemplateToSubject0Warp.nii.gz','/Users/arno/Data/antsCorticalThickness/Twins-2-1/antsSubjectToTemplate0GenericAffine.mat','/Users/arno/Data/antsCorticalThickness/Twins-2-1/antsSubjectToTemplate1Warp.nii.gz']\n >>> transform_files = [transform_files[0],transform_files[1],'/Users/arno/Data/mindboggle_cache/f36e3d5d99f7c4a9bb70e2494ed7340b/OASIS-30_Atropos_template_to_MNI152_affine.txt']\n >>> vtk_file = '/Users/arno/mindboggle_working/Twins-2-1/Mindboggle/_hemi_lh/Surface_to_vtk/lh.pial.vtk'\n >>> faces, lines, indices, points, npoints, scalars, name, foo1 = read_vtk(vtk_file)\n >>> inverse_booleans = [0,0,1]\n >>> transformed_points = antsApplyTransformsToPoints(points, transform_files, inverse_booleans)\n\n \"\"\"\n import os\n\n from mindboggle.utils.utils import execute\n\n #-------------------------------------------------------------------------\n # Write points (x,y,z,1) to a .csv file:\n #-------------------------------------------------------------------------\n points_file = os.path.join(os.getcwd(), 'points.csv')\n fid = open(points_file, 'wa')\n fid.write('x,y,z,t\\n')\n for point in points:\n string_of_zeros = (4 - len(point)) * ',0'\n fid.write(','.join([str(x) for x in point]) + string_of_zeros + '\\n')\n fid.close()\n\n #-------------------------------------------------------------------------\n # Apply transforms to points in .csv file:\n #-------------------------------------------------------------------------\n transformed_points_file = os.path.join(os.getcwd(),\n 'transformed_points.csv')\n transform_string = ''\n for ixfm, transform_file in enumerate(transform_files):\n transform_string += \" --t [{0},{1}]\".\\\n format(transform_file, str(inverse_booleans[ixfm]))\n cmd = ['antsApplyTransformsToPoints', '-d', '3', '-i', points_file,\n '-o', transformed_points_file, transform_string]\n execute(cmd, 'os')\n if not os.path.exists(transformed_points_file):\n str1 = \"antsApplyTransformsToPoints did not create \"\n raise(IOError(str1 + transformed_points_file + \".\"))\n\n #-------------------------------------------------------------------------\n # Return transformed points:\n #-------------------------------------------------------------------------\n fid = open(transformed_points_file, 'r')\n lines = fid.readlines()\n fid.close()\n transformed_points = []\n for iline, line in enumerate(lines):\n if iline > 0:\n point_xyz1 = [float(x) for x in line.split(',')]\n transformed_points.append(point_xyz1[0:3])\n\n\n return transformed_points\n\n\ndef ImageMath(volume1, volume2, operator='m', output_file=''):\n \"\"\"\n Use the ImageMath function in ANTs to perform operation on two volumes::\n\n m : Multiply --- use vm for vector multiply\n + : Add --- use v+ for vector add\n - : Subtract --- use v- for vector subtract\n / : Divide\n ^ : Power\n exp : Take exponent exp(imagevalue*value)\n addtozero : add image-b to image-a only over points where image-a has zero values\n overadd : replace image-a pixel with image-b pixel if image-b pixel is non-zero\n abs : absolute value\n total : Sums up values in an image or in image1*image2 (img2 is the probability mask)\n mean : Average of values in an image or in image1*image2 (img2 is the probability mask)\n vtotal : Sums up volumetrically weighted values in an image or in image1*image2 (img2 is the probability mask)\n Decision : Computes result=1./(1.+exp(-1.0*( pix1-0.25)/pix2))\n Neg : Produce image negative\n\n\n Parameters\n ----------\n volume1 : string\n nibabel-readable image volume\n volume2 : string\n nibabel-readable image volume\n operator : string\n ImageMath string corresponding to mathematical operator\n output_file : string\n nibabel-readable image volume\n\n Returns\n -------\n output_file : string\n name of output nibabel-readable image volume\n\n Examples\n --------\n >>> import os\n >>> from mindboggle.utils.ants import ImageMath\n >>> from mindboggle.utils.plots import plot_volumes\n >>> path = os.path.join(os.environ['MINDBOGGLE_DATA'])\n >>> volume1 = os.path.join(path, 'arno', 'mri', 't1weighted.nii.gz')\n >>> volume2 = os.path.join(path, 'arno', 'mri', 'mask.nii.gz')\n >>> operator = 'm'\n >>> output_file = ''\n >>> output_file = ImageMath(volume1, volume2, operator, output_file)\n >>> # View\n >>> plot_volumes(output_file)\n\n \"\"\"\n import os\n from mindboggle.utils.utils import execute\n\n if not output_file:\n output_file = os.path.join(os.getcwd(),\n os.path.basename(volume1) + '_' +\n os.path.basename(volume2))\n\n cmd = ['ImageMath', '3', output_file, operator, volume1, volume2]\n execute(cmd, 'os')\n if not os.path.exists(output_file):\n raise(IOError(\"ImageMath did not create \" + output_file + \".\"))\n\n return output_file\n\n\ndef ThresholdImage(volume, output_file='', threshlo=1, threshhi=10000):\n \"\"\"\n Use the ThresholdImage function in ANTs to threshold image volume::\n\n Usage: ThresholdImage ImageDimension ImageIn.ext outImage.ext\n threshlo threshhi \n\n Parameters\n ----------\n volume : string\n nibabel-readable image volume\n output_file : string\n nibabel-readable image volume\n threshlo : integer\n lower threshold\n threshhi : integer\n upper threshold\n\n Returns\n -------\n output_file : string\n name of output nibabel-readable image volume\n\n Examples\n --------\n >>> import os\n >>> from mindboggle.utils.ants import ThresholdImage\n >>> from mindboggle.utils.plots import plot_volumes\n >>> path = os.path.join(os.environ['MINDBOGGLE_DATA'])\n >>> volume = os.path.join(path, 'arno', 'mri', 't1weighted.nii.gz')\n >>> output_file = ''\n >>> threshlo = 500\n >>> threshhi = 10000\n >>> output_file = ThresholdImage(volume, output_file, threshlo, threshhi)\n >>> # View\n >>> plot_volumes(output_file)\n\n \"\"\"\n import os\n from mindboggle.utils.utils import execute\n\n if not output_file:\n output_file = os.path.join(os.getcwd(),\n 'threshold_' + os.path.basename(volume))\n\n cmd = 'ThresholdImage 3 {0} {1} {2} {3}'.format(volume, output_file,\n threshlo, threshhi)\n execute(cmd, 'os')\n if not os.path.exists(output_file):\n raise(IOError(\"ThresholdImage did not create \" + output_file + \".\"))\n\n return output_file\n\n\ndef PropagateLabelsThroughMask(mask, labels, mask_index=None,\n output_file='', binarize=True, stopvalue=''):\n \"\"\"\n Use ANTs to fill a binary volume mask with initial labels.\n\n This program uses ThresholdImage and the ImageMath\n PropagateLabelsThroughMask functions in ANTs.\n\n ThresholdImage ImageDimension ImageIn.ext outImage.ext\n threshlo threshhi \n\n PropagateLabelsThroughMask: Final output is the propagated label image.\n ImageMath ImageDimension Out.ext PropagateLabelsThroughMask\n speed/binaryimagemask.nii.gz initiallabelimage.nii.gz ...\n\n Parameters\n ----------\n mask : string\n nibabel-readable image volume\n labels : string\n nibabel-readable image volume with integer labels\n mask_index : integer (optional)\n mask with just voxels having this value\n output_file : string\n nibabel-readable labeled image volume\n binarize : Boolean\n binarize mask?\n stopvalue : integer\n stopping value\n\n Returns\n -------\n output_file : string\n name of labeled output nibabel-readable image volume\n\n Examples\n --------\n >>> import os\n >>> from mindboggle.utils.ants import PropagateLabelsThroughMask\n >>> from mindboggle.utils.plots import plot_volumes\n >>> path = os.path.join(os.environ['MINDBOGGLE_DATA'])\n >>> labels = os.path.join(path, 'arno', 'labels', 'labels.DKT25.manual.nii.gz')\n >>> mask = os.path.join(path, 'arno', 'mri', 't1weighted_brain.nii.gz')\n >>> mask_index = None\n >>> output_file = ''\n >>> binarize = True\n >>> stopvalue = None\n >>> output_file = PropagateLabelsThroughMask(mask, labels, mask_index, output_file, binarize, stopvalue)\n >>> # View\n >>> plot_volumes(output_file)\n\n \"\"\"\n import os\n from mindboggle.utils.utils import execute\n\n if not output_file:\n output_file = os.path.join(os.getcwd(),\n 'PropagateLabelsThroughMask.nii.gz')\n output_file = os.path.join(os.getcwd(),\n os.path.basename(labels) + '_through_' +\n os.path.basename(mask))\n\n print('mask: {0}, labels: {1}'.format(mask, labels))\n\n # Binarize image volume:\n if binarize:\n temp_file = os.path.join(os.getcwd(),\n 'PropagateLabelsThroughMask.nii.gz')\n cmd = ['ThresholdImage', '3', mask, temp_file, '0 1 0 1']\n execute(cmd, 'os')\n mask = temp_file\n\n # Mask with just voxels having mask_index value:\n if mask_index:\n mask2 = os.path.join(os.getcwd(), 'temp.nii.gz')\n cmd = 'ThresholdImage 3 {0} {1} {2} {3} 1 0'.format(mask, mask2,\n mask_index, mask_index)\n execute(cmd)\n else:\n mask2 = mask\n\n # Propagate labels:\n cmd = ['ImageMath', '3', output_file, 'PropagateLabelsThroughMask',\n mask2, labels]\n if stopvalue:\n cmd.extend(stopvalue)\n execute(cmd, 'os')\n if not os.path.exists(output_file):\n raise(IOError(\"ImageMath did not create \" + output_file + \".\"))\n\n return output_file\n\n\ndef fill_volume_with_surface_labels(hemi, left_mask, right_mask,\n surface_files, mask_index=None,\n output_file='', binarize=False):\n \"\"\"\n Use ANTs to fill a volume mask with surface mesh labels.\n\n Note ::\n\n - This uses PropagateLabelsThroughMask in the ANTs ImageMath function.\n\n - Partial volume information is lost when mapping surface to volume.\n\n Parameters\n ----------\n hemi : string\n either 'lh' or 'rh', indicating brain's left or right hemisphere\n left_mask : string\n nibabel-readable left brain image mask volume\n right_mask : string\n nibabel-readable left brain image mask volume\n surface_files : string or list of strings\n VTK file(s) containing surface mesh(es) with labels as scalars\n mask_index : integer (optional)\n mask with just voxels having this value\n output_file : string\n name of output file\n binarize : Boolean\n binarize mask?\n\n Returns\n -------\n output_file : string\n name of labeled output nibabel-readable image volume\n\n Examples\n --------\n >>> import os\n >>> from mindboggle.utils.ants import fill_volume_with_surface_labels\n >>> from mindboggle.utils.plots import plot_volumes\n >>> path = os.path.join(os.environ['MINDBOGGLE_DATA'])\n >>> surface_files = [os.path.join(path, 'arno', 'labels',\n >>> 'lh.labels.DKT25.manual.vtk'), os.path.join(path, 'arno', 'labels',\n >>> 'rh.labels.DKT25.manual.vtk')]\n >>> # For a quick test, simply mask with whole brain:\n >>> hemi = 'rh'\n >>> left_mask = os.path.join(path, 'arno', 'mri', 't1weighted_brain.nii.gz')\n >>> right_mask = os.path.join(path, 'arno', 'mri', 't1weighted_brain.nii.gz')\n >>> mask_index = None\n >>> output_file = ''\n >>> binarize = True\n >>> output_file = fill_volume_with_surface_labels(hemi, left_mask, right_mask, surface_files, mask_index, output_file, binarize)\n >>> # View\n >>> plot_volumes(output_file)\n\n \"\"\"\n import os\n\n from mindboggle.utils.io_vtk import transform_to_volume\n from mindboggle.labels.relabel import overwrite_volume_labels\n from mindboggle.utils.ants import PropagateLabelsThroughMask\n\n if isinstance(surface_files, str):\n surface_files = [surface_files]\n\n if hemi == 'lh':\n mask = left_mask\n elif hemi == 'rh':\n mask = right_mask\n\n # Transform vtk coordinates to voxel index coordinates in a target\n # volume by using the header transformation:\n surface_in_volume = transform_to_volume(surface_files[0], mask)\n\n # Do the same for additional vtk surfaces:\n if len(surface_files) == 2:\n surfaces_in_volume = os.path.join(os.getcwd(), 'surfaces.nii.gz')\n surface_in_volume2 = transform_to_volume(surface_files[1], mask)\n\n overwrite_volume_labels(surface_in_volume, surface_in_volume2,\n surfaces_in_volume, ignore_labels=[0])\n surface_in_volume = surfaces_in_volume\n\n # Use ANTs to fill a binary volume mask with initial labels:\n output_file = PropagateLabelsThroughMask(mask, surface_in_volume,\n mask_index, output_file,\n binarize)\n if not os.path.exists(output_file):\n str1 = \"PropagateLabelsThroughMask() did not create \"\n raise(IOError(str1 + output_file + \".\"))\n\n return output_file # surface_in_volume\n\n\ndef thickinthehead(segmented_file, labeled_file, cortex_value=2,\n noncortex_value=3, labels=[], names=[], resize=True,\n propagate=True, output_dir='', save_table=False,\n output_table=''):\n \"\"\"\n Compute a simple thickness measure for each labeled cortex region.\n\n Note::\n\n - Cortex, noncortex, & label files are from the same coregistered brain.\n - Calls ANTs functions: ImageMath, Threshold, ResampleImageBySpacing\n - There may be slight discrepancies between volumes computed by\n thickinthehead() and volumes computed by volume_per_label();\n in 31 of 600+ ADNI 1.5T images, some volume_per_label() volumes\n were slightly larger (in the third decimal place), presumably due to\n label propagation through the cortex.\n\n Example preprocessing steps ::\n\n 1. Run Freesurfer and antsCorticalThickness.sh on T1-weighted image.\n 2. Convert FreeSurfer volume labels (e.g., wmparc.mgz or aparc+aseg.mgz)\n to cortex (2) and noncortex (3) segments using relabel_volume()\n function [refer to LABELS.py or FreeSurferColorLUT labels file].\n 3. Convert ANTs Atropos-segmented volume (tmpBrainSegmentation.nii.gz)\n to cortex and noncortex segments, by converting 1-labels to 0 and\n 4-labels to 3 with the relabel_volume() function\n (the latter is to include deep-gray matter with noncortical tissues).\n 4. Combine FreeSurfer and ANTs segmentation volumes to obtain a single\n cortex (2) and noncortex (3) segmentation file using the function\n combine_2labels_in_2volumes(). This function takes the union of\n cortex voxels from the segmentations, the union of the noncortex\n voxels from the segmentations, and overwrites intersecting cortex\n and noncortex voxels with noncortex (3) labels.\n ANTs tends to include more cortical gray matter at the periphery of\n the brain than Freesurfer, and FreeSurfer tends to include more white\n matter that extends deep into gyral folds than ANTs, so the above\n attempts to remedy their differences by overlaying ANTs cortical gray\n with FreeSurfer white matter.\n 5. Optional, see Step 2 below:\n Fill segmented cortex with cortex labels and noncortex with\n noncortex labels using the PropagateLabelsThroughMask() function\n (which calls ImageMath ... PropagateLabelsThroughMask in ANTs).\n The labels can be initialized using FreeSurfer (e.g. wmparc.mgz)\n or ANTs (by applying the nonlinear inverse transform generated by\n antsCorticalThickness.sh to labels in the Atropos template space).\n [Note: Any further labeling steps may be applied, such as\n overwriting cerebrum with intersecting cerebellum labels.]\n\n Steps ::\n\n 1. Extract noncortex and cortex.\n 2. Either mask labels with cortex or fill cortex with labels.\n 3. Resample cortex and noncortex files from 1x1x1 to 0.5x0.5x0.5\n to better represent the contours of the boundaries of the cortex.\n 4. Extract outer and inner boundary voxels of the cortex,\n by eroding 1 (resampled) voxel for cortex voxels (2) bordering\n the outside of the brain (0) and bordering noncortex (3).\n 5. Estimate middle cortical surface area by the average volume\n of the outer and inner boundary voxels of the cortex.\n 6. Compute the volume of a labeled region of cortex.\n 7. Estimate the thickness of the labeled cortical region as the\n volume of the labeled region (#6) divided by the surface area (#5).\n\n Parameters\n ----------\n segmented_file : string\n image volume with cortex and noncortex (and any other) labels\n labeled_file : string\n corresponding image volume with index labels\n cortex_value : integer\n cortex label value in segmented_file\n noncortex_value : integer\n noncortex label value in segmented_file\n labels : list of integers\n label indices\n names : list of strings\n label names\n resize : Boolean\n resize (2x) segmented_file for more accurate thickness estimates?\n propagate : Boolean\n propagate labels through cortex?\n output_dir : string\n output directory\n save_table : Boolean\n save output table file with label volumes and thickness values?\n output_table : string\n name of output table file with label volumes and thickness values\n\n Returns\n -------\n label_volume_thickness : list of lists of integers and floats\n label indices, volumes, and thickness values (default -1)\n output_table : string\n name of output table file with label volumes and thickness values\n\n Examples\n --------\n >>> from mindboggle.utils.ants import thickinthehead\n >>> segmented_file = '/Users/arno/Data/antsCorticalThickness/OASIS-TRT-20-1/antsBrainSegmentation.nii.gz'\n >>> labeled_file = '/appsdir/freesurfer/subjects/OASIS-TRT-20-1/mri/labels.DKT31.manual.nii.gz'\n >>> cortex_value = 2\n >>> noncortex_value = 3\n >>> #labels = [2]\n >>> labels = range(1002,1036) + range(2002,2036)\n >>> labels.remove(1004)\n >>> labels.remove(2004)\n >>> labels.remove(1032)\n >>> labels.remove(2032)\n >>> labels.remove(1033)\n >>> labels.remove(2033)\n >>> names = []\n >>> resize = True\n >>> propagate = False\n >>> output_dir = ''\n >>> save_table = True\n >>> output_table = ''\n >>> label_volume_thickness, output_table = thickinthehead(segmented_file, labeled_file, cortex_value, noncortex_value, labels, names, resize, propagate, output_dir, save_table, output_table)\n\n \"\"\"\n import os\n import numpy as np\n import nibabel as nb\n\n from mindboggle.utils.utils import execute\n\n #-------------------------------------------------------------------------\n # Output files:\n #-------------------------------------------------------------------------\n if output_dir:\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n else:\n output_dir = os.getcwd()\n cortex = os.path.join(output_dir, 'cortex.nii.gz')\n noncortex = os.path.join(output_dir, 'noncortex.nii.gz')\n temp = os.path.join(output_dir, 'temp.nii.gz')\n inner_edge = os.path.join(output_dir, 'cortex_inner_edge.nii.gz')\n use_outer_edge = True\n if use_outer_edge:\n outer_edge = os.path.join(output_dir, 'cortex_outer_edge.nii.gz')\n\n if save_table:\n if output_table:\n output_table = os.path.join(os.getcwd(), output_table)\n else:\n output_table = os.path.join(os.getcwd(), 'thickinthehead_per_label.csv')\n fid = open(output_table, 'w')\n if names:\n fid.write(\"Label name,Label number,Volume,Thickness (thickinthehead)\\n\")\n else:\n fid.write(\"Label number,Volume,Thickness (thickinthehead)\\n\")\n else:\n output_table = ''\n\n #-------------------------------------------------------------------------\n # Extract noncortex and cortex:\n #-------------------------------------------------------------------------\n cmd = ['ThresholdImage 3', segmented_file,\n noncortex, str(noncortex_value), str(noncortex_value), '1 0']\n execute(cmd)\n cmd = ['ThresholdImage 3', segmented_file,\n cortex, str(cortex_value), str(cortex_value), '1 0']\n execute(cmd)\n\n #-------------------------------------------------------------------------\n # Either mask labels with cortex or fill cortex with labels:\n #-------------------------------------------------------------------------\n if propagate:\n cmd = ['ImageMath', '3', cortex, 'PropagateLabelsThroughMask',\n cortex, labeled_file]\n execute(cmd)\n else:\n cmd = ['ImageMath 3', cortex, 'm', cortex, labeled_file]\n execute(cmd)\n\n #-------------------------------------------------------------------------\n # Load data and dimensions:\n #-------------------------------------------------------------------------\n if resize:\n rescale = 2.0\n else:\n rescale = 1.0\n compute_real_volume = True\n if compute_real_volume:\n img = nb.load(cortex)\n hdr = img.get_header()\n vv_orig = np.prod(hdr.get_zooms())\n vv = np.prod([x/rescale for x in hdr.get_zooms()])\n cortex_data = img.get_data().ravel()\n else:\n vv = 1/rescale\n cortex_data = nb.load(cortex).get_data().ravel()\n\n #-------------------------------------------------------------------------\n # Resample cortex and noncortex files from 1x1x1 to 0.5x0.5x0.5\n # to better represent the contours of the boundaries of the cortex:\n #-------------------------------------------------------------------------\n if resize:\n dims = ' '.join([str(1/rescale), str(1/rescale), str(1/rescale)])\n cmd = ['ResampleImageBySpacing 3', cortex, cortex, dims, '0 0 1']\n execute(cmd)\n cmd = ['ResampleImageBySpacing 3', noncortex, noncortex, dims, '0 0 1']\n execute(cmd)\n\n #-------------------------------------------------------------------------\n # Extract outer and inner boundary voxels of the cortex,\n # by eroding 1 (resampled) voxel for cortex voxels (2) bordering\n # the outside of the brain (0) and bordering noncortex (3):\n #-------------------------------------------------------------------------\n cmd = ['ImageMath 3', inner_edge, 'MD', noncortex, '1']\n execute(cmd)\n cmd = ['ImageMath 3', inner_edge, 'm', cortex, inner_edge]\n execute(cmd)\n if use_outer_edge:\n cmd = ['ThresholdImage 3', cortex, outer_edge, '1 10000 1 0']\n execute(cmd)\n cmd = ['ImageMath 3', outer_edge, 'ME', outer_edge, '1']\n execute(cmd)\n cmd = ['ThresholdImage 3', outer_edge, outer_edge, '1 1 0 1']\n execute(cmd)\n cmd = ['ImageMath 3', outer_edge, 'm', cortex, outer_edge]\n execute(cmd)\n cmd = ['ThresholdImage 3', inner_edge, temp, '1 10000 1 0']\n execute(cmd)\n cmd = ['ThresholdImage 3', temp, temp, '1 1 0 1']\n execute(cmd)\n cmd = ['ImageMath 3', outer_edge, 'm', temp, outer_edge]\n execute(cmd)\n\n #-------------------------------------------------------------------------\n # Load data:\n #-------------------------------------------------------------------------\n inner_edge_data = nb.load(inner_edge).get_data().ravel()\n if use_outer_edge:\n outer_edge_data = nb.load(outer_edge).get_data().ravel()\n\n #-------------------------------------------------------------------------\n # Loop through labels:\n #-------------------------------------------------------------------------\n if not labels:\n labeled_data = nb.load(labeled_file).get_data().ravel()\n labels = np.unique(labeled_data)\n labels = [int(x) for x in labels]\n label_volume_thickness = -1 * np.ones((len(labels), 3))\n label_volume_thickness[:, 0] = labels\n for ilabel, label in enumerate(labels):\n if names:\n name = names[ilabel]\n\n #---------------------------------------------------------------------\n # Compute thickness as a ratio of label volume and edge volume:\n # - Estimate middle cortical surface area by the average volume\n # of the outer and inner boundary voxels of the cortex.\n # - Compute the volume of a labeled region of cortex.\n # - Estimate the thickness of the labeled cortical region as the\n # volume of the labeled region divided by the surface area.\n #---------------------------------------------------------------------\n label_cortex_volume = vv_orig * len(np.where(cortex_data==label)[0])\n label_inner_edge_volume = vv * len(np.where(inner_edge_data==label)[0])\n if label_inner_edge_volume:\n if use_outer_edge:\n label_outer_edge_volume = \\\n vv * len(np.where(outer_edge_data==label)[0])\n label_area = (label_inner_edge_volume +\n label_outer_edge_volume) / 2.0\n else:\n label_area = label_inner_edge_volume\n thickness = label_cortex_volume / label_area\n label_volume_thickness[ilabel, 1] = label_cortex_volume\n label_volume_thickness[ilabel, 2] = thickness\n\n #print('label {0} volume: cortex={1:2.2f}, inner={2:2.2f}, '\n # 'outer={3:2.2f}, area51={4:2.2f}, thickness={5:2.2f}mm'.\n # format(name, label, label_cortex_volume, label_inner_edge_volume,\n # label_outer_edge_volume, label_area, thickness))\n if names:\n print('{0} ({1}) volume={2:2.2f}, thickness={3:2.2f}mm'.\n format(name, label, label_cortex_volume, thickness))\n else:\n print('{0}, volume={2:2.2f}, thickness={3:2.2f}mm'.\n format(label, label_cortex_volume, thickness))\n\n if save_table:\n if names:\n fid.write('{0}, {1}, {2:2.4f}, {3:2.4f}\\n'.format(name,\n label, label_cortex_volume, thickness))\n else:\n fid.write('{0}, {1:2.4f}, {2:2.4f}\\n'.format(label,\n label_cortex_volume, thickness))\n\n label_volume_thickness = label_volume_thickness.transpose().tolist()\n\n return label_volume_thickness, output_table\n\n\n# def ANTS(source, target, iterations='30x99x11', output_stem=''):\n# \"\"\"\n# Use ANTs to register a source image volume to a target image volume.\n#\n# This program uses the ANTs SyN registration method.\n#\n# Parameters\n# ----------\n# source : string\n# file name of source image volume\n# target : string\n# file name of target image volume\n# iterations : string\n# number of iterations (\"0\" for affine, \"30x99x11\" default)\n# output_stem : string\n# file name stem for output transform matrix\n#\n# Returns\n# -------\n# affine_transform : string\n# file name for affine transform matrix\n# nonlinear_transform : string\n# file name for nonlinear transform nifti file\n# nonlinear_inverse_transform : string\n# file name for nonlinear inverse transform nifti file\n# output_stem : string\n# file name stem for output transform matrix\n#\n# Examples\n# --------\n# >>> import os\n# >>> from mindboggle.utils.ants import ANTS\n# >>> path = os.environ['MINDBOGGLE_DATA']\n# >>> source = os.path.join(path, 'arno', 'mri', 't1weighted_brain.nii.gz')\n# >>> target = os.path.join(path, 'atlases', 'MNI152_T1_1mm_brain.nii.gz')\n# >>> iterations = \"0\"\n# >>> output_stem = \"\"\n# >>> #\n# >>> ANTS(source, target, iterations, output_stem)\n#\n# \"\"\"\n# import os\n# from mindboggle.utils.utils import execute\n#\n# if not output_stem:\n# src = os.path.basename(source).split('.')[0]\n# tgt = os.path.basename(target).split('.')[0]\n# output_stem = os.path.join(os.getcwd(), src+'_to_'+tgt)\n#\n# cmd = ['ANTS', '3', '-m CC[' + target + ',' + source + ',1,2]',\n# '-r Gauss[2,0]', '-t SyN[0.5] -i', iterations,\n# '-o', output_stem, '--use-Histogram-Matching',\n# '--number-of-affine-iterations 10000x10000x10000x10000x10000']\n# execute(cmd, 'os')\n#\n# affine_transform = output_stem + 'Affine.txt'\n# nonlinear_transform = output_stem + 'Warp.nii.gz'\n# nonlinear_inverse_transform = output_stem + 'InverseWarp.nii.gz'\n#\n# if not os.path.exists(affine_transform):\n# raise(IOError(\"ANTs did not create \" + affine_transform + \".\"))\n# if not os.path.exists(nonlinear_transform):\n# raise(IOError(\"ANTs did not create \" + nonlinear_transform + \".\"))\n# if not os.path.exists(nonlinear_inverse_transform):\n# raise(IOError(\"ANTs did not create \" + nonlinear_inverse_transform + \".\"))\n#\n# return affine_transform, nonlinear_transform,\\\n# nonlinear_inverse_transform, output_stem\n#\n#\n# def WarpImageMultiTransform(source, target, output='',\n# interp='--use-NN', xfm_stem='',\n# affine_transform='', nonlinear_transform='',\n# inverse=False, affine_only=False):\n# \"\"\"\n# Use ANTs to transform a source image volume to a target image volume.\n#\n# This program uses the ANTs WarpImageMultiTransform function.\n#\n# Parameters\n# ----------\n# source : string\n# file name of source image volume\n# target : string\n# file name of target (reference) image volume\n# output : string\n# file name of output image volume\n# interp : string\n# interpolation type (\"--use-NN\" for nearest neighbor)\n# xfm_stem : string\n# file name stem for output transform\n# affine_transform : string\n# file containing affine transform\n# nonlinear_transform : string\n# file containing nonlinear transform\n# inverse : Boolean\n# apply inverse transform?\n# affine_only : Boolean\n# apply only affine transform?\n#\n# Returns\n# -------\n# output : string\n# output label file name\n#\n# \"\"\"\n# import os\n# import sys\n# from mindboggle.utils.utils import execute\n#\n# if xfm_stem:\n# affine_transform = xfm_stem + 'Affine.txt'\n# if inverse:\n# nonlinear_transform = xfm_stem + 'InverseWarp.nii.gz'\n# else:\n# nonlinear_transform = xfm_stem + 'Warp.nii.gz'\n# elif not affine_transform and not nonlinear_transform:\n# sys.exit('Provide either xfm_stem or affine_transform and '\n# 'nonlinear_transform.')\n#\n# if not output:\n# output = os.path.join(os.getcwd(), 'WarpImageMultiTransform.nii.gz')\n#\n# if not os.path.exists(nonlinear_transform):\n# affine_only = True\n#\n# if affine_only:\n# if inverse:\n# cmd = ['WarpImageMultiTransform', '3', source, output, '-R',\n# target, interp, '-i', affine_transform]\n# else:\n# cmd = ['WarpImageMultiTransform', '3', source, output, '-R',\n# target, interp, affine_transform]\n# else:\n# if inverse:\n# cmd = ['WarpImageMultiTransform', '3', source, output, '-R',\n# target, interp, '-i', affine_transform, nonlinear_transform]\n# else:\n# cmd = ['WarpImageMultiTransform', '3', source, output, '-R',\n# target, interp, nonlinear_transform, affine_transform]\n# execute(cmd, 'os')\n#\n# if not os.path.exists(output):\n# raise(IOError(\"WarpImageMultiTransform did not create \" + output + \".\"))\n#\n# return output\n#\n#\n# def ComposeMultiTransform(transform_files, inverse_Booleans,\n# output_transform_file='', ext='.txt'):\n# \"\"\"\n# Run ANTs ComposeMultiTransform function to create a single transform.\n#\n# Parameters\n# ----------\n# transform_files : list of strings\n# transform file names\n# inverse_Booleans : list of Booleans\n# Booleans to indicate which transforms to take the inverse of\n# output_transform_file : string\n# transform file name\n# ext : string\n# '.txt' to save transform file as text, '.mat' for data file\n#\n# Returns\n# -------\n# output_transform_file : string\n# single composed transform file name\n#\n# Examples\n# --------\n# >>> from mindboggle.utils.ants import ComposeMultiTransform\n# >>> transform_files = ['affine1.mat', 'affine2.mat']\n# >>> transform_files = ['/data/Brains/Mindboggle101/antsCorticalThickness/OASIS-TRT-20_volumes/OASIS-TRT-20-1/antsTemplateToSubject0GenericAffine.mat','/data/Brains/Mindboggle101/antsCorticalThickness/OASIS-TRT-20_volumes/OASIS-TRT-20-1/antsTemplateToSubject0GenericAffine.mat']\n# >>> inverse_Booleans = [False, False]\n# >>> output_transform_file = ''\n# >>> ext = '.txt'\n# >>> ComposeMultiTransform(transform_files, inverse_Booleans, output_transform_file, ext)\n#\n# \"\"\"\n# import os\n#\n# from mindboggle.utils.utils import execute\n#\n# if not output_transform_file:\n# output_transform_file = os.path.join(os.getcwd(), 'affine' + ext)\n#\n# xfms = []\n# for ixfm, xfm in enumerate(transform_files):\n# if inverse_Booleans[ixfm]:\n# xfms.append('-i')\n# xfms.append(xfm)\n#\n# cmd = ['ComposeMultiTransform 3', output_transform_file, ' '.join(xfms)]\n# print(cmd)\n# execute(cmd, 'os')\n# #if not os.path.exists(output_transform_file):\n# # raise(IOError(output_transform_file + \" not found\"))\n#\n# return output_transform_file\n\n\n","sub_path":"mindboggle/utils/ants.py","file_name":"ants.py","file_ext":"py","file_size_in_byte":39423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154733159","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 29 13:32:36 2020\n利用建立好的bp模型,进行图像分类的验证\n@author: 地三仙\n# one-hot编码的结果是比较奇怪的,最好是先转换成二维数组\n# 展平方法:a.flatten() a是np.array,函一维数组\n\"\"\"\nfrom bp import Network\nfrom sklearn.preprocessing import OneHotEncoder\nimport numpy as np\nfrom datetime import datetime as t\nimport matplotlib.pyplot as plt\n\n# 1.数据预处理\n# 从本地获取数字图像的数据集 .npz\ndef get_data(path):\n f = np.load(path)\n x_train_all, y_train_all = f['x_train'], f['y_train']\n x_test, y_test = f['x_test'], f['y_test']\n f.close()\n return x_train_all, y_train_all, x_test, y_test\n# 1.1数据集划分\npath = \"C:/Users/地三仙/.keras/datasets/fashion-mnist/mnist.npz\" # 数据条目一样 npz文件比压缩文件更小\nx_train_all, y_train_all, x_test, y_test = get_data(path)\nx_validate, y_validate = x_train_all[ :5000], y_train_all[ :5000] # 本案例没有使用\nx_train, y_train = x_train_all[5000: ], y_train_all[5000: ]\nprint(x_train.shape, y_train.shape)\nprint(x_test.shape, y_test.shape)\n\n# 查看数据\ndef show_images(n_rows, n_cols ,x_data, y_data):\n assert len(x_data) == len(y_data)\n assert n_rows * n_cols < len(x_data)\n plt.figure(figsize = (n_cols * 1.4, n_rows * 1.6)) # 宽、高\n for row in range(n_rows):\n for col in range(n_cols):\n index = row * n_cols + col\n plt.subplot(n_rows, n_cols, index+1)\n plt.imshow(x_data[index],cmap='binary')\n plt.axis('off')\n plt.title(str(y_data[index]))\n plt.show()\n\nshow_images(5, 3 ,x_train[:100], y_train[:100])\n \n \n# 1.2数据展平:三维数据变二维数据\ndef flatten(tri_arr):\n data = [a.flatten() for a in tri_arr]\n return np.array(data)\n \nx_train_flatten = flatten(x_train)\nx_validate_flatten = flatten(x_validate)\nx_test_flatten = flatten(x_test)\nprint(x_train_flatten.shape)\n\n# 1.3对标签数据进行独热编码\nenc = OneHotEncoder()\nenc.fit(y_train_all.reshape(-1,1)) \n# one-hot编码的结果是比较奇怪的,最好是先转换成二维数组\ny_train_onehot = enc.transform(y_train.reshape(-1,1)).toarray()\ny_validate_onehot = enc.transform(y_validate.reshape(-1,1)).toarray()\ny_test_onehot = enc.transform(y_test.reshape(-1,1)).toarray()\nprint(x_train_flatten.shape, y_train_onehot.shape)\nprint(y_test_onehot[0].shape)\n\n# 2.构建模型\nnet = Network([784, 100, 50, 10]) # 28X28展平为784 两层隐藏层\nstart = t.now()\nprint(\"开始时间:\" , start)\nnet.SGD(list(zip(x_train_flatten, y_train_onehot)), 3, 16, 2,\n list(zip(x_test_flatten, y_test_onehot)))\nend = t.now()\nprint(\"结束时间:\", end)\nprint(\"训练用时:\", end - start)\n\n# 3.预测一下\ndef predict(net, x):\n y_predict = net.feedforward(x.flatten())\n print(\"预测样本为\")\n plt.imshow(x, cmap='binary')\n plt.show()\n print(\"预测值为:\" + str(np.argmax(y_predict)))\n\npredict(net, x_validate[2])\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215546748","text":"from sklearn.neighbors import KernelDensity\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(20)\nX = np.concatenate((np.random.normal(0, 1, 10), np.random.normal(5, 1, 20)))[:, np.newaxis]\n\n# training\nmodel = KernelDensity(kernel='gaussian', bandwidth=0.2); # kernel = 'gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine'\nmodel.fit(X)\nlog_dens = model.score_samples(X)\ny_pred = np.exp(log_dens)\n\n# visualization\nfig, axes = plt.subplots(1,3, figsize=(15,10))\naxes[0].plot(X[:,0], lw=0, marker='o'); axes[0].set_title('series data or raw data')\naxes[1].hist(X[:,0], bins=np.linspace(-5,10,10)); axes[1].set_title('histogram')\naxes[2].scatter(X[:,0], y_pred); axes[2].set_title('gaussian kernel estimation')\nplt.show()\n","sub_path":"sklearn/estimation_kde.py","file_name":"estimation_kde.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"25155522","text":"from vtk import *\nfrom tonic import camera as tc\n\ndef update_camera(renderer, cameraData):\n camera = renderer.GetActiveCamera()\n camera.SetPosition(cameraData['position'])\n camera.SetFocalPoint(cameraData['focalPoint'])\n camera.SetViewUp(cameraData['viewUp'])\n\ndef create_spherical_camera(renderer, dataHandler, phiValues, thetaValues):\n camera = renderer.GetActiveCamera()\n return tc.SphericalCamera(dataHandler, camera.GetFocalPoint(), camera.GetPosition(), camera.GetViewUp(), phiValues, thetaValues)\n\ndef create_cylindrical_camera(renderer, dataHandler, phiValues, translationValues):\n camera = renderer.GetActiveCamera()\n return tc.CylindricalCamera(dataHandler, camera.GetFocalPoint(), camera.GetPosition(), camera.GetViewUp(), phiValues, translationValues)\n\nclass CaptureRenderWindow(object):\n def __init__(self, magnification=1):\n self.windowToImage = vtkWindowToImageFilter()\n self.windowToImage.SetMagnification(magnification)\n self.windowToImage.SetInputBufferTypeToRGB()\n self.windowToImage.ReadFrontBufferOn()\n self.writer = None\n\n def SetRenderWindow(self, renderWindow):\n self.windowToImage.SetInput(renderWindow)\n\n def SetFormat(self, mimeType):\n if mimeType == 'image/png':\n self.writer = vtkPNGWriter()\n self.writer.SetInputConnection(self.windowToImage.GetOutputPort())\n elif mimeType == 'image/jpg':\n self.writer = vtkJPEGWriter()\n self.writer.SetInputConnection(self.windowToImage.GetOutputPort())\n\n def writeImage(self, path):\n if self.writer:\n self.windowToImage.Modified()\n self.windowToImage.Update()\n self.writer.SetFileName(path)\n self.writer.Write()\n","sub_path":"python/tonic/vtk/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"474040369","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nimport os.path\nimport yaml\nimport com.utils.app_utils as ut\n\nif __name__ == '__main__':\n\n os.environ[\"PYSPARK_SUBMIT_ARGS\"] = (\n '--packages \"org.apache.hadoop:hadoop-aws:2.7.4\" pyspark-shell'\n )\n\n # Create the SparkSession\n spark = SparkSession \\\n .builder \\\n .appName(\"DSL examples\") \\\n .master('local[*]') \\\n .getOrCreate()\n spark.sparkContext.setLogLevel('ERROR')\n\n current_dir = os.path.abspath(os.path.dirname(__file__))\n app_config_path = os.path.abspath(current_dir + \"/../../\" + \"application.yml\")\n app_secrets_path = os.path.abspath(current_dir + \"/../../\" + \".secrets\")\n\n conf = open(app_config_path)\n app_conf = yaml.load(conf, Loader=yaml.FullLoader)\n secret = open(app_secrets_path)\n app_secret = yaml.load(secret, Loader=yaml.FullLoader)\n\n # Setup spark to use s3\n hadoop_conf = spark.sparkContext._jsc.hadoopConfiguration()\n hadoop_conf.set(\"fs.s3a.access.key\", app_secret[\"s3_conf\"][\"access_key\"])\n hadoop_conf.set(\"fs.s3a.secret.key\", app_secret[\"s3_conf\"][\"secret_access_key\"])\n\n src_list = app_conf['source_list']\n staging_dir = app_conf[\"s3_conf\"][\"staging_dir\"]\n #\n for src in src_list:\n src_conf = app_conf[src]\n stg_path = \"s3a://\" + app_conf[\"s3_conf\"][\"s3_bucket\"] + \"/\" + staging_dir + \"/\" + src\n if src == 'SB':\n print(\"\\nReading data from MySQL DB - SB,\")\n jdbc_params = {\"url\": ut.get_mysql_jdbc_url(app_secret),\n \"lowerBound\": \"1\",\n \"upperBound\": \"100\",\n \"dbtable\": src_conf[\"mysql_conf\"][\"query\"],\n \"numPartitions\": \"2\",\n \"partitionColumn\": src_conf[\"mysql_conf\"][\"partition_column\"],\n \"user\": app_secret[\"mysql_conf\"][\"username\"],\n \"password\": app_secret[\"mysql_conf\"][\"password\"]\n }\n sb_df = ut.read_from_mysql(jdbc_params, spark)\\\n .withColumn(\"run_dt\", current_date())\n sb_df.show()\n\n sb_df.write\\\n .partitionBy(\"run_dt\")\\\n .mode(\"overwrite\")\\\n .parquet(stg_path)\n\n elif src == 'OL':\n ol_df = spark.read\\\n .format(\"com.springml.spark.sftp\")\\\n .option(\"host\", app_secret[\"sftp_conf\"][\"hostname\"])\\\n .option(\"port\", app_secret[\"sftp_conf\"][\"port\"])\\\n .option(\"username\", app_secret[\"sftp_conf\"][\"username\"])\\\n .option(\"pem\", os.path.abspath(current_dir + \"/../../\" + app_secret[\"sftp_conf\"][\"pem\"]))\\\n .option(\"fileType\", \"csv\")\\\n .option(\"delimiter\", \"|\")\\\n .load(src_conf[\"sftp_conf\"][\"directory\"] + \"/\" + src_conf[\"sftp_conf\"][\"filename\"])\\\n .withColumn(\"run_dt\", current_date())\n\n ol_df.show()\n\n ol_df.write\\\n .partitionBy(\"run_dt\")\\\n .mode(\"overwrite\")\\\n .parquet(stg_path)\n\n spark.stop()\n\n","sub_path":"com/nielsen/source_data_loading.py","file_name":"source_data_loading.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"392910545","text":"#minimum_variance_portfolio.py\n\"\"\"\nGrant White\nMarch 29, 2020\n\"\"\"\n\nimport numpy as np\nfrom cvxopt import matrix, solvers\n\n\ndef portfolio(filename=\"portfolio.txt\"):\n \"\"\"Markowitz Portfolio Optimization\n Finds the minimum variance portfolio with and without short-selling.\n Solves:\n minimize (1/2)(x.T)Px + (q.T)x\n subject to Gx <= h\n Ax = b \n\n Parameters:\n filename (str): The name of the portfolio data file.\n Each column is a differnt asset.\n Each row is a different year (or other unit of time)\n The values are the returns.\n\n Returns:\n (ndarray) The optimal portfolio with short selling.\n (ndarray) The optimal portfolio without short selling.\n \"\"\"\n\n #read in data\n data = np.loadtxt(filename)\n n = len(data[0]) - 1\n\n #create the covariance matrix\n P = np.cov(data[:,1:], rowvar=False)\n\n #expected rate of return\n mu = np.average(data[:,1:], axis=0)\n R = 1.13\n\n #matricies\n q = np.zeros(n)\n G = -np.eye(n)\n h = np.zeros(n)\n A = np.vstack((np.ones(n), mu))\n b = np.array((1, R))\n\n #convert to cvxopt matricies\n P = matrix(P)\n q = matrix(q)\n G = matrix(G)\n h = matrix(h)\n A = matrix(A)\n b = matrix(b)\n\n #solve\n solvers.options['show_progress'] = False\n sol = solvers.qp(P, q, G, h, A, b)\n sol_short = solvers.qp(P=P, q=q, A=A, b=b)\n\n #return optimal portfolio with and without short-selling\n return np.ravel(sol_short['x']), np.ravel(sol['x'])\n","sub_path":"PortfolioOptimization/minimum_variance_portfolio.py","file_name":"minimum_variance_portfolio.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"61435933","text":"from keras import Sequential, Input, Model, optimizers\nfrom keras.layers import Embedding, Flatten, Dense, Dot, Activation, Reshape, Concatenate\nfrom keras.utils import plot_model\nfrom keras_preprocessing import sequence\nfrom keras_preprocessing.sequence import skipgrams\nfrom keras_preprocessing.text import Tokenizer\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\nwindow_size = 5\nvector_dim = 100\nvocab_size = 10000\nepoch = 1\n\n\ndef collect_data():\n with open('../datasets/ptb.train.txt', 'r') as f:\n lines = f.readlines()\n # st是sentence的缩写\n raw_dataset = [st.split() for st in lines]\n print('sentences: %d' % len(raw_dataset))\n\n tokenizer = Tokenizer(num_words=vocab_size)\n tokenizer.fit_on_texts(raw_dataset)\n sequences = tokenizer.texts_to_sequences(raw_dataset)\n word_index = tokenizer.word_index # 最常见10000个词,词典\n\n return sequences, word_index\n\n\ndef create_models():\n # inputs\n w_inputs = Input(shape=(1,), dtype='int32')\n w = Embedding(vocab_size, vector_dim)(w_inputs)\n\n # context\n c_inputs = Input(shape=(1,), dtype='int32')\n c = Embedding(vocab_size, vector_dim)(c_inputs)\n o = Dot(axes=2)([w, c])\n # o = Reshape((1,))(o)\n o = Flatten()(o)\n o = Activation('sigmoid', name='sigmoid')(o)\n\n model = Model(inputs=[w_inputs, c_inputs], outputs=o)\n\n model.compile(optimizer=optimizers.RMSprop(lr=0.001),\n loss='binary_crossentropy',\n metrics=['accuracy'])\n # plot_model(model, show_layer_names=True, show_shapes=True, to_file='./plot_model.png')\n return model\n\n\nif __name__ == '__main__':\n sequences, word_index = collect_data()\n model = create_models()\n model.summary()\n x, y = [], []\n for i, doc in enumerate(sequences):\n sampling_table = sequence.make_sampling_table(vocab_size)\n data, labels = skipgrams(sequence=doc, vocabulary_size=vocab_size, window_size=window_size,negative_samples=5,\n sampling_table=sampling_table)\n x.extend(data)\n y.extend(labels)\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1)\n x_train_input = [np.array(x) for x in zip(*x_train)]\n x_test_input = [np.array(x) for x in zip(*x_test)]\n history = model.fit(x_train_input, y_train, epochs=epoch, batch_size=512, validation_data=[x_test_input, y_test])\n vectors = model.get_weights()[0]\n f = open('../models/word2vec.txt', 'w')\n f.write('{} {}\\n'.format(vocab_size - 1, vector_dim))\n for word, i in word_index.items():\n f.write('{} {}\\n'.format(word, ' '.join(map(str, list(vectors[i, :])))))\n f.close()\n # Plot training & validation accuracy values\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n\n # Plot training & validation loss values\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n print('training completed!')\n","sub_path":"Chapter03-Word Vectorize/word2vec-training.py","file_name":"word2vec-training.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588138337","text":"exit_not_chosen = True\r\n\r\nwhile exit_not_chosen:\r\n sides = input(\r\n \"\\nPlease type the lengths of your Triangles sides separated by commas or 'exit' to quit the programme\\n\").lower()\r\n\r\n if sides == \"exit\":\r\n exit_not_chosen = False\r\n else:\r\n sides = sides.split(\",\") # Splits input based on where commas are\r\n sides = list(map(int, sides)) # Converts input from string to integer\r\n sides.sort() # Sorts list in order of lowest to highest\r\n\r\n if sides[0] ** 2 + sides[1] ** 2 == sides[2] ** 2:\r\n print(\"Yes, this is a Pythagorean Triple\")\r\n else:\r\n print(\"Sorry, this is not a Pythagorean Triple\")\r\n","sub_path":"Pythagorean Triples Checker.py","file_name":"Pythagorean Triples Checker.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"21283476","text":"#encoding:utf-8\nfrom functions import insertVoteWeb, checkDate, checkQuestionOp, checkOnlyOneVotePerUser, checkQuestionOpInPoll, checkAge\nimport unittest\nimport datetime\nfrom exceptions import PollDateException, NoQuestionOptionException, MoreThanOneVoteException, UserAgeException\nfrom models import Poll, UserAccount, Vote\n\nclass TestInsertMethods(unittest.TestCase):\n\n def testInsertVote(self):\n Vote.objects.all().delete()\n testPoll = Poll.objects.get(id = 1) \n testPoll.startdate = datetime.datetime.strptime(\"2010-2-12\", '%Y-%m-%d').date()\n testPoll.save() \n testUser = UserAccount.objects.get(id = 4)\n testQuestionOptions = \"12&56\"\n testInsert = insertVoteWeb(testPoll.id, testUser.id, testQuestionOptions)\n self.assertIsNotNone(testInsert, \"Error en la insercion del voto\")\n Vote.objects.all().delete()\n \n def testCheckDate(self):\n testPoll = Poll.objects.get(id = 2) \n self.assertRaises(PollDateException, checkDate, testPoll.id)\n \n def testCheckQuestionOp(self):\n self.assertRaises(NoQuestionOptionException, checkQuestionOp,\"114&512&71\")\n \n def testCheckQuestionOpInPoll(self):\n self.assertRaises(NoQuestionOptionException, checkQuestionOpInPoll, 1, \"12&53\")\n \n def testIncreasePollVotes(self):\n Vote.objects.all().delete()\n testPoll = Poll.objects.get(id = 1) \n testPoll.votos_actuales = 0\n testPoll.save()\n testPoll.startdate = datetime.datetime.strptime(\"2010-2-12\", '%Y-%m-%d').date()\n testPoll.save() \n \n testUser1 = UserAccount.objects.get(id = 4)\n testUser2 = UserAccount.objects.get(id = 5)\n \n testQuestionOptions = \"12&56\"\n insertVoteWeb(testPoll.id, testUser1.id, testQuestionOptions)\n votosPoll1 = Poll.objects.get(id = testPoll.id)\n self.assertEqual(votosPoll1.votos_actuales, 1)\n \n insertVoteWeb(testPoll.id, testUser2.id, testQuestionOptions)\n votosPoll2 = Poll.objects.get(id = testPoll.id)\n self.assertEqual(votosPoll2.votos_actuales, 2)\n \n Vote.objects.all().delete()\n\n def testCheckOnlyOneVotePerUser(self):\n Vote.objects.all().delete()\n testPoll = Poll.objects.get(id = 1) \n testPoll.startdate = datetime.datetime.strptime(\"2010-2-12\", '%Y-%m-%d').date()\n testPoll.save()\n \n testUser = UserAccount.objects.get(id = 4)\n testQuestionOptions = \"12&56\"\n insertVoteWeb(testPoll.id, testUser.id, testQuestionOptions)\n self.assertRaises(MoreThanOneVoteException, checkOnlyOneVotePerUser, testPoll.id, testUser.id)\n Vote.objects.all().delete()\n\n def testAge(self):\n self.assertRaises(UserAgeException, checkAge, 3)\n self.assertEqual(checkAge(4), 42, \"Error, la edad del usuario no es la esperada\")\n \nif __name__ == '__main__':\n unittest.main() \n \n","sub_path":"project/AlmacenamientoVotos/almvotes/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119596503","text":"import os\nfrom PIL import Image\n\nsource_dir = '/home/jackon/datasets/porn_hot_images/original_images'\ntarget_dir = '/home/jackon/datasets/porn_hot_images/resized-256x256'\n\ntarget_size = (256, 256)\nname_subfix = '.256x256.jpg'\n\n\ndef main(source_dir, target_dir):\n for label in os.listdir(source_dir):\n label_src = os.path.join(source_dir, label)\n label_target = os.path.join(target_dir, label)\n if not os.path.exists(label_target):\n os.makedirs(label_target)\n\n label_images = os.listdir(label_src)\n label_images_count = len(label_images)\n cnt = 0\n\n print('=== start processing %s. count = %s' % (label, label_images_count))\n for img in label_images:\n cnt += 1\n if cnt % 1000 == 0:\n print('(%s/%s) processing %s' % (cnt, label_images_count, img))\n # break # for test\n try:\n im_src = os.path.join(label_src, img)\n im = Image.open(im_src)\n if im.mode != 'RGB':\n im = im.convert('RGB')\n new_im = im.resize(target_size)\n new_name = os.path.join(label_target, img + name_subfix)\n new_im.save(new_name)\n except Exception as e:\n print('!!! skip image! %s' % im_src)\n print(e)\n\n\nif __name__ == '__main__':\n main(source_dir, target_dir)\n","sub_path":"tools/resize_images.py","file_name":"resize_images.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"510446022","text":"# -*- coding: utf-8 -*-\n\nimport types\nfrom sqlalchemy import event\nfrom sqlalchemy.orm import util, Session, ScopedSession\n\n__all__ = ['Sample', 'Restorable', 'DBHistory']\n\n\nclass sample_property(object):\n\n def __init__(self, method, name=None):\n self.method = method\n self.__doc__ = method.__doc__\n self.name = name or method.__name__\n\n def __get__(self, inst, cls):\n if inst is None:\n return self\n result = self.method(inst)\n if isinstance(result, (list, tuple)):\n inst.db.add_all(result)\n else:\n inst.db.add(result)\n inst.used_properties.add(self.name)\n setattr(inst, self.name, result)\n return result\n\n def __call__(self, obj):\n return self.method(obj)\n\n\nclass Sample(object):\n\n class __metaclass__(type):\n def __new__(cls, cls_name, bases, attributes):\n self = type.__new__(cls, cls_name, bases, attributes)\n for name in dir(self):\n if name.startswith('_') or name == 'create_all':\n continue\n value = getattr(self, name)\n if isinstance(value, types.MethodType):\n new_value = value.im_func\n # already decorated attribute, assigned from another class\n elif isinstance(value, sample_property) and name!= value.name:\n new_value = value.method\n # classmethod, staticmethod and etc\n else:\n continue\n setattr(self, name, sample_property(new_value, name=name))\n return self\n\n def __init__(self, db, **kwargs):\n if isinstance(db, ScopedSession):\n db = db.registry()\n self.db = db\n self.used_properties = set()\n self.__dict__.update(kwargs)\n\n def create_all(self):\n if self.db.autocommit:\n self.db.begin()\n map(lambda name: getattr(self, name), dir(self))\n self.db.commit()\n\n\nclass Restorable(object):\n\n def __init__(self, db, watch=None):\n if isinstance(db, ScopedSession):\n db = db.registry()\n self.db = db\n self.watch = watch or db\n self.history = {}\n\n def __enter__(self):\n event.listen(self.watch, 'after_flush', self.after_flush)\n\n def __exit__(self, type, value, traceback):\n db = self.db\n db.rollback()\n db.expunge_all()\n old_autoflush = db.autoflush\n db.autoflush = False\n if db.autocommit:\n db.begin()\n for cls, ident_set in self.history.items():\n for ident in ident_set:\n instance = db.query(cls).get(ident)\n if instance is not None:\n db.delete(instance)\n db.commit()\n db.close()\n db.autoflush = old_autoflush\n event.Events._remove(self.watch, 'after_flush',\n self.after_flush)\n\n def after_flush(self, db, flush_context, instances=None):\n for instance in db.new:\n cls, ident = util.identity_key(instance=instance)\n self.history.setdefault(cls, set()).add(ident)\n\n\nclass DBHistory(object):\n\n def __init__(self, session):\n assert isinstance(session, (Session, ScopedSession))\n self.session = session\n #XXX: It is not clear do we need events on class or object\n self._target = session\n if isinstance(session, ScopedSession):\n self._target = session.registry()\n self.created = set()\n self.deleted = set()\n self.updated = set()\n self.created_idents = {}\n self.updated_idents = {}\n self.deleted_idents = {}\n\n def last(self, model_cls, mode):\n assert mode in ('created', 'updated', 'deleted')\n if mode == 'deleted':\n # Because there is not data in DB we return detached object set.\n return set([inst for inst in self.deleted \\\n if isinstance(inst, model_cls)])\n idents = getattr(self, '%s_idents' % mode).get(model_cls, set())\n return set([self.session.query(model_cls).get(ident) \\\n for ident in idents])\n\n def last_created(self, model_cls):\n return self.last(model_cls, 'created')\n\n def last_updated(self, model_cls):\n return self.last(model_cls, 'updated')\n\n def last_deleted(self, model_cls):\n return self.last(model_cls, 'deleted')\n\n def assert_(self, model_cls, ident=None, mode='created'):\n dataset = self.last(model_cls, mode)\n error_msg = 'No instances of %s were %s' % (model_cls, mode)\n assert dataset, error_msg\n if ident is not None:\n ident = ident if isinstance(ident, (tuple, list)) else (ident,)\n item = [i for i in dataset \\\n if util.identity_key(instance=i)[1] == ident]\n assert item,'No insatances of %s with identity %r were %s' % \\\n (model_cls, ident, mode)\n return item[0]\n return dataset\n\n def assert_created(self, model_cls, ident=None):\n return self.assert_(model_cls, ident, 'created')\n\n def assert_updated(self, model_cls, ident=None):\n return self.assert_(model_cls, ident, 'updated')\n\n def assert_deleted(self, model_cls, ident=None):\n return self.assert_(model_cls, ident, 'deleted')\n\n def assert_one(self, dataset, model_cls, mode):\n if len(dataset) != 1:\n raise AssertionError('%d instance(s) of %s %s, '\n 'need only one' % (len(dataset),\n model_cls,\n mode))\n return dataset.pop()\n\n def assert_created_one(self, model_cls):\n result = self.assert_created(model_cls)\n return self.assert_one(result, model_cls, 'created')\n\n def assert_deleted_one(self, model_cls):\n result = self.assert_deleted(model_cls)\n return self.assert_one(result, model_cls, 'deleted')\n\n def assert_updated_one(self, model_cls):\n result = self.assert_updated(model_cls)\n return self.assert_one(result, model_cls, 'updated')\n\n def clear(self):\n self.created = set()\n self.deleted = set()\n self.updated = set()\n self.created_idents = {}\n self.updated_idents = {}\n self.deleted_idents = {}\n\n def __enter__(self):\n event.listen(self._target, 'after_flush', self._after_flush)\n return self\n\n def __exit__(self, type, value, traceback):\n event.Events._remove(self._target, 'after_flush', self._after_flush)\n\n def _populate_idents_dict(self, idents, objects):\n for obj in objects:\n ident = util.identity_key(instance=obj)\n idents.setdefault(ident[0], set()).add(ident[1])\n\n def _after_flush(self, db, flush_context, instances=None):\n def identityset_to_set(obj):\n return set(obj._members.values())\n self.created = self.created.union(identityset_to_set(db.new))\n self.updated = self.updated.union(identityset_to_set(db.dirty))\n self.deleted = self.deleted.union(identityset_to_set(db.deleted))\n self._populate_idents_dict(self.created_idents, self.created)\n self._populate_idents_dict(self.updated_idents, self.updated)\n self._populate_idents_dict(self.deleted_idents, self.deleted)\n","sub_path":"testalchemy.py","file_name":"testalchemy.py","file_ext":"py","file_size_in_byte":7420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59501738","text":"#!/usr/bin/python\n#\n# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Unit tests for downloader module.\"\"\"\n\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nimport mox\n\nimport build_artifact\nimport common_util\nimport devserver\nimport downloader\n\n\n# Fake Dev Server Layout:\nTEST_LAYOUT = {\n 'test-board-1': ['R17-1413.0.0-a1-b1346', 'R17-18.0.0-a1-b1346'],\n 'test-board-2': ['R16-2241.0.0-a0-b2', 'R17-2.0.0-a1-b1346'],\n 'test-board-3': []\n}\n\n\nclass DownloaderTestBase(mox.MoxTestBase):\n\n def setUp(self):\n mox.MoxTestBase.setUp(self)\n self._work_dir = tempfile.mkdtemp('downloader-test')\n self.build = 'R17-1413.0.0-a1-b1346'\n self.archive_url_prefix = (\n 'gs://chromeos-image-archive/x86-mario-release/' + self.build)\n\n def tearDown(self):\n shutil.rmtree(self._work_dir, ignore_errors=True)\n\n def _CommonDownloaderSetup(self, ignore_background=False):\n \"\"\"Common code to downloader tests.\n\n Mocks out key util module methods, creates mock artifacts and sets\n appropriate expectations.\n\n @ignore_background Indicate that background artifacts should be ignored.\n\n @return iterable of artifact objects with appropriate expectations.\n \"\"\"\n board = 'x86-mario-release'\n self.mox.StubOutWithMock(common_util, 'AcquireLock')\n self.mox.StubOutWithMock(common_util, 'GatherArtifactDownloads')\n self.mox.StubOutWithMock(common_util, 'ReleaseLock')\n self.mox.StubOutWithMock(tempfile, 'mkdtemp')\n\n lock_tag = self._ClassUnderTest().GenerateLockTag(board, self.build)\n common_util.AcquireLock(\n static_dir=self._work_dir,\n tag=lock_tag).AndReturn(self._work_dir)\n common_util.ReleaseLock(static_dir=self._work_dir, tag=lock_tag)\n\n tempfile.mkdtemp(suffix=mox.IgnoreArg()).AndReturn(self._work_dir)\n return self._GenerateArtifacts(ignore_background)\n\n def _CreateArtifactDownloader(self, artifacts):\n \"\"\"Create and return a Downloader of the appropriate type.\n\n The returned downloader will expect to download and stage the\n Artifacts listed in [artifacts].\n\n @param artifacts: iterable of Artifacts.\n @return instance of downloader.Downloader or subclass.\n \"\"\"\n raise NotImplementedError()\n\n def _ClassUnderTest(self):\n \"\"\"Return class object of the type being tested.\n\n @return downloader.Downloader class object, or subclass.\n \"\"\"\n raise NotImplementedError()\n\n def _GenerateArtifacts(self, ignore_background):\n \"\"\"Instantiate artifact mocks and set expectations on them.\n\n @ignore_background Indicate that background artifacts should be ignored.\n This gets passed by CommonDownloaderSetup.\n\n @return iterable of artifact objects with appropriate expectations.\n \"\"\"\n raise NotImplementedError()\n\n\nclass DownloaderTest(DownloaderTestBase):\n \"\"\"Unit tests for downloader.Downloader.\n\n setUp() and tearDown() inherited from DownloaderTestBase.\n \"\"\"\n\n def _CreateArtifactDownloader(self, artifacts):\n d = downloader.Downloader(self._work_dir)\n self.mox.StubOutWithMock(d, 'GatherArtifactDownloads')\n d.GatherArtifactDownloads(\n self._work_dir, self.archive_url_prefix, self._work_dir,\n self.build).AndReturn(artifacts)\n return d\n\n def _ClassUnderTest(self):\n return downloader.Downloader\n\n def _GenerateArtifacts(self, ignore_background):\n \"\"\"Instantiate artifact mocks and set expectations on them.\n\n Sets up artifacts and sets up expectations for synchronous artifacts to\n be downloaded first.\n\n @ignore_background If True, doesn't use mocks for download/stage methods.\n\n @return iterable of artifact objects with appropriate expectations.\n \"\"\"\n artifacts = []\n for index in range(5):\n artifact = self.mox.CreateMock(build_artifact.BuildArtifact)\n # Make every other artifact synchronous.\n if index % 2 == 0:\n artifact.Synchronous = lambda: True\n artifact.Download()\n artifact.Stage()\n else:\n artifact.Synchronous = lambda: False\n if ignore_background:\n artifact.Download = lambda: None\n artifact.Stage = lambda: None\n\n artifacts.append(artifact)\n\n return artifacts\n\n def testDownloaderSerially(self):\n \"\"\"Runs through the standard downloader workflow with no backgrounding.\"\"\"\n artifacts = self._CommonDownloaderSetup()\n\n # Downloads non-synchronous artifacts second.\n for index, artifact in enumerate(artifacts):\n if index % 2 != 0:\n artifact.Download()\n artifact.Stage()\n\n d = self._CreateArtifactDownloader(artifacts)\n self.mox.ReplayAll()\n self.assertEqual(d.Download(self.archive_url_prefix, background=False),\n 'Success')\n self.mox.VerifyAll()\n\n def testDownloaderInBackground(self):\n \"\"\"Runs through the standard downloader workflow with backgrounding.\"\"\"\n artifacts = self._CommonDownloaderSetup(ignore_background=True)\n d = self._CreateArtifactDownloader(artifacts)\n self.mox.ReplayAll()\n d.Download(self.archive_url_prefix, background=True)\n self.assertEqual(d.GetStatusOfBackgroundDownloads(), 'Success')\n self.mox.VerifyAll()\n\n def testInteractionWithDevserver(self):\n \"\"\"Tests interaction between the downloader and devserver methods.\"\"\"\n artifacts = self._CommonDownloaderSetup(ignore_background=True)\n common_util.GatherArtifactDownloads(\n self._work_dir, self.archive_url_prefix, self._work_dir,\n self.build).AndReturn(artifacts)\n\n class FakeUpdater():\n static_dir = self._work_dir\n\n devserver.updater = FakeUpdater()\n\n self.mox.ReplayAll()\n dev = devserver.DevServerRoot()\n status = dev.download(archive_url=self.archive_url_prefix)\n self.assertTrue(status, 'Success')\n status = dev.wait_for_status(archive_url=self.archive_url_prefix)\n self.assertTrue(status, 'Success')\n self.mox.VerifyAll()\n\n def testBuildStaged(self):\n \"\"\"Test whether we can correctly check if a build is previously staged.\"\"\"\n base_url = 'gs://chrome-awesome/'\n build_dir = 'x86-awesome-release/R99-1234.0-r1'\n archive_url = base_url + build_dir\n archive_url_non_staged = base_url + 'x86-awesome-release/R99-1234.0-r2'\n # Create the directory to reflect staging.\n os.makedirs(os.path.join(self._work_dir, build_dir))\n\n self.assertTrue(downloader.Downloader.BuildStaged(archive_url,\n self._work_dir))\n self.assertTrue(os.path.exists(\n os.path.join(os.path.join(self._work_dir, build_dir),\n downloader.Downloader._TIMESTAMP_FILENAME)))\n self.assertFalse(downloader.Downloader.BuildStaged(archive_url_non_staged,\n self._work_dir))\n def testTrybotBuildStaged(self):\n \"\"\"Test whether a previous staged trybot-build can be corrected detected\"\"\"\n base_url = 'gs://chrome-awesome/'\n build_dir = 'trybot/date/x86-awesome-release/R99-1234.0-r1'\n archive_url = base_url + build_dir\n archive_url_non_staged = base_url + 'x86-awesome-release/R99-1234.0-r2'\n # Create the directory to reflect staging.\n os.makedirs(os.path.join(self._work_dir, build_dir))\n\n self.assertTrue(downloader.Downloader.BuildStaged(archive_url,\n self._work_dir))\n self.assertFalse(downloader.Downloader.BuildStaged(archive_url_non_staged,\n self._work_dir))\n\nclass SymbolDownloaderTest(DownloaderTestBase):\n \"\"\"Unit tests for downloader.SymbolDownloader.\n\n setUp() and tearDown() inherited from DownloaderTestBase.\n \"\"\"\n\n def _CreateArtifactDownloader(self, artifacts):\n d = downloader.SymbolDownloader(self._work_dir)\n self.mox.StubOutWithMock(d, 'GatherArtifactDownloads')\n d.GatherArtifactDownloads(\n self._work_dir, self.archive_url_prefix,\n self._work_dir).AndReturn(artifacts)\n return d\n\n def _ClassUnderTest(self):\n return downloader.SymbolDownloader\n\n def _GenerateArtifacts(self, unused_ignore_background):\n \"\"\"Instantiate artifact mocks and set expectations on them.\n\n Sets up a DebugTarballBuildArtifact and sets up expectation that it will be\n downloaded and staged.\n\n @return iterable of one artifact object with appropriate expectations.\n \"\"\"\n artifact = self.mox.CreateMock(build_artifact.BuildArtifact)\n artifact.Synchronous = lambda: True\n artifact.Download()\n artifact.Stage()\n return [artifact]\n\n def testDownloaderSerially(self):\n \"\"\"Runs through the symbol downloader workflow.\"\"\"\n d = self._CreateArtifactDownloader(self._CommonDownloaderSetup())\n\n self.mox.ReplayAll()\n self.assertEqual(d.Download(self.archive_url_prefix), 'Success')\n self.mox.VerifyAll()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"downloader_unittest.py","file_name":"downloader_unittest.py","file_ext":"py","file_size_in_byte":8899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"244884122","text":"# -*- coding: UTF-8 -*-\n# -----------------------------------------------------------------------------\n#\n# P A G E B O T\n#\n# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens\n# www.pagebot.io\n# Licensed under MIT conditions\n#\n# Supporting DrawBot, www.drawbot.com\n# Supporting Flat, xxyxyz.org/flat\n# -----------------------------------------------------------------------------\n#\n# basecontext.py\n#\nimport os\nfrom pagebot.style import DISPLAY_BLOCK\n\nclass BaseContext:\n \"\"\"A BaseContext instance abstracts the specific functions of a platform\n (for instance DrawBot, Flat or HTML), thus hiding e.g. the type of\n BabelString instance needed, and the type of HTML/CSS file structure to be\n created.\"\"\"\n\n # In case of specific builder addressing, callers can check here.\n isDrawBot = False\n isFlat = False\n isSvg = False\n isInDesign = False\n # Indication to Typesetter that by default tags should not be included in output.\n useTags = False\n\n # To be redefined by inheriting context classes.\n STRING_CLASS = None\n EXPORT_TYPES = None\n\n def __repr__(self):\n return '<%s>' % self.__class__.__name__\n\n # S C R E E N\n\n def screenSize(self):\n \"\"\"Answers the current screen size.\"\"\"\n return None\n\n # T E X T\n\n def newString(self, s, e=None, style=None, w=None, h=None, pixelFit=True):\n \"\"\"Creates a new styles BabelString instance of self.STRING_CLASS from\n `s` (converted to plain unicode string), using e or style as\n typographic parameters. Ignore and just answer `s` if it is already a\n self.STRING_CLASS instance.\"\"\"\n if not isinstance(s, self.STRING_CLASS):\n # Otherwise convert s into plain string, from whatever it is now.\n s = str(s)\n s = self.STRING_CLASS.newString(s, context=self, e=e,\n style=style, w=w, h=h, pixelFit=pixelFit)\n assert isinstance(s, self.STRING_CLASS)\n return s\n\n def fitString(self, s, e=None, style=None, w=None, h=None, pixelFit=True):\n \"\"\"Creates a new styles BabelString instance of self.STRING_CLASS from\n s assuming that style['font'] is a Variable Font instnace, or a path\n pointing to one. If the for is not a VF, then behavior is the same as\n newString. (converted to plain unicode string), using e or style as\n typographic parameters. Ignore and just answer s if it is already a\n `self.STRING_CLASS` instance.\n \"\"\"\n if not isinstance(s, self.STRING_CLASS):\n # Otherwise convert s into plain string, from whatever it is now.\n s = str(s)\n s = self.STRING_CLASS.fitString(s, context=self, e=e, style=style, w=w, h=h,\n pixelFit=pixelFit)\n assert isinstance(s, self.STRING_CLASS)\n return s\n\n def newText(self, textStyles, e=None, w=None, h=None, newLine=False):\n \"\"\"Answers a BabelString as a combination of all text and styles in\n textStyles, which is should have format\n\n [(baseString, style), (baseString, style), ...]\n\n Add return \\n to the string is the newLine attribute is True or if a\n style has\n\n style.get('display') == DISPLAY_BLOCK\n\n \"\"\"\n assert isinstance(textStyles, (tuple, list))\n s = None\n\n for t, style in textStyles:\n if newLine or (style and style.get('display') == DISPLAY_BLOCK):\n t += '\\n'\n bs = self.newString(t, style=style, e=e, w=w, h=h)\n if s is None:\n s = bs\n else:\n s += bs\n return s\n\n # G L Y P H\n\n def intersectWithLine(self, glyph, line):\n \"\"\"Answers the sorted set of intersecting points between the straight\n line and the flatteded glyph path.\"\"\"\n intersections = set() # As set, make sure to remove any doubles.\n\n def det(a, b):\n return a[0] * b[1] - a[1] * b[0]\n\n (lx0, ly0), (lx1, ly1) = line\n maxX = max(lx0, lx1)\n minX = min(lx0, lx1)\n maxY = max(ly0, ly1)\n minY = min(ly0, ly1)\n glyphPath = self.getGlyphPath(glyph)\n contours = self.getFlattenedContours(glyphPath)\n if not contours: # Could not generate path or flattenedPath. Or there are no contours. Give up.\n return None\n for contour in contours:\n for n in range(len(contour)):\n pLine = contour[n], contour[n-1]\n (px0, py0), (px1, py1) = pLine\n if minY > max(py0, py1) or maxY < min(py0, py1) or minX > max(px0, px1) or maxX < min(px0, px1):\n continue # Skip if boundings boxes don't overlap.\n\n xdiff = (line[0][0] - line[1][0], pLine[0][0] - pLine[1][0])\n ydiff = (line[0][1] - line[1][1], pLine[0][1] - pLine[1][1])\n\n div = det(xdiff, ydiff)\n if div == 0:\n continue # No intersection\n\n d = (det(*line), det(*pLine))\n intersections.add((det(d, xdiff) / div, det(d, ydiff) / div))\n\n # Answer the set as sorted list, increasing x, from left to right.\n return sorted(intersections)\n\n\n # P A T H\n\n def checkExportPath(self, path):\n \"\"\"If the path starts with \"_export\" make sure it exists, otherwise\n create it. The _export folders are used to export documents locally,\n without saving them to git. The _export name is included in the git\n .gitignore file.\n\n >>> context = BaseContext()\n >>> context.checkExportPath('_export/myFile.pdf')\n >>> os.path.exists('_export')\n True\n \"\"\"\n if path.startswith('_export'):\n dirPath = '/'.join(path.split('/')[:-1])\n if not os.path.exists(dirPath):\n os.makedirs(dirPath)\n\n # V A R I A B L E\n\n def Variable(self, ui, globals):\n \"\"\"Offers interactive global value manipulation in DrawBot. Can be\n ignored in other contexts.\"\"\"\n pass\n\nif __name__ == '__main__':\n import doctest\n import sys\n sys.exit(doctest.testmod()[0])\n","sub_path":"Lib/pagebot/contexts/basecontext.py","file_name":"basecontext.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"146212935","text":"from collections import namedtuple,deque,defaultdict,OrderedDict,Counter\n\n#创建一个自定义的tuple对象\nPoint = namedtuple('point',['x','y','z'])\np = Point(1,2,3)\nprint(p.x)\nprint(isinstance(p,tuple))\n\n#高效实现插入和删除操作的双向列表\nq = deque(['a','b','c'])\nprint(q)\nq.append('x')\nq.appendleft('y')\nprint(q)\n\n#使用dict时,如果key不存在,返回一个默认值\ndd = defaultdict(lambda:'N/A')\ndd['key1'] = 'abc'\nprint(dd['key1'])\nprint(dd['key2'])\n\n#有序dict\nd1={'a':1,'b':2,'c':3}\nd2 = dict([('a',1),('b',2),('c',3)])\nprint(d1==d2) #d1,d2是无序的\nd3 = OrderedDict([('a',1),('b',2),('c',3)])\nprint(d3) #d3是有序的\n\nod = OrderedDict()\nod['z'] = 1\nod['y'] = 2\nod['x'] = 3\nprint(list(od.keys()))\n\n#统计字符出现的个数(三种方式)\nc = Counter()\nfor ch in 'programming':\n c[ch] = c[ch] +1\nprint(c)\n\nstring = 'programming'\nprint(Counter(string))\n\nc = {}\nfor item in 'programming':\n c[item] = c[item]+1 if item in c else 1\nprint(c)\n","sub_path":"learn_python/built_in_module/create_collections.py","file_name":"create_collections.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"625101245","text":"from bottle import template, request, redirect, response\nfrom datetime import datetime\n\nimport string, random, helperMethods\n'''\n Our Model class\n This should control the actual \"logic\" of your website\n And nicely abstracts away the program logic from your page loading\n It should exist as a separate layer to any database or data structure that you might be using\n Nothing here should be stateful, if it's stateful let the database handle it\n'''\n\n# remove this and put it in sql file handler\nimport sqlite3\ncon = sqlite3.connect('./db/webdevils.db')\ncur = con.cursor()\nCOOKIE_SECRET_KEY = \"some-secret\" # prevent cookie manipulation\n\n#-----------------------------------------------------------------------------\n# Content\n#-----------------------------------------------------------------------------\n\n\ndef show_content(section,page1):\n\n user = helperMethods.token_user_info()\n\n int = None\n\n # if (page1 == 'Basic HTML'):\n # int = 1\n # elif(page1 == 'Formatting'):\n # int = 2\n # elif(page1 == 'Forms and Input'):\n # int = 3\n # elif(page1 == 'Properties'):\n # int = 4\n # elif(page1 == 'Selectors'):\n # int = 5\n # elif(page1 == 'Functions'):\n # int = 6\n page1 = page1.replace(\"-\", \" \")\n\n\n cur.execute('SELECT title,description,category_type FROM all_content WHERE name = (?)',(page1,))\n con.commit()\n\n information = helperMethods.usersList(cur.fetchall())\n\n return template('content.tpl',{'user':user,'content':information})\n","sub_path":"source_code/routes/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"469080330","text":"#!/usr/bin/env python\n# -*- encoding:utf-8 -*-\n# Purpose: 根据分组样本从突变检出表中提取对应的panel位点的突变信息,未提取出的从对应样本的tag.tsv中提取. \n# Author: Wangb\n# Note:\n# Last updated on: 20- -\nimport sys\nimport pandas as pd\n\npanel_demo = pd.read_excel('/GPFS06/AnalysisTemp06/cln07/200528_project/panel_demo.xlsx',encoding=\"utf-8\")\n\nsample_ID_maching = pd.read_excel('/GPFS06/AnalysisTemp06/cln07/200528_project/sample_ID.xlsx',encoding=\"utf-8\")\nsample_ID_maching.columns = ['Cell line ID','Tumor proportion','Sample ID','Sid']\n\nmutant_out = pd.read_excel('/GPFS06/AnalysisTemp06/cln07/200528_project/mutant_out.xlsx',encoding=\"utf-8\")\nnew_mutant_out = mutant_out.loc[:,[' Geneseeq sample ID','Gene','Type','AAChange','Chromosome','Chr.start','Chr.end']]\nnew_mutant_out.columns = ['sampleID','Gene','Type','AAChange','Chromosome','Chr.start','Chr.end']\nnew_mutant_out['Type'] = \"Y|\" + new_mutant_out['Type']\n\ndef single_group(panel_demo,sample_ID_maching,new_mutant_out,group):\n\t\t#按组别处理,最后合并所有组\n\t\tpanel_demo_chr1 = panel_demo.loc[panel_demo['Cell line ID']==group,:]\n\t\t#取出组中所有样本\n\t\ttestname_list = sample_ID_maching.loc[sample_ID_maching['Cell line ID']==group,:]['Sid'].astype('str').values.tolist()\n\t\t#建立空DF\n\t\tresult = pd.DataFrame(columns = ['Cell line ID', 'Chr', 'Position', 'Ref', 'Alt', 'Gene', 'Tumor_AF', 'Variant Type'])\n\n\t\tfor testname in testname_list:\n\t\t\t\t#提取ratio,例:0.002,0.0075\n\t\t\t\tratio = sample_ID_maching.loc[sample_ID_maching['Sid']==testname,'Tumor proportion'].values[0]\n\t\t\t\tratio = str(ratio)\n\t\t\t\t#从new_out中提取相关信息并格式化\n\t\t\t\ttestname_df = new_mutant_out.loc[new_mutant_out['sampleID']==testname,:]\n\t\t\t\ttestname_df['Ref'] = testname_df.AAChange.apply(lambda x: x.split(\">\")[0][-1])\n\t\t\t\ttestname_df['Alt'] = testname_df.AAChange.apply(lambda x: x.split(\">\")[-1][0])\n\t\t\t\ttestname_df['Chromosome'] = 'chr'+testname_df['Chromosome'].astype('str')\n\t\t\t\ttestname_df.rename(columns={'Chr.start':'Position','Chromosome':'Chr'},inplace=True)\n\t\t\t\t#合并 panel_demo 与testname_df\n\t\t\t\t#add\n\t\t\t\tmerge1 = pd.merge(panel_demo_chr1,testname_df,how='left',on = ['Chr','Position'])\n\t\t\t\tmerge1.rename(columns={'Type':ratio,'Ref_x':'Ref','Alt_x':'Alt','Gene_x':'Gene'},inplace=True)\n\t\t\t\tmerge1.drop(['sampleID','AAChange','Chr.end','Ref_y','Alt_y','Gene_y'], axis=1, inplace=True)\n\n\t\t\t\t#提取第二张表的信息\n\t\t\t\ttsv = pd.read_csv('/GPFS06/AnalysisTemp06/cln07/200528_project/Tag_tsv/{}.csv'.format(testname),sep=' ')\n\t\t\t\ttsv['Chr'] = tsv['Chr.start'].apply(lambda x: x.split(\":\")[0])\n\t\t\t\ttsv['Position'] = tsv['Chr.start'].apply(lambda x: x.split(\":\")[1])\n\t\t\t\ttsv['Position'] = tsv['Position'].astype('int')\n\t\t\t\t#add alt AF in TAGS\n\t\t\t\ttsv['TAGS'] = tsv['TAGS']+\";AD:AF(\"+tsv['alt'].map(str)+\";\"+tsv['AF'].map(str)+\")\"\t\n\t\t\t\ttsv['Chr'] = 'chr'+tsv['Chr']\n\t\t\t\ttsv['TAGS'] = 'N|'+tsv['TAGS']\n\t\t\t\t#tsv.rename(columns={'TAGS':ratio},inplace=True)\n\t\t\t\t#为了合并第表2的信息,需要进行将表1 的Na合并表2,在进行合并\n\t\t\t\t#拆分\n\t\t\t\tsplit_na = merge1.loc[merge1[ratio].isnull(),:]\n\t\t\t\tsplit_c1 = merge1.loc[~merge1[ratio].isnull(),:]\n\t\t\t\t#合并\n\t\t\t\tmerge2 = pd.merge(split_na,tsv,how='left',on=['Chr','Position','Ref','Alt','Gene'])\n\t\t\t\tsplit_c2 = merge2[['Cell line ID', 'Chr', 'Position', 'Ref', 'Alt', 'Gene', 'Tumor_AF', 'Variant Type','TAGS']]\n\t\t\t\tsplit_c2.rename(columns={'TAGS':ratio},inplace=True)\n\t\t\t\t#合并成总的表\n\t\t\t\tmerge_suc = pd.concat([split_c1,split_c2],axis = 0)\n\t\t\t\t#追加\n\t\t\t\tresult_tmp = pd.merge(merge_suc,result,how='left')\n\t\t\t\tresult = result_tmp\n\t\treturn result_tmp\n#建立空DF\ntmp_df = pd.DataFrame(columns = ['Cell line ID', 'Chr', 'Position', 'Ref', 'Alt', 'Gene', 'Tumor_AF', 'Variant Type','0.002','0.0075','0.015','0.05'])\nfor group in range(1,9):\n\tsingle_df = single_group(panel_demo,sample_ID_maching,new_mutant_out,group)\n\tmerge_group = pd.concat([tmp_df,single_df],axis = 0)\n\t#设定列的顺序\n\torder_list = ['Cell line ID', 'Chr', 'Position', 'Ref', 'Alt', 'Gene', 'Tumor_AF', 'Variant Type','0.002','0.0075','0.015','0.05']\n\tmerge_groupx = merge_group[order_list]\n\ttmp_df = merge_groupx\nmerge_groupx.to_excel('final.3.0.xlsx',header = True,index = False)\nmerge_groupx.to_csv('final.3.0.csv',header = True,index = False)\n","sub_path":"Pandas/format_pandas.py","file_name":"format_pandas.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589834275","text":"from Subscriber import Subscriber\nimport time\nimport sys\nimport threading\n\nprint('--------Unit Test:')\nprint('# Here is the subscriber side.')\n\ndef sub1_op():\n\taddress = sys.argv[1] if len(sys.argv) > 1 else \"localhost\"\n\tport = '5557'\n\tsub1 = Subscriber(address, port, 'foods', '20')\n\tsub1_logfile = './Output/' + sub1.myID + '-subscriber.log'\n\twith open(sub1_logfile, 'w') as log:\n\t\tlog.write('ID: ' + sub1.myID + '\\n')\n\t\tlog.write('Topic: ' + sub1.topic + '\\n')\n\t\tlog.write('History publications: %s\\n' % sub1.history_count)\n\t\tlog.write('Connection: tcp://' + address + ':' + port + '\\n')\n\tsub1.prepare()\n\tsub1.handler()\n\n\ndef sub2_op():\n\taddress = sys.argv[1] if len(sys.argv) > 1 else \"localhost\"\n\tport = '5557'\n\tsub2 = Subscriber(address, port, 'animals', '5')\n\tsub2_logfile = './Output/' + sub2.myID + '-subscriber.log'\n\twith open(sub2_logfile, 'w') as log:\n\t\tlog.write('ID: ' + sub2.myID + '\\n')\n\t\tlog.write('Topic: ' + sub2.topic + '\\n')\n\t\tlog.write('History publications: %s\\n' % sub2.history_count)\n\t\tlog.write('Connection: tcp://' + address + ':' + port + '\\n')\n\tsub2.prepare()\n\tsub2.handler()\n\ndef sub3_op():\n\taddress = sys.argv[1] if len(sys.argv) > 1 else \"localhost\"\n\tport = '5557'\n\tsub3 = Subscriber(address, port, 'laptops', '10')\n\tsub3_logfile = './Output/' + sub3.myID + '-subscriber.log'\n\twith open(sub3_logfile, 'w') as log:\n\t\tlog.write('ID: ' + sub3.myID + '\\n')\n\t\tlog.write('Topic: ' + sub3.topic + '\\n')\n\t\tlog.write('History publications: %s\\n' % sub3.history_count)\n\t\tlog.write('Connection: tcp://' + address + ':' + port + '\\n')\n\tsub3.prepare()\n\tsub3.handler()\n\ndef sub4_op():\n\taddress = sys.argv[1] if len(sys.argv) > 1 else \"localhost\"\n\tport = '5557'\n\tsub4 = Subscriber(address, port, 'animals', '10')\n\tsub4_logfile = './Output/' + sub4.myID + '-subscriber.log'\n\twith open(sub4_logfile, 'w') as log:\n\t\tlog.write('ID: ' + sub4.myID + '\\n')\n\t\tlog.write('Topic: ' + sub4.topic + '\\n')\n\t\tlog.write('History publications: %s\\n' % sub4.history_count)\n\t\tlog.write('Connection: tcp://' + address + ':' + port + '\\n')\n\tsub4.prepare()\n\tsub4.handler()\n\ndef sub5_op():\n\taddress = sys.argv[1] if len(sys.argv) > 1 else \"localhost\"\n\tport = '5557'\n\tsub5 = Subscriber(address, port, 'foods', '10')\n\tsub5_logfile = './Output/' + sub5.myID + '-subscriber.log'\n\twith open(sub5_logfile, 'w') as log:\n\t\tlog.write('ID: ' + sub5.myID + '\\n')\n\t\tlog.write('Topic: ' + sub5.topic + '\\n')\n\t\tlog.write('History publications: %s\\n' % sub5.history_count)\n\t\tlog.write('Connection: tcp://' + address + ':' + port + '\\n')\n\tsub5.prepare()\n\tsub5.handler()\n\nif __name__ == '__main__':\n\tprint('Note: Press Ctr+C, if you want to exit.')\n\t\n\tsub1_thr = threading.Thread(target= sub1_op, args=())\n\tthreading.Thread.setDaemon(sub1_thr, True)\n\tsub2_thr = threading.Thread(target= sub2_op, args=())\n\tthreading.Thread.setDaemon(sub2_thr, True)\n\tsub3_thr = threading.Thread(target= sub3_op, args=())\n\tthreading.Thread.setDaemon(sub3_thr, True)\n\tsub4_thr = threading.Thread(target= sub4_op, args=())\n\tthreading.Thread.setDaemon(sub4_thr, True)\n\tsub5_thr = threading.Thread(target= sub5_op, args=())\n\tthreading.Thread.setDaemon(sub5_thr, True)\n\n\tsub1_thr.start()\n\ttime.sleep(3)\n\tsub2_thr.start()\n\ttime.sleep(3)\n\tsub3_thr.start()\n\ttime.sleep(3)\n\tsub4_thr.start()\n\ttime.sleep(3)\n\tsub5_thr.start()\n\n\twhile True:\n\t\tpass\n\t\t\n","sub_path":"Assignment1/SourceCode/lSubscriberT.py","file_name":"lSubscriberT.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529243235","text":"import sys\nimport cv2\nimport numpy as np\nimport os\nfrom math import radians, cos, sin, asin, sqrt\nfrom lakeRecognition import waterImage\nfrom lakeRecognition.lakeClass import Lakes\n\n\nclass Map:\n def __init__(self, startLatitude, startLongitude, endLatitude, endLongitude):\n self.lakeContour = []\n self.contour = []\n self.lakeArea = []\n\n self.longNext = 0.05155\n self.latNext = -0.00000636 * float(startLatitude) ** 2 - 0.00005506 * float(startLatitude) + 0.05190551\n\n self.latitudeDir = 'up' if float(startLatitude) < float(endLatitude) else 'down'\n self.latitudeIt = np.ceil(np.absolute(float(startLatitude) - float(endLatitude)) / self.latNext) // 2 * 2 + 1\n if (self.latitudeDir == 'down'):\n self.latitude = [float(startLatitude) - i * self.latNext for i in range(0, self.latitudeIt.astype(int))]\n elif (self.latitudeDir == 'up'):\n self.latitude = [float(endLatitude) - i * self.latNext for i in range(0, self.latitudeIt.astype(int))]\n\n self.longitudeDir = 'left' if float(startLongitude) < float(endLongitude) else 'right'\n self.longitudeIt = np.ceil(\n np.absolute(float(startLongitude) - float(endLongitude)) / self.longNext) // 2 * 2 + 1\n if (self.longitudeDir == 'left'):\n self.longitude = [float(startLongitude) + i * self.longNext for i in range(0, self.longitudeIt.astype(int))]\n elif (self.longitudeDir == 'right'):\n self.longitude = [float(endLongitude) + i * self.longNext for i in range(0, self.longitudeIt.astype(int))]\n\n self.horizontalCenter = self.longitude[(self.longitudeIt // 2 + 1).astype(int) - 1]\n self.verticalCenter = self.latitude[(self.latitudeIt // 2 + 1).astype(int) - 1]\n\n croppedImage = [[None for _ in range(self.longitudeIt.astype(int))] for _ in range(self.latitudeIt.astype(int))]\n for i in range(0, self.latitudeIt.astype(int)):\n for j in range(0, self.longitudeIt.astype(int)):\n croppedImage[i][j] = self.getSatelliteImage(str(\"{0:.6f}\".format(self.latitude[i])),\n str(\"{0:.6f}\".format(self.longitude[j])))\n self.imageAdded = self.addImages(croppedImage)\n self.resolution = self.distanceXY([0, 0], [0, 1])\n\n def getSatelliteImage(self, lat, lon):\n if not waterImage.get_waterbody_image(lat, lon):\n sys.exit(\"Error: Fetching water bodies images was unsuccesful. EXITING.\")\n else:\n imageName = 'lakeRecognition/WaterBodiesImages/google-map_' + lat + '_' + lon + '.jpg'\n imCropped = self.cropImage(imageName)\n os.remove(imageName)\n return imCropped\n\n def satImageProcess(self, image):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (3, 3), 0)\n thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]\n cv2.rectangle(thresh, (0, 0), (image.shape[1], image.shape[0]), 255, 3)\n cv2.imwrite('WaterBodiesImages/thresh.jpg', thresh)\n return thresh\n\n def findLakeContour(self, imageFiltered, originalImage, lakeList):\n _, contour, hierarchy = cv2.findContours(imageFiltered, cv2.RETR_TREE,\n cv2.CHAIN_APPROX_NONE)\n i = 0\n j = []\n\n for c in contour:\n if (hierarchy[0][i][3] == 0) and (cv2.contourArea(c) > 200):\n j.append(i)\n i += 1\n\n [lakeList.append(Lakes(contour[i], cv2.contourArea(contour[i]), self.resolution)) for i in j]\n\n cv2.drawContours(originalImage, [lake.lakeContour for lake in lakeList], -1, (0, 0, 255))\n cv2.imwrite('WaterBodiesImages/final.jpg', originalImage)\n # print(\"Lake contour detected\")\n return originalImage\n\n def addImages(self, images):\n line = len(images)\n column = len(images[0])\n lineAdded = [None for _ in range(line)]\n for i in range(line):\n lineAdded[i] = np.hstack(images[i][:])\n if line > 0:\n finalImage = np.vstack(lineAdded[:])\n else:\n finalImage = lineAdded[0]\n cv2.imwrite('WaterBodiesImages/imageAdded.jpg', finalImage)\n # print(\"Map constructed\")\n return finalImage\n\n def cropImage(self, imageName):\n image = cv2.imread(imageName)\n image = image[19:620, 19:620]\n return image\n\n def xy2LatLon(self, point):\n xCenter = self.imageAdded.shape[1] // 2 + 1\n yCenter = self.imageAdded.shape[0] // 2 + 1\n lon = self.horizontalCenter + (point[0] - xCenter) * self.longNext / 601\n lat = self.verticalCenter + (yCenter - point[1]) * self.latNext / 601\n return lat, lon\n\n def distanceXY(self, point1, point2):\n lat1, lon1 = self.xy2LatLon(point1)\n lat2, lon2 = self.xy2LatLon(point2)\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * asin(sqrt(a))\n # Radius of earth in kilometers is 6371\n km = 6371 * c\n return km * 1000\n","sub_path":"lakeRecognition/mapClass.py","file_name":"mapClass.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340528417","text":"from Input import getInput\nfrom pandas import DataFrame\nfrom pylab import scatter, show\n\n\ndef addCoordinates(coords: list):\n x = 0\n y = 0\n for coordinate in coords:\n x += coordinate[0]\n y += coordinate[1]\n return [x,y]\n\n\ndata = getInput(\"Day10_Input.txt\")\n\npoints = []\nvelocitys = []\n\nfor line in data:\n points.append(list(map(int, line.split(\"<\")[1].split(\">\")[0].split(\",\"))))\n velocitys.append(list(map(int, line.split(\"<\")[2].split(\">\")[0].split(\",\"))))\n\nfor i in range(12000):\n x = [x for x, y in points]\n y = [y for x, y in points]\n\n # Part 2 Answer\n print(\"Seconds passed: {}\".format(i))\n\n # Part 1 Answer - requires visual inspection\n # Lots of trial and error to find this tight range with the message\n if i > 10938 and i < 10946:\n scatter(x, y, s=100, marker=\"X\")\n show()\n\n for pos, point in enumerate(points):\n points[pos] = addCoordinates([point, velocitys[pos]])\n","sub_path":"python/Day10.py","file_name":"Day10.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184393601","text":"# For the sudoku game implementation.\nimport numpy as np\n\nclass SudokuBoard(object):\n \"\"\"\n A representation of a sudoku board. \n \"\"\"\n\n def __init__(self, board, puzzle_number):\n \"\"\"\n Initializes a sudoku board.\n \n Parameters:\n board (np.array): A 9x9 numpy array object that represents the sudoku board\n \"\"\"\n\n self.original_board = board\n self.board = board\n self.board_history = [board]\n self.move_count = 0\n self.puzzle_number = puzzle_number\n\n\n def add_cell(self, coord, num):\n \"\"\"\n Method to update a cell value and update boards.\n\n Parameters:\n coord (tuple): The coordinate of the cell.\n num (int): The new value.\n \"\"\"\n self.clear_history()\n if (self.board[coord[0], coord[1]] == 0 and \n self.original_board[coord[0], coord[1]] == 0):\n # Create new board and move into board history.\n new_board = self.board.copy()\n new_board[coord[0], coord[1]] = num\n\n # This way moves can be overwritten\n self.move_count += 1\n self.board_history.insert(self.move_count, new_board)\n self.board = new_board\n\n # Delete all boards ahead of the new board\n del(self.board_history[self.move_count + 1:])\n return True\n \n return False\n\n\n def remove_cell(self, coord):\n \"\"\"\n Removes an added number from the board.\n\n Parameters:\n coord (tuple): The coordinate of the cell.\n \"\"\"\n # Check if cell selected is not original cell and has a number\n \n if (self.board[coord[0], coord[1]] != 0 and \n self.original_board[coord[0], coord[1]] == 0):\n self.move_count +=1\n new_board = self.board.copy()\n new_board[coord[0], coord[1]] = 0\n self.board_history.insert(self.move_count, new_board)\n self.board = new_board\n self.clear_history()\n return True\n\n self.clear_history()\n return False\n\n def erase_ahead_coord(self, coord):\n \"\"\"\n Method which deletes all previously entered points ahead of and including the coord.\n\n Parameters:\n coord (tuple): The coordinate of the cell.\n \"\"\"\n # In first deletion row only remove past the column number\n for k in range(coord[1], 9):\n if self.original_board[coord[0]][k] == 0:\n self.remove_cell((coord[0], k))\n\n # Past the specific row delete all\n for i in range(coord[0]+1, 9):\n for j in range(9):\n if self.original_board[i][j] == 0:\n self.remove_cell((i,j))\n\n \n def set_board(self, board):\n \"\"\"\n Method which sets the current board to an input board.\n \"\"\"\n self.board_history.append(board)\n self.board = board\n self.clear_history()\n\n\n def clear_history(self):\n \"\"\"\n Clear the history of the board once board is large i.e. >100\n \"\"\"\n if len(self.board_history) >= 100:\n self.board_history.pop(0)\n \n\n def clear(self):\n \"\"\" Clears the game and restores original board. \"\"\"\n self.board = self.original_board\n self.board_history = [self.original_board]\n self.move_count = 0\n\n\n def get_sub_squares(self):\n \"\"\"\n Method that gives the 3x3 subsquares for the current sudoku board in a dictionary of numpy arrays. Subsquares keys in the dictionary are labeled according to:\n 1 2 3\n 4 5 6\n 7 8 9\n\n Parameters:\n square (int): The square needed.\n \"\"\"\n square_dict = {}\n square_no = 1\n\n for i in range(0, 9, 3):\n for j in range(0, 9, 3):\n a = self.board[:][i:i+3]\n square_dict[square_no] = np.transpose(np.transpose(a)[:][j:j+3])\n square_no += 1\n\n return square_dict\n\n \n def check_board_full(self):\n \"\"\"\n Checks if a board is full.\n \"\"\"\n for i in range(9):\n for j in range(9):\n if self.board[i][j] == 0:\n return False\n\n return True\n\n \n def check_board(self):\n \"\"\"\n This method wil move through a board checking all rows, columns and square to be valid (i.e. not having more that two occurances). Returns False if an invalid row, column or square is found. True otherwise. \n \"\"\"\n # Check rows\n for i in range(9):\n for num in range(1, 10):\n if self.board[i].tolist().count(num) > 1:\n return False\n\n # Check columns\n for i in range(9):\n column = []\n for j in range(9):\n column.append(self.board[j][i])\n \n for num in range(1, 10):\n if column.count(num) > 1:\n return False\n \n squares = self.get_sub_squares()\n # Check squares:\n for i in range(1, 10):\n square = squares[i]\n square = square.flatten().tolist()\n for num in range(1, 10):\n if square.count(num) > 1:\n return False\n\n return True\n\n\n def get_top_sum(self):\n \"\"\" Method for project euler. Gets top three numbers. \"\"\"\n num = \"\"\n for i in range(3):\n num += str(int(self.board[0][i]))\n\n return int(num)\n\n\n def get_row_numbers(self, row):\n \"\"\"\n Method for getting missing numbers along a row.\n\n Parameters:\n row (int): The row to get missing numbers from.\n\n Returns:\n (list): List of numbers missing. \n \"\"\"\n return [i for i in range(1,10) if i not in self.board[row]]\n\n\n def get_column_numbers(self, column):\n \"\"\"\n Method for getting missing numbers along a column.\n\n Parameters:\n column (int): The column to get missing numbers from.\n\n Returns:\n (list): List of numbers missing. \n \"\"\"\n column_list = []\n for i in range(9):\n column_list.append(self.board[i][column])\n\n return [i for i in range(1,10) if i not in column_list]\n\n\n def get_square_numbers(self, square):\n \"\"\"\n Method for getting missing numbers in a 3x3 square in following number scheme:\n 1 2 3\n 4 5 6\n 7 8 9\n\n Parameters:\n square (int): The square to get missing numbers from.\n\n Returns:\n (list): List of missing numbers \n \"\"\"\n square = self.get_sub_squares()[square]\n square = square.flatten().tolist()\n return [i for i in range(1, 10) if i not in square]\n\n \n\n \n\n\n\n ","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"143747","text":"def smallmissno(array):\n posarr=[]\n for val in array:\n if val>0:\n posarr.append(val)\n print (\"\\nArray with positive numbers:\",posarr)#0 is neither positive nor negative number\n mini=1\n while 1:\n if mini in array:\n mini=mini+1\n else:\n print (\"\\nThe least positive number missing in an array: %d\"%mini)\n break\n\n#array=[0,10,2,-10,-20]\n#array=[2, 3, 7, 6, 8, -1, -10, 15]\narray=[2, 3, -7, 6, 8, 1, -10, 15]\n#array=[1, 1, 0, -1, -2]\n#array=[-20,-10,-30]\n#array=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]\nprint (\"\\nGiven array:\",array)\nsmallmissno(array)\n","sub_path":"arrays/q14_miss_smallposno.py","file_name":"q14_miss_smallposno.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"153938343","text":"\n# Identify num of times each word repeats in the sentence\nx = '''test.txt\nhello world\nthis is my first python program\npython is fun\nhello world\nhello world'''\n\nx_list = x.split()\nprint([(word, x_list.count(word)) for word in set(x_list)])\n\nprint({i: x_list.count(i) for i in x_list})\n\ninput_list = [1, 2, 3, 3, 4, 4, 4]\nprint([(element, input_list.count(element)) for element in set(input_list)])\n# print([(element, input_list.count(element)) for element in input_list])\n\nx = [1, 2, 3]\ny = [3, 4, 5]\n\nprint(set(x) ^ set(y))\n\ndef isPrimeno(num):\n count = 0\n for i in range(1, num + 1):\n if num % i == 0:\n count += 1\n return count == 2\n\np = [i for i in range(1,101) if(isPrimeno(i))]\nprint(p)\nlist1 = ['a', 'b', 'c', 'd']\ndict = {list1.index(i) : i for i in list1}\nprint(dict)\n\n","sub_path":"MyAssigments/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"175995056","text":"import numpy as np\r\nfrom typing import Tuple\r\nimport math\r\n\r\nCOEFFICIENTS = np.array([\r\n [1, 0, 0, 0, 0, 0],\r\n [0, 1, 0, 0, 0, 0],\r\n [0, 0, .5, 0, 0, 0],\r\n [-10, -6, -1.5, 10, -4, .5],\r\n [15, 8, 1.5, -15, 7, -1],\r\n [-6, -3, -.5, 6, -3, .5]\r\n])\r\n\r\n\r\nclass Spline:\r\n def __init__(self, waypoint_0: np.ndarray, waypoint_1: np.ndarray, radius: float = 0, module_offset: float = 0):\r\n \"\"\"Create spline object\"\"\"\r\n\r\n self.waypoint_0 = waypoint_0\r\n self.waypoint_1 = waypoint_1\r\n self.r = radius\r\n self.module_offset = module_offset\r\n\r\n self.x_waypoint = np.array(\r\n [waypoint_0[0][0], waypoint_0[1][0], waypoint_0[2][0], waypoint_1[0][0], waypoint_1[1][0],\r\n waypoint_1[2][0]])\r\n self.y_waypoint = np.array(\r\n [waypoint_0[0][1], waypoint_0[1][1], waypoint_0[2][1], waypoint_1[0][1], waypoint_1[1][1],\r\n waypoint_1[2][1]])\r\n self.theta_waypoint = np.array(\r\n [waypoint_0[0][2] + module_offset, waypoint_0[1][2], waypoint_0[2][2], waypoint_1[0][2] + module_offset,\r\n waypoint_1[1][2],\r\n waypoint_1[2][2]])\r\n\r\n def position(self, t: float) -> Tuple:\r\n \"\"\"Compute position given parameter\"\"\"\r\n\r\n # Trust the linear algebra\r\n temp = np.matmul(np.array([1, t, t ** 2, t ** 3, t ** 4, t ** 5]), COEFFICIENTS)\r\n\r\n theta = np.dot(self.theta_waypoint.T, temp)\r\n x = np.dot(self.x_waypoint.T, temp) + self.r * math.cos(theta)\r\n y = np.dot(self.y_waypoint.T, temp) + self.r * math.sin(theta)\r\n\r\n return x, y, theta\r\n\r\n def d_position(self, t: float) -> Tuple:\r\n \"\"\"Compute first derivative of position given parameter\"\"\"\r\n\r\n # Trust the linear algebra\r\n temp = np.matmul(np.array([1, t, t ** 2, t ** 3, t ** 4, t ** 5]), COEFFICIENTS)\r\n d_temp = np.matmul(np.array([0, 1, 2 * t, 3 * t ** 2, 4 * t ** 3, 5 * t ** 4]), COEFFICIENTS)\r\n\r\n theta = np.dot(self.theta_waypoint.T, temp)\r\n d_theta = np.dot(self.theta_waypoint.T, d_temp)\r\n d_x = np.dot(self.x_waypoint.T, d_temp) - self.r * math.sin(theta) * d_theta\r\n d_y = np.dot(self.y_waypoint.T, d_temp) + self.r * math.cos(theta) * d_theta\r\n\r\n return d_x, d_y, d_theta\r\n\r\n def dd_position(self, t: float) -> Tuple:\r\n \"\"\"Compute second derivative of position given parameter\"\"\"\r\n\r\n # Trust the linear algebra\r\n temp = np.matmul(np.array([1, t, t ** 2, t ** 3, t ** 4, t ** 5]), COEFFICIENTS)\r\n d_temp = np.matmul(np.array([0, 1, 2 * t, 3 * t ** 2, 4 * t ** 3, 5 * t ** 4]), COEFFICIENTS)\r\n dd_temp = np.matmul(np.array([0, 0, 2, 6 * t, 12 * t ** 2, 20 * t ** 3]), COEFFICIENTS)\r\n\r\n theta = np.dot(self.theta_waypoint.T, temp)\r\n d_theta = np.dot(self.theta_waypoint.T, d_temp)\r\n dd_theta = np.dot(self.theta_waypoint.T, dd_temp)\r\n dd_x = np.dot(self.x_waypoint.T, dd_temp) - self.r * (math.cos(theta) * d_theta ** 2 + math.sin(theta) * dd_theta)\r\n dd_y = np.dot(self.y_waypoint.T, dd_temp) + self.r * (-math.sin(theta) * d_theta ** 2 + math.cos(theta) * dd_theta)\r\n\r\n return dd_x, dd_y, dd_theta\r\n\r\n def curvature(self, t: float) -> float:\r\n \"\"\"Compute curvature given parameter\"\"\"\r\n\r\n # Trust the calculus\r\n d_x, d_y, d_theta = self.d_position(t)\r\n dd_x, dd_y, dd_theta = self.dd_position(t)\r\n\r\n return (d_x * dd_y - d_y * dd_x) / (math.sqrt(d_x ** 2 + d_y ** 2) ** 3)","sub_path":"splines.py","file_name":"splines.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461903857","text":"from panda3d.core import CollideMask, CollisionNode, CollisionRay, CollisionHandlerQueue\nfrom direct.actor.Actor import Actor\nfrom panda3d.ai import *\nimport random\n\nimport logging\nlog=logging.getLogger(__name__)\n\nclass Zorrito:\n \n STATE_IDLE=\"Idle\"\n STATE_WANDER=\"Wander\"\n STATE_PURSUIT=\"Pursuit\"\n \n PURSUIT_DISTANCE=8\n \n def __init__(self, base, player):\n self.base=base\n self.player=player\n # actor\n self.actor=Actor(\"models/zorrito\")\n self.actor.reparentTo(self.base.render)\n self.actor.setScale(0.15)\n # collision\n # ray\n collRay=CollisionRay(0, 0, 1.5, 0, 0, -1)\n collRayN=CollisionNode(\"playerCollRay\")\n collRayN.addSolid(collRay)\n collRayN.setFromCollideMask(1)\n collRayN.setIntoCollideMask(CollideMask.allOff())\n #collRayNP=self.actor.attachNewNode(collRayN)\n self.collQRay=CollisionHandlerQueue()\n #self.base.cTrav.addCollider(collRayNP, self.collQRay)\n # ai\n self.aiWorld=AIWorld(self.base.render)\n self.aiChar=AICharacter(\"aiZorrito\", self.actor, 150, 0.05, 6)\n self.aiWorld.addAiChar(self.aiChar)\n self.aiBehaviors=self.aiChar.getAiBehaviors()\n self.aiBehaviors.initPathFind(\"models/navmesh.csv\")\n # state\n self.distanceToPlayer=1000\n self.zOffset=0\n self.terrainSurfZ=0\n self.state=Zorrito.STATE_IDLE\n self.currentStateTimeout=4+6*random.random()\n # uptade task\n self.base.taskMgr.add(self.update, \"zorritoUpdateTask\")\n \n def processTerrainRelation(self): # -> [terrainSurfZ, zOffset]\n collEntries=self.collQRay.getEntries()\n #\n if len(collEntries)==0:\n #log.error(\"out of terrain, pos=%s\"%str(self.actor.getPos()))\n return 0, 0\n #\n gndZ=-1000\n for entry in collEntries:\n eName=entry.getIntoNodePath().getName()\n eZ=entry.getSurfacePoint(self.base.render).getZ()\n if eName.startswith(\"Ground\"):\n if eZ>gndZ:\n gndZ=eZ\n zOffset=self.actor.getZ()-gndZ\n return gndZ, zOffset\n \n def defineState(self):\n #\n newState=self.state\n # from Idle,Wander -> Idle,Wander,Pursuit\n if self.state==Zorrito.STATE_IDLE or self.state==Zorrito.STATE_WANDER:\n if self.distanceToPlayer<=Zorrito.PURSUIT_DISTANCE:\n newState=Zorrito.STATE_PURSUIT\n self.currentStateTimeout=0\n else:\n if self.currentStateTimeout==0:\n newState, self.currentStateTimeout=self.newRandomState((Zorrito.STATE_IDLE, Zorrito.STATE_WANDER))\n elif self.state==Zorrito.STATE_PURSUIT:\n if self.aiBehaviors.behaviorStatus(\"pathfollow\")==\"done\" or self.distanceToPlayer>Zorrito.PURSUIT_DISTANCE:\n newState=Zorrito.STATE_IDLE\n return newState\n\n def processState(self, dt):\n # terrain sdjustment\n if self.zOffset!=0:\n self.actor.setZ(self.terrainSurfZ)\n\n def onStateChanged(self, newState):\n curState=self.state\n self.aiBehaviors.removeAi(\"all\")\n if newState==Zorrito.STATE_WANDER:\n self.aiBehaviors.wander(5, 0, 10, 1)\n elif newState==Zorrito.STATE_PURSUIT:\n status=self.aiBehaviors.behaviorStatus(\"pathfollow\")\n if status!=\"done\" and status!=\"active\":\n self.aiBehaviors.pathFindTo(self.player.actor)\n log.debug(\"state change %s -> %s\"%(str(curState), str(newState)))\n \n def newRandomState(self, states): # -> (new state, timeout)\n newState=random.choice(states)\n timeout=4+6*random.random()\n return (newState, timeout)\n\n def update(self, task):\n # clock\n dt=self.base.taskMgr.globalClock.getDt()\n if self.currentStateTimeout>0:\n self.currentStateTimeout-=dt\n elif self.currentStateTimeout<0:\n self.currentStateTimeout=0\n # update vars\n # terrain relation\n self.terrainSurfZ, self.zOffset=self.processTerrainRelation()\n # distance to player\n diffVec=self.player.actor.getPos()-self.actor.getPos()\n diffVec.setZ(0)\n self.distanceToPlayer=diffVec.length()\n # state\n newState=self.defineState()\n if self.state!=newState:\n self.onStateChanged(newState)\n self.state=newState\n self.processState(dt)\n # ai\n self.aiWorld.update()\n return task.cont\n \n","sub_path":"zorrito.py","file_name":"zorrito.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"267814019","text":"import math\n\ndef prime(n):\n if n == 2:\n return True\n if n%2 == 0 or n <= 1:\n return False\n sqr = int(math.sqrt(n)) + 1\n for x in range(3, sqr, 2):\n if n%x == 0:\n return False\n return True\n\npnum = 0\nnum = 0\ngo = True\nwhile go:\n if prime(num) == True:\n pnum += 1\n if pnum == 10001:\n go = False\n print (num)\n num += 1\n","sub_path":"project7.py","file_name":"project7.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340529906","text":"#! /usr/bin/python\n\nimport sys\nfrom TOSSIM import *\n\nt = Tossim([])\nm = t.getNode(3)\nm.bootAtTime(45654)\n\nf = open(\"log.txt\", \"w\")\nt.addChannel(\"Boot\", f)\nt.addChannel(\"Boot\", sys.stdout)\nt.addChannel(\"RadioCountToLedsC\", sys.stdout)\n\nwhile not m.isOn():\n t.runNextEvent()\n","sub_path":"simple_tossim.py","file_name":"simple_tossim.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"192463818","text":"\"\"\"\nProject handling for the pprof study.\n\"\"\"\nfrom os import path, listdir\nfrom abc import abstractmethod\nfrom plumbum import local\nfrom plumbum.cmd import mv, chmod, rm, mkdir, rmdir # pylint: disable=E0401\nfrom pprof.settings import config\nfrom pprof.utils.db import persist_project\n\nPROJECT_BIN_F_EXT = \".bin\"\nPROJECT_BLOB_F_EXT = \".postproc\"\n\n\nclass ProjectRegistry(type):\n \"\"\"Registry for pprof projects.\"\"\"\n\n projects = {}\n\n def __init__(cls, name, bases, dict):\n \"\"\"Registers a project in the registry.\"\"\"\n super(ProjectRegistry, cls).__init__(name, bases, dict)\n\n if cls.NAME is not None and cls.DOMAIN is not None:\n ProjectRegistry.projects[cls.NAME] = cls\n\n\nclass Project(object, metaclass=ProjectRegistry):\n \"\"\"\n pprof's Project class.\n\n A project defines how run-time testing and cleaning is done for this\n IR project\n \"\"\"\n\n NAME = None\n DOMAIN = None\n GROUP = None\n\n def __new__(cls, *args, **kwargs):\n \"\"\"Create a new project instance and set some defaults.\"\"\"\n new_self = super(Project, cls).__new__(cls)\n if cls.NAME is None:\n raise AttributeError(\n \"{} @ {} does not define a NAME class attribute.\".format(\n cls.__name__, cls.__module__))\n if cls.DOMAIN is None:\n raise AttributeError(\n \"{} @ {} does not define a DOMAIN class attribute.\".format(\n cls.__name__, cls.__module__))\n if cls.GROUP is None:\n raise AttributeError(\n \"{} @ {} does not define a GROUP class attribute.\".format(\n cls.__name__, cls.__module__))\n new_self.name = cls.NAME\n new_self.domain = cls.DOMAIN\n new_self.group = cls.GROUP\n return new_self\n\n def __init__(self, exp, group=None):\n \"\"\"\n Setup a new project.\n\n Args:\n exp: The experiment this project belongs to.\n group: The group this project belongs to. This is useful for\n finding group specific test input files.\n \"\"\"\n self.experiment = exp\n self.group_name = group\n self.sourcedir = path.join(config[\"sourcedir\"], self.name)\n self.builddir = path.join(config[\"builddir\"], exp.name, self.name)\n if group:\n self.testdir = path.join(config[\"testdir\"], self.domain, group,\n self.name)\n else:\n self.testdir = path.join(config[\"testdir\"], self.domain, self.name)\n\n self.cflags = []\n self.ldflags = []\n\n self.setup_derived_filenames()\n\n persist_project(self)\n\n def setup_derived_filenames(self):\n \"\"\" Construct all derived file names. \"\"\"\n self.run_f = path.join(self.builddir, self.name)\n self.bin_f = self.run_f + PROJECT_BIN_F_EXT\n\n def run_tests(self, experiment):\n \"\"\"\n Run the tests of this project.\n\n Clients override this method to provide customized run-time tests.\n\n Args:\n experiment: The experiment we run this project under\n \"\"\"\n from pprof.utils.run import run\n from plumbum import local\n exp = wrap(self.run_f, experiment)\n with local.cwd(self.builddir):\n run(exp)\n\n def run(self, experiment):\n \"\"\"\n Run the tests of this project.\n\n This method initializes the default environment and takes care of\n cleaning up the mess we made, after a successfull run.\n\n Args:\n experiment: The experiment we run this project under\n \"\"\"\n from pprof.utils.run import GuardedRunException\n from pprof.utils.run import (begin_run_group, end_run_group,\n fail_run_group)\n with local.cwd(self.builddir):\n with local.env(PPROF_USE_DATABASE=1,\n PPROF_DB_RUN_GROUP=self.run_uuid,\n PPROF_DOMAIN=self.domain,\n PPROF_GROUP=self.group_name,\n PPROF_SRC_URI=self.src_uri):\n\n group, session = begin_run_group(self)\n try:\n self.run_tests(experiment)\n end_run_group(group, session)\n except GuardedRunException:\n fail_run_group(group, session)\n except KeyboardInterrupt as key_int:\n fail_run_group(group, session)\n raise key_int\n if not config[\"keep\"]:\n self.clean()\n\n def clean(self):\n \"\"\" Clean the project build directory. \"\"\"\n if path.exists(self.builddir) and listdir(self.builddir) == []:\n rmdir(self.builddir)\n elif path.exists(self.builddir) and listdir(self.builddir) != []:\n rm(\"-rf\", self.builddir)\n\n @property\n def compiler_extension(self):\n \"\"\" Return the compiler extension registered to this project. \"\"\"\n try:\n return self._compiler_extension\n except AttributeError:\n self._compiler_extension = None\n return self._compiler_extension\n\n @compiler_extension.setter\n def compiler_extension(self, func):\n \"\"\"\n Set a function as compiler extension.\n\n Args:\n func: The compiler extension function. The minimal signature that\n is required is ::\n f(cc, **kwargs)\n where cc is the original compiler command.\n\n \"\"\"\n self._compiler_extension = func\n\n @property\n def run_uuid(self):\n \"\"\"\n Get the UUID that groups all tests for one project run.\n\n Args:\n create_new: Create a fresh UUID (Default: False)\n \"\"\"\n from os import getenv\n from uuid import uuid4\n\n try:\n if self._run_uuid is None:\n self._run_uuid = getenv(\"PPROF_DB_RUN_GROUP\", uuid4())\n except AttributeError:\n self._run_uuid = getenv(\"PPROF_DB_RUN_GROUP\", uuid4())\n return self._run_uuid\n\n @run_uuid.setter\n def run_uuid(self, value):\n \"\"\"\n Set a new UUID for this project.\n\n Args:\n value: The new value to set.\n \"\"\"\n from uuid import UUID\n if isinstance(value, UUID):\n self._run_uuid = value\n\n def prepare(self):\n \"\"\" Prepare the build diretory. \"\"\"\n if not path.exists(self.builddir):\n mkdir(self.builddir)\n\n @abstractmethod\n def download(self):\n \"\"\" Download the input source for this project. \"\"\"\n pass\n\n @abstractmethod\n def configure(self):\n \"\"\" Configure the project. \"\"\"\n pass\n\n @abstractmethod\n def build(self):\n \"\"\" Build the project. \"\"\"\n pass\n\n\ndef strip_path_prefix(ipath, prefix):\n \"\"\"Strip prefix from path.\"\"\"\n if prefix is None:\n return ipath\n\n return ipath[len(prefix):] if ipath.startswith(prefix) else ipath\n\n\ndef wrap(name, runner, sprefix=None):\n \"\"\" Wrap the binary :name: with the function :runner:.\n\n This module generates a python tool that replaces :name:\n The function in runner only accepts the replaced binaries\n name as argument. We use the cloudpickle package to\n perform the serialization, make sure :runner: can be serialized\n with it and you're fine.\n\n Args:\n name: Binary we want to wrap\n runner: Function that should run instead of :name:\n\n Returns:\n A plumbum command, ready to launch.\n \"\"\"\n import dill\n\n name_absolute = path.abspath(name)\n real_f = name_absolute + PROJECT_BIN_F_EXT\n mv(name_absolute, real_f)\n\n blob_f = name_absolute + PROJECT_BLOB_F_EXT\n with open(blob_f, 'wb') as blob:\n dill.dump(runner, blob, protocol=-1, recurse=True)\n\n with open(name_absolute, 'w') as wrapper:\n lines = '''#!/usr/bin/env python3\n#\n\nfrom plumbum import cli, local\nfrom os import path\nimport sys\nimport dill\n\nrun_f = \"{runf}\"\nargs = sys.argv[1:]\nf = None\nif path.exists(\"{blobf}\"):\n with local.env(PPROF_DB_HOST=\"{db_host}\",\n PPROF_DB_PORT=\"{db_port}\",\n PPROF_DB_NAME=\"{db_name}\",\n PPROF_DB_USER=\"{db_user}\",\n PPROF_DB_PASS=\"{db_pass}\",\n PPROF_LIKWID_DIR=\"{likwiddir}\",\n LD_LIBRARY_PATH=\"{ld_lib_path}\",\n PPROF_CMD=run_f + \" \".join(args)):\n with open(\"{blobf}\", \"rb\") as p:\n f = dill.load(p)\n if f is not None:\n if not sys.stdin.isatty():\n f(run_f, args, has_stdin = True)\n else:\n f(run_f, args)\n else:\n sys.exit(1)\n\n'''.format(db_host=config[\"db_host\"],\n db_port=config[\"db_port\"],\n db_name=config[\"db_name\"],\n db_user=config[\"db_user\"],\n db_pass=config[\"db_pass\"],\n likwiddir=config[\"likwiddir\"],\n ld_lib_path=config[\"ld_library_path\"],\n blobf=strip_path_prefix(blob_f, sprefix),\n runf=strip_path_prefix(real_f, sprefix))\n wrapper.write(lines)\n chmod(\"+x\", name_absolute)\n return local[name_absolute]\n\n\ndef wrap_dynamic(name, runner, sprefix=None):\n \"\"\"\n Wrap the binary :name with the function :runner.\n\n This module generates a python tool :name: that can replace\n a yet unspecified binary.\n It behaves similar to the :wrap: function. However, the first\n argument is the actual binary name.\n\n Args:\n name: name of the python module\n runner: Function that should run the real binary\n\n Returns: plumbum command, readty to launch.\n\n \"\"\"\n import dill\n\n name_absolute = path.abspath(name)\n blob_f = name_absolute + PROJECT_BLOB_F_EXT\n with open(blob_f, 'wb') as blob:\n blob.write(dill.dumps(runner))\n\n with open(name_absolute, 'w') as wrapper:\n lines = '''#!/usr/bin/env python3\n#\n\nfrom pprof.project import Project\nfrom pprof.experiment import Experiment\nfrom plumbum import cli, local\nfrom os import path, getenv\nimport sys\nimport dill\n\nif not len(sys.argv) >= 2:\n os.stderr.write(\"Not enough arguments provided!\\\\n\")\n os.stderr.write(\"Got: \" + sys.argv + \"\\\\n\")\n sys.exit(1)\n\nf = None\nrun_f = sys.argv[1]\nargs = sys.argv[2:]\nproject_name = path.basename(run_f)\nif path.exists(\"{blobf}\"):\n with local.env(PPROF_DB_HOST=\"{db_host}\",\n PPROF_DB_PORT=\"{db_port}\",\n PPROF_DB_NAME=\"{db_name}\",\n PPROF_DB_USER=\"{db_user}\",\n PPROF_DB_PASS=\"{db_pass}\",\n PPROF_PROJECT=project_name,\n PPROF_LIKWID_DIR=\"{likwiddir}\",\n LD_LIBRARY_PATH=\"{ld_lib_path}\",\n PPROF_CMD=run_f):\n with open(\"{blobf}\", \"rb\") as p:\n f = dill.load(p)\n if f is not None:\n exp_name = getenv(\"PPROF_EXPERIMENT\", \"unknown\")\n domain_name = getenv(\"PPROF_DOMAIN\", \"unknown\")\n group_name = getenv(\"PPROF_GROUP\", \"unknwon\")\n e = Experiment(exp_name, [], group_name)\n p = Project(e, project_name, domain_name, group_name)\n\n if not sys.stdin.isatty():\n f(run_f, args, has_stdin = True, project_name = project_name)\n else:\n f(run_f, args, project_name = project_name)\n else:\n sys.exit(1)\n\n'''.format(db_host=config[\"db_host\"],\n db_port=config[\"db_port\"],\n db_name=config[\"db_name\"],\n db_user=config[\"db_user\"],\n db_pass=config[\"db_pass\"],\n likwiddir=config[\"likwiddir\"],\n ld_lib_path=config[\"ld_library_path\"],\n blobf=strip_path_prefix(blob_f, sprefix))\n wrapper.write(lines)\n chmod(\"+x\", name_absolute)\n return local[name_absolute]\n","sub_path":"pprof/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":11774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"552458101","text":"import collections\n\n\ndef main():\n N = int(input())\n A = list(map(int, input().split()))\n counter = collections.Counter(A)\n ans = 0\n for k, v in counter.items():\n if v > k:\n ans += v - k\n elif v < k:\n ans += v\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Python_codes/p03487/s763320065.py","file_name":"s763320065.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592205576","text":"# This Python file uses the following encoding: utf-8\nimport os, sys\n\nimport json\nimport sys\nimport numpy as np\nimport collections\nimport itertools\nfrom collections import Counter\nimport re\nimport pandas as pd\nimport gensim \nfrom gensim.models import Word2Vec, Doc2Vec\nimport csv\nimport xlrd\nfrom keras.utils import np_utils # utilities for one-hot encoding of ground truth values\nfrom gensim.models import Word2Vec, Doc2Vec\nfrom gensim.models.keyedvectors import KeyedVectors\n\"\"\"\n\n\n\"\"\"\ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning for datasets.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\ndef load_data_labels_all_aspects():\n filename = 'data_cur.txt'\n with open(filename, 'r') as myfile:\n data=myfile.read().replace('\\n', '')\n data_json = json.loads(data)\n number_of_data = len(data_json)\n number_of_label = 7\n one_label = [0]*number_of_label\n labels = []\n x_train = []\n # for each data select data and label\n # general_satisfy = 1, apperance = 2, price = 3, battery = 4, performance =5, screen =6, camera =7\n for i in range(number_of_data):\n for j in range(7):\n if(data_json[i]['sentiment'][j]['value'] != 'disabled'):\n one_label[j] = 1\n row_arr = re.split(r'[ \\.]+', data_json[i]['review'])\n row_arr = [clean_vob(x) for x in row_arr]\n x_train.append(row_arr)\n labels.append(one_label)\n one_label = [0]*number_of_label\n\n return [x_train, np.asarray(labels)]\n\ndef load_data_labels_single_aspects():\n # filename = 'data_cur.txt'\n # filename1 = 'tokenize_data_products.txt'\n filename = 'data/tokenized_data.csv'\n data = []\n firstLine = True\n x_text = []\n y = []\n\n\n with open(filename) as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in spamreader:\n if firstLine:\n firstLine = False\n continue\n cur_row = clean_str(row[2])\n row_arr = cur_row.split(\" \")\n x_text.append(row_arr)\n y.append(int(row[1])-1)\n re = []\n for i in y:\n if i not in re:\n re.append(i)\n\n re = np.asarray(re)\n re = re.astype(int)\n max_label = np.max(re)\n\n num_classes = np.unique(y).shape[0] \n \n Y_train = np_utils.to_categorical(y, max_label+1) \n # with open(filename, 'r') as myfile:\n # data=myfile.read().replace('\\n', '')\n # data_json = json.loads(data)\n\n # with open(filename1) as f:\n # content = f.readlines()\n # content = [x.strip() for x in content] \n # number_of_data = len(data_json)\n\n # number_of_label = 2\n # one_label = [0]*number_of_label\n # labels = []\n # x_train = []\n # # general_satisfy = 1, apperance = 2, price = 3, battery = 4, performance =5, screen =6, camera =7\n # for i in range(number_of_data):\n # # irrelevance\n # if(data_json[i]['sentiment'][6]['value'] != 'disabled'):\n # one_label[1] = 1\n # else:\n # #relevance\n # one_label[0] = 1\n # row_arr = re.split(r'[ \\.]+', content[i])\n # row_arr = [clean_vob(x) for x in row_arr]\n # x_train.append(row_arr)\n # labels.append(one_label)\n # one_label = [0]*number_of_label\n return [x_text, np.asarray(Y_train)] \n\ndef pad_sentences(sentences, padding_word=\"\"):\n \"\"\"\n Pads all sentences to the same length. The length is defined by the longest sentence.\n Returns padded sentences.\n \"\"\"\n sequence_length = max(len(x) for x in sentences)\n padded_sentences = []\n for i in range(len(sentences)):\n sentence = sentences[i]\n num_padding = sequence_length - len(sentence)\n new_sentence = sentence + [padding_word] * num_padding\n padded_sentences.append(new_sentence)\n return (padded_sentences,sequence_length)\n\ndef build_vocab(sentences):\n \"\"\"\n Builds a vocabulary mapping from word to index based on the sentences.\n Returns vocabulary mapping and inverse vocabulary mapping.\n \"\"\"\n # Build vocabulary\n word_counts = Counter(itertools.chain(*sentences))\n\n # word_model = gensim.models.Word2Vec(padded_x_train, size=200, min_count = 1, window = 5)\n\n\n vocabulary_inv = [x[0] for x in word_counts.most_common()]\n vocabulary_inv = list(sorted(vocabulary_inv))\n vocabulary = {x: i for i, x in enumerate(vocabulary_inv)}\n\n return [vocabulary, vocabulary_inv]\n\ndef clean_vob(word):\n word = word.replace(\".\",\"\")\n word = word.replace(\",\",\"\")\n word = word.replace(\"\\\"\",\"\")\n return word\n\n\ndef build_input_data(sentences, labels, vocabulary):\n \"\"\"\n Maps sentences and labels to vectors based on a vocabulary.\n \"\"\"\n #(980,99)\n x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences])\n #(99,)\n # x = np.array([vocabulary[word] for word in sentences[0]])\n # x = np.array(x)\n\n\n y = np.array(labels)\n return [x, y]\n\ndef replace_not_exist_in_vob(vob, text):\n for i in range(len(text[0])):\n if(text[0][i] not in vob.keys()):\n text[0][i] = \"\" \n\ndef load_data():\n sentences, labels = load_data_labels_single_aspects()\n # sentences, labels = load_data_labels_all_aspects()\n padded_x_train, MAX_SEQUENCE_LENGTH = pad_sentences(sentences)\n # model_wv = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)\n model_wv = gensim.models.Word2Vec(padded_x_train, size=2*MAX_SEQUENCE_LENGTH+1, min_count = 1, window = 5)\n weights = model_wv.wv.syn0\n voca = dict([(k, v.index) for k, v in model_wv.wv.vocab.items()])\n print(model_wv.wv.most_similar(\"urban\"))\n print(len(voca))\n sentences_padded, maxxlen = pad_sentences(sentences)\n # vocabulary_inv = []\n vocabulary, vocabulary_inv = build_vocab(sentences_padded)\n x, y = build_input_data(sentences_padded, labels, vocabulary)\n with open(\"vocabulary_list.txt\", \"w\") as text_file:\n text_file.write(\"Vocab : {0}\".format(len(vocabulary)))\n text_file.write(\"\\n\")\n text_file.write(\"sequence_length : {0}\".format(vocabulary))\n text_file.write(\"\\n\")\n with open(\"vocab.txt\", \"w\") as text_file:\n text_file.write(\"Vocab : {0}\".format(len(voca)))\n text_file.write(\"\\n\")\n text_file.write(\"sequence_length : {0}\".format(voca))\n text_file.write(\"\\n\")\n return [x, y, voca, weights]\n\ndef preprocess_single_sentence(sentence):\n x_text = []\n # x_text.append(clean_vob(sentence).split(\" \"))\n sentence = re.split(r'[ \\.]+', sentence)\n sentence = [clean_vob(x) for x in sentence]\n x_text.append(sentence)\n return x_text\n\ndef pad_single_sentence(sentence, size, padding_word=\"\"):\n \"\"\"\n Pads all sentences to the same length. The length is defined by the longest sentence.\n Returns padded sentences.\n \"\"\"\n sequence_length = size\n padded_sentences = []\n # for i in range(len(sentences)):\n sentence = sentence[0]\n num_padding = sequence_length - len(sentence)\n new_sentence = sentence + [padding_word] * num_padding\n padded_sentences.append(new_sentence)\n return padded_sentences\n\ndef replace_process(sentence, vocab):\n x = preprocess_single_sentence(sentence)\n for i in x:\n if(i not in vocab):\n x.remove(i)\n return x \n# m[0][i] => text; m[1][i] => label\nif __name__ == \"__main__\":\n x, y, vocbulary, vocabulary_inv = load_data()\n # print(vocbulary)\n # print(x.shape)\n\n\n\n\n\n","sub_path":"data_helpers.py","file_name":"data_helpers.py","file_ext":"py","file_size_in_byte":8160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"165607014","text":"from datetime import datetime\nfrom typing import ( \n Optional,\n List\n)\n\nfrom starlette.exceptions import HTTPException\nfrom starlette.status import HTTP_404_NOT_FOUND\n\nfrom ..crud.user import get_user\nfrom ..db.mongodb import AsyncIOMotorClient\nfrom ..core.config import ( \n database_name,\n sensors_collection_name \n)\nfrom ..models.sensors import ( \n Sensors,\n SensorsInDB,\n SensorsInCreate,\n SensorsInUpdate,\n SensorsList,\n)\nfrom bson.objectid import ObjectId\n\n\nasync def getSensor(\n conn: AsyncIOMotorClient,\n id: str\n) -> SensorsInDB:\n row = await conn[database_name][sensors_collection_name].find_one({\"_id\": ObjectId(id)})\n if row:\n row['id'] = str(row['_id'])\n row.pop('_id', None)\n return row\n \n\nasync def fetchSensors(\n conn: AsyncIOMotorClient\n) -> List[SensorsInDB]:\n sensors = []\n rows = conn[database_name][sensors_collection_name].find({})\n async for row in rows:\n row['id'] = str(row['_id'])\n sensors.append(SensorsInDB(**row)) \n return sensors \n\nasync def createSensor(\n conn: AsyncIOMotorClient, \n sensors: SensorsInCreate,\n) -> SensorsInDB: \n sensors_doc = sensors.dict()\n sensors_doc['createdAt'] = datetime.now()\n sensors_doc['updatedAt'] = datetime.now() \n row = await conn[database_name][sensors_collection_name].insert_one(sensors_doc)\n sensors_doc['id'] = str(ObjectId(row.inserted_id))\n \n return SensorsInDB(\n **sensors_doc\n ) \n\nasync def updateSensor(\n conn: AsyncIOMotorClient, \n id: str, \n sensors: SensorsInUpdate\n) -> SensorsInDB:\n sensors_doc = await getSensor(conn, id)\n sensors_doc[\"description\"] = sensors.description\n sensors_doc[\"data_reading\"] = datetime.strptime(sensors.data_reading, '%Y-%m-%dT%H:%M:%S.%fZ')\n sensors_doc[\"reading\"] = datetime.strptime(sensors.reading, '%Y-%m-%dT%H:%M:%S.%fZ') \n sensors_doc['updatedAt'] = datetime.now()\n update_at = await conn[database_name][sensors_collection_name].update_one({\"_id\": ObjectId(id)}, {'$set': sensors_doc})\n sensors_doc[\"update_at\"] = update_at\n return sensors_doc\n\n \n\nasync def deleteSensor(\n conn: AsyncIOMotorClient, \n id: str\n):\n delete_at = await conn[database_name][sensors_collection_name].delete_one({ \"_id\": ObjectId(id)})\n return delete_at\n \n \n \n","sub_path":"app/crud/sensors.py","file_name":"sensors.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"292450825","text":"# Written by Joshua Cahill\n# This program reads information from the majorIncidents.json files and inserts it into the database\n\nimport json\nimport re\nimport time\nfrom datetime import datetime\nimport mysql.connector\nimport os\n\n\ndatabase_file = open(\"aws_database_details.txt\", \"r\")\ndatabase_details = database_file.read().split(',')\ndatabase_file.close()\n\nfileDir = input(\"Enter the full path of the directory that contains the files:\\n\")\n\nfileList = os.listdir(fileDir)\nfileList.sort() # sort the list by datetime so we read it in increasing date\n\n# open the database connection\nconn = mysql.connector.connect(user=database_details[0], password=database_details[1], host=database_details[2], database=database_details[3])\nc = conn.cursor()\n\nfor filename in fileList:\n\n\t#print (filename)\n\t#continue\n\n\tdate_time_string = filename.split(\"-majorIncidents\")[0]\n\tdate_time_object = datetime.strptime(date_time_string, '%Y-%m-%d-%H-%M-%S')\n\n\twith open(fileDir + filename, \"r\") as f:\n\t\t\n\t\t# extract the data from the file into JSON\n\t\tdata = json.loads(f.read())\n\n\t\t# for each fire in the JSON\n\t\tfor fire in data['features']:\n\t\t\t#title = fire['properties']['title']\n\t\t\t#startDate = fire['properties']['pubDate']\n\t\t\t#startDate = datetime.strptime(startDate, '%d/%m/%Y %I:%M:%S %p')\n\t\t\t#startDate = startDate.strftime('%Y-%m-%d %H:%M:%S')\n\t\t\t# the following comes from the description\n\t\t\t#location = re.search(r'LOCATION: (.*?) = 10 and len(allcormedians_nonan[i]) >= 10:\n wilcoxonresults[:, i] = wilcoxon(allrawmedians_nonan[i], allcormedians_nonan[i])\n \n # How to sort the regions\n # By increaseing p-value\n sortidx = np.argsort(wilcoxonresults[1, :])#[::-1]\n # By increasing dice score\n #sortidx = np.argsort([np.median(s) for s in alldicegtcorscores_nonan])#[::-1]\n \n # Bonferroni correction\n alpha = 0.05\n num_sub_test = len(wilcoxonresults[1, :][~np.isnan(wilcoxonresults[1, :])])\n cutoff = alpha/num_sub_test\n print(\"Threshold for significant p-value is %f\" % cutoff)\n \n # Extract number of significant regions\n top = np.argwhere(np.sort(wilcoxonresults[1, :]) < cutoff)[-1][0] + 1\n #top = 66\n #top = 10\n \n # Then sort significant regions by decreasing gtvscor-gtcsraw dice score improvement\n print(\"SE her\")\n alldicescoreimprovements_nonan = \\\n [gtcordicescores_region-gtrawdicescores_region for \\\n gtcordicescores_region, gtrawdicescores_region in zip(alldicegtcorscores_nonan, alldicegtrawscores_nonan)]\n topmediandicescoreimprovements = np.array([np.median(scores) for scores in np.array(alldicescoreimprovements_nonan)[sortidx][:top]])\n sortidx2 = np.argsort(topmediandicescoreimprovements)[::-1]\n \n # The significant regions\n topregions = mniroinames[sortidx][:top][sortidx2]\n print(\"Number of significant regions: %i\" % top)\n print(\"The significant regions are: \")\n print(topregions)\n toppvalues = wilcoxonresults[1, :][sortidx][:top][sortidx2]\n print(\"p-values are: \")\n #print(toppvalues)\n #topmediandicegtcorscores = np.array([np.median(scores) for scores in np.array(alldicegtcorscores_nonan)[sortidx][:top]])\n print(\"Top median dice score improvements are: \")\n print(topmediandicescoreimprovements[sortidx2])\n \n descriptionchoice = 3\n description = [\"TOPUP impact on gradient echo DSC rCBV\", \\\n \"TOPUP impact on spin echo DSC rCBV\", \\\n \"EPIC impact on gradient echo DSC rCBV\", \\\n \"EPIC impact on spin echo DSC rCBV\"]\n \n fig = plt.figure(figsize=[2*6.4, 4.8], tight_layout=True)\n \n fig.suptitle(description[descriptionchoice] + \" (p < \" + \"{:.4f}\".format(cutoff) + \")\")\n \n gs = gridspec.GridSpec(1, 5)\n \n ax1 = fig.add_subplot(gs[0, 0:3])\n ax2 = fig.add_subplot(gs[0, 3], sharey=ax1)\n ax3 = fig.add_subplot(gs[0, 4], sharey=ax1)\n \n # Making split violin kernel density plot\n # Prepare median values for uncorrected rCBV\n topmediandata = np.array(allrawmedians_nonan)[sortidx][:top][sortidx2]\n topmediandatadf = \\\n pd.DataFrame({\"Median rCBV\" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topmediandata])}).explode(\"Median rCBV\")\n topcorrectiontypedf = \\\n pd.DataFrame({\"Correction\" : np.array([pd.Series([\"Uncorrected\" for num_samples in range(len(samples))], dtype=\"category\") for samples in topmediandata])}).explode(\"Correction\")\n topregionsdatadf = \\\n pd.DataFrame({\"Region\" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype=\"category\") for region, samples in zip(topregions, topmediandata)])}).explode(\"Region\")\n d1 = pd.concat((topcorrectiontypedf, topregionsdatadf, topmediandatadf), axis=1).astype({\"Correction\" : str, \"Region\" : str, \"Median rCBV\" : float})\n \n # --\"-- corrected rCBV\n topmediandata = np.array(allcormedians_nonan)[sortidx][:top][sortidx2]\n topmediandatadf = \\\n pd.DataFrame({\"Median rCBV\" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topmediandata])}).explode(\"Median rCBV\")\n topcorrectiontypedf = \\\n pd.DataFrame({\"Correction\" : np.array([pd.Series([\"Corrected\" for num_samples in range(len(samples))], dtype=\"category\") for samples in topmediandata])}).explode(\"Correction\")\n topregionsdatadf = \\\n pd.DataFrame({\"Region\" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype=\"category\") for region, samples in zip(topregions, topmediandata)])}).explode(\"Region\")\n d2 = pd.concat((topcorrectiontypedf, topregionsdatadf, topmediandatadf), axis=1).astype({\"Correction\" : str, \"Region\" : str, \"Median rCBV\" : float})\n \n # Combine dataframes for uncorrected and corrected median rCBV\n d = pd.concat((d1, d2))\n \n # Plot rCBV\n sns.violinplot(x=\"Median rCBV\",\n y=\"Region\",\n hue=\"Correction\",\n split=True, \n inner=\"quart\",\n data=d, \n ax=ax1)\n # Set xlim for ax1\n ax1.set_xlim(0,7) # TODO: manual\n \n # Plot p-values\n sns.barplot(x=toppvalues,\n y=topregions,\n ax=ax3)\n \n ax3.set_xlabel(\"Wilcoxon p-value\")\n \n plt.setp(ax3.get_yticklabels(), visible=False)\n \n # Prepare Dice score improvements for swarm plot\n topdicedata = np.array(alldicescoreimprovements_nonan)[sortidx][:top][sortidx2]\n topregionsdatadf = \\\n pd.DataFrame({\"Region\" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype=\"category\") for region, samples in zip(topregions, topdicedata)])}).explode(\"Region\")\n topdicedatadf = \\\n pd.DataFrame({\"Dice improvement\" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topdicedata])}).explode(\"Dice improvement\")\n d = pd.concat((topregionsdatadf, topdicedatadf), axis=1).astype({\"Region\" : str, \"Dice improvement\" : float})\n \n # Plot Dice score improvements\n #sns.swarmplot(x=\"Dice improvement\", y=\"Region\", data=d, ax=ax2)\n sns.boxplot(x=\"Dice improvement\", y=\"Region\", data=d, ax=ax2)\n #sns.pointplot(x=\"Dice improvement\", y=\"Region\", data=d, ax=ax2, color=\"red\", scale=.5)\n #sns.pointplot(x=\"Dice improvement\", y=\"Region\", data=d, ax=ax2, estimator=np.median, color=\"red\", scale=.5)\n #ax2.plot(y=[0]*len(d))\n ax2.axvline(0, color='r', linestyle='--')\n #sns.lineplot(x=\"Dice improvement\", y=\"Region\", data=d, ax=ax2)\n #ax2.plot(topmediandicescoreimprovements[sortidx2], 'r-o', linewidth=4)\n #mx=pd.DataFrame(d.groupby(\"Region\")[\"Dice improvement\"].median())\n #print(mx)\n #m=d.groupby(\"Region\")[\"Dice improvement\"].median()\n #print(mx2[\"Region\"])\n #print(type(d[\"Region\"][0]))# = mx.values.astype(float)\n #print(type(mx.index[0]))\n #sns.lineplot(y=np.array(mx2.values, dtype=float), x=np.array(mx2.index, dtype=str), ax=ax2)\n \n ax2.set_xlim(-0.4,0.4) # TODO: Set manually\n \n ax3.set_xlim(0,0.0005) # TODO: Set manually\n \n #md1\n #md2\n #md = pd.DataFrame({\"Region\" : np.array(m.index, dtype=str), \"Dice improvement\" : np.array(m.values, dtype=float)})\n \n #print(m)\n #sns.lineplot(x=\"Dice improvement\", y=\"Region\", data=md, ax=ax2)\n #print(np.array(mx2.index, dtype=str))\n #print(np.array(mx2.values, dtype=float))\n \n plt.setp(ax2.get_yticklabels(), visible=False)\n ax2.set_ylabel(\"\")\n \n # Make some free space for suptitle\n gs.tight_layout(fig, rect=[0, 0, 1, 0.95])\n \n plt.show()","sub_path":"scripts/.ipynb_checkpoints/wilcoxon-and-mni-rois-dice-analysis-checkpoint.py","file_name":"wilcoxon-and-mni-rois-dice-analysis-checkpoint.py","file_ext":"py","file_size_in_byte":15287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101833606","text":"from flask import render_template, flash, redirect\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flask import render_template, flash, redirect, session, url_for, request, g, jsonify, json\nfrom flask_login import login_user, logout_user, current_user, login_required\n#from flask_login import login_manager\n\nfrom flask_login import LoginManager\nfrom config import basedir\nimport config\n\nfrom app import app, db\nfrom app import lm\nfrom .forms import LoginForm\n\nfrom .models import User, Post, Tag, Action, Pro, Con\n\nfrom .forms import LoginForm, EditForm\n\nfrom sqlalchemy import update\n\nfrom .content_management import Content\n\nfrom .posts import post_select2\n\n\n\n@app.route('/action_select', methods=['GET', 'POST'])\ndef action_select():\n print(\"in action_select\")\n\n post = Post.query.filter(Post.selected==True).first()\n if post == None:\n flash(\"Please select a post first \")\n return redirect(url_for('index'))\n print(\"in action_select\")\n\t\n #import pdb; pdb.set_trace()\n\n actions = Action.query.join(Post.actions).filter(Post.id==post.id)\n\n if (actions.count() == 0):\n flash(\"There is no actions for this post.\")\n print (\"actions count is 0 \")\n redirect(url_for('flash_err'))\n return render_template('select_action.html', actions=actions)\n #return redirect(url_for('index'))\n\t\t\n actions = Action.query.all()\t\t\t\n for action in actions:\n print(\"In action_select seting action %s to False\", action.title)\n pribr(action.title)\n action.selected = False\n\n if request.method == 'GET':\n return render_template('select_action.html', actions=actions)\n\t\t\n selected_action_id = int(request.form['selected_action'])\n print (selected_action_id)\n action = Action.query.get_or_404(selected_action_id)\n print(\"In action_select seting action %s to True\", action.title)\n pribr(action.title)\n action.selected = True\n print(action.title)\n db.session.commit()\n action = Action.query.get_or_404(selected_action_id)\n print(action.selected)\n #actions = Action.query.all()\n print(\"end action_select calling render_template show_selected_action \")\n print(\"\")\n return render_template('show_selected_action.html', actions=actions)\n\t\n\n\n@app.route('/action_select2/', methods=['GET', 'POST'])\ndef action_select2(selected_action_id):\n print(\"IIIIIIIIIIIIIIIIn action_select2\")\n print(selected_action_id)\n post = Post.query.filter(Post.selected==True).first()\n if post == None:\n flash(\"Please select a post first \")\n return redirect(url_for('index'))\n print(\"in action_select\")\n\t\n #import pdb; pdb.set_trace()\n\n actions = Action.query.join(Post.actions).filter(Post.id==post.id)\n\n if (actions.count() == 0):\n flash(\"There is no actions for this post.\")\n print (\"actions count is 0 \")\n redirect(url_for('flash_err'))\n return render_template('select_action.html', actions=actions)\n #return redirect(url_for('index'))\n\t\t\n actions = Action.query.all()\t\t\n for action in actions:\n print(\"In action_select2 seting action %s to False\", action.title)\n print(action.title)\n action.selected = False\n\n print(selected_action_id)\n action = Action.query.get_or_404(selected_action_id)\n print(\"In action_select2 seting action %s to True\", action.title)\n print(action.title)\n action.selected = True\n\t\n db.session.flush()\n db.session.commit()\n db.session.refresh(action)\n\t\n action = Action.query.filter(Action.selected==True).first()\n\n print(\"end of action_select2 before calling actions_by_post action selected is %s\", action.title)\n print(action.title)\t\n return redirect(url_for('actions_by_post'))\t\n print(\"\")\t\n #return render_template('show_selected_action.html', actions=actions)\n\n\t\t\n@app.route('/actions_by_post', methods=['POST', 'GET'])\n@login_required\ndef actions_by_post():\n\t\n #import pdb; pdb.set_trace()\n post = Post.query.filter(Post.selected==True).first()\n\n if post == None:\n flash(\"Please select a post first \")\n return redirect(url_for('index'))\n\t\t\n print(\"post\")\n print(post.title)\n\t\n actions = Action.query.join(Post.actions).filter(Post.id==post.id)\n\t\t\n return render_template('show_post_actions2.html',\n post=post,\n actions=actions\n\t\t\t\t\t\t\t)\n\t\n@app.route('/actions_by_post2/', methods=['POST', 'GET'])\n@login_required\ndef actions_by_post2(selected_post_id):\n post_select2(selected_post_id)\n return redirect(url_for('actions_by_post'))\t\t\t\n\n\n@app.route('/action/add', methods=['GET', 'POST'])\ndef action_add():\n\n user = User.query.get_or_404(g.user.id)\n author_id = user.id\n \n post = Post.query.filter(Post.selected==True).first()\n print(post.title)\n if post == None:\n flash(\"Please select a post first \")\n return redirect(url_for('post_select'))\n \n #print request\n \n if request.method == 'GET':\n return render_template('add_action.html', post=post)\n \n #get data from form and insert to postgress db\n title = request.form.get('title')\n body = request.form.get('description')\n\t\n #import pdb; pdb.set_trace() \t\n action = Action(title, body, author_id)\t\n\t\n post.actions.append(action)\t\n\t \n db.session.add(action) \n db.session.commit() \n db.session.refresh(action)\n # test insert res\n url = url_for('actions_by_post')\n return redirect(url) \n\t\n\n@app.route('/action2/add/', methods=['GET', 'POST'])\ndef action_add2(selected_post_id):\n print(selected_post_id)\n post_select2(selected_post_id)\n return action_add()\n \n\n#update selected action\n#from https://teamtreehouse.com/community/add-a-a-with-an-href-attribute-that-points-to-the-url-for-the-cancelorder-view-cant-find-my-error \n@app.route('/action2/update/', methods=['GET', 'POST'])\ndef action_update(selected_action_id):\n\n post = Post.query.filter(Post.selected==True).first()\n print(post.title)\n if post == None:\n flash(\"Please select a post first \")\n return redirect(url_for('post_select'))\n \n action_select2(selected_action_id)\n\t\t\n action = Action.query.get_or_404(selected_action_id)\n if request.method == 'GET':\n return render_template('update_action.html', post=post, action=action)\n\t\t\n #get data from form and insert to postgress db\n #import pdb; pdb.set_trace() \t\n action.title = request.form.get('title')\t\n action.body = request.form.get('description')\n \n db.session.commit() \n db.session.refresh(action)\n\t\n return redirect(url_for('actions_by_post'))\t\t\t\n#end update selected action \t\t\n\n\n@app.route('/action/delete/', methods=['GET', 'POST'])\n#Here author is user_id\ndef action_delete():\n \n post = Post.query.filter(Post.selected==True).first()\n print(post.title)\n if post == None:\n flash(\"Please select a post first \")\n return redirect(url_for('post_select'))\n\t\t\n action = Action.query.filter(Action.selected==True).first()\n \n if action == None:\n flash(\"Please select an action first \")\n return redirect(url_for('action_select'))\n\t\t\n #print request\n pros = Pro.query.join(Action.pros).filter(Action.id==action.id)\n cons = Con.query.join(Action.cons).filter(Action.id==action.id)\n \n\n for pro in pros:\t\t\n print(pro.description)\n db.session.delete(pro)\n for con in cons:\n print(con.description)\n db.session.delete(con)\n\t\t\t\n db.session.delete(action)\t\t\t\n db.session.commit() \n\t\n return redirect(url_for('actions_by_post'))\n#end action_delete\n\n\t\t\n#action_delete2\n@app.route('/action/delete2/', methods=['GET', 'POST'])\ndef action_delete2(selected_action_id):\n\n action_select2(selected_action_id)\n return action_delete()\n#end action_delete2\n\t\t\n#actions\n\n\t\t\t\t\t\t\t \t\t\t\t\t\n","sub_path":"app/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":8000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59096045","text":"#Mariana Ponce Gonzàlez\r\n#Ejercicio de trapecio\r\n\r\n#La entrada seran las horas trabajadas y el pago por hora\r\ndef calcularpago(horastrabajadas, pagoxhora):\r\n#calcula el pago\r\n pago = horastrabajadas * pagoxhora\r\n#Los datos de salida seran el pago\r\n return pago\r\n\r\n#La entrada seran las horas trabajadas y el pago por hora\r\ndef calculextra(horastrabajadas, pagoxhora):\r\n#calcula el pago extra\r\n extra = ((horastrabajadas * pagoxhora)*.65)+(horastrabajadas * pagoxhora)\r\n#Los datos de salida seran el pago extra\r\n return extra\r\n\r\ndef main():\r\n h = int(input(\"Teclea las horas normales trabajadas \"))\r\n p = int(input(\"Teclea las horas extras trabajadas \"))\r\n e = int(input(\"Teclea lael pago por hora \"))\r\n t = calcularpago(h,e)\r\n te = calculextra(e, p)\r\n to = t + te\r\n \r\n print(\"El pago normal es %.2f \" % (t))\r\n print(\"El pago extra es %.2f \" % (te))\r\n print(\"El pago total %.2f \" % (to))\r\n \r\nmain()","sub_path":"Pago.py","file_name":"Pago.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"19971143","text":"#! python3\n# -*- coding:UTF-8 -*-\n\"\"\"\n# 198. House Robber\n# Created on 2019/11/27 10:11\n# rob\n# @author: ChangFeng\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n \"\"\"\n TLE\n :param nums:\n :return:\n \"\"\"\n\n def helper(opts, i):\n if i < 0:\n return 0\n return max(helper(opts, i - 1), helper(opts, i - 2) + opts[i])\n\n return helper(nums, len(nums) - 1)\n\n def rob(self, nums: List[int]) -> int:\n if not nums:\n return 0\n dp = [0 for _ in range(len(nums) + 1)]\n dp[0] = 0\n dp[1] = nums[0]\n for i in range(1, len(nums)):\n dp[i + 1] = max(dp[i], dp[i - 1] + nums[i])\n return dp[-1]\n\n def rob(self, nums: List[int]) -> int:\n if not nums:\n return 0\n pre1 = pre2 = 0\n for num in nums:\n tmp = pre1\n pre1 = max(pre1, pre2 + num)\n pre2 = tmp\n return pre1\n\n\ndef main():\n test_case = [2, 7, 9, 3, 1]\n print(Solution().rob(test_case))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"algorithms/rob.py","file_name":"rob.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"19016272","text":"from functools import reduce\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import batch_norm\nfrom enum import Enum\n\n\nclass Phase(Enum):\n train = 1\n validation = 2\n predict = 3\n\n\nclass Layer(Enum):\n token = 1\n tag = 2\n deprel = 3\n feature = 4\n char = 5\n\n\nclass ParseModel:\n def __init__(\n self,\n config,\n shapes):\n batch_size = None\n\n # Are we training or not?\n self._is_training = tf.placeholder(tf.bool, [], \"is_training\")\n\n # Labels for training and validation.\n self._targets = tf.placeholder(tf.int32, batch_size, \"targets\")\n\n n_tokens = int(shapes['tokens'])\n self._tokens = tf.placeholder(tf.int32, [batch_size, n_tokens],\n \"tokens\")\n\n n_tags = int(shapes['tags'])\n self._tags = tf.placeholder(tf.int32, [batch_size, n_tags], \"tags\")\n\n n_deprels = int(shapes['deprels'])\n self._deprels = tf.placeholder(\n tf.int32, [batch_size, n_deprels], \"deprels\")\n\n n_features = int(shapes['features'])\n self._features = tf.placeholder(\n tf.int32, [batch_size, n_features], \"features\")\n\n n_chars = int(shapes['chars'])\n self._chars = tf.placeholder(tf.int32, [batch_size, n_chars], \"chars\")\n\n # For tokens, tags, and characters, we use pre-trained embeddings.\n # Todo: make this more flexible.\n self._token_embeds = tf.placeholder(\n tf.float32, [None, 50], \"token_embeds\")\n self._tag_embeds = tf.placeholder(tf.float32, [None, 50], \"tag_embeds\")\n self._char_embeds = tf.placeholder(\n tf.float32, [None, 50], \"char_embeds\")\n\n token_input = tf.nn.embedding_lookup(self._token_embeds, self._tokens)\n token_input = tf.reshape(\n token_input, [\n tf.shape(\n self._tokens)[0], self._tokens.shape[1] * self._token_embeds.shape[1]])\n\n tag_input = tf.nn.embedding_lookup(self._tag_embeds, self._tags)\n tag_input = tf.reshape(\n tag_input, [\n tf.shape(\n self._tags)[0], self._tags.shape[1] * self._tag_embeds.shape[1]])\n\n char_input = tf.nn.embedding_lookup(self._char_embeds, self._chars)\n char_input = tf.reshape(\n char_input, [\n tf.shape(\n self._chars)[0], self._chars.shape[1] * self._char_embeds.shape[1]])\n with tf.variable_scope(\"char_norm\"):\n char_input = tf.layers.batch_normalization(\n char_input, scale=True, momentum=0.80, training=self.is_training, fused=True)\n\n # The integer-encoded characters consist of n suffix/prefix pairs. Find\n # n.\n prefix_len = int(shapes[\"prefix_len\"])\n suffix_len = int(shapes[\"suffix_len\"])\n n_morph_tokens = int(self._chars.shape[1]) // (prefix_len + suffix_len)\n char_input = tf.split(char_input, n_morph_tokens, 1)\n\n morph_w = tf.get_variable(\n \"morph_w\", [\n char_input[0].get_shape()[1], config.morph_hidden_size])\n morph_b = tf.get_variable(\"morph_b\", [config.morph_hidden_size])\n\n morph = list(map(lambda i: tf.nn.relu(\n tf.matmul(i, morph_w) + morph_b), char_input))\n morph = tf.concat(morph, 1)\n\n # For dependency relations, we train a separate layer, which could be seen as an\n # embeddings layer.\n n_deprel_embeds = int(shapes[\"deprel_embeds\"])\n with tf.device(\"/cpu:0\"):\n deprel_embeds = tf.get_variable(\n \"deprel_embed\", [\n n_deprel_embeds, config.deprel_embed_size])\n\n deprel_input = tf.nn.embedding_lookup(deprel_embeds, self._deprels)\n deprel_input = tf.reshape(deprel_input, [tf.shape(self._deprels)[\n 0], self._deprels.shape[1] * deprel_embeds.shape[1]])\n\n n_attachment_addrs = 2\n self._assoc_strengths = tf.placeholder(\n tf.float32, [batch_size, n_deprel_embeds * n_attachment_addrs], \"assoc_strengths\")\n\n # Features are converted to a one-hot representation.\n n_features = int(shapes[\"n_features\"])\n features = tf.one_hot(self._features, n_features, axis=-1)\n features = tf.contrib.layers.flatten(features)\n\n inputs = tf.concat([token_input,\n tag_input,\n deprel_input,\n features,\n morph,\n self._assoc_strengths],\n 1,\n name=\"concat_inputs\")\n with tf.variable_scope(\"input_norm\"):\n inputs = tf.layers.batch_normalization(\n inputs, scale=True, momentum=0.98, training=self.is_training, fused=True)\n\n if config.keep_prob_input < 1:\n inputs = tf.contrib.layers.dropout(\n inputs,\n keep_prob=config.keep_prob_input,\n is_training=self.is_training)\n\n hidden_w = tf.get_variable(\n \"hidden_w\", [\n inputs.get_shape()[1], config.hidden_size])\n hidden_b = tf.get_variable(\"hidden_b\", [config.hidden_size])\n hidden = tf.matmul(inputs, hidden_w) + hidden_b\n hidden = tf.nn.relu(hidden)\n\n with tf.variable_scope(\"hidden_norm\"):\n hidden = tf.layers.batch_normalization(\n hidden, scale=True, momentum=0.97, training=self.is_training, fused=True)\n\n if config.keep_prob < 1:\n hidden = tf.contrib.layers.dropout(\n hidden, keep_prob=config.keep_prob, is_training=self.is_training)\n\n n_labels = int(shapes[\"n_labels\"])\n output_w = tf.get_variable(\"output_w\", [config.hidden_size, n_labels])\n output_b = tf.get_variable(\"output_b\", [n_labels])\n logits = tf.add(tf.matmul(hidden, output_w), output_b, name=\"logits\")\n\n losses = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=self._targets)\n self._loss = loss = tf.reduce_sum(losses, name=\"loss\")\n\n _, labels = tf.nn.top_k(logits)\n labels = tf.reshape(labels, [-1])\n correct = tf.equal(self._targets, labels)\n self._accuracy = tf.divide(\n tf.reduce_sum(\n tf.cast(\n correct, tf.float32)), tf.cast(\n tf.shape(\n self._targets)[0], tf.float32), name=\"accuracy\")\n\n self._lr = tf.placeholder(tf.float32, [], \"lr\")\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self._train_op = tf.train.AdagradOptimizer(\n self.lr).minimize(loss, name=\"train\")\n\n @property\n def accuracy(self):\n return self._accuracy\n\n @property\n def correct(self):\n return self._correct\n\n @property\n def char_embeds(self):\n return self._char_embeds\n\n @property\n def chars(self):\n return self._chars\n\n @property\n def deprels(self):\n return self._deprels\n\n @property\n def is_training(self):\n return self._is_training\n\n @property\n def features(self):\n return self._features\n\n @property\n def lr(self):\n return self._lr\n\n @property\n def assoc_strengths(self):\n return self._assoc_strengths\n\n @property\n def tags(self):\n return self._tags\n\n @property\n def tokens(self):\n return self._tokens\n\n @property\n def tag_embeds(self):\n return self._tag_embeds\n\n @property\n def token_embeds(self):\n return self._token_embeds\n\n @property\n def loss(self):\n return self._loss\n\n @property\n def train_op(self):\n return self._train_op\n\n @property\n def targets(self):\n return self._targets\n","sub_path":"dpar-utils/tensorflow/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"129352547","text":"from drone_dancer import drone_dancer\nimport time\nfrom play_song import play_song\nfrom cluster import cluster\nimport scipy.io.wavfile as wavfile\n\nbeat_num = 0\n\nflipped = False\n\ndef hook():\n global beat_num\n\n duration = audio.current_beat_s() - 0.01 # 10ms less than a beat\n\n cluster_array_iterator = int(audio.current_chunk()/10.0)\n\n if class_labels[cluster_array_iterator]:\n print('setting going hard')\n dancer.set_mood(dancer.dance_moods.MOOD_GO_HARD)\n dancer.auto_dance()\n else:\n print('setting chill')\n duration = audio.current_beat_s() * 4 - 0.5 # 500ms less than a beat\n dancer.set_mood(dancer.dance_moods.MOOD_CHILL)\n\n if beat_num % 4 == 0:\n dancer.auto_dance()\n\n # todo implement auto dance every x beats\n\n beat_num = beat_num + 1\n\n\nfilename = '../music/AllForNothing.wav'\n\nrate, raw_data = wavfile.read(filename)\ndata = (raw_data[:,0]/2.0+raw_data[:,1]/2.0)\n\n\n# get mfcc todo use cluster labels\ntime_song, labels, class_labels = cluster(data,samplerate=44100)\n\naudio = play_song(filename)\n\ndancer = drone_dancer()\n\n# set max yaw\n# dancer.drone.setConfig('control:indoor_control_yaw', '6.11')\ndancer.drone.setConfig('control:control_yaw', '6.11')\nCDC = dancer.drone.ConfigDataCount\nwhile CDC == dancer.drone.ConfigDataCount: time.sleep(0.01)\n\n\ndancer.takeoff(True)\n\n\nprint('waiting for drone to be ready')\nwhile not dancer.ready():\n time.sleep(0.05)\n\n\n\nprint('drone ready, starting song')\naudio.start()\n\nwhile audio.current_time() < 0.1: # todo this may cause underrun\n time.sleep(0.001)\n\n\n\n\nprint('setting beat event hook')\naudio.set_beat_event(hook)\n\ndancer.start_dancing()\n\n# print('sleeping for 15 seconds then stopping')\n\n# time.sleep(50)\n\ntime_threshold = 0.01\n\ntime.sleep(100)\n\n# while True:\n# # catch up\n# while time_song[cluster_array_iterator] < audio.current_time() - time_threshold*2.0:\n# print('here, current time %f' % audio.current_time())\n# cluster_array_iterator = cluster_array_iterator + 1\n#\n# if abs(time_song[cluster_array_iterator] - audio.current_time()) < time_threshold:\n# print('cluster time:')\n# print time_song[cluster_array_iterator]\n# print('cluster label')\n# print(labels[cluster_array_iterator])\n# cluster_array_iterator = cluster_array_iterator + 1\n# time.sleep(0.01)\n\n\ndancer.stop_dancing()\n\ndancer.land()\n\naudio.stop()","sub_path":"code/PS-drone/routine_cluster_test.py","file_name":"routine_cluster_test.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"68885702","text":"#!/usr/bin/env python\nimport argparse\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport ptitprince as pt\n\n\ndef plot_csv(filename: str, pngpath: str):\n csv = pd.read_csv(filename)\n\n f, ax = plt.subplots(figsize=(8, 6))\n ax = pt.RainCloud(\n x=\"type\",\n y=\"seconds\",\n hue=\"source\",\n data=csv,\n palette=\"Set2\",\n # bw = .2,\n width_viol=0.6,\n ax=ax,\n orient=\"h\",\n alpha=0.65,\n # dodge = True,\n jitter=0.03,\n move=0.2,\n # pointplot = True,\n )\n\n # ax.set(ylim=(0.0002, 5))\n ax.set_xscale(\"log\")\n ax.set_xlabel(\"seconds per chunk\")\n ax.axes.get_yaxis().get_label().set_visible(False)\n handles, labels = ax.get_legend_handles_labels()\n plt.legend(handles[0:3], labels[0:3], loc=\"lower left\")\n plt.tight_layout()\n f.savefig(pngpath, dpi=600)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"csv\", help=\"input csv file\")\n parser.add_argument(\"png\", help=\"output png file\")\n ns = parser.parse_args()\n plot_csv(ns.csv, ns.png)\n","sub_path":"benchmark/plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"189770059","text":"#!/usr/bin/env python\n# ODE integration\n\n\nfrom numpy import exp, linspace\n\n\ndef integrate(f, T, steps, u0):\n \"\"\"Integrates function f(x) from 0 to T in steps with initial value u0\"\"\"\n h = T/float(steps)\n t = linspace(0, T, steps + 1)\n I = f(t[0])\n for k in range(1, steps):\n I += 2 * f(t[k])\n I += f(t[-1])\n I *= h / 2\n I += u0\n return I\n\n\ndef ftest(x):\n return x * exp(x**2)\n\n\ndef main():\n f0 = 0\n I = integrate(ftest, 2, 100, f0)\n print(\"Integral: {0}\".format(I))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SPP/ode.py","file_name":"ode.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"478023177","text":"# Import required packages\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom gym.utils import seeding\r\nimport gym\r\nfrom gym import spaces\r\n\r\n# Read and process the raw data set\r\ndata = pd.read_csv('D:/jiashi/adj_close.csv')\r\nstock_num = len(data.columns)-2\r\n\r\n# Replace NA stock price with 0\r\nnewdata = data.fillna(0)\r\n\r\n# Load the file for print the balance, reward and logging\r\noutput = open(\"D:/jiashi/balance.txt\", \"w+\")\r\nreward_file = open(\"D:/jiashi/reward.txt\", \"w+\")\r\nlogging = open(\"D:/jiashi/log.txt\", \"w+\")\r\nrender_file = open(\"D:/jiashi/render.txt\", \"w+\")\r\n\r\n# 252 trading days a year for 7 years of training, which include 2 years of validation.\r\n\r\ntraining_start = 0\r\ntraining_end = 252 * 7\r\ntraining_length = training_end - training_start\r\n\r\nvalidation_start = 252 * 5\r\nvalidation_end = 252 * 7\r\n\r\n# 2 years of test\r\ntest_start = 252 * 7\r\ntest_end = 252 * 9\r\ntest_length = test_end - test_start\r\n\r\ntrain_data = newdata.iloc[training_start:training_end,:]\r\n\r\nvalidation_data = newdata.iloc[validation_start:validation_end,:]\r\n\r\ntest_data = newdata.iloc[test_start:test_end,:]\r\n\r\n# Environment parameters\r\niteration = 0\r\nTRADE_THRESHOLD = 5 # buy or sell maximum 5 shares per time\r\nINITIAL_BALANCE = 1000000\r\nINITIAL_BASELINE = train_data['^GSPC'][0]\r\nTRADING_FEE = 0.0002 # the rate of trading fee per transaction\r\nINITIAL_TRADE = 7 # decrease the reward to day number / INITIAL_TRADE for first INITIAL_TRADE days\r\n\r\nclass StockEnv(gym.Env):\r\n metadata = {'render.modes': ['human']}\r\n\r\n def __init__(self, day = 0, money = INITIAL_BALANCE , scope = 1):\r\n self.day = day\r\n \r\n self.action_space = spaces.Box(low = np.array([-TRADE_THRESHOLD]*stock_num), \r\n high = np.array([TRADE_THRESHOLD]*stock_num),\r\n dtype=np.int8) \r\n\r\n # observation matrix:\r\n # obs_space[0:training_end+1,0] : total asset of day i before transaction\r\n # obs_space[1:training_end+1,1:506]1-505: price of SP 500 stocks every day\r\n # obs_space[1:training_end+1,506]: price of SP 500 index as the baseline\r\n # obs_space[0,1:506]: number of shares per stock at day i\r\n # Only record test_length days of observations\r\n self.observation_space = spaces.Box(low=0, high=np.inf, \r\n shape = (test_length+1,stock_num+2),\r\n dtype=np.float16)\r\n \r\n # Create the initial state\r\n temp = np.zeros([test_length+1,stock_num+2])\r\n temp[self.day+1,1:stock_num+2] = train_data.iloc[self.day, 1:stock_num+2]\r\n \r\n self.terminal = False\r\n \r\n self.state = temp\r\n self.reward = 0\r\n \r\n self.balance_memory = [INITIAL_BALANCE]\r\n\r\n self.reset()\r\n self._seed()\r\n\r\n\r\n def _transaction_stock(self, action):\r\n balance = self.balance_memory[self.day]\r\n \r\n \r\n for i in range(action.shape[0]):\r\n share = int(action[i])\r\n index = int(self.day) % int(test_length)\r\n # Sell the ith stock\r\n if share < 0:\r\n if self.state[0, i+1] > 0:\r\n # Calculate shares to sell\r\n sell = min(abs(share), self.state[0, i+1])\r\n \r\n # Update balance\r\n balance += self.state[index+1, i+1] * int(sell) * (1 - TRADING_FEE)\r\n \r\n # Update holdings\r\n self.state[0, i+1] -= int(sell)\r\n \r\n else:\r\n pass\r\n \r\n # Buy the ith stock\r\n elif share > 0:\r\n # Check the price of the stock\r\n if (self.state[index+1, i+1]==0):\r\n pass\r\n else:\r\n # Calculate shares to buy\r\n available_amount = balance // (self.state[index+1, i + 1] * (1 + TRADING_FEE))\r\n buy = int(min(share, available_amount))\r\n \r\n # Update balance\r\n balance -= self.state[index+1, i + 1]*buy*(1+TRADING_FEE)\r\n \r\n # Update holdings\r\n self.state[0, i+1] += buy\r\n \r\n # Hold\r\n else:\r\n pass\r\n self.balance_memory.append(balance)\r\n \r\n def step(self, action):\r\n # print(self.day)\r\n self.terminal = self.day >= training_length - 1\r\n # print(actions)\r\n\r\n if self.terminal:\r\n # print(self.state[:,0], file = output)\r\n return self.state, self.reward, self.terminal,{}\r\n\r\n else:\r\n \r\n # Do the transaction\r\n \r\n self._transaction_stock(action)\r\n \r\n \r\n self.day += 1\r\n \r\n \r\n \r\n if self.day < test_length:\r\n # Update price and total asset after the transaction\r\n self.state[self.day+1, 1:stock_num+2] = train_data.iloc[self.day, 1:stock_num+2] \r\n self.state[self.day+1, 0] = self.balance_memory[self.day] + np.sum(self.state[0, 1:stock_num+1]*self.state[self.day+1, 1:stock_num+1])\r\n \r\n # Calculate the reward: Annualized Sharpe Ratio\r\n sd = np.std((self.state[0:self.day+1, 0]-INITIAL_BALANCE)/INITIAL_BALANCE)\r\n earn = (self.state[self.day+1, 0] - INITIAL_BALANCE)/ INITIAL_BALANCE\r\n baseline = (self.state[self.day+1, stock_num+1] - INITIAL_BASELINE)/INITIAL_BASELINE\r\n \r\n if sd == 0:\r\n sharp = 0\r\n else:\r\n sharp = (earn - baseline) / sd * np.sqrt(255/self.day)\r\n \r\n if self.day <= INITIAL_TRADE:\r\n self.reward = sharp * self.day / INITIAL_TRADE\r\n else:\r\n self.reward = sharp\r\n \r\n else:\r\n index = int(self.day) % int(test_length)\r\n \r\n # Update price and total asset after the transaction\r\n self.state[index+1, 1:stock_num+2] = train_data.iloc[self.day, 1:stock_num+2] \r\n self.state[index+1, 0] = self.balance_memory[self.day] + np.sum(self.state[0, 1:stock_num+1]*self.state[index+1, 1:stock_num+1])\r\n \r\n # Calculate the reward: Annualized Sharpe Ratio\r\n sd = np.std((self.state[:, 0]-INITIAL_BALANCE)/INITIAL_BALANCE)\r\n earn = (self.state[index+1, 0] - INITIAL_BALANCE)/ INITIAL_BALANCE\r\n baseline = (self.state[index+1, stock_num+1] - INITIAL_BASELINE)/INITIAL_BASELINE\r\n \r\n self.reward = (earn - baseline) / sd * np.sqrt(255/test_length)\r\n \r\n print(\"{0}, {1}\".format(self.day, self.reward), file = reward_file)\r\n \r\n return self.state, self.reward, self.terminal, {}\r\n\r\n def reset(self):\r\n\r\n \r\n self.terminal = False\r\n \r\n self.reward = 0\r\n \r\n self.balance_memory = [INITIAL_BALANCE]\r\n \r\n self.day = 0\r\n # Create the initial state\r\n temp = np.zeros([test_length+1,stock_num+2])\r\n temp[self.day+1,1:stock_num+2] = train_data.iloc[self.day, 1:stock_num+2]\r\n self.state = temp\r\n \r\n return self.state\r\n \r\n def render(self, mode='human'):\r\n print(self.state[:,0], file = output)\r\n \r\n print(self.state[0, :], file = render_file)\r\n return self.state\r\n\r\n def _seed(self, seed=None):\r\n self.np_random, seed = seeding.np_random(seed)\r\n return [seed]\r\n ","sub_path":"stocks/stocks_env.py","file_name":"stocks_env.py","file_ext":"py","file_size_in_byte":7831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342756501","text":"#-*-coding:utf-8 -*-\n'''\n分析腰椎间盘突出患者住院费用的影响因素\n'''\n#-*-coding:utf-8 -*-\n'''\n病人一次住院费用影响因素分析\n'''\nimport numpy as np\nfrom sklearn import cross_validation, ensemble\n\n\ndef train(clf,x_train,y_train,x_test,y_test):\n clf.fit(x_train,y_train)\n result = clf.predict(x_test)\n print (result)\n\ndata=open(\"dataset/DataOfYZJPTC.csv\",'r')\nout=open(\"dataset/rf_result.txt\",'w+')\nkeys=[]\nvalues=[]\ntest=[]\n###按行读取训练集文件\nfor line in data:\n key=line.strip(\"\\n\").split(',')\n keys.append(key[1:17])\n values.append(key[17])\ntraining=np.array(keys)\ntraining_set=training.reshape(training.shape[0],16)\nlabel=np.array(values).ravel() ##只提取类标签\n\n####对训练集进行划分(7:3比例进行划分)\nx_train, x_test, y_train, y_test =cross_validation.train_test_split(\n training_set,label, test_size=0.3, random_state=0)\nrf_model= ensemble.RandomForestRegressor(n_estimators=90)\ntrain(rf_model,x_train,y_train,x_test,y_test)\nprint(rf_model.feature_importances_)","sub_path":"factor/factorOfYZJPTC.py","file_name":"factorOfYZJPTC.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"580257317","text":"#!/usr/bin/python3 \n# also works with python 2\n\n\"\"\"\n Lib for accessing ACDC CCH (API v2)\n\n (c) Copyright 2015 Tigran Avanesov, SnT, University of Luxembourg\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n\nimport sys\nimport os\nimport json\n\nPACKAGE_PARENT = '.'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlog = logging.getLogger(__file__)\n\nimport requests\n\nfrom urltoolz import *\n\n\nclass CCHv2:\n\n def __init__(self, apikey, scheme=\"https\", host = \"webservice.db.acdc-project.eu\", port=3000):\n\n self.session = requests.Session()\n\n # Disable ssl verification! TODO: remove from production\n self.session.verify = False\n\n self.baseurl = build_base_url(scheme, host, port) \n self.apikey = apikey\n self.apiv = \"v2\"\n\n self.session.headers.update({\n \"Authorization\" : 'Token token=\"%s\"'%self.apikey,\n \"Content-Type\" : \"application/json\",\n })\n\n def req(self, path=\"/\", data=None, headers = None, reqtype = 'get'):\n \"\"\" gets the data \"\"\"\n\n if headers is None: \n headers = {}\n if data is None: \n data = {}\n\n\n res = None\n try:\n r = None\n if reqtype == 'get': \n r = self.session.get(url_join(self.baseurl, 'api', self.apiv, path), headers = headers, data = data)\n elif reqtype == 'post': \n r = self.session.post(url_join(self.baseurl, 'api', self.apiv, path), headers = headers, data = json.dumps(data))\n else:\n log.error('Unsupported request type. Not implemented?')\n\n log.debug('Queried: %s', r.url)\n\n if r.status_code == 401:\n log.warning(\"Unauthorized: Your API key probably has no access for the requested data\")\n log.warning(\"Reason: %s\"%r.reason)\n else:\n r.raise_for_status()\n res = r.json()\n except Exception as e:\n log.error(\"Error getting data: %s\",e)\n finally:\n return res\n\n def submit_report(self, data):\n \"\"\" submits a report\n\n e.g. \n cchv2 = CCHv2(apikey=\"YOURKEY\")\n r = cchv2.submit_report(data = {\n 'report_category': 'eu.acdc.minimal', \n 'report_type' : 'Test v2',\n 'timestamp' : '2014-09-30T17:00:11+02:00', \n 'source_key': 'uri',\n 'source_value' : 'http://exit0.de',\n 'confidence_level': 0.11,\n 'version': 1,\n }\n )\n \"\"\"\n return self.req(path=\"reports\", data=data, reqtype = \"post\")\n\n def get_reports(self):\n \"\"\" get all reports submitted by the given api key (for the last x minutes, x = 15 usually) \"\"\"\n return self.req(path=\"reports\", reqtype = \"get\")\n\n def get_report(self, rep_id):\n \"\"\" get report with the given id (submitted for the last x minutes, x = 15 usually) \"\"\"\n return self.req(path=url_join(\"reports\", str(rep_id)), reqtype = \"get\")\n\n def get_reports_by_asn(self, asn):\n \"\"\" Gets reports for a given ASN (if allowed) \"\"\" \n \n sasn = str(asn)\n if not sasn.startswith('AS'):\n sasn = 'AS' + sasn\n\n return self.req(path=url_join('asns', sasn), reqtype = \"get\")\n\n\n def get_reports_by_ips(self, ips, incident = None):\n \"\"\" Gets reports for a given IP (if allowed) ;\n Can also specify the incident id?\"\"\" \n \n path = url_join('ips', ips)\n if incident is not None:\n path = url_join(path, str(incident))\n return self.req(path=path, reqtype = \"get\")\n\nif __name__ == \"__main__\":\n\n print(\"To try the library, please, see examples-v2.py\")\n\n","sub_path":"pyacdc_apiv2/apiv2.py","file_name":"apiv2.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"255367337","text":"import configparser\nimport os\nimport pathlib\nimport shutil\nimport sys\n\n\ndef install_gdsdiff() -> None:\n home = pathlib.Path.home()\n git_config_path = home / \".gitconfig\"\n git_attributes_path = home / \".gitattributes\"\n\n if git_config_path.exists():\n git_config_str = open(git_config_path).read()\n else:\n git_config_str = \"empty\"\n\n if git_attributes_path.exists():\n git_attributes_str = open(git_attributes_path).read()\n else:\n git_attributes_str = \"empty\"\n\n if \"gds_diff\" not in git_config_str:\n print(\"gdsdiff shows boolean differences in Klayout\")\n print(\"git diff FILE.GDS\")\n print(\"Appending the gdsdiff command to your ~/.gitconfig\")\n\n config = configparser.RawConfigParser()\n config.read(git_config_path)\n key = 'diff \"gds_diff\"'\n\n if key not in config.sections():\n config.add_section(key)\n config.set(key, \"command\", \"python -m gdsfactory.gdsdiff.gds_diff_git\")\n config.set(key, \"binary\", \"True\")\n\n with open(git_config_path, \"w+\") as f:\n config.write(f, space_around_delimiters=True)\n\n if \"gds_diff\" not in git_attributes_str:\n print(\"Appending the gdsdiff command to your ~/.gitattributes\")\n\n with open(git_attributes_path, \"a\") as f:\n f.write(\"*.gds diff=gds_diff\\n\")\n\n\ndef get_klayout_path() -> pathlib.Path:\n if sys.platform == \"win32\":\n klayout_folder = \"KLayout\"\n else:\n klayout_folder = \".klayout\"\n home = pathlib.Path.home()\n return home / klayout_folder\n\n\ndef install_klive() -> None:\n dest_folder = get_klayout_path() / \"pymacros\"\n dest_folder.mkdir(exist_ok=True, parents=True)\n cwd = pathlib.Path(__file__).resolve().parent\n src = cwd / \"klayout\" / \"pymacros\" / \"klive.lym\"\n dest = dest_folder / \"klive.lym\"\n\n if dest.exists():\n print(f\"removing klive already installed in {dest}\")\n os.remove(dest)\n\n shutil.copy(src, dest)\n print(f\"klive installed to {dest}\")\n\n\ndef copy(src: pathlib.Path, dest: pathlib.Path) -> None:\n \"\"\"overwrite file or directory\"\"\"\n dest_folder = dest.parent\n dest_folder.mkdir(exist_ok=True, parents=True)\n\n if dest.exists() or dest.is_symlink():\n print(f\"removing {dest} already installed\")\n if dest.is_dir():\n shutil.rmtree(dest)\n else:\n os.remove(dest)\n\n if src.is_dir():\n shutil.copytree(src, dest)\n else:\n shutil.copy(src, dest)\n print(f\"{src} copied to {dest}\")\n\n\ndef install_generic_tech() -> None:\n if sys.platform == \"win32\":\n klayout_folder = \"KLayout\"\n else:\n klayout_folder = \".klayout\"\n\n cwd = pathlib.Path(__file__).resolve().parent\n home = pathlib.Path.home()\n src = cwd / \"klayout\" / \"tech\"\n dest = home / klayout_folder / \"tech\" / \"generic\"\n\n copy(src, dest)\n\n src = cwd / \"klayout\" / \"drc\" / \"generic.lydrc\"\n dest = home / klayout_folder / \"drc\" / \"generic.lydrc\"\n copy(src, dest)\n\n\nif __name__ == \"__main__\":\n cwd = pathlib.Path(__file__).resolve().parent\n home = pathlib.Path.home()\n src = cwd / \"klayout\" / \"tech\"\n\n install_gdsdiff()\n install_klive()\n install_generic_tech()\n","sub_path":"gdsfactory/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213224730","text":"import RPi.GPIO as GPIO\nimport time\n\nboard = [\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]\n]\n\npins = [\n [\n [14, 8, 4],\n [18, 12, 27],\n [24, 20, 10]\n ],\n [\n [15, 7, 17],\n [23, 16, 22],\n [25, 21, 9]\n ]\n]\n\nallPins = [14, 8, 4, 18, 12, 27, 24, 20, 10, 15, 7, 17, 23, 16, 22, 25, 21, 9]\n\ndef displayBoard():\n row = 0\n while row <= 2:\n column = 0\n while column <= 2:\n if board[row][column] == 1:\n GPIO.output(pins[0][row][column], GPIO.HIGH)\n elif board[row][column] == 2:\n GPIO.output(pins[1][row][column], GPIO.HIGH)\n column += 1\n row += 1\n\ndef checkBoard():\n possibilities = [[ [i[0] for i in board], [i[1] for i in board], [i[2] for i in board] ], [i for i in board], [ [board[i][2 - i] for i in [0, 1, 2]], [board[i][i] for i in [0, 1, 2]] ]]\n x = False\n for possibility in possibilities:\n for thingy in possibility:\n if thingy[0] == thingy[1] == thingy[2] and thingy[0] != 0 and thingy[1] != 0 and thingy[2] != 0:\n return \"Player %i has won the game!\" % (thingy[0])\n x = True\n if not x: return False\n \n\ndef makeMove(player):\n row = int(input(\"Player %i, choose a row (1 - 3): \" % (player)))\n column = int(input(\"Player %i, choose a column (1 - 3): \" % (player)))\n if board[row - 1][column - 1] != 0:\n print(\"Spot is already taken\")\n makeMove(player)\n board[row - 1][column - 1] = player\n displayBoard()\n\ndef game():\n start = input(\"Would you like to start a new game (y/n)? \")\n if start == \"y\" or start == \"yes\":\n for i in allPins:\n GPIO.setup(i, GPIO.OUT)\n GPIO.output(i, GPIO.LOW)\n print(\"Player 1 is Blue\\nPlayer 2 is Red\\nLet's Begin!\\n\")\n for i in range(9):\n makeMove(1)\n a = checkBoard()\n if a:\n print(a)\n break\n makeMove(2)\n a = checkBoard()\n if a:\n print(a)\n break\n else:\n print(\"Goodbye then!\")\n\nif __name__ == \"__main__\":\n game()","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"634615835","text":"import sqlite3\r\n\r\ndbase = sqlite3.connect('library.db')\r\n\r\nprint('Database is opened')\r\n\r\n\"\"\"dbase.execute(''' CREATE TABLE bookctg(\r\nBOOKCATEGORYID INT PRIMARY KEY NOT NULL,\r\nCATEGORYNAME TEXT NOT NULL)''')\r\n\r\ndbase.execute(''' CREATE TABLE books(\r\nBOOKID INT PRIMARY KEY NOT NULL,\r\nBOOKNAME TEXT NOT NULL,\r\nBOOKAUTHOR TEXT NOT NULL,\r\nBOOKPUBLISHER TEXT NOT NULL,\r\nBOOKPAGE INT NOT NULL,\r\nFOREIGN KEY(USERID) REFERENCES user(USERID))''')\r\n\r\n\r\n\r\n\r\ndbase.execute(''' CREATE TABLE user(\r\nUSERID INT PRIMARY KEY NOT NULL,\r\nUSERNAME TEXT NOT NULL,\r\nUSERSURNAME TEXT NOT NULL,\r\nPHONENUMBER CHAR(11) NOT NULL,\r\nUSERLOGINNAME VARCHAR(15) NOT NULL,\r\nPASSWORD INT NOT NULL,\r\nBOOKID INT\r\n''')\r\n\r\n\r\ndbase.execute(''' CREATE TABLE admin(\r\nADMINID INT PRIMARY KEY NOT NULL,\r\nADMINUSERNAME VARCHAR(15) NOT NULL,\r\nADMINPASS INT NOT NULL) \r\n''')\r\n\r\n\r\ndbase.execute(''' CREATE TABLE borrow( #borrow \r\nISSUEID INT PRIMARY KEY NOT NULL,\r\nUSERID INT NOT NULL,\r\nBOOKID INT NOT NULL,\r\nISSUEDATE VARCHAR(50) NOT NULL,\r\nRETURNDATE VARCHAR(50) NOT NULL,\r\nBORROW INT NOT NULL,\r\nFOREIGN KEY(USERID) REFERENCES user(USERID),\r\nFOREIGN KEY(BOOKID) REFERENCES books(BOOKID))\r\n''')\r\n\r\n\r\n\"\"\"\r\n\r\n#dbase.execute(\"\"\"INSERT INTO books VALUES(?,?,?,?,?,?,?,?) \"\"\",('1','Rüzgarın Adı','Jack', 'Pegasus', '450','1','','') )\r\n\r\ndbase.execute(''' INSERT INTO user VALUES(?,?,?,?,?,?,?)''',('2','Elif','Yilmaz', '05340330927','elifyilmaz','123456','3'))\r\n#dbase.commit()\r\n\r\n#dbase.execute(\"\"\" INSERT INTO admin VALUES(?,?,?)\"\"\", ('1','elif','12305'))\r\n#dbase.commit()\r\n\r\n\r\n#dbase.execute(\"\"\" ALTER TABLE user ADD BOOKID int \"\"\")\r\n\r\n#dbase.execute(\"\"\" ALTER TABLE user ADD BOOKNAME varchar(30) \"\"\")\r\n#dbase.execute(\"\"\"ALTER TABLE books ADD BORROWUSERID int \"\"\")\r\n#dbase.execute(\"\"\" ALTER TABLE books ADD BORROWUSERNAME varchar(30) \"\"\")\r\n\r\n#dbase.execute(\"\"\" DROP TABLE user \"\"\")\r\n\r\n#dbase.execute(\"\"\"INSERT INTO books VALUES(?,?,?,?,?,?,?) \"\"\",('1','Rüzgarın Adı','Jack', 'Pegasus', '450','','') )\r\n#dbase.execute(\"\"\"INSERT INTO issuereturn VALUES(?,?,?,?,?,?) \"\"\",('1','5','9', '8','','') )\r\n\r\n#dbase.execute(''' ALTER TABLE issuereturn RENAME TO borrow''')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndbase.commit()\r\n\r\ndbase.close()","sub_path":"dbbagla.py","file_name":"dbbagla.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"420863865","text":"import tkinter\r\nimport re\r\n# from simpleeval import simple_eval\r\n\r\nBUTTON_HEIGHT = 3\r\nBUTTON_WIDTH = 5\r\nFONT_SIZE = 10\r\nSIGNS = ['*', '/', '+', '-']\r\nthere_is_dot = False\r\n\r\n\r\ndef number_entry(event):\r\n if text.get() == 'nan':\r\n clear()\r\n\r\n new_text = text.get()\r\n\r\n new_text += event.widget['text']\r\n\r\n text.set(new_text)\r\n\r\n\r\ndef sign_entry(event):\r\n global there_is_dot\r\n\r\n new_text = text.get()\r\n\r\n if not new_text and event.widget['text'] == '-':\r\n pass\r\n elif not new_text or new_text[-1] in SIGNS: # re.match(r'\\+|-|\\*|\\\\', new_text[-1])\r\n return\r\n\r\n new_text += event.widget['text']\r\n text.set(new_text)\r\n # is_dot = not is_dot\r\n there_is_dot = False\r\n\r\n\r\ndef remove_zeros(exp):\r\n pattern = r'(\\d+|[^ 0-9])'\r\n lst = re.split(pattern, exp)\r\n result = ''\r\n\r\n for element in lst:\r\n result += element.lstrip('0')\r\n\r\n return result\r\n\r\n\r\ndef evaluate():\r\n\r\n new_text = remove_zeros(text.get())\r\n\r\n # try:\r\n # result = simple_eval(new_text)\r\n # text.set(result)\r\n #\r\n # except ZeroDivisionError:\r\n # text.set('nan')\r\n # except SyntaxError:\r\n # return\r\n try:\r\n result = eval(new_text)\r\n text.set(result)\r\n except ZeroDivisionError:\r\n text.set('nan')\r\n except SyntaxError:\r\n return\r\n\r\n\r\ndef backspace():\r\n global there_is_dot\r\n\r\n new_text = text.get()\r\n\r\n if new_text[-1] in SIGNS:\r\n there_is_dot = True\r\n\r\n new_text = new_text[:-1]\r\n text.set(new_text)\r\n\r\n\r\ndef clear():\r\n text.set('')\r\n\r\n\r\ndef dot(event):\r\n global there_is_dot\r\n\r\n if there_is_dot:\r\n return\r\n print(event.widget['text'])\r\n new_text = text.get()\r\n\r\n new_text += event.widget['text']\r\n text.set(new_text)\r\n there_is_dot = True\r\n\r\n\r\nmain_window = tkinter.Tk()\r\nmain_window.title('Calculator')\r\nmain_window.geometry('360x480')\r\nmain_window.configure(background='#cbd6d6')\r\nmain_window.resizable(width=False, height=False)\r\ntext = tkinter.StringVar()\r\ndisplay = tkinter.Entry(main_window, width=40, textvariable=text, state='readonly') # demonstrate eval problems\r\ndisplay.grid(row=0, column=0, columnspan=3, sticky='e')\r\n\r\nbuttons = {}\r\nplacement = ['en', 'n', 'wn']\r\n\r\nfor i in range(9, -1, -1):\r\n buttons[f'button_{i}'] = tkinter.Button(main_window, font=(\"Helvetica\", FONT_SIZE), text=f'{i}', height=BUTTON_HEIGHT, width=BUTTON_WIDTH)\r\n buttons[f'button_{i}'].grid(row=i // 3 + 1, column=i % 3, sticky='n')\r\n\r\nfor button in buttons.values():\r\n button.bind('', lambda event: number_entry(event))\r\n\r\nplus_button = tkinter.Button(main_window, text='+', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH)\r\nplus_button.grid(column=3, row=1, sticky='n')\r\nplus_button.bind('', lambda event: sign_entry(event))\r\n\r\nminus_button = tkinter.Button(main_window, text='-', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH)\r\nminus_button.grid(column=3, row=2, sticky='n')\r\nminus_button.bind('', lambda event: sign_entry(event))\r\n\r\nmult_button = tkinter.Button(main_window, text='*', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH)\r\nmult_button.grid(column=3, row=3, sticky='n')\r\nmult_button.bind('', lambda event: sign_entry(event))\r\n\r\ndiv_button = tkinter.Button(main_window, text='/', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH)\r\ndiv_button.grid(column=3, row=4, sticky='n')\r\ndiv_button.bind('', lambda event: sign_entry(event))\r\n\r\nequal_button = tkinter.Button(main_window, text='=', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH, command=evaluate)\r\nequal_button.grid(column=2, row=4, sticky='n')\r\n\r\nclear_button = tkinter.Button(main_window, text='C', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH, command=clear)\r\nclear_button.grid(column=1, row=4, sticky='n')\r\n\r\nbackspace_button = tkinter.Button(main_window, text='<-', font=(\"Helvetica\", FONT_SIZE), height=1, width=2, command=backspace)\r\nbackspace_button.grid(column=3, row=0, sticky='e')\r\n\r\ndot_button = tkinter.Button(main_window, text='.', font=(\"Helvetica\", FONT_SIZE), height=BUTTON_HEIGHT, width=BUTTON_WIDTH)\r\ndot_button.grid(row=5, column=1, columnspan=2)\r\ndot_button.bind('', lambda event: dot(event))\r\n\r\n\r\nmain_window.rowconfigure(0, weight=1)\r\nmain_window.rowconfigure(1, weight=1)\r\nmain_window.rowconfigure(2, weight=1)\r\nmain_window.rowconfigure(3, weight=1)\r\nmain_window.rowconfigure(4, weight=1)\r\nmain_window.rowconfigure(5, weight=1)\r\n\r\nmain_window.columnconfigure(0, weight=1)\r\nmain_window.columnconfigure(1, weight=1)\r\nmain_window.columnconfigure(2, weight=1)\r\nmain_window.columnconfigure(3, weight=1)\r\n\r\n\r\nmain_window.mainloop()\r\n\r\n# tkinter.Scrollbar\r\n# tkinter.Listbox\r\n","sub_path":"Practical exercises/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":4835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"117690698","text":"\nfrom collections import OrderedDict\nfrom math import floor\n\nfrom numpy.testing.utils import assert_almost_equal\nfrom scipy.ndimage.filters import gaussian_filter\nfrom scipy.stats import multivariate_normal, entropy\n\nfrom duckietown_msgs.msg import SegmentList\nimport duckietown_utils as dtu\n\nfrom duckietown_utils.parameters import Configurable\n\nimport numpy as np\n\nfrom .lane_filter_interface import LaneFilterInterface\n\nfrom scipy.stats import multivariate_normal\nfrom scipy.ndimage.filters import gaussian_filter\nfrom math import floor, sqrt\nimport copy\n\nimport rospy\n\ndef wrap(angle):\n \"\"\"Takes in any angle (in radians), and expresses it inside the [-np.pi, np.pi] range.\n \n Arguments:\n angle {float} -- An angle in radians\n \n Returns:\n float -- The angle projected within the range (-np.pi, np.pi]\n \"\"\"\n two_pi = 2 * np.pi\n angle %= two_pi\n if angle < 0:\n angle += two_pi\n # angle is now inside [0, 2pi]\n if angle > np.pi:\n angle -= two_pi\n assert (- np.pi) < angle <= np.pi\n return angle\n\ndef R(theta):\n return np.array([\n [np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)],\n ])\n\n\n\n\ndef cos_and_sin(x):\n return np.array([\n np.cos(x),\n np.sin(x),\n ])\n\n\ndef TR(theta_rad, Ax, Ay):\n return np.array([\n [np.cos(theta_rad), -np.sin(theta_rad), Ax],\n [np.sin(theta_rad), np.cos(theta_rad), Ay],\n [0, 0, 1],\n ])\n\n\nclass LaneFitlerParticle(Configurable, LaneFilterInterface):\n\n class Particle():\n def __init__(self, d, phi, config):\n self.d = d\n self.phi = phi\n self.weight = 1\n\n self.d_max = config['d_max']\n self.d_min = config['d_min']\n self.phi_max = config['phi_max']\n self.phi_min = config['phi_min']\n self.sigma_d = config['sigma_d']\n self.sigma_phi = config['sigma_phi']\n\n def predict(self, dt, v, w):\n \"\"\"update d and phi depending on dt, v and w\n \n Arguments:\n dt {float} -- [the time delay elapsed since the last prediction.]\n v {[type]} -- [the commanded linear (tangential) velocity of the robot]\n w {[type]} -- [the commanded angular velocity of the robot]\n \n lets's consider the displacement with respect to the previous position:\n ^(x)\n (y) |\n <----|\n \n \n The displacement is (y, x), with:\n - X is the displacement in direction parallel to the lane\n - Y is the displacement in the direction perpendicular to the lane.\n \n \"\"\"\n # DT bug.\n dt *= 0.15\n\n if w == 0:\n # going in a straight line.\n displacement = dt * v * cos_and_sin(self.phi)\n # d is displaced in 'y', and phi stays the same.\n self.d += displacement[1]\n else:\n # calculate the displacement due to omega\n angle_performed_along_arc = dt * w\n tangential_velocity = v\n angular_velocity = w\n radius_of_curvature = np.abs(tangential_velocity / angular_velocity)\n\n # get the projections of the distance traveled relative to current heading phi.\n dx = radius_of_curvature * np.sin(angle_performed_along_arc)\n dy = radius_of_curvature * (1 - np.cos(angle_performed_along_arc))\n \n \n # This displacement is in the frame with heading phi though.\n # Therefore we need to correct for that as well by rotating it by -phi.\n rotation = R(-self.phi)\n displacement = np.matmul(np.array([dy, dx]), rotation)\n \n # The orientation changed since we moved along the arc.\n # It can easily be shown that the change in phi due to the arc motion\n # is equal to the angle performed along the arc.\n change_in_phi = angle_performed_along_arc\n self.phi += change_in_phi\n self.d += displacement[1]\n\n self.d += np.random.normal(0, self.sigma_d)\n self.phi += np.random.normal(0, self.sigma_phi)\n\n # We clip d and phi to stay within the desired maximal range\n self.d = np.clip(self.d, self.d_min, self.d_max)\n self.phi = np.clip(self.phi, self.phi_min, self.phi_max)\n\n def update(self, ds, phis):\n # Change weight depending on the likelihood of ds and phis from the measurements\n\n ########\n # Your code here\n # TODO: How can you estimate the likelihood of the measurements given this particular particle?\n # Here, the d and phi values for a given segment can be recovered using function self.process(segment).\n # Suggestion: remember how it was done in the histogram filter.\n # Maybe you can compute a distance from your particle to each measured pair of (d,phi)\n # and compute a score based on the quantity of pairs that is not further than a given threshold? Other ideas are welcome too!\n ########\n average_distance = 0\n if len(ds) > 0 and len(phis) > 0: \n normalized_d_distances = ((ds - self.d) / (self.d_max - self.d_min)) ** 2\n normalized_phi_distances = ((phis - self.phi) / (self.phi_max - self.phi_min)) ** 2\n # this is the normalized average distance (between 0 and 1)\n average_distance = np.mean(normalized_d_distances + normalized_phi_distances) / 2\n self.weight = 1 - average_distance\n\n def perturb(self, dd, dphi):\n self.d += dd\n self.phi += dphi\n # We clip d and phi to stay within the desired maximal range\n self.d = np.clip(self.d, self.d_min, self.d_max)\n self.phi = np.clip(self.phi, self.phi_min, self.phi_max)\n\n\n def __init__(self):\n # Parameters\n self.nb_particles = 500\n\n ## Initialization \n self.mean_d_0 = 0 # Expected value of d at initialization\n self.mean_phi_0 = 0 # Expected value of phi at initialization\n self.sigma_d_0 = 0.1 # Standard deviation of d at initialization\n self.sigma_phi_0 = 0.1 # Standard deviation of phi at initialization\n\n ## Prediction step noise\n self.sigma_d = 0.010 # 0.001\n self.sigma_phi = 0.010 # 0.002\n\n ## Roughening\n self.rough_d = 0.010 # 0.001\n self.rough_phi = 0.020 # 0.002\n\n ## Environment parameters\n self.linewidth_white = 0.05\n self.linewidth_yellow = 0.025\n self.lanewidth = 0.23\n\n ## Limits\n self.d_max = 0.3 \n self.d_min = -0.15\n self.phi_min = -1.5\n self.phi_max = 1.5\n self.range_est = 0.33 # Maximum distance for a segment to be considered\n self.delta_d = 0.02 # Maximum error on d for a segment to be considered as an inlier\n self.delta_phi = 0.1 # Maximum error on phi for a segment to be considered as an inlier\n self.min_max = 0.1 # Minimum maximal weight \n\n # Attributes\n self.particles = []\n self.particle_config = {\n 'd_max': self.d_max,\n 'd_min': self.d_min,\n 'phi_max': self.phi_max,\n 'phi_min': self.phi_min, \n 'sigma_d': self.sigma_d, \n 'sigma_phi': self.sigma_phi, \n }\n\n # Initialization\n self.initialize()\n\n def initialize(self):\n # Initialize the particle filter\n initial_particles = []\n\n # Parameters to be passed\n config = self.particle_config\n\n ds = np.random.uniform(self.d_min, self.d_max, size=self.nb_particles)\n phis = np.random.uniform(self.phi_min, self.phi_max, size=self.nb_particles)\n for i in range(self.nb_particles):\n d = 0\n phi = 0\n\n ########\n # Your code here\n # TODO: Initialize the particle set using a given distribution.\n # You can use the initialization parameters.\n # Would sampling from a Gaussian distribution be a good idea?\n # Could you also want to sample from an uniform distribution, in order to be able to recover from an initial state that is far from the Gaussian center?\n ########\n initial_particles.append(self.Particle(ds[i], phis[i], config))\n self.particles = initial_particles\n\n def predict(self, dt, v, w):\n # Prediction step for the particle filter\n for particle in self.particles:\n particle.predict(dt, v, w)\n\n def update(self, segment_list):\n # Measurement update state for the particle filter\n segmentArray = self.prepareSegments(segment_list)\n self.updateWeights(segment_list)\n self.resample()\n self.roughen()\n\n def updateWeights(self, segment_list):\n ds = []\n phis = []\n # Compute the ds and phis from the segments\n for segment in segment_list:\n d, phi, _ = self.process(segment)\n ds.append(d)\n phis.append(phi)\n # Update the particle weights\n for particle in self.particles:\n particle.update(ds, phis) \n \n def resample(self):\n # Sample a new set of particles\n weights = np.array([p.weight for p in self.particles], dtype=np.float32)\n # for some reason, we sometiems start with negative weights? \n weights -= np.min(weights)\n if np.sum(weights) == 0:\n # sometimes weights is all zeroes, for some reason.\n # In this case, I guess we set the weights as all equal:\n weights = np.ones_like(weights, dtype=np.float32) \n probabilities = weights / np.sum(weights)\n \n assert np.all(probabilities >= 0), probabilities\n assert np.isclose(np.sum(probabilities), 1.0), probabilities\n # print(\"probabilities:\", probabilities)\n indices_to_keep = np.random.choice(self.nb_particles, size=self.nb_particles, p=probabilities)\n\n indices_kept = set()\n new_particles = []\n for index in indices_to_keep:\n particle = self.particles[index]\n\n if index in indices_kept:\n # if we already have this particle, make a new copy:\n particle = self.Particle(particle.d, particle.phi, self.particle_config)\n new_particles.append(particle)\n else:\n # if we haven't sampled this particle already, just add it:\n new_particles.append(particle)\n indices_kept.add(index)\n self.particles = new_particles\n\n def roughen(self):\n # Roughen the particles set to avoid sample impoverishment\n for particle in self.particles:\n dd = np.random.normal(loc = 0.0, scale = self.rough_d)\n dphi = np.random.normal(loc = 0.0, scale = self.rough_phi)\n particle.perturb(dd, dphi)\n\n def getEstimate(self):\n # Get the estimate of d and phi\n d = 0\n phi = 0\n ########\n # Your code here\n # TODO: What is the best way to give an estimate of the state given a set of particles?\n # Would it be a random sampling? An average? Putting them in bins and chosing the most populated one?\n ########\n\n # Here we perform a weighted average of the particles.\n ds = np.array([p.d for p in self.particles])\n phis = np.array([p.phi for p in self.particles])\n weights = np.array([p.weight for p in self.particles])\n weights /= np.sum(weights)\n\n d = np.dot(weights, ds)\n phi = np.dot(weights, phis)\n\n # print(\"Estimate: d:\", d, \" phi:\", phi)\n return [d, phi]\n\n \n def isInLane(self):\n # Test to know if the bot is in the lane\n ########\n # Your code here\n # TODO: Remember the way the histogram filter was determining if the robot is or is not in the lane.\n # What was the idea behind it? How could this be applied to a particle filter?\n ########\n return max(p.weight for p in self.particles) > self.min_max\n\n### Other functions - no modification needed ###\n def process(self, segment):\n # Returns d_i the distance from the middle of the lane\n # phi_i the angle from the lane direction\n # l_i the distance from the bot in perpendicular projection\n p1 = np.array([segment.points[0].x, segment.points[0].y])\n p2 = np.array([segment.points[1].x, segment.points[1].y])\n t_hat = (p2 - p1) / np.linalg.norm(p2 - p1)\n\n n_hat = np.array([-t_hat[1], t_hat[0]])\n d1 = np.inner(n_hat, p1)\n d2 = np.inner(n_hat, p2)\n l1 = np.inner(t_hat, p1)\n l2 = np.inner(t_hat, p2)\n if (l1 < 0):\n l1 = -l1\n if (l2 < 0):\n l2 = -l2\n\n l_i = (l1 + l2) / 2\n d_i = (d1 + d2) / 2\n phi_i = np.arcsin(t_hat[1])\n if segment.color == segment.WHITE: # right lane is white\n if(p1[0] > p2[0]): # right edge of white lane\n d_i = d_i - self.linewidth_white\n else: # left edge of white lane\n d_i = - d_i\n phi_i = -phi_i\n d_i = d_i - self.lanewidth / 2\n\n elif segment.color == segment.YELLOW: # left lane is yellow\n if (p2[0] > p1[0]): # left edge of yellow lane\n d_i = d_i - self.linewidth_yellow\n phi_i = -phi_i\n else: # right edge of white lane\n d_i = -d_i\n d_i = self.lanewidth / 2 - d_i\n\n return d_i, phi_i, l_i\n\n def getStatus(self):\n return LaneFilterInterface.GOOD\n\n def get_inlier_segments(self, segments, d, phi):\n inlier_segments = []\n for segment in segments:\n d_s, phi_s, l = self.process(segment)\n if abs(d_s - d) < self.delta_d and abs(phi_s - phi) self.range_est:\n continue\n else:\n segmentsRangeArray.append(segment)\n return segmentsRangeArray\n\n def getSegmentDistance(self, segment):\n x_c = (segment.points[0].x + segment.points[1].x) / 2\n y_c = (segment.points[0].y + segment.points[1].y) / 2\n return sqrt(x_c**2 + y_c**2)\n\n def getBeliefArray(self):\n # Returns the representation of the belief as an array (for visualization purposes)\n ds, phis = np.mgrid[self.d_min:self.d_max:self.delta_d, self.phi_min:self.phi_max:self.delta_phi]\n beliefArray = np.zeros(ds.shape)\n # Image of the particle set\n for particle in self.particles:\n d_i = particle.d\n phi_i = particle.phi\n # if the vote lands outside of the histogram discard it\n if d_i > self.d_max or d_i < self.d_min or phi_i < self.phi_min or phi_i > self.phi_max:\n continue\n \n i = int(floor((d_i - self.d_min) / self.delta_d))\n j = int(floor((phi_i - self.phi_min) / self.delta_phi))\n\n if i == beliefArray.shape[0]:\n i -= 1\n if j == beliefArray.shape[1]:\n j -= 1\n\n beliefArray[i, j] = beliefArray[i, j] + 1 \n\n if np.linalg.norm(beliefArray) == 0:\n return beliefArray\n beliefArray = beliefArray / np.sum(beliefArray)\n return beliefArray\n \n\nclass LaneFilterHistogram(Configurable, LaneFilterInterface):\n #\"\"\"LaneFilterHistogram\"\"\"\n\n def __init__(self, configuration):\n param_names = [\n 'mean_d_0',\n 'mean_phi_0',\n 'sigma_d_0',\n 'sigma_phi_0',\n 'delta_d',\n 'delta_phi',\n 'd_max',\n 'd_min',\n 'phi_max',\n 'phi_min',\n 'cov_v',\n 'linewidth_white',\n 'linewidth_yellow',\n 'lanewidth',\n 'min_max',\n 'sigma_d_mask',\n 'sigma_phi_mask',\n 'curvature_res',\n 'range_min',\n 'range_est',\n 'range_max',\n 'curvature_right',\n 'curvature_left',\n ]\n\n configuration = copy.deepcopy(configuration)\n Configurable.__init__(self, param_names, configuration)\n\n self.d, self.phi = np.mgrid[self.d_min:self.d_max:self.delta_d,\n self.phi_min:self.phi_max:self.delta_phi]\n self.d_pcolor, self.phi_pcolor = \\\n np.mgrid[self.d_min:(self.d_max + self.delta_d):self.delta_d,\n self.phi_min:(self.phi_max + self.delta_phi):self.delta_phi]\n\n self.beliefArray = np.empty(self.d.shape)\n self.range_arr = np.zeros(1)\n self.mean_0 = [self.mean_d_0, self.mean_phi_0]\n self.cov_0 = [[self.sigma_d_0, 0], [0, self.sigma_phi_0]]\n self.cov_mask = [self.sigma_d_mask, self.sigma_phi_mask]\n\n self.d_med_arr = []\n self.phi_med_arr = []\n self.median_filter_size = 5\n\n self.initialize()\n self.updateRangeArray()\n\n # Additional variables\n self.red_to_white = False\n self.use_yellow = True\n self.range_est_min = 0\n self.filtered_segments = []\n\n def getStatus(self):\n return LaneFilterInterface.GOOD\n\n def predict(self, dt, v, w):\n delta_t = dt\n d_t = self.d + v * delta_t * np.sin(self.phi)\n phi_t = self.phi + w * delta_t\n p_belief = np.zeros(self.beliefArray.shape)\n\n for i in range(self.beliefArray.shape[0]):\n for j in range(self.beliefArray.shape[1]):\n if self.beliefArray[i, j] > 0:\n if d_t[i, j] > self.d_max or d_t[i, j] < self.d_min or phi_t[i, j] < self.phi_min or phi_t[i, j] > self.phi_max:\n continue\n i_new = int(\n floor((d_t[i, j] - self.d_min) / self.delta_d))\n j_new = int(\n floor((phi_t[i, j] - self.phi_min) / self.delta_phi))\n p_belief[i_new, j_new] += self.beliefArray[i, j]\n s_belief = np.zeros(self.beliefArray.shape)\n gaussian_filter(p_belief, self.cov_mask,\n output=s_belief, mode='constant')\n\n if np.sum(s_belief) == 0:\n return\n self.beliefArray = s_belief / np.sum(s_belief)\n\n # prepare the segments for the creation of the belief arrays\n def prepareSegments(self, segments):\n segmentsRangeArray = []\n self.filtered_segments = []\n for segment in segments:\n # Optional transform from RED to WHITE\n if self.red_to_white and segment.color == segment.RED:\n segment.color = segment.WHITE\n\n # Optional filtering out YELLOW\n if not self.use_yellow and segment.color == segment.YELLOW: continue\n\n # we don't care about RED ones for now\n if segment.color != segment.WHITE and segment.color != segment.YELLOW:\n continue\n # filter out any segments that are behind us\n if segment.points[0].x < 0 or segment.points[1].x < 0:\n continue\n\n self.filtered_segments.append(segment)\n # only consider points in a certain range from the Duckiebot for the position estimation\n point_range = self.getSegmentDistance(segment)\n if point_range < self.range_est and point_range > self.range_est_min:\n segmentsRangeArray.append(segment)\n\n return segmentsRangeArray\n\n def updateRangeArray(self):\n self.beliefArray = np.empty(self.d.shape)\n self.initialize()\n\n # generate the belief arrays\n def update(self, segments):\n # prepare the segments for each belief array\n segmentsRangeArray = self.prepareSegments(segments)\n # generate all belief arrays\n measurement_likelihood = self.generate_measurement_likelihood(segmentsRangeArray)\n\n if measurement_likelihood is not None:\n self.beliefArray = np.multiply(self.beliefArray, measurement_likelihood)\n if np.sum(self.beliefArray) == 0:\n self.beliefArray = measurement_likelihood\n else:\n self.beliefArray = self.beliefArray / np.sum(self.beliefArray)\n\n def generate_measurement_likelihood(self, segments):\n # initialize measurement likelihood to all zeros\n measurement_likelihood = np.zeros(self.d.shape)\n for segment in segments:\n d_i, phi_i, l_i = self.generateVote(segment)\n # if the vote lands outside of the histogram discard it\n if d_i > self.d_max or d_i < self.d_min or phi_i < self.phi_min or phi_i > self.phi_max:\n continue\n i = int(floor((d_i - self.d_min) / self.delta_d))\n j = int(floor((phi_i - self.phi_min) / self.delta_phi))\n measurement_likelihood[i, j] += 1\n if np.linalg.norm(measurement_likelihood) == 0:\n return None\n measurement_likelihood = measurement_likelihood / np.sum(measurement_likelihood)\n return measurement_likelihood\n\n # get the maximal values d_max and phi_max from the belief array. \n def getEstimate(self):\n maxids = np.unravel_index(self.beliefArray.argmax(), self.beliefArray.shape)\n d_max = self.d_min + (maxids[0] + 0.5) * self.delta_d\n phi_max = self.phi_min + (maxids[1] + 0.5) * self.delta_phi\n return [d_max, phi_max]\n\n def get_estimate(self):\n d, phi = self.getEstimate()\n res = OrderedDict()\n res['d'] = d\n res['phi'] = phi\n return res\n\n # return the maximal value of the beliefArray\n def getMax(self):\n return self.beliefArray.max()\n\n def isInLane(self):\n return self.getMax() > self.min_max\n\n def initialize(self):\n pos = np.empty(self.d.shape + (2,))\n pos[:, :, 0] = self.d\n pos[:, :, 1] = self.phi\n self.cov_0\n RV = multivariate_normal(self.mean_0, self.cov_0)\n self.beliefArray = RV.pdf(pos)\n\n # generate a vote for one segment\n def generateVote(self, segment):\n p1 = np.array([segment.points[0].x, segment.points[0].y])\n p2 = np.array([segment.points[1].x, segment.points[1].y])\n t_hat = (p2 - p1) / np.linalg.norm(p2 - p1)\n n_hat = np.array([-t_hat[1], t_hat[0]])\n d1 = np.inner(n_hat, p1)\n d2 = np.inner(n_hat, p2)\n l1 = np.inner(t_hat, p1)\n l2 = np.inner(t_hat, p2)\n if (l1 < 0):\n l1 = -l1\n if (l2 < 0):\n l2 = -l2\n l_i = (l1 + l2) / 2\n d_i = (d1 + d2) / 2\n phi_i = np.arcsin(t_hat[1])\n if segment.color == segment.WHITE: # right lane is white\n if(p1[0] > p2[0]): # right edge of white lane\n d_i = d_i - self.linewidth_white\n else: # left edge of white lane\n d_i = - d_i\n phi_i = -phi_i\n d_i = d_i - self.lanewidth / 2\n elif segment.color == segment.YELLOW: # left lane is yellow\n if (p2[0] > p1[0]): # left edge of yellow lane\n d_i = d_i - self.linewidth_yellow\n phi_i = -phi_i\n else: # right edge of white lane\n d_i = -d_i\n d_i = self.lanewidth / 2 - d_i\n return d_i, phi_i, l_i\n\n def get_inlier_segments(self, segments, d_max, phi_max):\n inlier_segments = []\n for segment in segments:\n d_s, phi_s, l = self.generateVote(segment)\n if abs(d_s - d_max) < self.delta_d and abs(phi_s - phi_max)= 3.12 must be installed to build the following extensions: \" +\n \", \".join(e.name for e in self.extensions))\n\n # if platform.system() == \"Windows\":\n # cmake_version = LooseVersion(re.search(r'version\\s*([\\d.]+)',\n # out.decode()).group(1))\n # if cmake_version < '3.12.0':\n # raise RuntimeError(\"Cmake >= 3.12.0 is required\")\n\n for ext in self.extensions:\n self.build_extension(ext)\n\n def build_extension(self, ext):\n extdir = os.path.abspath(\n os.path.dirname(self.get_ext_fullpath(ext.name)))\n cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir]\n cfg = 'Debug' if self.debug else 'Release'\n build_args = ['--config', cfg]\n\n if platform.system() == \"Windows\":\n cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(\n cfg.upper(),\n extdir)]\n if sys.maxsize > 2**32:\n cmake_args += ['-A', 'x64']\n build_args += ['--', '/m']\n else:\n cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]\n build_args += ['--', '-j2']\n\n env = os.environ.copy()\n env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(\n env.get('CXXFLAGS', ''),\n self.distribution.get_version())\n if not os.path.exists(self.build_temp):\n os.makedirs(self.build_temp)\n subprocess.check_call(['cmake', ext.sourcedir] + cmake_args,\n cwd=self.build_temp, env=env)\n subprocess.check_call(['cmake', '--build', '.', '--target', 'python'] + build_args,\n cwd=self.build_temp)\n print() # add an empty line to pretty print\n\nsetup(\n name='datasketches',\n version='0.0.1',\n author='Jon Malkin',\n author_email='jon.malkin@yahoo.com',\n description='A wrapper for the C++ Datasketches library',\n long_description='',\n # tell setuptools to look for any packages under 'python/src'\n packages=find_packages('python/src'),\n # tell setuptools that all packages will be under the 'python/src' directory\n # and nowhere else\n package_dir={'':'python/src'},\n # likely need to add all source paths for proper sdist packages\n ext_modules=[CMakeExtension('datasketches')],\n # add custom build_ext command\n cmdclass={'build_ext': CMakeBuild},\n zip_safe=False\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"443483497","text":"\n#126. Word Ladder II\n\nclass stack:\n def __init__(self):\n self.body = []\n\n def push(self, data):\n self.body.append(data)\n\n def pop(self):\n if (len(self.body) == 0):\n return None\n else:\n return self.body.pop()\n\n def isEmpty(self):\n return True if len(self.body) == 0 else False\n \ndef connect(s1, s2):\n if (len(s1) != len(s2)):\n return False\n \n diff = 0 \n for i in range(len(s1)):\n if (s1[i] != s2[i]): diff += 1\n \n return (diff == 1)\n \ndef ladder(s1, s2, di):\n if (len(s1) != len(s2)):\n return []\n \n s = stack()\n s.push([])\n s.push(s1) \n while(not s.isEmpty()):\n n = s.pop()\n history = s.pop()\n history.append(n)\n if (connect(n, s2)):\n history.append(s2)\n return history \n for i in range(len(di)-1,-1,-1):\n if (connect(n, di[i])):\n s.push(history)\n s.push(di.pop(i))\n \n return []\n\ndictionary = [\"hot\", \"dot\", \"dog\", \"lot\", \"log\", \"cog\"]\nprint(ladder(\"hit\", \"cog\", dictionary))\n\n \n ","sub_path":"Leetcode/126.py","file_name":"126.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"53201118","text":"import os\nimport logging\nfrom logging.config import fileConfig\nfrom flask import Flask, request, redirect\nfrom twilio import twiml\nimport sys\n\nfrom datetime import datetime\n\nsys.path.insert(0, 'HelpBot/')\n\nfrom GoogleMaps import GoogleMaps\nimport pyowm\nfrom MessageParser import MessageParser, BadMessage\n\nimport psycopg2\nimport os\nimport urlparse\n\nfileConfig('logging_config.ini')\nlogger = logging.getLogger()\n\nurlparse.uses_netloc.append(\"postgres\")\nurl = urlparse.urlparse(os.environ[\"DATABASE_URL\"])\n\nconn = psycopg2.connect(\n database=url.path[1:],\n user=url.username,\n password=url.password,\n host=url.hostname,\n port=url.port\n)\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef receive_and_respond():\n sender = request.values.get('From')\n\n logger.debug(\"[App] - Received request from \" + sender)\n\n if request.values.get('Body') == None:\n logger.debug(\"[App] - Message was empty\")\n return \"No Message\"\n\n request_body = request.values.get('Body').lower()\n\n message_parser = MessageParser()\n\n if request_body == 'commands':\n body = \"\"\"\n To get directions:\n directions from to <'depart at' or 'arrive by'> \n \"\"\"\n elif 'directions' in request_body:\n try:\n if request_body.strip() == 'directions':\n with conn.cursor() as curs:\n curs.execute(\"SELECT last_gmaps_query FROM textinfo WHERE sender = %s\", (sender,))\n request_body = curs.fetchone()[0]\n logger.debug(\"[app] - Google Mapsgit p last request: \" + request_body)\n if request_body is None:\n raise BadMessage(\"No previous request\")\n\n parameters = message_parser.parse_directions(request_body)\n logger.debug(\"[App] - Google Maps Parameters: \" + str(parameters))\n gmaps = GoogleMaps(os.environ['GOOGLE_MAPS_API_KEY'])\n if parameters['time_modifier'].lower() == 'depart at':\n directions = gmaps.get_directions(origin=parameters['origin'], destination=parameters['destination'],\n mode=parameters['mode'], departure_time=parameters['time'])\n elif parameters['time_modifier'].lower() == 'arrive by':\n directions = gmaps.get_directions(origin=parameters['origin'], destination=parameters['destination'],\n mode=parameters['mode'], arrival_time=parameters['time'])\n body = str(directions)\n logger.debug(\"[App] - Google Maps Response: \" + body)\n\n with conn.cursor() as curs:\n vals = {\n \"sender\": sender,\n \"last_weather_query\": \"\",\n \"last_gmaps_query\": request_body\n }\n query = \"INSERT INTO textinfo (sender, last_weather_query, last_gmaps_query) VALUES (%(sender)s, %(last_weather_query)s, %(last_gmaps_query)s) ON CONFLICT (sender) DO UPDATE SET last_gmaps_query = %(last_gmaps_query)s\"\n curs.execute(query, vals)\n conn.commit()\n\n except Exception as e:\n logger.error(\"[App] - Google Maps Exception: \" + str(e))\n body = \"Please follow message format: directions from to <'depart at' or 'arrive by'> \"\n\n elif 'weather' in request_body:\n try:\n if request_body.strip() == 'weather':\n with conn.cursor() as curs:\n curs.execute(\"SELECT last_weather_query FROM textinfo WHERE sender = %s\", (sender,))\n request_body = curs.fetchone()[0]\n logger.debug(\"[app] - Weather last request: \" + request_body)\n if request_body is None:\n raise BadMessage(\"No previous request\")\n\n weather_location = message_parser.parse_weather_string(request_body)\n logger.debug(\"[App] - Weather Location: \" + weather_location['location'])\n owm = pyowm.OWM(os.environ['WEATHER_API'])\n observation = owm.weather_at_place(weather_location['location'])\n weather = observation.get_weather()\n temperature = weather.get_temperature(unit='celsius')\n location = observation.get_location()\n body = \"Currently, in {}, it is {} degrees ({} degrees - {} degrees) with {}.\".format(location.get_name(),\n temperature['temp'],\n temperature['temp_min'],\n temperature['temp_max'],\n weather.get_detailed_status())\n\n with conn.cursor() as curs:\n vals = {\n \"sender\": sender,\n \"last_weather_query\": request_body,\n \"last_gmaps_query\": \"\"\n }\n query = \"INSERT INTO textinfo (sender, last_weather_query, last_gmaps_query) VALUES (%(sender)s, %(last_weather_query)s, %(last_gmaps_query)s) ON CONFLICT (sender) DO UPDATE SET last_weather_query = %(last_weather_query)s\"\n curs.execute(query, vals)\n conn.commit()\n\n except Exception as e:\n logger.error(\"[App] - Weather: \" + str(e))\n body = \"Please follow message format: weather in \"\n\n logger.debug(\"[App] - Weather Response: \" + body)\n\n else:\n body = \"Invalid command. Text 'commands' for list of all commands\"\n\n resp = twiml.Response()\n resp.message(body)\n return str(resp)\n\n\nif __name__ == \"__main__\":\n # use heroku assigned port, or use port 5000 locally\n port = int(os.getenv('PORT', 5000))\n app.run(host='0.0.0.0', port=port, debug=True)\n conn.close()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343629900","text":"from django.db import models\nfrom django.db.models.deletion import CASCADE\nfrom django.contrib.auth.models import User \n\n# Create your models here.\n# creating database tables and it attributes\nclass Award(models.Model):\n name=models.CharField(max_length=300)\n description=models.TextField(max_length=50000) \n developer=models.CharField(max_length=300)\n created_date=models.DateField()\n averangeRating=models.FloatField(default=0)\n image=models.URLField(default=None, null=True)\n linktosite=models.URLField(default=None, null=True)\n \n\n\n def __str__(self):\n return self.name\n\nclass Review(models.Model):\n project=models.ForeignKey(Award, on_delete=models.CASCADE)\n user=models.ForeignKey(User, on_delete=CASCADE)\n comment=models.TextField(max_length=1500)\n rating=models.FloatField(default=0)\n\n\n def __str__(self):\n return self.user.username","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"285604376","text":"import time\nfrom random import randint\nfrom tch2 import app\n\nSTATUS_OFF = 'OFF'\nSTATUS_READY = 'READY'\nSTATUS_BUSY = 'BUSY'\n\n\nclass Browser:\n def __init__(self):\n app.logger.info('browser init')\n self.code = randint(1, 100000)\n self.status = STATUS_OFF\n\n def start(self):\n app.logger.info('browser started')\n self.status = STATUS_READY\n\n def stop(self):\n app.logger.info('browser stopped')\n self.status = STATUS_OFF\n\n def work(self, obj_id):\n if self.status == STATUS_OFF:\n app.logger.debug('browser can not work with {} / OFF'.format(obj_id))\n return 'fail status: OFF'\n if self.status == STATUS_BUSY:\n app.logger.debug('browser can not work with {} / BUSY'.format(obj_id))\n return 'fail status: BUSY'\n\n # начинаем работу браузера, выставляем статус BUSY\n self.status = STATUS_BUSY\n try:\n app.logger.debug('browser start work with {}'.format(obj_id))\n time.sleep(randint(1, 10))\n if randint(0, 10) < 3:\n print(2 / 0)\n app.logger.debug('browser finish work with {}'.format(obj_id))\n except Exception as err:\n app.logger.debug('browser error: ' + str(err))\n finally:\n # в конце метода обязательно должны статус поставить в READY значение, чтобы другие нити смогли начать работу\n self.status = STATUS_READY\n\n\n# важно чтобы этот объект был строго один. Не должно быть в системе ни при каких условиях больше одного объекта browser\nbrowser = Browser()\n","sub_path":"tch2/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"448566101","text":"# Marilu D\n\n\n#program that takes years as input and prints out an estimated pop.\n\n\n#define some useful constants\nbirthsPerSeconds = 7\ndeathsPerSecond = 13\nnewImmigrantsPerSecond = 35\ncurrentPop = 307357870\n\n\n#prompt user for input\nyears = int(input(\"Enter the number of years: \"))\n\n#math\nbirthsPerYear = int(60 * 60 * 24 * 365 / birthsPerSeconds)\ndeathsPerYear = int(60 * 60 * 24 * 365 / deathsPerSecond)\nimmigrantsPerYear = int(60 * 60 * 24 * 365 / newImmigrantsPerSecond)\n\n#compute number of years/pop.\nestimatedPop = currentPop + (birthsPerYear - deathsPerYear + immigrantsPerYear) * years\n\n#print estimated pop\nprint(\"The Estimated population is = \", estimatedPop)\n\n","sub_path":"hw1q4mfd.py","file_name":"hw1q4mfd.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"447499504","text":"import matplotlib.pyplot as plt\n\n\nclass FittedModel:\n \"\"\"This class provides method to analyse the trained model.\"\"\"\n\n def __init__(self, input_model, date, save_dir):\n self.input_model = input_model\n self.date = date\n self.save_dir = save_dir\n\n def save_acc_fig(self):\n\n \"\"\"This function generates figure of accuracy.\"\"\"\n plt.figure()\n plt.gcf().clear()\n plt.plot(self.input_model.fitted_model.history['acc'])\n plt.plot(self.input_model.fitted_model.history['val_acc'])\n plt.title('Model Accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n plt.savefig(self.save_dir + self.date + \"_Accuracy.png\")\n\n def save_loss_fig(self):\n\n \"\"\"This function generates figure of loss.\"\"\"\n\n plt.figure()\n plt.gcf().clear()\n plt.plot(self.input_model.fitted_model.history['loss'])\n plt.plot(self.input_model.fitted_model.history['val_loss'])\n plt.title('Model Loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n plt.savefig(self.save_dir + self.date + \"_Loss.png\")\n\n def f2_evaluation(self):\n print(\"TO BE UPDATED\")\n\n def predict_image(self, test_image_dir):\n self.input_model.predict()\n\n","sub_path":"ShipDetection/Evaluation/Evaluation.py","file_name":"Evaluation.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"375532568","text":"# base_object.py\nimport json\nimport logging\n\nfrom collections.abc import MutableMapping, Sequence\nfrom urllib.parse import urljoin\n\nimport aiohttp\n\nfrom boxcomtools.base.exceptions import HTTPError\n\n\nclass BaseObject:\n\n __resource__ = \"\"\n\n def __init__(self, session=None, object_id=None):\n self._session = session\n self._object_id = object_id\n self._data = None\n\n def to_json(self):\n return {}\n\n def get_url(self, ext=None):\n \"\"\"\n returns base url for resource API endpoint\n __resource__ should be defined in child classes\n \"\"\"\n url = urljoin(self.request_url, self.__resource__) + \"/\"\n url = urljoin(url, self._object_id)\n if ext:\n return urljoin(url, ext)\n return url\n\n @property\n def headers(self):\n return {\n \"Authorization\": \"Bearer \" + self._session.access_token,\n \"Content-Type\": \"application/json\"\n }\n\n async def create(self, data=None):\n raise NotImplementedError\n\n async def get(self):\n \"\"\"\n Returns a dict\n \"\"\"\n self._data = await self.request(self.get_url())\n return self._data\n\n async def delete(self, object_id):\n raise NotImplementedError\n\n async def update(self, object_id, payload=None):\n raise NotImplementedError\n\n async def __request(self, url, method, headers, data):\n if isinstance(data, (MutableMapping, Sequence)):\n data = json.dumps(data)\n async with method(url,\n headers=headers,\n data=data) as resp:\n body = await resp.text()\n if resp.status == 200:\n try:\n return json.loads(body)\n except ValueError:\n logging.exception(\"Can't parse Response\")\n raise HTTPError(resp.status, body)\n\n async def request(self, url, method=\"GET\", data=None):\n if not data: data = {}\n async with aiohttp.ClientSession() as session:\n method = getattr(session, method.lower(), None)\n if method:\n return await self.__request(url, method, self.headers, data)\n raise Exception(\"ERROR in object request method\")\n\n def _attach_to_object(self, data):\n for k, v in data.items():\n try:\n setattr(self, k, v)\n except AttributeError as e:\n logging.exception(e)\n\n @property\n def id(self):\n return self._object_id\n","sub_path":"boxcomtools/base/base_object.py","file_name":"base_object.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128982395","text":"import json\nimport os\nimport time\n\nfrom flask import Flask, render_template, request, jsonify\n\nfrom src.base64_grader import base64_grader\n\nroot = os.getcwd()\nUPLOAD_FOLDER = os.path.join(root, 'files')\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n@app.route('/')\ndef upload_file():\n return render_template('webcam.html')\n\n@app.route('/uploader', methods=['POST'])\ndef uploader():\n outputFileName = \"bs_\"+str(round(time.time()))\n #imageFileName = os.path.join(root, 'app_cache', 'images', outputFileName)\n imgData = request.values['imgdata']\n #print(imgData)\n imgData = imgData.split(',')[-1]\n\n try:\n out = base64_grader(imgData)\n out=json.dumps(out)\n out=json.loads(out)\n #print(out)\n return jsonify(out)\n except IndexError as e:\n #print(out)\n return jsonify(\"error in detecting contours\")\n print(e)\n except Exception as e1:\n\n return jsonify(\"need zero values to unpack or other than bubble detection\")\n print(e1)\n return(e1)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0',port=7000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"639899201","text":"#!/usr/bin/env python3\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom dateutil.parser import parse as parse_date\nimport datetime as dt\nimport re\nimport json\nimport os\nimport site\n\nsite.addsitedir('./node_modules/.bin')\n\nbrowser = webdriver.PhantomJS()\n\ntry:\n url = 'https://portal.hmc.edu/ICS/Portal_Homepage.jnz?portlet=Course_Schedules&screen=Advanced+Course+Search&screenType=next'\n browser.get(url)\n\n title = browser.find_element_by_id('pg0_V_txtTitleRestrictor')\n title.clear()\n title.send_keys('*')\n\n search = browser.find_element_by_id('pg0_V_btnSearch')\n search.click()\n\n show_all = browser.find_element_by_id('pg0_V_lnkShowAll')\n show_all.click()\n\n html = browser.page_source\nfinally:\n browser.quit()\n\nsoup = BeautifulSoup(html, 'lxml')\n\ntable = soup.find(id='pg0_V_dgCourses')\nbody = table.find('tbody')\nrows = body.find_all('tr', recursive=False)\n\nraw_courses = []\n\nfor row in rows:\n if 'style' in row.attrs and row.attrs['style'] == 'display:none;':\n continue\n elements = row.find_all('td')\n add, course_code, name, faculty, seats, status, schedule, credits, begin, end = elements\n raw_courses.append({\n 'course_code': course_code.text,\n 'course_name': name.text,\n 'faculty': faculty.text,\n 'seats': seats.text,\n 'status': status.text,\n 'schedule': [stime.text for stime in schedule.find_all('li')],\n 'credits': credits.text,\n 'begin_date': begin.text,\n 'end_date': end.text,\n })\n\ncourses = []\n\ndef schedule_sort_key(slot):\n return slot['days'], slot['startTime'], slot['endTime'], slot['days']\n\ndef days_sort_key(day):\n return 'MTWRFSU'.index(day)\n\nfor raw_course in raw_courses:\n course_code = raw_course['course_code'].strip()\n course_regex = r'([A-Z]+) *?([0-9]+) *([A-Z]*[0-9]?) *([A-Z]{2})-([0-9]+)'\n department, course_number, num_suffix, school, section = re.match(\n course_regex, course_code).groups()\n course_number = int(course_number)\n section = int(section)\n course_name = raw_course['course_name'].strip()\n faculty = re.split(r'\\s*\\n\\s*', raw_course['faculty'].strip())\n faculty = list(set(faculty))\n faculty.sort()\n open_seats, total_seats = map(\n int, re.match(r'([0-9]+)/([0-9]+)', raw_course['seats']).groups())\n course_status = raw_course['status'].lower()\n schedule_regex = r'(?:([MTWRFSU]+)\\xa0)?([0-9]+:[0-9]+(?: ?[AP]M)?) - ([0-9]+:[0-9]+ ?[AP]M); ([A-Za-z0-9, ]+)'\n schedule = []\n for slot in raw_course['schedule']:\n if slot.startswith('0:00 - 0:00 AM'):\n continue\n match = re.match(schedule_regex, slot)\n assert match, (\"Couldn't parse schedule: \" + repr(slot) +\n ' (for course {})'.format(repr(course_code)))\n days, start, end, location = match.groups()\n if days:\n days = list(set(days))\n assert days\n for day in days:\n assert day in 'MTWRFSU'\n days.sort(key=days_sort_key)\n days = ''.join(days)\n else:\n days = []\n if not start.endswith('AM') or start.endswith('PM'):\n start += end[-2:]\n start = parse_date(start).time()\n end = parse_date(end).time()\n location = ' '.join(location.strip().split())\n # API uses camelCase since the rest is in JavaScript\n schedule.append({\n 'days': days,\n 'location': location,\n 'startTime': start.strftime('%H:%M'),\n 'endTime': end.strftime('%H:%M'),\n })\n schedule.sort(key=schedule_sort_key)\n quarter_credits = round(float(raw_course['credits']) / 0.25)\n begin_date = parse_date(raw_course['begin_date']).date()\n end_date = parse_date(raw_course['end_date']).date()\n # First half-semester courses start before February 1\n first_half = begin_date < dt.date(begin_date.year, 2, 1)\n # Second half-semester courses end after April 1\n second_half = end_date > dt.date(end_date.year, 4, 1)\n assert first_half or second_half\n courses.append({\n 'department': department,\n 'courseNumber': course_number,\n 'courseCodeSuffix': num_suffix,\n 'school': school,\n 'section': section,\n 'courseName': course_name,\n 'faculty': faculty,\n 'openSeats': open_seats,\n 'totalSeats': total_seats,\n 'courseStatus': course_status,\n 'schedule': schedule,\n 'quarterCredits': quarter_credits,\n 'firstHalfSemester': first_half,\n 'secondHalfSemester': second_half,\n 'startDate': begin_date.strftime('%Y-%m-%d'),\n 'endDate': end_date.strftime('%Y-%m-%d'),\n })\n\ndef course_sort_key(course):\n return (\n course['department'],\n course['courseNumber'],\n course['courseCodeSuffix'],\n course['school'],\n course['section'],\n )\n\ncourses.sort(key=course_sort_key)\n\nwith open('courses.json.tmp', 'w') as f:\n json.dump(courses, f)\n\nos.rename('courses.json.tmp', 'courses.json')\n","sub_path":"fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"645246226","text":"import os\nfrom pathlib import Path\n\ndays = [f'day{i}' for i in range(2,32)]\nfiles = ['input.txt', 'sample.txt']\n\nfor day in days:\n path = Path('inputs') / day\n os.mkdir(path)\n for filename in files:\n filepath = path / filename\n print(filepath)\n filepath.touch()\n","sub_path":"setup_files.py","file_name":"setup_files.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"484273963","text":"from models.test_suite_models.trace import Trace\nfrom tests.base_test_case import BaseTestCase\n\n\nclass TestBugDbHandler(BaseTestCase):\n\n def setUp(self):\n super(TestBugDbHandler, self).setUp()\n\n def test_getTestMethods(self):\n test_methods_from_db = self.db_handler.get_all_test_methods()\n expected_test_methods = [(method_id, method_name, is_real_faulty, is_test_method)\n for (method_id, method_name, is_real_faulty, is_test_method)\n in self.get_raw_methods()\n if is_test_method == 1]\n self.assertEqual(len(expected_test_methods), len(test_methods_from_db))\n\n def test_getLogicMethods(self):\n logic_methods_from_db = self.db_handler.get_all_logic_methods()\n expected_logic_methods = [(method_id, method_name, is_real_faulty, is_test_method)\n for (method_id, method_name, is_real_faulty, is_test_method)\n in self.get_raw_methods()\n if is_test_method == 0]\n self.assertEqual(len(expected_logic_methods), len(logic_methods_from_db))\n\n def test_getTraceOfLogicMethod(self):\n logic_method_id = 'mid0'\n logic_methods_from_db = self.db_handler.get_all_logic_methods()\n mid0 = [m for m in logic_methods_from_db if m.logic_method_id == logic_method_id][0]\n traces = self.db_handler.get_all_traces_of_logic_method(mid0)\n outcomes = self.get_raw_outcomes()\n expected_traces = []\n for t in self.get_raw_traces():\n tmid, mid, primary_order, secondary_order, args, ret_val, was_exception_thrown, had_unhandled_exception, exec_time = t\n is_failing = [is_failing for outcomes_tmid, is_failing in outcomes if outcomes_tmid == tmid][0]\n if mid == logic_method_id:\n trace = Trace(tmid, mid, primary_order, secondary_order, args, ret_val, was_exception_thrown,\n had_unhandled_exception, exec_time, is_failing)\n expected_traces.append(trace)\n self.assertEqual(len(expected_traces), len(traces))\n","sub_path":"tests/test_bugdb_handler.py","file_name":"test_bugdb_handler.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"217700871","text":"# Copyright 2014-2015 Canonical Limited.\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 os\nimport re\nfrom stat import S_ISBLK\n\nfrom subprocess import (\n CalledProcessError,\n check_call,\n check_output,\n call\n)\n\nfrom charmhelpers.core.hookenv import (\n log,\n WARNING,\n INFO\n)\n\n\ndef _luks_uuid(dev):\n \"\"\"\n Check to see if dev is a LUKS encrypted volume, returning the UUID\n of volume if it is.\n\n :param: dev: path to block device to check.\n :returns: str. UUID of LUKS device or None if not a LUKS device\n \"\"\"\n try:\n cmd = ['cryptsetup', 'luksUUID', dev]\n return check_output(cmd).decode('UTF-8').strip()\n except CalledProcessError:\n return None\n\n\ndef is_luks_device(dev):\n \"\"\"\n Determine if dev is a LUKS-formatted block device.\n\n :param: dev: A full path to a block device to check for LUKS header\n presence\n :returns: boolean: indicates whether a device is used based on LUKS header.\n \"\"\"\n return True if _luks_uuid(dev) else False\n\n\ndef is_mapped_luks_device(dev):\n \"\"\"\n Determine if dev is a mapped LUKS device\n :param: dev: A full path to a block device to be checked\n :returns: boolean: indicates whether a device is mapped\n \"\"\"\n _, dirs, _ = next(os.walk(\n '/sys/class/block/{}/holders/'\n .format(os.path.basename(os.path.realpath(dev))))\n )\n is_held = len(dirs) > 0\n return is_held and is_luks_device(dev)\n\n\ndef is_block_device(path):\n '''\n Confirm device at path is a valid block device node.\n\n :returns: boolean: True if path is a block device, False if not.\n '''\n if not os.path.exists(path):\n return False\n return S_ISBLK(os.stat(path).st_mode)\n\n\ndef zap_disk(block_device):\n '''\n Clear a block device of partition table. Relies on sgdisk, which is\n installed as pat of the 'gdisk' package in Ubuntu.\n\n :param block_device: str: Full path of block device to clean.\n '''\n # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b\n # sometimes sgdisk exits non-zero; this is OK, dd will clean up\n call(['sgdisk', '--zap-all', '--', block_device])\n call(['sgdisk', '--clear', '--mbrtogpt', '--', block_device])\n dev_end = check_output(['blockdev', '--getsz',\n block_device]).decode('UTF-8')\n gpt_end = int(dev_end.split()[0]) - 100\n check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device),\n 'bs=1M', 'count=1'])\n check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device),\n 'bs=512', 'count=100', 'seek=%s' % (gpt_end)])\n\n\ndef is_device_mounted(device):\n '''Given a device path, return True if that device is mounted, and False\n if it isn't.\n\n :param device: str: Full path of the device to check.\n :returns: boolean: True if the path represents a mounted device, False if\n it doesn't.\n '''\n try:\n out = check_output(['lsblk', '-P', device]).decode('UTF-8')\n except Exception:\n return False\n return bool(re.search(r'MOUNTPOINT=\".+\"', out))\n\n\ndef mkfs_xfs(device, force=False, inode_size=None):\n \"\"\"Format device with XFS filesystem.\n\n By default this should fail if the device already has a filesystem on it.\n :param device: Full path to device to format\n :ptype device: tr\n :param force: Force operation\n :ptype: force: boolean\n :param inode_size: XFS inode size in bytes; if set to 0 or None,\n the value used will be the XFS system default\n :ptype inode_size: int\"\"\"\n cmd = ['mkfs.xfs']\n if force:\n cmd.append(\"-f\")\n\n if inode_size:\n if inode_size >= 256 and inode_size <= 2048:\n cmd += ['-i', \"size={}\".format(inode_size)]\n else:\n log(\"Config value xfs-inode-size={} is invalid. Using system default.\".format(inode_size), level=WARNING)\n else:\n log(\"Using XFS filesystem with system default inode size.\", level=INFO)\n\n cmd += [device]\n check_call(cmd)\n","sub_path":"hooks/charmhelpers/contrib/storage/linux/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"562895881","text":"import pylab as py\nfrom operator import itemgetter\n\ndef open_file():\n '''Asks for an input file. Reprompts if there is an error.'''\n filename = input(\"Input a file name: \")\n while True:\n try:\n # Attempts to open file\n fp = open(filename)\n return fp\n except:\n # Reprompts for file\n print(\"Unable to open file. Please try again.\")\n filename = input(\"Input a file name: \")\n\ndef update_dictionary(dictionary, year, hurricane_name, data):\n '''Takes a dictionary and updates it.'''\n if year not in dictionary.keys():\n # Makes a list if the year is not in the keys\n new_list = []\n dictionary[year] = {hurricane_name:new_list}\n new_list.append(data)\n elif year in dictionary.keys() and \\\n hurricane_name not in dictionary[year].keys():\n # Makes a list if the name is not in the keys\n new_list = []\n dictionary[year][hurricane_name] = new_list\n new_list.append(data)\n elif year in dictionary.keys() and \\\n hurricane_name in dictionary[year].keys():\n # Adds data to the dictionary\n dictionary[year][hurricane_name].append(data)\n return dictionary\n\ndef create_dictionary(fp):\n '''Creates a dictionary and sends it to update_dictionary()'''\n # Creates an empty dictionary\n my_dict = {}\n for line in fp:\n line = line.strip().split()\n # Gets data from each line\n year = line[0]\n hurricane_name = line[1]\n lat = float(line[3])\n lon = float(line[4])\n date = line[5]\n wind = float(line[6])\n try:\n pressure = float(line[7])\n except ValueError:\n pressure = line[7]\n tup = (lat, lon, date, wind, pressure)\n # Sends information to update_dictionary()\n new = update_dictionary(my_dict, year, hurricane_name, tup)\n # Updates the dictionary\n my_dict.update(new)\n return my_dict\n\ndef display_table(dictionary, year):\n '''Displays data for the user based on a given year.'''\n # Sorts the year\n sorted_dict = sorted(dictionary[year].items(), key = lambda t: t[0])\n for tup in sorted_dict:\n name = tup[0]\n # Sorts the data\n tup = sorted(tup[1], key = itemgetter(3,0,1), reverse = True)\n coordinates1 = str('%.2f' %(float(tup[0][0])))\n coordinates2 = str('%.2f' %(float(tup[0][1])))\n wind_speed = float(tup[0][3])\n date = str(tup[0][2])\n print(\"{:15s}{:>15s}{:>20.2f}{:>15s}\".format(name, \\\n (\"( \"+coordinates1+\",\"+coordinates2+\")\"), wind_speed, date))\n\ndef get_years(dictionary):\n '''Gets the min and max year from the dictionary.'''\n new_sort = sorted(dictionary)\n min_year = min(new_sort, key = int)\n max_year = max(new_sort, key = int)\n tup = (min_year, max_year)\n return tup\n \ndef prepare_plot(dictionary, year):\n '''Prepares the data for plotting.'''\n # Sorts the dictionary by keys\n sorted_dict = sorted(dictionary[year].items(), key = lambda t: t[0])\n # These are new lists for returning the information\n name_list = []\n speed_list = []\n coordinate_list = []\n # Appends data to the lists\n for tup in sorted_dict:\n names = tup[0]\n name_list.append(names)\n # Sorts data\n tup = sorted(tup[1], key = itemgetter(3), reverse = True)\n max_speed = float(tup[0][3])\n speed_list.append(max_speed)\n coordinates = [tup[0][0:2], tup[1][0:2]]\n coordinate_list.append(coordinates)\n return name_list, coordinate_list, speed_list\n \ndef plot_map(year, size, names, coordinates):\n '''Plots a map and requires year, size, names, and coordinates.'''\n \n img = py.imread(\"world-map.jpg\")\n\n max_longitude, max_latitude = 180, 90\n \n py.imshow(img,extent=[-max_longitude,max_longitude,\\\n -max_latitude,max_latitude])\n \n xshift = (50,190) \n yshift = (90,30)\n \n py.xlim((-max_longitude+xshift[0],max_longitude-xshift[1]))\n py.ylim((-max_latitude+yshift[0],max_latitude-yshift[1]))\n\t\n cmap = py.get_cmap('gnuplot')\n colors = [cmap(i/size) for i in range(size)]\n \n for i,key in enumerate(names):\n lat = [ lat for lat,lon in coordinates[i] ]\n lon = [ lon for lat,lon in coordinates[i] ]\n py.plot(lon,lat,color=colors[i],label=key)\n \n py.legend(bbox_to_anchor=(0.,-0.5,1.,0.102),loc=0, ncol=3,mode='expand',\\\n borderaxespad=0., fontsize=10)\n \n py.xlabel(\"Longitude (degrees)\")\n py.ylabel(\"Latitude (degrees)\")\n py.title(\"Hurricane Trayectories for {}\".format(year))\n py.show()\n\ndef plot_wind_chart(year,size,names,max_speed):\n '''Plots a wind chart and requires year, size, names, and max sped'''\n \n cat_limit = [ [v for i in range(size)] for v in [64,83,96,113,137] ]\n \n COLORS = [\"g\",\"b\",\"y\",\"m\",\"r\"]\n \n for i in range(5):\n py.plot(range(size),cat_limit[i],COLORS[i],\\\n label=\"category-{:d}\".format(i+1))\n \n py.legend(bbox_to_anchor=(1.05, 1.),loc=2,\\\n borderaxespad=0., fontsize=10)\n \n py.xticks(range(size),names,rotation='vertical')\n py.ylim(0,180)\n \n py.ylabel(\"Wind Speed (knots)\")\n py.xlabel(\"Hurricane Name\")\n py.title(\"Max Hurricane Wind Speed for {}\".format(year))\n py.plot(range(size),max_speed)\n py.show()\n \ndef main():\n # Opens the file\n fp = open_file()\n # Creates the dictionary\n original = create_dictionary(fp)\n # Gets the min and max years\n min_max_years = get_years(original)\n # Displays information\n print(\"Hurricane Record Software\")\n print(\"Records from {:4s} to {:4s}\".format(min_max_years[0], \\\n min_max_years[1]))\n answer = input(\"Enter the year to show hurricane data or 'quit': \").\\\n lower()\n while answer not in original:\n # Reprompts if the year is not valid\n print(\"Error with the year key! Try another year\")\n answer = input(\"Enter the year to show hurricane data or 'quit': \")\\\n .lower()\n while answer != 'quit':\n print(\"{:^70s}\".format(\"Peak Wind Speed for the Hurricanes in \" + \\\n answer))\n print(\"{:15s}{:>15s}{:>20s}{:>15s}\".format(\"Name\",\"Coordinates\",\\\n \"Wind Speed (knots)\",\"Date\"))\n display_table(original, answer)\n # Asks if user wants to plot\n plot_answer = input(\"\\nDo you want to plot? \").lower()\n if plot_answer == \"yes\":\n names, coordinates, max_speed = prepare_plot(original, answer)\n plot_map(answer, len(original[answer]), names, coordinates)\n plot_wind_chart(answer, len(original[answer]), names, max_speed)\n answer = \\\n input(\"Enter the year to show hurricane data or 'quit': \").lower()\n while answer not in original and answer != 'quit':\n print(\"Error with the year key! Try another year\")\n answer = \\\n input\\\n (\"Enter the year to show hurricane data or 'quit': \").lower()\n else:\n answer = \\\n input(\"Enter the year to show hurricane data or 'quit': \").lower()\n while answer not in original and answer != 'quit':\n answer = \\\n input\\\n (\"Enter the year to show hurricane data or 'quit': \").lower()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hurricane.py","file_name":"hurricane.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592141599","text":"''' \nThis script demonstrates using rbf.filter.filter to denoise and \ndifferentiate a time series\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom rbf.filter import filter\nnp.random.seed(1)\n\nt = np.linspace(0.0,5.0,200)\nu_true,udiff_true = np.sin(t),np.cos(t) # true signal\nsigma_obs = 0.5*np.ones(t.shape)\nu_obs = u_true + np.random.normal(0.0,sigma_obs) # observed\n# find the filtered solution\nu_pred,sigma_pred = filter(t[:,None],u_obs,sigma_obs,\n samples=1000,n=3,\n cutoff=0.5)\n# find the derivative of the filtered solution\nudiff_pred,sigmadiff_pred = filter(t[:,None],u_obs,sigma_obs,\n samples=1000,n=3,\n cutoff=0.5,diffs=(1,))\n\n# plot the results\nfig,ax = plt.subplots(2,1)\nax[0].plot(t,u_obs,'k.',label='observed',zorder=0)\nax[0].plot(t,u_true,'r-',label='true signal',zorder=2)\nax[0].plot(t,u_pred,'b-',label='filtered',zorder=1)\nax[0].fill_between(t,u_pred-sigma_pred,u_pred+sigma_pred,\n color='b',alpha=0.4,edgecolor='none',zorder=1)\nax[0].legend(frameon=False) \nax[1].plot(t,udiff_true,'r-',label='true signal derivative',zorder=2)\nax[1].plot(t,udiff_pred,'b-',label='filtered derivative',zorder=1)\nax[1].fill_between(t,udiff_pred-sigmadiff_pred,\n udiff_pred+sigmadiff_pred,\n color='b',alpha=0.4,edgecolor='none',zorder=1)\nax[1].legend(frameon=False) \nplt.tight_layout()\nplt.savefig('../figures/filter.b.png')\nplt.show()\n\n","sub_path":"prj_src/nn_examples/rbf_examples/RBF-master/docs/scripts/filter.b.py","file_name":"filter.b.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"399652036","text":"from django.conf.urls.defaults import patterns, url, include\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^djangoadmin/', include(admin.site.urls)),\n url(r'', include('venuesbasedleantest.urls')),\n)\n","sub_path":"scr/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"232131213","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.http import JsonResponse\nfrom reposition import models\nfrom django.db import connection, connections\nfrom utils.login_admin import login_required, permission\nfrom cxmadmin import base\nfrom django.views.decorators.csrf import csrf_exempt\nfrom backend.forms.org import PositionForm, Permission2Action2roleForm\n\nresult_dict = {'status': 200, 'message': None, 'data': None}\ntitle_dict = {'position_index': '组织机构',\n 'roles': '权限角色',\n 'roles_add': '增加角色',\n 'roles_edit': '修改角色',\n 'position_edit': '职位修改',\n 'assign': '权限分配',\n 'employees': '员工管理',\n 'employees_add': '添加员工',\n 'employees_edit': '员工信息修改'}\n\n\ndef get_menu_dict():\n cursor = connection.cursor()\n cursor.execute(\n \"\"\"SELECT t.*,t1.counts FROM (SELECT m.`id`,m.`caption` ,p.id AS p_id,p.`caption` AS p_caption FROM permission AS p, menu AS m WHERE p.`menu_id`=m.`id` AND p.`weight` = 0) AS t,(SELECT COUNT(caption) AS counts,menu_id FROM permission AS p1 WHERE p1.`weight`=0 GROUP BY menu_id) AS t1 WHERE t.id =t1.menu_id\"\"\")\n # \"\"\"SELECT t.*,t1.counts FROM (SELECT m.`id`,m.`caption` ,p.id AS p_id,p.`caption` AS p_caption FROM permission AS p, menu AS m WHERE p.`menu_id`=m.`id`) AS t,(SELECT COUNT(caption) AS counts,menu_id FROM permission GROUP BY menu_id) AS t1 WHERE t.id =t1.menu_id\"\"\")\n menu_list = cursor.fetchall()\n munu_dict = {}\n # print(menu_list)\n for line in menu_list:\n if line[0] in munu_dict.keys():\n munu_dict[line[0]][1]['menu'].append((line[2], line[3]))\n else:\n munu_dict[line[0]] = [({'number': line[4], 'name': line[1]}), ({'menu': [(line[2], line[3])]})]\n return munu_dict\n\n\n# 职位信息\n@login_required\n@permission\ndef position_index(request, *args, **kwargs):\n common_info = {}\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['title'] = title_dict['position_index']\n common_info['edit_url'] = 'position_edit'\n common_info['html_url'] = 'organization/org_position.html'\n common_info['department_obj'] = models.Department.objects.all()\n common_info['form_obj'] = PositionForm()\n return base.table_obj_list(request, 'reposition', 'position', common_info)\n\n\n# 部门添加\n@login_required\n@permission\ndef deparment_add(request, *args, **kwargs):\n if request.method == 'POST':\n name = request.POST.get('name')\n if len(name) <= 30:\n models.Department.objects.create(name=name)\n result_dict['message'] = '部门添加成功'\n else:\n result_dict['status'] = 801\n result_dict['message'] = '长度超过30个字符'\n return JsonResponse(result_dict)\n\n\n# 部门修改\n@csrf_exempt\n@login_required\n@permission\ndef deparment_edit(request, *args, **kwargs):\n if request.method == 'POST':\n name = request.POST.get('name')\n id = request.POST.get('id')\n department_obj = models.Department.objects.filter(id=id).first()\n if department_obj:\n department_obj.name = name\n department_obj.save()\n result_dict['message'] = '部门修改成功'\n else:\n result_dict['status'] = 801\n result_dict['message'] = '长度超过30个字符'\n return JsonResponse(result_dict)\n\n\n# 部门删除\n@csrf_exempt\n@login_required\n@permission\ndef deparment_del(request, *args, **kwargs):\n if request.method == 'POST':\n id = request.POST.get('id')\n department_obj = models.Department.objects.filter(id=id).first()\n if department_obj:\n models.Department.objects.filter(id=id).delete()\n result_dict['message'] = '部门删除成功'\n else:\n result_dict['status'] = 801\n result_dict['message'] = '非法操作'\n return JsonResponse(result_dict)\n\n\n# 职位增加\n@login_required\n@permission\ndef position_add(request, *args, **kwargs):\n if request.method == 'POST':\n position_form = PositionForm(data=request.POST)\n if position_form.is_valid():\n position_form.save()\n result_dict['message'] = '职位添加成功'\n else:\n result_dict['status'] = 801\n result_dict['message'] = list(position_form.errors.values())[0][0]\n else:\n result_dict['status'] = 801\n result_dict['message'] = '非法操作'\n return JsonResponse(result_dict)\n\n\n# 职位修改\n@login_required\n@permission\ndef position_edit(request, obj_id, *args, **kwargs):\n common_info = {}\n common_info['obj_id'] = obj_id\n common_info['html_url'] = 'organization/org_position_edit.html'\n common_info['redirect_url'] = 'org_position'\n common_info['return_link'] = 'org_position'\n common_info['title'] = title_dict['position_edit']\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_change(request, 'reposition', 'position', common_info)\n\n\n# # 员工分配角色\n# def assign_role(request,id,*args,**kwargs):\n# role_obj=models.Role.objects.all()\n# return render(request,'organization/assign_role.html',{'role_obj':role_obj})\n#\n\n\n# 角色权限分配\n@login_required\n@permission\ndef assign(req, id, *args, **kwargs):\n menu_string = kwargs.get('menu_string')\n munu_dict = get_menu_dict()\n permission_obj = models.Permission.objects.filter(menu_id__isnull=True, weight=0).all()\n permission_action_obj = models.Permission2Action.objects.all()\n if req.method == 'POST':\n action_list = req.POST.getlist('action_id')\n for l in action_list:\n models.Permission2Action2Role.objects.create(p2a_id=l, role_id=id)\n return redirect('organization_roles')\n\n return render(req, 'organization/assign.html', {'title': title_dict['assign'],\n 'munu_dict': munu_dict,\n 'permission_obj': permission_obj,\n 'menu_string': menu_string,\n 'permission_action_obj': permission_action_obj,\n })\n\n\ndef bind_permission(req):\n munu_dict = get_menu_dict()\n permission_obj = models.Permission.objects.all()\n action_obj = models.Action.objects.all()\n # 所有菜单绑定action\n # for line in permission_obj:\n # for i in [1, 2, 3, 4]:\n # data = {'permission': line, 'action_id': i}\n # models.Permission2Action.objects.create(**data)\n\n return render(req, 'organization/assign.html', {'title': title_dict['assign'],\n 'munu_dict': munu_dict,\n 'action_obj': action_obj,\n })\n\n\n@login_required\n@permission\ndef roles(request, *args, **kwargs):\n common_info = {}\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['title'] = title_dict['roles']\n common_info['add_url'] = 'organization_roles_add'\n common_info['edit_url'] = 'organization_roles_edit'\n common_info['html_url'] = 'organization/org_roles.html'\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_list(request, 'reposition', 'role', common_info)\n\n\n@login_required\n@permission\ndef roles_add(request, *args, **kwargs):\n common_info = {}\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['title'] = title_dict['roles_add']\n common_info['redirect_url'] = 'organization_roles'\n common_info['return_link'] = 'organization_roles'\n common_info['html_url'] = 'organization/org_roles_add.html'\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_add(request, 'reposition', 'role', common_info)\n\n\n@login_required\n@permission\ndef roles_edit(request, role_id, *args, **kwargs):\n common_info = {}\n common_info['title'] = title_dict['roles_edit']\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['obj_id'] = role_id\n common_info['redirect_url'] = 'organization_roles'\n common_info['return_link'] = 'organization_roles'\n common_info['html_url'] = 'organization/org_roles_edit.html'\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_change(request, 'reposition', 'role', common_info)\n\n\n@login_required\n@permission\ndef employees(request, *args, **kwargs):\n common_info = {}\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['title'] = title_dict['employees']\n common_info['add_url'] = 'org_employees_add'\n common_info['edit_url'] = 'org_employees_edit'\n common_info['html_url'] = 'organization/org_employee.html'\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_list(request, 'reposition', 'employees', common_info)\n\n\n@login_required\n@permission\ndef employees_add(request, *args, **kwargs):\n common_info = {}\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['title'] = title_dict['employees_add']\n common_info['redirect_url'] = 'org_employees'\n common_info['return_link'] = 'org_employees'\n common_info['html_url'] = 'organization/org_employee_add.html'\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_add(request, 'reposition', 'employees', common_info)\n\n\n@login_required\n@permission\ndef employees_edit(request, obj_id, *args, **kwargs):\n common_info = {}\n common_info['title'] = title_dict['employees_edit']\n common_info['menu_string'] = kwargs.get('menu_string')\n common_info['obj_id'] = obj_id\n common_info['redirect_url'] = 'org_employees'\n common_info['return_link'] = 'org_employees'\n common_info['html_url'] = 'organization/org_employee_edit.html'\n common_info['department_obj'] = models.Department.objects.all()\n return base.table_obj_change(request, 'reposition', 'employees', common_info)\n","sub_path":"backend/views/organization.py","file_name":"organization.py","file_ext":"py","file_size_in_byte":10188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364357516","text":"import math\n\ndef parent(i):\n\treturn int(math.ceil((i -1)/2))\t\ndef left(i):\n\treturn 2*i+1\ndef right(i):\n\treturn (2*i)+2\n\t\n#Die processList wird in eine Heap-Struktur transformiert \ndef buildPriorityQueue( processList ):\n\treturn sorted(processList, key=lambda process:process[0])\n \n# child = index, parent = index\n# stoppt, wenn 0 erreicht wird oder parent <= child\ndef _bubbleUp(list,child, prnt):\n\tif child == 0 or list[child] >= list[prnt]:\n\t\tm = \">> \" + repr(list[child]) + \" >= \" + repr(list[prnt]) + \" ]or : \" + repr(child == 0)\n\t\tprint (m)\n\t\treturn\n\telse :\n\t\tlist[child], list[prnt] = list[prnt], list[child]\n\t\tnewParent = parent(prnt)\n\t\t_bubbleUp(list, prnt, newParent)\n\t\t\ndef insert( priorityQueue, newProcess ): \n\tnextSlot = len(priorityQueue)\n\tpriorityQueue.append(newProcess)\n\tprnt = parent(nextSlot)\n\t_bubbleUp(priorityQueue,nextSlot,prnt)\n\t\n\ndef isEmpty( priorityQueue ) :\n\treturn not priorityQueue\n\t\ndef removeProcess( priorityQueue ):\n\tif isEmpty(priorityQueue):\n\t\treturn None\n\tresult,priorityQueue[0] = priorityQueue[0], priorityQueue.pop()\n\tpriorityQueue.sort(key=lambda process:process[0])\n\treturn result\n\nlist=[(4,\"a\"),(3,\"b\"),(10,\"c\"),(7,\"d\"),(8,\"e\"),(0,\"f\")]\nheap = buildPriorityQueue(list)\n\nv = (-1,\"h\")\ninsert(heap, v)\n\nv = (1,\"g\")\ninsert(heap, v)\n\nv = (15,\"i\")\ninsert(heap, v)\n\nv = (12,\"j\")\ninsert(heap, v)\n\nv = (16,\"k\")\ninsert(heap, v)\n\nv = (-3,\"k\")\ninsert(heap, v)\n\nv = (-2,\"k\")\ninsert(heap, v)\n\nprint (heap)\n\nv = removeProcess(heap)\n\nv = removeProcess(heap)\nv = removeProcess(heap)\nv = removeProcess(heap)\nv = removeProcess(heap)\n\nprint (heap)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"felix/jul_4_6.py","file_name":"jul_4_6.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258150975","text":"import json\nimport queue\nimport os\nimport cgi\nimport time\nimport traceback\nimport logging\nimport gevent\nimport gevent.fileobject\nimport threading\nimport numpy\n\nfrom inspect import signature\n\nfrom object_database.view import RevisionConflictException\nfrom object_database.view import current_transaction\nfrom object_database.util import Timer\n\nMAX_TIMEOUT = 1.0\nMAX_TRIES = 10\nMAX_FPS = 10\n\n_cur_cell = threading.local()\n\ndef quoteForJs(string, quoteType):\n if quoteType == \"'\":\n return string.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\").replace(\"\\n\", \"\\\\n\")\n else:\n return string.replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"').replace(\"\\n\", \"\\\\n\")\n\ndef multiReplace(msg, replacements):\n for k,v in replacements.items():\n assert k[:4] == \"____\", k\n\n chunks = msg.split(\"____\")\n outChunks = []\n for chunk in chunks:\n subchunk = chunk.split(\"__\", 1)\n if len(subchunk) == 2:\n lookup = \"____\" + subchunk[0] + \"__\"\n if lookup in replacements:\n outChunks.append(replacements.pop(lookup))\n outChunks.append(subchunk[1])\n else:\n outChunks.append(\"____\" + chunk)\n else:\n outChunks.append(\"____\" + chunk)\n\n assert not replacements, \"Didn't use up replacement %s in %s\" % (replacements.keys(), msg)\n\n return \"\".join(outChunks)\n\ndef augmentToBeUnique(listOfItems):\n \"\"\"Returns a list of [(x,index)] for each 'x' in listOfItems, where index is the number of times\n we've seen 'x' before.\n \"\"\"\n counts = {}\n output = []\n for x in listOfItems:\n counts[x] = counts.setdefault(x, 0) + 1\n output.append((x,counts[x]-1))\n\n return output\n\n\nclass GeventPipe:\n \"\"\"A simple mechanism for triggering the gevent webserver from a thread other than\n the webserver thread. Gevent itself expects everything to happen on greenlets. The\n database connection in the background is not based on gevent, so we cannot use any\n standard gevent-based event or queue objects from the db-trigger thread.\n \"\"\"\n def __init__(self):\n self.read_fd, self.write_fd = os.pipe()\n self.fileobj = gevent.fileobject.FileObjectPosix(self.read_fd, bufsize=2)\n self.netChange = 0\n\n def wait(self):\n self.fileobj.read(1)\n self.netChange -= 1\n\n def trigger(self):\n # it's OK that we don't check if the bytes are written because we're just\n # trying to wake up the other side. If the operating system's buffer is full,\n # then that means the other side hasn't been clearing the bytes anyways,\n # and that it will come back around and read our data.\n if self.netChange > 2:\n return\n\n self.netChange += 1\n os.write(self.write_fd, b\"\\n\")\n\n\nclass Cells:\n def __init__(self, db):\n self.db = db\n\n self.db.registerOnTransactionHandler(self._onTransaction)\n\n # map: Cell.identity -> Cell\n self._cells = {}\n\n # map: Cell.identity -> set(Cell)\n self._cellsKnownChildren = {}\n\n # set(Cell)\n self._dirtyNodes = set()\n\n # set(Cell)\n self._nodesToBroadcast = set()\n\n # set(Cell)\n self._nodesToDiscard = set()\n\n self._transactionQueue = queue.Queue()\n\n self._gEventHasTransactions = GeventPipe()\n\n # map: db.key -> set(Cell)\n self._subscribedCells = {}\n\n self._pendingPostscripts = []\n\n # used by _newID to generate unique identifiers\n self._id = 0\n\n self._logger = logging.getLogger(__name__)\n\n self._root = RootCell()\n\n self._addCell(self._root, parent=None)\n\n @property\n def root(self):\n return self._root\n\n def __contains__(self, cell_or_id):\n if isinstance(cell_or_id, Cell):\n return cell_or_id.identity in self._cells\n else:\n return cell_or_id in self._cells\n\n def __len__(self):\n return len(self._cells)\n\n def __getitem__(self, ix):\n return self._cells.get(ix)\n\n def _newID(self):\n self._id += 1\n return str(self._id)\n\n def triggerIfHasDirty(self):\n if self._dirtyNodes:\n self._gEventHasTransactions.trigger()\n\n def wait(self):\n self._gEventHasTransactions.wait()\n\n def _onTransaction(self, *trans):\n self._transactionQueue.put(trans)\n self._gEventHasTransactions.trigger()\n\n def _handleTransaction(self, key_value, priors, set_adds, set_removes, transactionId):\n \"\"\" Given the updates coming from a transaction, update self._subscribedCells. \"\"\"\n for k in list(key_value) + list(set_adds) + list(set_removes):\n if k in self._subscribedCells:\n\n self._subscribedCells[k] = set(\n cell for cell in self._subscribedCells[k] if not cell.garbageCollected\n )\n\n for cell in self._subscribedCells[k]:\n cell.markDirty()\n\n if not self._subscribedCells[k]:\n del self._subscribedCells[k]\n\n def _addCell(self, cell, parent):\n assert isinstance(cell, Cell), type(cell)\n assert cell.cells is None, cell\n\n cell.cells = self\n cell.parent = parent\n cell.level = parent.level + 1 if parent else 0\n\n assert cell.identity not in self._cellsKnownChildren\n self._cellsKnownChildren[cell.identity] = set()\n\n assert cell.identity not in self._cells\n self._cells[cell.identity] = cell\n\n self.markDirty(cell)\n\n def _cellOutOfScope(self, cell):\n for c in cell.children.values():\n self._cellOutOfScope(c)\n\n self.markToDiscard(cell)\n\n if cell.cells is not None:\n assert cell.cells == self\n del self._cells[cell.identity]\n del self._cellsKnownChildren[cell.identity]\n for sub in cell.subscriptions:\n self.unsubscribeCell(cell, sub)\n\n cell.garbageCollected = True\n\n def subscribeCell(self, cell, subscription):\n self._subscribedCells.setdefault(subscription, set()).add(cell)\n\n def unsubscribeCell(self, cell, subscription):\n if subscription in self._subscribedCells:\n self._subscribedCells[subscription].discard(cell)\n if not self._subscribedCells[subscription]:\n del self._subscribedCells[subscription]\n\n def markDirty(self, cell):\n assert not cell.garbageCollected, (cell, cell.text if isinstance(cell, Text) else \"\")\n\n self._dirtyNodes.add(cell)\n\n def markToDiscard(self, cell):\n assert not cell.garbageCollected, (cell, cell.text if isinstance(cell, Text) else \"\")\n\n self._nodesToDiscard.add(cell)\n\n def markToBroadcast(self, node):\n assert node.cells is self\n\n self._nodesToBroadcast.add(node)\n\n def renderMessages(self):\n self._recalculateCells()\n\n res = []\n\n # map cells:set >\n cellsByLevel = {}\n\n for n in self._nodesToBroadcast:\n if n not in self._nodesToDiscard:\n cellsByLevel.setdefault(n.level, set()).add(n)\n\n for level, cells in reversed(sorted(cellsByLevel.items())):\n for n in cells:\n res.append(self.updateMessageFor(n))\n\n for n in self._nodesToDiscard:\n if n.cells is not None:\n assert n.cells == self\n res.append({'id': n.identity, 'discard': True})\n\n #the client reverses the order of postscripts because it wants\n #to do parent nodes before child nodes. We want our postscripts\n #here to happen in order, because they're triggered by messages.\n for js in reversed(self._pendingPostscripts):\n res.append({'postscript': js})\n\n self._pendingPostscripts.clear()\n\n self._nodesToBroadcast = set()\n self._nodesToDiscard = set()\n\n return res\n\n def _recalculateCells(self):\n # handle all the transactions so far\n old_queue = self._transactionQueue\n self._transactionQueue = queue.Queue()\n\n try:\n while True:\n self._handleTransaction(*old_queue.get_nowait())\n except queue.Empty:\n pass\n\n while self._dirtyNodes:\n n = self._dirtyNodes.pop()\n\n if not n.garbageCollected:\n self.markToBroadcast(n)\n\n origChildren = self._cellsKnownChildren[n.identity]\n\n try:\n _cur_cell.cell = n\n while True:\n try:\n n.prepare()\n n.recalculate()\n break\n except SubscribeAndRetry as e:\n e.callback(self.db)\n\n for childname, child_cell in n.children.items():\n if not isinstance(child_cell, Cell):\n raise Exception(\"Cell of type %s had a non-cell child %s of type %s != Cell.\" % (\n type(n),\n childname,\n type(child_cell)\n ))\n\n except Exception:\n self._logger.error(\"Node %s had exception during recalculation:\\n%s\", n, traceback.format_exc())\n self._logger.error(\"Subscribed cell threw an exception:\\n%s\", traceback.format_exc())\n n.children = {'____contents__': Traceback(traceback.format_exc())}\n n.contents = \"____contents__\"\n finally:\n _cur_cell.cell = None\n\n newChildren = set(n.children.values())\n\n for c in newChildren.difference(origChildren):\n self._addCell(c, n)\n\n for c in origChildren.difference(newChildren):\n self._cellOutOfScope(c)\n\n self._cellsKnownChildren[n.identity] = newChildren\n\n def updateMessageFor(self, cell):\n contents = cell.contents\n assert isinstance(contents, str), \"Cell %s produced %s for its contents which is not a string\" % (cell, contents)\n\n formatArgs = {}\n\n replaceDict = {}\n\n for childName, childNode in cell.children.items():\n formatArgs[childName] = \"
    \" % (cell.identity + \"_\" + childName)\n replaceDict[cell.identity + \"_\" + childName] = childNode.identity\n\n try:\n contents = multiReplace(contents, formatArgs)\n except Exception:\n raise Exception(\"Failed to format these contents with args %s:\\n\\n%s\", formatArgs, contents)\n\n res = {\n 'id': cell.identity,\n 'contents': contents,\n 'replacements': replaceDict\n }\n\n if cell.postscript:\n res['postscript'] = cell.postscript\n return res\n\n\nclass Slot:\n \"\"\"Holds some arbitrary state for use in a session. Not mirrored in the DB.\"\"\"\n def __init__(self, value=None):\n self._value = value\n self._subscribedCells = set()\n\n def setter(self, val):\n return lambda: self.set(val)\n\n def getWithoutRegisteringDependency(self):\n return self._value\n\n def get(self):\n if _cur_cell.cell:\n self._subscribedCells.add(_cur_cell.cell)\n return self._value\n\n def set(self, val):\n if val != self._value:\n self._value = val\n for c in self._subscribedCells:\n c.markDirty()\n self._subscribedCells = set()\n\nclass Cell:\n def __init__(self):\n self.cells = None # will get set when its added to a 'Cells' object\n self.parent = None\n self.level = None\n self.children = {} # local node def to global node def\n self.contents = \"\" # some contents containing a local node def\n self._identity = None\n self._tag = None\n self.postscript = None\n self.garbageCollected = False\n self.subscriptions = set()\n self._nowrap = False\n self._width = None\n self._overflow = None\n self._color = None\n self._height = None\n self.serializationContext = None\n\n self._logger = logging.getLogger(__name__)\n\n def triggerPostscript(self, javascript):\n self.cells._pendingPostscripts.append(javascript)\n\n def tagged(self, tag):\n \"\"\"Give a tag to the cell, which can help us find interesting cells during test.\"\"\"\n self._tag = tag\n return self\n\n def findChildrenByTag(self, tag, stopSearchingAtTag=True, isRoot=True):\n \"\"\"Search the cell and its children for all cells with the given tag.\n\n If `stopSearchingAtTag`, then if we encounter a non-None tag that doesn't\n match, stop searching immediately.\n \"\"\"\n cells = []\n\n if self._tag == tag:\n cells.append(self)\n\n if self._tag is not None and stopSearchingAtTag and not isRoot:\n return cells\n\n for child in self.children:\n cells.extend(self.children[child].findChildrenByTag(tag,stopSearchingAtTag,False))\n\n return cells\n\n def visitAllChildren(self, visitor):\n visitor(self)\n for child in self.children.values():\n child.visitAllChildren(visitor)\n\n def findChildrenMatching(self, filter):\n res = []\n def visitor(cell):\n if filter(cell):\n res.append(cell)\n\n self.visitAllChildren(visitor)\n\n return res\n\n def childByIndex(self, ix):\n return self.children[sorted(self.children)[ix]]\n\n def childrenWithExceptions(self):\n return self.findChildrenMatching(lambda cell: isinstance(cell, Traceback))\n\n def onMessageWithTransaction(self, *args):\n \"\"\"Call our inner 'onMessage' function with a transaction and a revision conflict retry loop.\"\"\"\n while True:\n try:\n with self.transaction() as t:\n self.onMessage(*args)\n return\n except RevisionConflictException as e:\n tries += 1\n if tries > MAX_TRIES or time.time() - t0 > MAX_TIMEOUT:\n self._logger.error(\"OnMessage timed out. This should really fail.\")\n return\n except Exception:\n self._logger.error(\"Exception in dropdown logic:\\n%s\", traceback.format_exc())\n return\n\n\n def withSerializationContext(self, context):\n self.serializationContext = context\n return self\n\n def _clearSubscriptions(self):\n if self.cells:\n for sub in self.subscriptions:\n self.cells.unsubscribeCell(self, sub)\n\n self.subscriptions = set()\n\n def _resetSubscriptionsToViewReads(self, view):\n new_subscriptions = set(view._reads).union(set(view._indexReads))\n\n for k in new_subscriptions.difference(self.subscriptions):\n self.cells.subscribeCell(self, k)\n\n for k in self.subscriptions.difference(new_subscriptions):\n self.cells.unsubscribeCell(self, k)\n\n self.subscriptions = new_subscriptions\n\n def view(self):\n return self.cells.db.view().setSerializationContext(self.serializationContext)\n\n def transaction(self):\n return self.cells.db.transaction().setSerializationContext(self.serializationContext)\n\n def prepare(self):\n if self.serializationContext is None and self.parent is not None:\n if self.parent.serializationContext is None:\n self.parent.prepare()\n self.serializationContext = self.parent.serializationContext\n\n def sortsAs(self):\n return None\n\n def _divStyle(self, existing=None):\n if existing:\n res = [existing]\n else:\n res = []\n\n if self._nowrap:\n res.append(\"display:inline-block\")\n\n if self._width is not None:\n if isinstance(self._width, int) or self._width.isdigit():\n res.append(\"width:%spx\" % self._width)\n else:\n res.append(\"width:%s\" % self._width)\n\n if self._height is not None:\n if isinstance(self._height, int) or self._height.isdigit():\n res.append(\"height:%spx\" % self._height)\n else:\n res.append(\"height:%s\" % self._height)\n\n if self._color is not None:\n res.append(\"color:%s\" % self._color)\n\n if self._overflow is not None:\n res.append(\"overflow:%s\" % self._overflow)\n\n if not res:\n return \"\"\n else:\n return \"style='%s'\" % \";\".join(res)\n\n def nowrap(self):\n self._nowrap = True\n return self\n\n def width(self, width):\n self._width = width\n return self\n\n def overflow(self, overflow):\n self._overflow = overflow\n return self\n\n def height(self, height):\n self._height = height\n return self\n\n def color(self, color):\n self._color = color\n return self\n\n def prepareForReuse(self):\n if not self.garbageCollected:\n return False\n\n self.cells = None\n self.postscript = None\n self.garbageCollected = False\n self._identity = None\n self.parent = None\n\n for c in self.children.values():\n c.prepareForReuse()\n\n return True\n\n @property\n def identity(self):\n if self._identity is None:\n assert self.cells is not None, \"Can't ask for identity for %s as it's not part of a cells package\" % self\n self._identity = self.cells._newID()\n return self._identity\n\n def markDirty(self):\n if not self.garbageCollected:\n self.cells.markDirty(self)\n\n def recalculate(self):\n pass\n\n @staticmethod\n def makeCell(x):\n if isinstance(x,(str, float, int, bool)):\n return Text(str(x), x)\n if x is None:\n return Span(\"\")\n if isinstance(x, Cell):\n return x\n assert False, \"don't know what to do with %s\" % x\n\n def __add__(self, other):\n return Sequence([self, Cell.makeCell(other)])\n\nclass Card(Cell):\n def __init__(self, inner, padding=None):\n super().__init__()\n\n self.children = {\"____contents__\": Cell.makeCell(inner)}\n\n other = \"\"\n if padding:\n other += \" p-\" + str(padding)\n\n self.contents = \"\"\"\n
    \n
    \n ____contents__\n
    \n
    \n \"\"\".replace('__other__', other)\n\n def sortsAs(self):\n return self.inner.sortsAs()\n\n\nclass CardTitle(Cell):\n def __init__(self, inner):\n super().__init__()\n\n self.children = {\"____contents__\": Cell.makeCell(inner)}\n self.contents = \"\"\"\n
    \n ____contents__\n
    \n \"\"\"\n def sortsAs(self):\n return self.inner.sortsAs()\n\nclass Octicon(Cell):\n def __init__(self, which):\n super().__init__()\n self.whichOcticon = which\n\n def sortsAs(self):\n return self.whichOcticon\n\n def recalculate(self):\n self.contents = (\n '' % self.whichOcticon\n ).replace('__style__', self._divStyle())\n\nclass Badge(Cell):\n def __init__(self, inner, style='primary'):\n super().__init__()\n self.inner = self.makeCell(inner)\n self.style = style\n\n def sortsAs(self):\n return self.inner.sortsAs()\n\n def recalculate(self):\n self.contents = \"\"\"____child__\"\"\".replace(\n \"__style__\", self.style\n )\n self.children = {'____child__': self.inner}\n\nclass Text(Cell):\n def __init__(self, text, sortAs=None):\n super().__init__()\n self.text = text\n self._sortAs = sortAs if sortAs is not None else text\n\n def sortsAs(self):\n return self._sortAs\n\n def recalculate(self):\n self.contents = \"
    %s
    \" % (\n self._divStyle(),\n cgi.escape(str(self.text)) if self.text else \" \"\n )\n\nclass Padding(Cell):\n def __init__(self):\n super().__init__()\n self.contents = \" \"\n\n def sortsAs(self):\n return \" \"\n\nclass Span(Cell):\n def __init__(self, text):\n super().__init__()\n self.contents = \"%s\" % cgi.escape(str(text))\n\n def sortsAs(self):\n return self.contents\n\nclass Sequence(Cell):\n def __init__(self, elements):\n super().__init__()\n elements = [Cell.makeCell(x) for x in elements]\n\n self.elements = elements\n self.children = {\"____c_%s__\" % i: elements[i] for i in range(len(elements)) }\n self.contents = \"
    \" % self._divStyle() + \"\\n\".join(\"____c_%s__\" % i for i in range(len(elements))) + \"
    \"\n\n def __add__(self, other):\n other = Cell.makeCell(other)\n if isinstance(other, Sequence):\n return Sequence(self.elements + other.elements)\n else:\n return Sequence(self.elements + [other])\n\n def sortsAs(self):\n if self.elements:\n return self.elements[0].sortsAs()\n return None\n\nclass Columns(Cell):\n def __init__(self, *elements):\n super().__init__()\n elements = [Cell.makeCell(x) for x in elements]\n\n self.elements = elements\n self.children = {\"____c_%s__\" % i: elements[i] for i in range(len(elements)) }\n self.contents = \"\"\"\n
    \n
    \n __contents__\n
    \n
    \n \"\"\".replace(\"__style__\", self._divStyle()).replace(\"__contents__\",\n \"\\n\".join(\n \"\"\"
    ____c_%s__
    \"\"\" % i\n for i in range(len(elements)))\n )\n\n def __add__(self, other):\n other = Cell.makeCell(other)\n if isinstance(other, Columns):\n return Columns(*(self.elements + other.elements))\n else:\n return super().__add__(other)\n\n def sortsAs(self):\n if self.elements:\n return self.elements[0].sortsAs()\n return None\n\nclass LargePendingDownloadDisplay(Cell):\n def __init__(self):\n super().__init__()\n\n self.contents = \"\"\"\n
    \n \n
    \n \"\"\"\n\nclass HeaderBar(Cell):\n def __init__(self, leftItems, centerItems=(), rightItems=()):\n super().__init__()\n self.leftItems = leftItems\n self.centerItems = centerItems\n self.rightItems = rightItems\n\n self.contents = \"\"\"\n
    \n
    \n
    \n %s\n
    \n
    \n
    \n
    \n %s\n
    \n
    \n
    \n
    \n %s\n
    \n
    \n
    \n \"\"\" % (\n \"\".join([\"____left_%s__\" % i for i in range(len(self.leftItems))]),\n \"\".join([\"____center_%s__\" % i for i in range(len(self.centerItems))]),\n \"\".join([\"____right_%s__\" % i for i in range(len(self.rightItems))]),\n )\n\n self.children = {'____left_%s__' % i: self.leftItems[i] for i in range(len(self.leftItems))}\n self.children.update({'____center_%s__' % i: self.centerItems[i] for i in range(len(self.centerItems))})\n self.children.update({'____right_%s__' % i: self.rightItems[i] for i in range(len(self.rightItems))})\n\nclass Main(Cell):\n def __init__(self, child):\n super().__init__()\n\n self.contents = \"\"\"\n
    \n
    \n ____child__\n
    \n
    \n \"\"\"\n self.children = {'____child__': child}\n\n\n\nclass _NavTab(Cell):\n def __init__(self, slot, index, target, child):\n super().__init__()\n\n self.slot = slot\n self.index = index\n self.target = target\n self.child = child\n\n def recalculate(self):\n self.contents = (\"\"\"\n
  • \n \n ____child__\n \n
  • \n \"\"\".replace(\"__identity__\", self.target)\n .replace(\"__ix__\", str(self.index))\n .replace(\"__active__\", \"active\" if self.index == self.slot.get() else \"\")\n )\n\n self.children['____child__'] = Cell.makeCell(self.child)\n\nclass Tabs(Cell):\n def __init__(self, headersAndChildren=(), **headersAndChildrenKwargs):\n super().__init__()\n\n self.whichSlot = Slot(0)\n self.headersAndChildren = list(headersAndChildren)\n self.headersAndChildren.extend(headersAndChildrenKwargs.items())\n\n def sortsAs(self):\n return None\n\n def setSlot(self, index):\n self.whichSlot.set(index)\n\n def recalculate(self):\n items = []\n\n self.children['____display__'] = Subscribed(lambda: self.headersAndChildren[self.whichSlot.get()][1])\n\n for i in range(len(self.headersAndChildren)):\n self.children['____header_{ix}__'.format(ix=i)] = _NavTab(self.whichSlot, i, self._identity, self.headersAndChildren[i][0])\n\n self.contents = \"\"\"\n
    \n
      \n __items__\n
    \n
    \n
    ____display__\n
    \n
    \n \"\"\".replace(\n \"__items__\",\n \"\".join(\n \"\"\" ____header___ix____ \"\"\".replace('__ix__', str(i))\n for i in range(len(self.headersAndChildren))\n )\n ).replace(\"__identity__\", self._identity)\n\n def onMessage(self, msgFrame):\n self.whichSlot.set(int(msgFrame['ix']))\n\nclass Dropdown(Cell):\n def __init__(self, title, headersAndLambdas, singleLambda=None, rightSide=False):\n \"\"\"\n Initialize a Dropdown menu.\n\n title - a cell containing the current value.\n headersAndLambdas - a list of pairs containing (cell, callback) for each menu item.\n\n OR\n\n title - a cell containing the current value.\n headersAndLambdas - a list of pairs containing cells for each item\n callback - a primary callback to call with the selected cell\n \"\"\"\n super().__init__()\n\n if singleLambda is not None:\n def makeCallback(cell):\n def callback():\n singleLambda(cell)\n return callback\n\n self.headersAndLambdas = [(header, makeCallback(header)) for header in headersAndLambdas]\n else:\n self.headersAndLambdas = headersAndLambdas\n\n self.title = Cell.makeCell(title)\n\n def sortsAs(self):\n return self.title.sortsAs()\n\n def recalculate(self):\n items = []\n\n self.children['____title__'] = self.title\n\n for i in range(len(self.headersAndLambdas)):\n header, onDropdown = self.headersAndLambdas[i]\n self.children[\"____child_%s__\" % i] = Cell.makeCell(header)\n\n items.append(\n \"\"\"\n \n ____child___ix____\n \n \"\"\".replace(\n \"__onclick__\",\n \"websocket.send(JSON.stringify({'event':'menu', 'ix': __ix__, 'target_cell': '__identity__'}))\"\n if not isinstance(onDropdown, str) else\n quoteForJs(\"window.location.href = '__url__'\".replace(\"__url__\", quoteForJs(onDropdown, \"'\")), '\"')\n ).replace(\"__ix__\", str(i)).replace(\"__identity__\", self.identity)\n )\n\n self.contents = \"\"\"\n
    \n ____title__\n \n
    \n __dropdown_items__\n
    \n
    \n \"\"\".replace(\"__identity__\", self.identity).replace(\"__dropdown_items__\", \"\\n\".join(items))\n\n def onMessage(self, msgFrame):\n fun = self.headersAndLambdas[msgFrame['ix']][1]\n fun()\n\nclass Container(Cell):\n def __init__(self, child=None):\n super().__init__()\n if child is None:\n self.contents = \"\"\n self.children = {}\n else:\n self.contents = \"
    ____child__
    \"\n self.children = {\"____child__\": Cell.makeCell(child)}\n\n def setChild(self, child):\n self.setContents(\"
    ____child__
    \", {\"____child__\": Cell.makeCell(child)})\n\n def setContents(self, newContents, newChildren):\n self.contents = newContents\n self.children = newChildren\n self.markDirty()\n\nclass Scrollable(Container):\n def __init__(self, child=None):\n super().__init__(child)\n self.overflow('auto')\n\nclass RootCell(Container):\n def setRootSerializationContext(self, context):\n self.serializationContext = context\n\n @property\n def identity(self):\n return \"page_root\"\n\n def setChild(self, child):\n self.setContents(\"
    ____c__
    \", {\"____c__\": child})\n\nclass Traceback(Cell):\n def __init__(self, traceback):\n super().__init__()\n self.contents = \"\"\"
    ____child__
    \"\"\"\n self.traceback = traceback\n self.children = {\"____child__\": Cell.makeCell(traceback)}\n\n def sortsAs(self):\n return self.traceback\n\nclass Code(Cell):\n def __init__(self, codeContents):\n super().__init__()\n self.contents = \"\"\"
    ____child__
    \"\"\"\n self.codeContents = codeContents\n self.children = {\"____child__\": Cell.makeCell(codeContents)}\n\n def sortsAs(self):\n return self.codeContents\n\nclass Subscribed(Cell):\n def __init__(self, f):\n super().__init__()\n\n self.f = f\n\n def prepareForReuse(self):\n self._clearSubscriptions()\n return super().prepareForReuse()\n\n def __repr__(self):\n return \"Subscribed(%s)\" % self.f\n\n def sortsAs(self):\n for c in self.children.values():\n return c.sortsAs()\n\n return Cell.makeCell(self.f()).sortsAs()\n\n def recalculate(self):\n with self.view() as v:\n self.contents = \"\"\"
    ____contents__
    \"\"\" % self._divStyle()\n try:\n c = Cell.makeCell(self.f())\n if c.cells is not None:\n c.prepareForReuse()\n self.children = {'____contents__': c}\n except SubscribeAndRetry:\n raise\n except Exception:\n self.children = {'____contents__': Traceback(traceback.format_exc())}\n self._logger.error(\"Subscribed inner function threw exception:\\n%s\", traceback.format_exc())\n\n self._resetSubscriptionsToViewReads(v)\n\nclass SubscribedSequence(Cell):\n def __init__(self, itemsFun, rendererFun):\n super().__init__()\n\n self.itemsFun = itemsFun\n self.rendererFun = rendererFun\n\n self.existingItems = {}\n self.spine = []\n\n def prepareForReuse(self):\n self._clearSubscriptions()\n self.existingItems = {}\n self.spine = []\n return super().prepareForReuse()\n\n def sortsAs(self):\n if '____child_0__' in self.children:\n return self.children['____child_0__'].sortsAs()\n\n def recalculate(self):\n with self.view() as v:\n try:\n self.spine = augmentToBeUnique(self.itemsFun())\n except SubscribeAndRetry:\n raise\n except Exception:\n self._logger.error(\"Spine calc threw an exception:\\n%s\", traceback.format_exc())\n self.spine = []\n\n self._resetSubscriptionsToViewReads(v)\n\n new_children = {}\n for ix, rowKey in enumerate(self.spine):\n if rowKey in self.existingItems:\n new_children[\"____child_%s__\" % ix] = self.existingItems[rowKey]\n else:\n try:\n self.existingItems[rowKey] = new_children[\"____child_%s__\" % ix] = Cell.makeCell(self.rendererFun(rowKey[0]))\n except SubscribeAndRetry:\n raise\n except Exception:\n self.existingItems[rowKey] = new_children[\"____child_%s__\" % ix] = Traceback(traceback.format_exc())\n\n self.children = new_children\n\n spineAsSet = set(self.spine)\n for i in list(self.existingItems):\n if i not in spineAsSet:\n del self.existingItems[i]\n\n self.contents = \"\"\"
    %s
    \"\"\" % (\n self._divStyle(),\n \"\\n\".join(['____child_%s__' % i for i in range(len(self.spine))])\n )\n\nclass Popover(Cell):\n def __init__(self, contents, title, detail, width=400):\n super().__init__()\n\n self.width = width\n self.children = {\n '____contents__': Cell.makeCell(contents),\n '____detail__': Cell.makeCell(detail),\n '____title__': Cell.makeCell(title)\n }\n\n def recalculate(self):\n self.contents = \"\"\"\n
    \n ____contents__\n
    \n
    \n
    bottom
    \n
    ____title__
    \n
    ____detail__
    \n
    \n
    \n\n
    \n \"\"\".replace(\"__style__\", self._divStyle()).replace(\"__identity__\", self.identity).replace(\"__width__\", str(self.width))\n\n def sortsAs(self):\n if '____title__' in self.children:\n return self.children['____title__'].sortsAs()\n\n\n\nclass Grid(Cell):\n def __init__(self, colFun, rowFun, headerFun, rowLabelFun, rendererFun):\n super().__init__()\n self.colFun = colFun\n self.rowFun = rowFun\n self.headerFun = headerFun\n self.rowLabelFun = rowLabelFun\n self.rendererFun = rendererFun\n\n self.existingItems = {}\n self.rows = []\n self.cols = []\n\n def prepareForReuse(self):\n self._clearSubscriptions()\n self.existingItems = {}\n self.rows = []\n self.cols = []\n super().prepareForReuse()\n\n def recalculate(self):\n with self.view() as v:\n try:\n self.rows = augmentToBeUnique(self.rowFun())\n except SubscribeAndRetry:\n raise\n except Exception:\n self._logger.error(\"Row fun calc threw an exception:\\n%s\", traceback.format_exc())\n self.rows = []\n try:\n self.cols = augmentToBeUnique(self.colFun())\n except SubscribeAndRetry:\n raise\n except Exception:\n self._logger.error(\"Col fun calc threw an exception:\\n%s\", traceback.format_exc())\n self.cols = []\n\n self._resetSubscriptionsToViewReads(v)\n\n new_children = {}\n seen = set()\n\n for col_ix, col in enumerate(self.cols):\n seen.add((None, col))\n if (None,col) in self.existingItems:\n new_children[\"____header_%s__\" % (col_ix)] = self.existingItems[(None,col)]\n else:\n try:\n self.existingItems[(None,col)] = new_children[\"____header_%s__\" % col_ix] = Cell.makeCell(self.headerFun(col[0]))\n except SubscribeAndRetry:\n raise\n except Exception:\n self.existingItems[(None,col)] = new_children[\"____header_%s__\" % col_ix] = Traceback(traceback.format_exc())\n\n if self.rowLabelFun is not None:\n for row_ix, row in enumerate(self.rows):\n seen.add((None, row))\n if (row, None) in self.existingItems:\n new_children[\"____rowlabel_%s__\" % (row_ix)] = self.existingItems[(row, None)]\n else:\n try:\n self.existingItems[(row, None)] = new_children[\"____rowlabel_%s__\" % row_ix] = Cell.makeCell(self.rowLabelFun(row[0]))\n except SubscribeAndRetry:\n raise\n except Exception:\n self.existingItems[(row, None)] = new_children[\"____rowlabel_%s__\" % row_ix] = Traceback(traceback.format_exc())\n\n seen = set()\n for row_ix, row in enumerate(self.rows):\n for col_ix, col in enumerate(self.cols):\n seen.add((row,col))\n if (row,col) in self.existingItems:\n new_children[\"____child_%s_%s__\" % (row_ix, col_ix)] = self.existingItems[(row,col)]\n else:\n try:\n self.existingItems[(row,col)] = new_children[\"____child_%s_%s__\" % (row_ix, col_ix)] = Cell.makeCell(self.rendererFun(row[0],col[0]))\n except SubscribeAndRetry:\n raise\n except Exception:\n self.existingItems[(row,col)] = new_children[\"____child_%s_%s__\" % (row_ix, col_ix)] = Traceback(traceback.format_exc())\n\n self.children = new_children\n\n for i in list(self.existingItems):\n if i not in seen:\n del self.existingItems[i]\n\n self.contents = \"\"\"\n \n \"\"\" + (\"\" if self.rowLabelFun is not None else \"\") + \"\"\"__headers__\n \n __rows__\n \n
    \n \"\"\".replace(\"__headers__\",\n \"\".join(\"____header_%s__\" % (col_ix)\n for col_ix in range(len(self.cols)))\n ).replace(\"__rows__\",\n \"\\n\".join(\"\" +\n (\"____rowlabel_%s__\" % row_ix if self.rowLabelFun is not None else \"\") +\n \"\".join(\n \"____child_%s_%s__\" % (row_ix, col_ix)\n for col_ix in range(len(self.cols))\n )\n + \"\"\n for row_ix in range(len(self.rows))\n )\n )\n\nclass SortWrapper:\n def __init__(self, x):\n self.x = x\n\n def __lt__(self, other):\n try:\n if type(self.x) is type(other.x):\n return self.x < other.x\n else:\n return str(type(self.x)) < str(type(other.x))\n except Exception:\n try:\n return str(self.x) < str(self.other)\n except Exception:\n return False\n\n def __eq__(self, other):\n try:\n if type(self.x) is type(other.x):\n return self.x == other.x\n else:\n return str(type(self.x)) == str(type(other.x))\n except Exception:\n try:\n return str(self.x) == str(self.other)\n except Exception:\n return True\n\nclass SingleLineTextBox(Cell):\n def __init__(self, slot, pattern=None):\n super().__init__()\n self.children = {}\n self.pattern = None\n self.slot = slot\n\n def recalculate(self):\n self.contents = (\n \"\"\"\n \n \"\"\".replace(\"__style__\", self._divStyle())\n .replace(\"__identity__\", self.identity)\n .replace(\"__contents__\", quoteForJs(self.slot.get(),'\"'))\n .replace(\"__pat__\", \"\" if not self.pattern else quoteForJs(self.pattern, '\"'))\n .replace(\"__sytle__\", self._divStyle())\n )\n\n def onMessage(self, msgFrame):\n self.slot.set(msgFrame['text'])\n\nclass Table(Cell):\n \"\"\"An active table with paging, filtering, sortable columns.\"\"\"\n def __init__(self, colFun, rowFun, headerFun, rendererFun, maxRowsPerPage=20):\n super().__init__()\n self.colFun = colFun\n self.rowFun = rowFun\n self.headerFun = headerFun\n self.rendererFun = rendererFun\n\n self.existingItems = {}\n self.rows = []\n self.cols = []\n\n self.maxRowsPerPage = maxRowsPerPage\n\n self.curPage = Slot(\"1\")\n self.sortColumn = Slot(None)\n self.sortColumnAscending = Slot(True)\n self.columnFilters = {}\n\n def prepareForReuse(self):\n self._clearSubscriptions()\n self.existingItems = {}\n self.rows = []\n self.cols = []\n super().prepareForReuse()\n\n def cachedRenderFun(self, row, col):\n if (row, col) in self.existingItems:\n return self.existingItems[row,col]\n else:\n return self.rendererFun(row, col)\n\n def filterRows(self, rows):\n for col in self.cols:\n if col not in self.columnFilters:\n self.columnFilters[col] = Slot(None)\n\n filterString = self.columnFilters.get(col).get()\n\n if filterString:\n new_rows = []\n for row in rows:\n filterAs = self.cachedRenderFun(row, col).sortsAs()\n\n if filterAs is None:\n filterAs = \"\"\n else:\n filterAs = str(filterAs)\n\n if filterString in filterAs:\n new_rows.append(row)\n rows = new_rows\n\n return rows\n\n def sortRows(self, rows):\n sc = self.sortColumn.get()\n\n if sc is not None and sc < len(self.cols):\n col = self.cols[sc]\n\n keymemo = {}\n def key(row):\n if row not in keymemo:\n try:\n r = self.cachedRenderFun(row, col)\n keymemo[row] = SortWrapper(r.sortsAs())\n except Exception:\n self._logger.error(traceback.format_exc())\n keymemo[row] = SortWrapper(None)\n\n return keymemo[row]\n\n rows = sorted(rows,key=key)\n\n if not self.sortColumnAscending.get():\n rows = list(reversed(rows))\n\n page = 0\n try:\n page = max(0, int(self.curPage.get())-1)\n page = min(page, (len(rows) - 1) // self.maxRowsPerPage)\n except Exception:\n self._logger.error(\"Failed to parse current page: %s\", traceback.format_exc())\n\n return rows[page * self.maxRowsPerPage:(page+1) * self.maxRowsPerPage]\n\n def makeHeaderCell(self, col_ix):\n col = self.cols[col_ix]\n\n if col not in self.columnFilters:\n self.columnFilters[col] = Slot(None)\n\n def icon():\n if self.sortColumn.get() != col_ix:\n return \"\"\n return Octicon(\"arrow-up\" if not self.sortColumnAscending.get() else \"arrow-down\")\n\n cell = Cell.makeCell(self.headerFun(col)).nowrap() + Padding() + Subscribed(icon).nowrap()\n def onClick():\n if self.sortColumn.get() == col_ix:\n self.sortColumnAscending.set(not self.sortColumnAscending.get())\n else:\n self.sortColumn.set(col_ix)\n self.sortColumnAscending.set(False)\n\n res = Clickable(cell, onClick, makeBold=True)\n\n if self.columnFilters[col].get() is None:\n res = res.nowrap() + Clickable(Octicon(\"search\"), lambda: self.columnFilters[col].set(\"\")).nowrap()\n else:\n res = res + SingleLineTextBox(self.columnFilters[col]).nowrap() + \\\n Button(Octicon(\"x\"), lambda: self.columnFilters[col].set(None), small=True)\n\n return Card(res, padding=1)\n\n def recalculate(self):\n with self.view() as v:\n try:\n self.cols = list(self.colFun())\n except SubscribeAndRetry:\n raise\n except Exception:\n self._logger.error(\"Col fun calc threw an exception:\\n%s\", traceback.format_exc())\n self.cols = []\n\n try:\n self.unfilteredRows = list(self.rowFun())\n self.filteredRows = self.filterRows(self.unfilteredRows)\n self.rows = self.sortRows(self.filteredRows)\n\n except SubscribeAndRetry:\n raise\n except Exception:\n self._logger.error(\"Row fun calc threw an exception:\\n%s\", traceback.format_exc())\n self.rows = []\n\n self._resetSubscriptionsToViewReads(v)\n\n new_children = {}\n seen = set()\n\n for col_ix, col in enumerate(self.cols):\n seen.add((None, col))\n if (None,col) in self.existingItems:\n new_children[\"____header_%s__\" % (col_ix)] = self.existingItems[(None,col)]\n else:\n try:\n self.existingItems[(None,col)] = new_children[\"____header_%s__\" % col_ix] = self.makeHeaderCell(col_ix)\n except SubscribeAndRetry:\n raise\n except Exception:\n self.existingItems[(None,col)] = new_children[\"____header_%s__\" % col_ix] = Traceback(traceback.format_exc())\n\n seen = set()\n for row_ix, row in enumerate(self.rows):\n for col_ix, col in enumerate(self.cols):\n seen.add((row,col))\n if (row,col) in self.existingItems:\n new_children[\"____child_%s_%s__\" % (row_ix, col_ix)] = self.existingItems[(row,col)]\n else:\n try:\n self.existingItems[(row,col)] = new_children[\"____child_%s_%s__\" % (row_ix, col_ix)] = Cell.makeCell(self.rendererFun(row,col))\n except SubscribeAndRetry:\n raise\n except Exception:\n self.existingItems[(row,col)] = new_children[\"____child_%s_%s__\" % (row_ix, col_ix)] = Traceback(traceback.format_exc())\n\n self.children = new_children\n\n for i in list(self.existingItems):\n if i not in seen:\n del self.existingItems[i]\n\n totalPages = ((len(self.filteredRows) - 1) // self.maxRowsPerPage + 1)\n\n rowDisplay = \"____left__ ____right__ Page ____page__ of \" + str(totalPages)\n if totalPages <= 1:\n self.children['____page__'] = Cell.makeCell(totalPages).nowrap()\n else:\n self.children['____page__'] = SingleLineTextBox(self.curPage, pattern=\"[0-9]+\").width(10 * len(str(totalPages)) + 6).height(20).nowrap()\n if self.curPage.get() == \"1\":\n self.children['____left__'] = Octicon(\"triangle-left\").nowrap().color(\"lightgray\")\n else:\n self.children['____left__'] = Clickable(Octicon(\"triangle-left\"), lambda: self.curPage.set(str(int(self.curPage.get())-1))).nowrap()\n\n if self.curPage.get() == str(totalPages):\n self.children['____right__'] = Octicon(\"triangle-right\").nowrap().color(\"lightgray\")\n else:\n self.children['____right__'] = Clickable(Octicon(\"triangle-right\"), lambda: self.curPage.set(str(int(self.curPage.get())+1))).nowrap()\n\n self.contents = (\"\"\"\n \n \"\"\" +\n ('' % rowDisplay) + \"\"\"__headers__\n \n __rows__\n \n
    %s
    \n \"\"\".replace(\"__headers__\",\n \"\".join('____header_%s__' % (col_ix)\n for col_ix in range(len(self.cols)))\n ).replace(\"__rows__\",\n \"\\n\".join(\"\" +\n (\"%s\" % (row_ix+1)) +\n \"\".join(\n \"____child_%s_%s__\" % (row_ix, col_ix)\n for col_ix in range(len(self.cols))\n )\n + \"\"\n for row_ix in range(len(self.rows))\n )\n )\n )\n\nclass Clickable(Cell):\n def __init__(self, content, f, makeBold=False, makeUnderling=False):\n super().__init__()\n self.f = f\n self.content = Cell.makeCell(content)\n self.bold = makeBold\n\n def calculatedOnClick(self):\n if isinstance(self.f, str):\n return quoteForJs(\"window.location.href = '__url__'\".replace(\"__url__\", quoteForJs(self.f, \"'\")), '\"')\n else:\n return \"websocket.send(JSON.stringify({'event':'click', 'target_cell': '__identity__'}))\".replace(\"__identity__\", self.identity)\n\n def recalculate(self):\n self.children = {'____contents__': self.content}\n\n self.contents = \"\"\"\n
    \n ____contents__\n
    \"\"\".replace(\n '__onclick__', self.calculatedOnClick()\n ).replace(\n '__style__',\n self._divStyle(\"cursor:pointer;*cursor: hand\" + (\";font-weight:bold\" if self.bold else \"\"))\n )\n\n def sortsAs(self):\n return self.content.sortsAs()\n\n def onMessage(self, msgFrame):\n self.f()\n\nclass Button(Clickable):\n def __init__(self, *args, small=False, **kwargs):\n Clickable.__init__(self, *args, **kwargs)\n self.small = small\n\n def recalculate(self):\n self.children = {'____contents__': self.content}\n self.contents = (\"\"\"\n \n ____contents__\n \"\"\"\n .replace(\"__size__\", \"\" if not self.small else \"btn-xs\")\n .replace('__identity__', self.identity)\n .replace(\"__onclick__\", self.calculatedOnClick())\n )\n\nclass LoadContentsFromUrl(Cell):\n def __init__(self, targetUrl):\n Cell.__init__(self)\n self.targetUrl = targetUrl\n\n def recalculate(self):\n self.children = {}\n self.contents = \"\"\"\n
    \n
    \n
    \n \"\"\".replace('__identity__', self._identity)\n\n self.postscript = (\n \"$('#loadtarget__identity__').load('__url__')\"\n .replace(\"__identity__\", self._identity)\n .replace(\"__url__\", quoteForJs(self.targetUrl, \"'\"))\n )\n\nclass SubscribeAndRetry(Exception):\n def __init__(self, callback):\n super().__init__(\"SubscribeAndRetry\")\n self.callback = callback\n\ndef ensureSubscribedType(t, lazy=False):\n if not current_transaction().db().isSubscribedToType(t):\n raise SubscribeAndRetry(\n Timer(\"Subscribing to type %s%s\", t, \" lazily\" if lazy else \"\")(\n lambda db: db.subscribeToType(t, lazySubscription=lazy)\n )\n )\n\ndef ensureSubscribedSchema(t, lazy=False):\n if not current_transaction().db().isSubscribedToSchema(t):\n raise SubscribeAndRetry(\n Timer(\"Subscribing to schema %s%s\", t, \" lazily\" if lazy else \"\")(\n lambda db: db.subscribeToSchema(t, lazySubscription=lazy)\n )\n )\n\nclass Expands(Cell):\n def __init__(self, closed, open, closedIcon=Octicon(\"diff-added)\"), openedIcon=Octicon(\"diff-removed\"), initialState=False):\n super().__init__()\n self.isExpanded = initialState\n self.closed = closed\n self.open = open\n self.openedIcon = openedIcon\n self.closedIcon = closedIcon\n\n def sortsAs(self):\n if self.isExpanded:\n return self.open.sortsAs()\n return self.closed.sortsAs()\n\n def recalculate(self):\n self.contents = \"\"\"\n
    \n
    \n ____icon__\n
    \n\n
    \n ____child__\n
    \n
    \n \"\"\".replace(\"__identity__\", self.identity)\n self.contents = self.contents.replace(\"__style__\", self._divStyle())\n self.children = {\n '____child__': self.open if self.isExpanded else self.closed,\n '____icon__': self.openedIcon if self.isExpanded else self.closedIcon\n }\n\n def onMessage(self, msgFrame):\n self.isExpanded = not self.isExpanded\n self.markDirty()\n\nclass CodeEditor(Cell):\n \"\"\"Produce a code editor.\"\"\"\n def __init__(self, onmessage=lambda msg: None, keybindings=None, noScroll=False, minLines=None, fontSize=None):\n \"\"\"Create a code editor\n\n onmessage - receives messages from the user as they type\n keybindings - map from keycode to a lambda function that will receive\n the current buffer and the current selection range\n\n You may call 'setContents' to override the current contents.\n \"\"\"\n super().__init__()\n self._slot = Slot((0,\"\"))\n self._onmessage = onmessage\n self.keybindings = keybindings or {}\n self.noScroll = noScroll\n self.fontSize = fontSize\n self.minLines = minLines\n\n def setContents(self, contents):\n self._slot.set((self._slot.getWithoutRegisteringDependency()[0]+1, contents))\n\n def onMessage(self, msgFrame):\n if msgFrame['event'] == 'keybinding':\n self.keybindings[msgFrame['key']](msgFrame['buffer'], msgFrame['selection'])\n else:\n self._onmessage(msgFrame['data'])\n\n def recalculate(self):\n self.children = {'____child__': Subscribed(lambda: CodeEditorTrigger(self))}\n self.contents = \"\"\"\n
    \n
    \n\n
    \n ____child__\n
    \n\n
    \n \"\"\".replace(\"__identity__\", self.identity).replace(\"__style__\", self._divStyle()) + \";\"\n\n self.postscript = \"\"\"\n var editor = ace.edit(\"editor__identity__\");\n aceEditors[\"editor__identity__\"] = editor\n\n console.log(\"setting up editor\")\n editor.setTheme(\"ace/theme/textmate\");\n editor.session.setMode(\"ace/mode/python\");\n editor.setAutoScrollEditorIntoView(true);\n editor.session.setUseSoftTabs(true);\n \"\"\"\n\n if self.fontSize is not None:\n self.postscript += \"\"\"\n editor.setOption(\"fontSize\", %s);\n \"\"\" % self.fontSize\n\n if self.minLines is not None:\n self.postscript += \"\"\"\n editor.setOption(\"minLines\", __minlines__);\n \"\"\".replace(\"__minlines__\", str(self.minLines))\n\n if self.noScroll:\n self.postscript += \"\"\"\n editor.setOption(\"maxLines\", Infinity);\n \"\"\"\n\n\n if self._onmessage is not None:\n self.postscript += \"\"\"\n editor.session.on('change', function(delta) {\n websocket.send(\n JSON.stringify(\n {'event': 'editor_change', 'target_cell': '__identity__', 'data': delta}\n )\n )\n });\n \"\"\"\n\n for kb in self.keybindings:\n self.postscript += \"\"\"\n editor.commands.addCommand({\n name: 'cmd___key__',\n bindKey: {win: 'Ctrl-__key__', mac: 'Command-__key__'},\n exec: function(editor) {\n websocket.send(\n JSON.stringify(\n {'event': 'keybinding', 'target_cell': '__identity__', 'key': '__key__',\n 'buffer': editor.getValue(), 'selection': editor.selection.getRange()}\n )\n )\n },\n readOnly: true // false if this command should not apply in readOnly mode\n });\n \"\"\".replace(\"__key__\", kb)\n\n self.postscript = self.postscript.replace(\"__identity__\", self.identity)\n\n\nclass CodeEditorTrigger(Cell):\n def __init__(self, editor):\n super().__init__()\n self.editor = editor\n\n def recalculate(self):\n self.contents = \"\"\"
    \"\"\"\n self.postscript = \"\"\"\n var editor = aceEditors[\"editor__identity__\"]\n console.log(\"setting contents\")\n\n curRange = editor.selection.getRange()\n var Range=require('ace/range').Range\n var range = new Range(curRange.start.row,curRange.start.column,curRange.end.row,curRange.end.column)\n console.log(range)\n\n editor.setValue(\"__text__\")\n editor.selection.setRange(range)\n\n \"\"\".replace(\"__identity__\", self.editor.identity).replace(\n \"__text__\", quoteForJs(self.editor._slot.get()[1], '\"')\n )\n\n\nclass Sheet(Cell):\n \"\"\"Make a nice spreadsheet viewer. The dataset needs to be static in this implementation.\"\"\"\n def __init__(self, columnNames, rowCount, rowFun, colWidth=200):\n super().__init__()\n\n self.columnNames = columnNames\n self.rowCount = rowCount\n self.rowFun = rowFun #for a row, the value of all the columns in a list.\n self.colWidth = colWidth\n self.error = Slot(None)\n self._overflow = \"auto\"\n self.rowsSent = set()\n\n def recalculate(self):\n self.contents = \"\"\"\n
    \n
    \n ____error__\n
    \n \"\"\".replace(\"__style__\", self._divStyle()).replace(\"__identity__\", self.identity)\n\n self.children = {\n '____error__': Subscribed(lambda: Traceback(self.error.get()) if self.error.get() is not None else Text(\"\"))\n }\n\n self.postscript = \"\"\"\n function model(opts) { return {} }\n\n function property(index) {\n return function (row) {\n return row[index]\n }\n }\n\n function SyntheticIntegerArray(size) {\n this.length = size\n this.cache = {}\n this.push = function() { }\n this.splice = function() {}\n\n this.slice = function(low, high) {\n if (high === undefined) {\n high = this.length\n }\n\n res = Array(high-low)\n initLow = low\n while (low < high) {\n out = this.cache[low]\n if (out === undefined) {\n websocket.send(JSON.stringify(\n {'event':'sheet_needs_data',\n 'target_cell': '__identity__',\n 'data': low\n }\n ))\n out = emptyRow\n }\n res[low-initLow] = out\n low = low + 1\n }\n\n return res\n }\n }\n\n var data = new SyntheticIntegerArray(__rows__)\n var container = document.getElementById('sheet__identity__');\n\n var colnames = [__column_names__]\n var columns = []\n var emptyRow = []\n\n for (var i = 0; i < colnames.length; i++) {\n columns.push({data: property(i)})\n emptyRow.push(\"\")\n }\n\n var currentTable = new Handsontable(container, {\n data: data,\n dataSchema: model,\n colHeaders: colnames,\n columns: columns,\n rowHeaders: true,\n rowHeaderWidth: 100,\n viewportRowRenderingOffset: 100,\n autoColumnSize: false,\n autoRowHeight: false,\n manualColumnResize: true,\n colWidths: __col_width__,\n rowHeights: 23,\n readOnly: true,\n ManualRowMove: false\n });\n\n handsOnTables[\"__identity__\"] = currentTable\n\n \"\"\".replace(\"__identity__\", self._identity\n ).replace(\"__rows__\", str(self.rowCount)\n ).replace(\"__column_names__\", \",\".join('\"%s\"' % quoteForJs(x,'\"') for x in self.columnNames)\n ).replace(\"__col_width__\", json.dumps(self.colWidth)\n )\n\n def onMessage(self, msgFrame):\n row = msgFrame['data']\n\n if row in self.rowsSent:\n return\n\n rows = []\n for rowToRender in range(max(0,row-100), min(row+100, self.rowCount)):\n if rowToRender not in self.rowsSent:\n self.rowsSent.add(rowToRender)\n rows.append(rowToRender)\n\n rowData = self.rowFun(rowToRender)\n\n self.triggerPostscript(\"\"\"\n var hot = handsOnTables[\"__identity__\"]\n\n hot.getSettings().data.cache[__row__] = __data__\n \"\"\"\n .replace(\"__row__\", str(rowToRender))\n .replace(\"__identity__\", self._identity)\n .replace(\"__data__\", json.dumps(rowData))\n )\n\n if rows:\n self.triggerPostscript(\"\"\"\n handsOnTables[\"__identity__\"].render()\n \"\"\"\n .replace(\"__identity__\", self._identity)\n )\n\n\nclass Plot(Cell):\n \"\"\"Produce some reactive line plots.\"\"\"\n def __init__(self, namedDataSubscriptions):\n \"\"\"Initialize a line plot.\n\n namedDataSubscriptions: a map from plot name to a lambda function\n producing either an array, or {x: array, y: array}\n \"\"\"\n super().__init__()\n\n self.namedDataSubscriptions = namedDataSubscriptions\n self.curXYRanges = Slot(None)\n self.error = Slot(None)\n\n def recalculate(self):\n self.contents = \"\"\"\n
    \n
    \n ____chart_updater__\n ____error__\n
    \n \"\"\".replace(\"__style__\", self._divStyle()).replace(\"__identity__\", self.identity)\n\n self.children = {\n '____chart_updater__': _PlotUpdater(self),\n '____error__': Subscribed(lambda: Traceback(self.error.get()) if self.error.get() is not None else Text(\"\"))\n }\n\n self.postscript = \"\"\"\n plotDiv = document.getElementById('plot__identity__');\n Plotly.plot(\n plotDiv,\n [],\n { margin: {t : 30, l: 30, r: 30, b:30 }\n },\n { scrollZoom: true, dragmode: 'pan', displaylogo: false, displayModeBar: 'hover',\n modeBarButtons: [ ['pan2d'], ['zoom2d'], ['zoomIn2d'], ['zoomOut2d'] ] }\n );\n plotDiv.on('plotly_relayout',\n function(eventdata){\n //if we're sending a string, then its a date object, and we want to send\n // a timestamp\n if (typeof(eventdata['xaxis.range[0]']) === 'string') {\n eventdata = Object.assign({},eventdata)\n eventdata[\"xaxis.range[0]\"] = Date.parse(eventdata[\"xaxis.range[0]\"]) / 1000.0\n eventdata[\"xaxis.range[1]\"] = Date.parse(eventdata[\"xaxis.range[1]\"]) / 1000.0\n }\n\n websocket.send(JSON.stringify(\n {'event':'plot_layout',\n 'target_cell': '__identity__',\n 'data': eventdata\n }\n )\n )\n });\n\n \"\"\".replace(\"__identity__\", self._identity)\n\n def onMessage(self, msgFrame):\n d = msgFrame['data']\n curVal = self.curXYRanges.get() or ((None, None), (None,None))\n\n self.curXYRanges.set(\n ((d.get('xaxis.range[0]', curVal[0][0]), d.get('xaxis.range[1]',curVal[0][1])),\n (d.get('yaxis.range[0]', curVal[1][0]), d.get('yaxis.range[1]',curVal[1][1])))\n )\n\nclass _PlotUpdater(Cell):\n \"\"\"Helper utility to push data into an existing line plot.\"\"\"\n def __init__(self, linePlot):\n super().__init__()\n\n self.linePlot = linePlot\n self.namedDataSubscriptions = linePlot.namedDataSubscriptions\n self.chartId = linePlot._identity\n\n def calculatedDataJson(self):\n series = self.callFun(self.namedDataSubscriptions)\n\n assert isinstance(series, (dict, list))\n\n if isinstance(series, dict):\n return [self.processSeries(callableOrData, name) for name, callableOrData in\n series.items()]\n else:\n return [self.processSeries(callableOrData, None) for callableOrData in\n series]\n\n def callFun(self, fun):\n if not callable(fun):\n return fun\n\n sig = signature(fun)\n if len(sig.parameters) == 0:\n return fun()\n if len(sig.parameters) == 1:\n return fun(self.linePlot)\n assert False, \"%s expects more than 1 argument\" % fun\n\n def processSeries(self, callableOrData, name):\n data = self.callFun(callableOrData)\n\n if isinstance(data, list):\n res = {'x': [float(x) for x in range(len(data))], 'y': [float(d) for d in data]}\n else:\n assert isinstance(data, dict)\n res = dict(data)\n\n for k,v in res.items():\n if isinstance(v, numpy.ndarray):\n res[k] = v.astype('float64').tostring().hex()\n\n if name is not None:\n res['name'] = name\n\n return res\n\n def recalculate(self):\n with self.view() as v:\n #we only exist to run our postscript\n self.contents = \"\"\"
    \"\"\"\n hadChildren = len(self.children) > 0\n self.children = {}\n self.postscript = \"\"\n self.linePlot.error.set(None)\n\n try:\n jsonDataToDraw = self.calculatedDataJson()\n self.postscript = \"\"\"\n plotDiv = document.getElementById('plot__identity__');\n data = __data__.map(mapPlotlyData)\n\n Plotly.react(\n plotDiv,\n data,\n plotDiv.layout,\n );\n\n \"\"\".replace(\"__identity__\", self.chartId).replace(\"__data__\",\n json.dumps(jsonDataToDraw)\n )\n except SubscribeAndRetry:\n raise\n except Exception:\n self._logger.error(traceback.format_exc())\n self.linePlot.error.set(traceback.format_exc())\n self.postscript = \"\"\"\n plotDiv = document.getElementById('plot__identity__');\n Plotly.purge(plotDiv)\n \"\"\".replace(\"__identity__\", self.chartId)\n\n\n self._resetSubscriptionsToViewReads(v)\n","sub_path":"object_database/web/cells.py","file_name":"cells.py","file_ext":"py","file_size_in_byte":70055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577228789","text":"# -*- coding: utf-8 -*-\n\nimport pytest\nfrom bin.Yaml import readYaml\n\n\"\"\"\n\n# @allure.feature # 用于定义被测试的功能,被测产品的需求点\n# @allure.story # 用于定义被测功能的用户场景,即子功能点\n# @allure.severity #用于定义用例优先级\n# @allure.issue #用于定义问题表识,关联标识已有的问题,可为一个url链接地址\n# @allure.testcase #用于用例标识,关联标识用例,可为一个url链接地址\n\n# @allure.attach # 用于向测试报告中输入一些附加的信息,通常是一些测试数据信息\n# @pytest.allure.step # 用于将一些通用的函数作为测试步骤输出到报告,调用此函数的地方会向报告中输出步骤\n# allure.environment(environment=env) #用于定义environment\n\n\"\"\"\ncontent = readYaml('application.yaml')\n# conf=readYaml('params/base.yaml')\n\n@pytest.fixture()\ndef action():\n # 定义环境\n env = content['ENV']\n print(env)\n # 定义报告中environment\n # if env == 'test':\n # host = conf['host']\n # tester = conf['tester']\n # elif env == 'product':\n # host = conf['host']\n # tester = conf['tester']\n # else:\n # conf.log.info('please check your env param!')\n # return None\n # print(host, tester)\n # allure.environment(environment=env)\n # allure.environment(hostname=host)\n # allure.environment(tester=tester)\n return env\n\n\n# if __name__ == '__main__':\n# action\n","sub_path":"autoTest/flow/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"14853612","text":"import numpy as np\r\nfrom scipy import optimize\r\n#x, y が 5 つの不等式\r\n#x + 2y <= 10,\r\n#x + y <= 6,\r\n#3x + y <= 12,\r\n#x >= 0,\r\n#y >= 0\r\n#を満たすとする.\r\n#2x + y は\r\nA = np.array([[1, 2],\r\n [1, 1],\r\n [3, 1]])\r\nb = np.array([10, 6, 12])\r\nc = np.array([-2, -1])\r\nkekka = optimize.linprog(c, A_ub=A, b_ub=b, bounds=((0,None), (0,None)))\r\nprint(kekka[\"x\"])\r\nupper =-1*kekka[\"fun\"]\r\nprint(\"答え:\"+str(upper))\r\n#x, y が 5 つの不等式\r\n#x + 14y <= 238,\r\n#8x + 7y <= 224,\r\n#8x + 3y <= 192,\r\n#x >= 0,\r\n#y >= 0\r\n#を満たすとする。\r\n#15x + 14y は、\r\nA = np.array([[1, 14],\r\n [8, 7],\r\n [8, 3]])\r\nb = np.array([238, 224, 192])\r\nc = np.array([-15, -14])\r\nkekka = optimize.linprog(c, A_ub=A, b_ub=b, bounds=((0,None), (0,None)))\r\nprint(kekka[\"x\"])\r\nupper =-1*kekka[\"fun\"]\r\nprint(\"答え:\"+str(upper))","sub_path":"O_kadai18_1.py","file_name":"O_kadai18_1.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568088057","text":"\"\"\"\nIdentification\n Module: utils\n Author: Victor Puska\n Written: Feb 09, 2018\n Copyright: (c) 2018 by VICTOR PUSKA.\n License: LICENSE_NAME, see LICENSE_FILE for more details.\n\nDescription\n Authentication and authority management for the application.\n\"\"\"\n\nimport urllib\nfrom flask import Flask, url_for\n\n\ndef get_routes(app: Flask):\n \"\"\"Return an array of tuples (endpoint, methods and url) listing the application routes\"\"\"\n rules = []\n args = {}\n for rule in app.url_map.iter_rules():\n for arg in rule.arguments:\n args[arg] = \"[{0}]\".format(arg)\n entry = (\n rule.endpoint, #endpoint\n \",\".join(rule.methods), #methods\n urllib.parse.unquote(url_for(rule.endpoint,**args)) #url\n )\n rules.append(entry)\n return rules\n\n\ndef get_datetime_format():\n return ()","sub_path":"extensions/core/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"84797215","text":"# coding=utf-8\n\nfrom pyspark import SparkContext, SparkConf\n\nsc = SparkContext('local', 'Simple App')\n\nlogFile = '/user-software/spark-2.0.0-bin-hadoop2.6/README.md'\nlogData = sc.textFile(logFile)\n\n# This program just counts the number of lines containing ‘a’ and the number containing ‘b’ in a text file.\nnumAs = logData.filter(lambda s : 'a' in s).count()\nnumBs = logData.filter(lambda s : 'b' in s).count()\nprint(numAs)\nprint(numBs)\n# We can run this application using the bin/spark-submit script\n# YOUR_SPARK_HOME/bin/spark-submit \\\n# --master local[4] \\\n# your spark application file\nsc.stop()","sub_path":"01-QuickStart/spark_application.py","file_name":"spark_application.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"60891592","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport math\n\nnum_column = 14 # 1-14列数据,15列标签\nnum_row = 32561\n\nimport pickle as pkl\nfrom lib_pkl_sl import *\n\nimport continuous_model\ncon_model = continuous_model.continuous()\nimport discrete\n\n# processing https://archive.ics.uci.edu/ml/datasets/Adult\n\nif __name__ == '__main__':\n # open xlsx\n import openpyxl\n wb = openpyxl.load_workbook('adult.data.xlsx')\n sheet = wb.active\n\n # extract data\n for j in range(num_column):\n contents = [sheet.cell(row = i+1, column = j+1).value for i in range(num_row)]\n from collections import Counter\n cnter = Counter(contents)\n most_common_elem = cnter.most_common(1)[0][0] # 频率最高的元素\n if contents.count(most_common_elem) > 0.6 * num_row:\n # 如果存在主类,就用二值处理\n to_add = discrete.binary(contents)\n else:\n # 如果是连续值,就直接标准化。\n # 因为源数据中没有正相关性强的属性,所以都默认没有正相关\n if type(contents[0]) == type(3) and len(set(contents)) > 20: # 数字,连续变量\n to_add = con_model.solve_no(contents)\n else:\n # 离散值,直接one-hot处理\n try:\n contents = [elem.strip() for elem in contents]\n except AttributeError:\n pass\n to_add = discrete.discrete(contents)\n print(j+1, \"To Add:\", to_add.shape)\n if len(to_add.shape) == 1:\n to_add = to_add.reshape(to_add.shape[0], 1)\n print(\"Reshape:\", to_add.shape)\n try:\n dataset = np.concatenate((dataset, to_add), axis = 1)\n except NameError:\n dataset = to_add\n print(j+1, \"Dataset:\", dataset.shape)\n print(\"Final Dataset:\", dataset.shape)\n\n label_lst = [sheet.cell(row = i+1, column = 15).value for i in range(num_row)]\n labelset = discrete.binary(label_lst, most_common_elem = ' <=50K')\n print(\"Final Labelset:\", labelset.shape)\n\n # save\n saveToFile([dataset, labelset], [\"dataset.pkl\", \"labelset.pkl\"])\n\n\n\n ","sub_path":"data-50k/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597296630","text":"import time\r\nimport pyautogui\r\n\r\n\r\ndef click_element(element):\r\n wait_until_element_is_visible(element)\r\n x, y = pyautogui.locateCenterOnScreen(element, confidence=.8)\r\n pyautogui.moveTo(x, y)\r\n pyautogui.click(x, y)\r\n\r\n\r\ndef wait_until_element_is_visible(image: str, waitTime=5):\r\n t = time.time()\r\n x = None\r\n while x is None:\r\n x = pyautogui.locateCenterOnScreen(image, confidence=.8)\r\n if time.time() - t > waitTime:\r\n raise TimeoutError(\"element not visible since 5s\")\r\n\r\n\r\ndef scroll_until_element_is_visible(images, direction=-1):\r\n x = None\r\n\r\n while x is None:\r\n for image in images:\r\n x = pyautogui.locateCenterOnScreen(image, confidence=.8)\r\n if x is not None:\r\n element = image\r\n break\r\n pyautogui.scroll(100 * direction)\r\n\r\n return element\r\n\r\n\r\ndef pageDown_until_element_is_visible(images):\r\n x = None\r\n\r\n while x is None:\r\n for image in images:\r\n x = pyautogui.locateCenterOnScreen(image, confidence=.8)\r\n if x is not None:\r\n element = image\r\n break\r\n pyautogui.press(\"num3\")\r\n pyautogui.press(\"numlock\")\r\n pyautogui.press(\"num3\")\r\n pyautogui.press(\"numlock\")\r\n\r\n return element\r\n\r\n\r\ndef open_right_click_mouse_menu():\r\n x, y = pyautogui.size()\r\n pyautogui.rightClick(x / 2, 0)\r\n\r\n\r\ndef click_element_in_right_click_mouse_menu(element):\r\n open_right_click_mouse_menu()\r\n wait_until_element_is_visible(element)\r\n x, y = pyautogui.locateCenterOnScreen('displaySettings.jpg', confidence=.9)\r\n pyautogui.click(x, y)\r\n","sub_path":"tests/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596777037","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*- \n# @author: Shengjia Yan\n# @date: 2018-11-16 Friday\n# @email: i@yanshengjia.com\n# Copyright @ Shengjia Yan. All Rights Reserved.\n\"\"\"\nThis module supports GEC analysis for English essays.\n\"\"\"\n\n\nimport re\nimport csv\nimport sys\nsys.path.append(\"..\")\nimport json\nimport xlrd\nfrom scipy.stats import pearsonr\nimport codecs\nimport numpy as np\nimport requests\nfrom src.gec.inference import TorchGEC\nfrom libs.fairseq.fairseq import options\nfrom src.gec.rule_engine import RuleEngine\nfrom utils.artist import Artist\n\n\nlocal_vocab_dir = '../data/vocab/lq'\nlocal_fairseq_model_path = '../data/model/seq2seq/mlconv_5_3_fp32_512_20181220.pt'\nlocal_bpe_codes_path = '../data/model/bpe/train.bpe.model'\nlocal_kenlm_path = '../data/model/language-model/concat_train.trie'\nlocal_rerank_weights_path = '../data/model/reranker-weights/eo_5_3_5_fp16_512_concat_train.txt'\nlocal_embed_path = '../data/embedding/wiki.vec'\nlocal_rules_path = '../config/rules.xml'\nlocal_rules_config_path = '../config/rules.xml'\n\n\ngrammar_score_table = {\n 'A': 5,\n 'B': 4,\n 'C': 3,\n 'D': 2,\n 'E': 1,\n 'F': 0,\n}\n\n\nclass Diagnostician(object):\n def __init__(self):\n self.torch_gec = self.launch_torch_gec()\n self.rule_engine = RuleEngine(local_rules_config_path)\n self.artist = Artist()\n\n def launch_torch_gec(self):\n print('Launching torchGEC...')\n parser = options.get_generation_parser(interactive=True)\n args = options.parse_args_and_arch(parser)\n torch_gec = TorchGEC(args, vocab_dir=local_vocab_dir, fairseq_model_path=local_fairseq_model_path,\n bpe_codes_path=local_bpe_codes_path, kenlm_path=local_kenlm_path,\n rerank_weights_path=local_rerank_weights_path,\n embed_path=local_embed_path, rules_config_path=local_rules_path)\n return torch_gec\n\n def read_excel(self, excel_path):\n print('Loading excel...')\n r_workbook = xlrd.open_workbook(excel_path)\n sheet_names = r_workbook.sheet_names()\n sheet_quantity = len(sheet_names)\n\n question_id_index = 0\n essay_index = 1\n grammar_score_index = 2\n\n res = []\n for sheet_index in range(sheet_quantity):\n print(\"Processing sheet: \" + sheet_names[sheet_index])\n r_worksheet = r_workbook.sheet_by_index(sheet_index)\n offset = 1 # change this depending on how many header rows are present\n for i in range(r_worksheet.nrows):\n if i < offset: # skip headers\n continue\n\n info = dict()\n info['question_id'] = r_worksheet.cell_value(i, question_id_index)\n info['essay'] = r_worksheet.cell_value(i, essay_index)\n info['grammar_score'] = r_worksheet.cell_value(i, grammar_score_index)\n res.append(info)\n break\n return res\n\n def read_dataset(self, dataset_path):\n with codecs.open(dataset_path, mode='r') as datafile:\n dataset = []\n for line in datafile:\n line = line.strip()\n line = line.lower()\n dataset.append(line)\n return dataset\n\n def chunks(self, dataset, chunk_size):\n for i in range(0, len(dataset), chunk_size):\n yield dataset[i:i + chunk_size]\n\n def infer_by_batch(self, dataset, output_path):\n with codecs.open(output_path, mode='a', errors='ignore') as out_file:\n out_file.seek(0)\n out_file.truncate()\n batch_num = 0\n chunk_size = 10000\n sent_index = 0\n for batch in list(self.chunks(dataset, chunk_size)):\n print('{} sentences processed'.format(batch_num * chunk_size))\n bpe_sentences = []\n for sent in batch:\n bpe_sentence = self.torch_gec.gec_assistant.bpe_one_sentence(sent)\n bpe_sentences.append(bpe_sentence)\n targets, mid_results = self.torch_gec.infer(bpe_sentences)\n\n for i in range(len(batch)):\n src = batch[i]\n trg = targets[i]\n op_list = self.torch_gec.gec_assistant.segment_diff(src, trg)\n op_list = self.torch_gec.gec_assistant.gec_errortype_classifier.predict(op_list)\n msg_list = []\n\n for op in op_list:\n op_name = op['op']\n start = op['start']\n end = op['end']\n src_seg = op['src_seg'].strip()\n trg_seg = op['trg_seg'].strip()\n error_types = op['error_type']\n msg = self.torch_gec.generate_msg(op_name, error_types, src, src_seg, trg_seg, start, end)\n msg_list.append(msg)\n\n r = dict()\n r['num'] = sent_index\n r['trg'] = trg\n r['msg'] = ' '.join(msg_list)\n r_text = json.dumps(r)\n out_file.write(r_text + '\\n')\n sent_index += 1\n batch_num += 1\n\n def save2csv(self, o_path, res):\n with codecs.open(o_path, mode='w', errors='ignore', encoding='utf8') as out_file:\n writer = csv.DictWriter(out_file, res[0].keys())\n writer.writeheader()\n for row in res:\n writer.writerow(row)\n\n def init_gec_dict(self):\n gec = dict()\n gec['ADJ'] = 0.0\n gec['ADP'] = 0.0\n gec['ADV'] = 0.0\n gec['VERB'] = 0.0\n gec['VERB_IN'] = 0.0\n gec['VERB_DE'] = 0.0\n gec['VERB_RE'] = 0.0\n gec['CONJ'] = 0.0\n gec['DET'] = 0.0\n gec['NOUN'] = 0.0\n gec['PRON'] = 0.0\n gec['FORMAT'] = 0.0\n gec['X'] = 0.0\n gec['NON_VERB'] = 0.0\n gec['STRUCTURAL_VERB'] = 0.0\n gec['NON_STRUCTURAL_VERB'] = 0.0\n return gec\n\n def essay_formatter(self, essay):\n essay = essay.replace(',', '.')\n essay = re.sub(r'(?<=[.,])(?=[^\\s])', r' ', essay)\n paragraphs, sentences = self.torch_gec.gec_assistant.split_sentences_nltk(essay)\n sentence_num = len(sentences)\n new_sentences = []\n for sent in sentences:\n sent = sent.capitalize()\n new_sentences.append(sent)\n essay = ' '.join(new_sentences)\n return essay, sentence_num\n\n def standardize(self, l):\n \"\"\"\n Z-standardization of l\n :param l: a list of integers\n :return:\n \"\"\"\n a = np.array(l)\n a_mean = np.mean(a)\n a_std = np.std(a)\n l_standardized = [(n - a_mean) / a_std for n in l]\n return l_standardized\n\n def render_gec(self, essay, result):\n new_essay = essay\n results = json.loads(result)\n matches = self.artist.assemble_gec_results(essay, results['matches'])\n\n for match in reversed(matches):\n offset = match['start']\n end = match['end']\n length = end - offset\n msg = match['msg']\n error_types = match['error_types']\n sliced = essay[offset: offset + length]\n\n try:\n msg = msg.replace('\\\"', '')\n msg = msg.replace('\\'', '')\n left_insert = \"<\"\n right_insert = \">\"\n new_essay = new_essay[:offset + length] + right_insert + new_essay[offset + length:]\n new_essay = new_essay[:offset] + left_insert + new_essay[offset:]\n except:\n continue\n return new_essay\n\n def diagnose(self, excel_path):\n non_verb_errortype_list = ['DET', 'PRON', 'NOUN', 'ADP', 'ADJ', 'ADV', 'X']\n structural_verb_errortype_list = ['VERB_IN', 'VERB_DE']\n non_structural_verb_errortype_list = ['VERB_RE']\n testset = self.read_excel(excel_path)\n\n # count all kinds of errors\n result = []\n counter = 0\n for case in testset:\n print(counter, flush=True)\n counter += 1\n essay, sentence_num = self.essay_formatter(case['essay'])\n question_id = case['question_id']\n grammar_score = case['grammar_score']\n case_result_text = self.torch_gec.pipeline(essay)\n case_result = json.loads(case_result_text)\n matches = case_result['matches']\n gec = self.init_gec_dict()\n\n for match in matches:\n ops = match['ops']\n for op in ops:\n op = self.rule_engine.match(op)\n\n for e_type in op['error_type']:\n if e_type in ['ADJ', 'ADV', 'DET', 'PRON']:\n gec[e_type] += 1\n elif e_type in ['VERB', 'AUX']:\n if op['op'] == 'replace':\n new_e_type = 'VERB_RE'\n gec[new_e_type] += 1\n elif op['op'] == 'insert':\n new_e_type = 'VERB_IN'\n gec[new_e_type] += 1\n elif op['op'] == 'delete':\n new_e_type = 'VERB_DE'\n gec[new_e_type] += 1\n elif e_type in ['ADP', 'PART']:\n new_e_type = 'ADP'\n gec[new_e_type] += 1\n elif e_type in ['NOUN', 'PROPN']:\n new_e_type = 'NOUN'\n gec[new_e_type] += 1\n elif e_type in ['CONJ', 'CCONJ', 'SCONJ']:\n new_e_type = 'CONJ'\n gec[new_e_type] += 1\n elif e_type in ['PUNCT', 'SYM', 'FORMAT', 'SPL']:\n pass\n elif e_type in ['INTJ', 'NUM', 'X']:\n new_e_type = 'X'\n gec[new_e_type] += 1\n else:\n pass\n\n # re-calculate error quantity per 10 sentences\n if gec['DET'] >= 3:\n gec['DET'] = 1\n else:\n gec['DET'] = 0\n\n for e_type in non_verb_errortype_list:\n if sentence_num != 0:\n gec[e_type] = (gec[e_type] * 10) / sentence_num\n gec['NON_VERB'] += gec[e_type]\n for e_type in structural_verb_errortype_list:\n if sentence_num != 0:\n gec[e_type] = (gec[e_type] * 10) / sentence_num\n gec['STRUCTURAL_VERB'] += gec[e_type]\n for e_type in non_structural_verb_errortype_list:\n if sentence_num != 0:\n gec[e_type] = (gec[e_type] * 10) / sentence_num\n gec['NON_STRUCTURAL_VERB'] += gec[e_type]\n\n gec['VERB'] = gec['VERB_IN'] + gec['VERB_DE'] + gec['VERB_RE']\n gec['question_id'] = question_id\n gec['original_essay'] = essay\n gec['tagged_essay'] = self.render_gec(essay, case_result_text)\n gec['grammar_score'] = grammar_score\n result.append(gec)\n\n # calculate gec score\n non_verb_errortype_coefficient = 0.4\n structural_verb_errortype_coefficient = 0.36\n non_structural_verb_errortype_coefficient = 0.24\n non_verb_error_list = []\n structural_verb_error_list = []\n non_structural_verb_error_list = []\n for gec in result:\n non_verb_error_list.append(gec['NON_VERB'])\n structural_verb_error_list.append(gec['STRUCTURAL_VERB'])\n non_structural_verb_error_list.append(gec['NON_STRUCTURAL_VERB'])\n\n non_verb_error_list_standardized = self.standardize(non_verb_error_list)\n structural_verb_error_list_standardized = self.standardize(structural_verb_error_list)\n non_structural_verb_error_list_standardized = self.standardize(non_structural_verb_error_list)\n\n for i in range(len(result)):\n result[i]['gec_score_standardized'] = non_verb_errortype_coefficient * non_verb_error_list_standardized[i] + structural_verb_errortype_coefficient * structural_verb_error_list_standardized[i] + non_structural_verb_errortype_coefficient * non_structural_verb_error_list_standardized[i]\n result[i]['gec_score_unstandardized'] = non_verb_errortype_coefficient * non_verb_error_list[i] + structural_verb_errortype_coefficient * structural_verb_error_list[i] + non_structural_verb_errortype_coefficient * non_structural_verb_error_list[i]\n\n self.save2csv('./result.csv', result)\n\n # calculate pearsonr\n gec_score_standardized_list = []\n gec_score_unstandarlized_list = []\n grammar_score_list = []\n error_sum_list = []\n\n for i in range(len(result)):\n # filter\n if len(result[i]['original_essay'].split(' ')) < 3:\n continue\n if result[i]['grammar_score'] == 0:\n continue\n if result[i]['grammar_score'] == 'F' or result[i]['grammar_score'] == 'E':\n continue\n\n gec_score_standardized_list.append(result[i]['gec_score_standardized'])\n gec_score_unstandarlized_list.append(result[i]['gec_score_unstandardized'])\n grammar_score = grammar_score_table[result[i]['grammar_score']]\n grammar_score_list.append(grammar_score)\n error_sum = result[i]['NON_VERB'] + result[i]['STRUCTURAL_VERB'] + result[i]['NON_STRUCTURAL_VERB']\n error_sum_list.append(error_sum)\n\n prs_0, _ = pearsonr(gec_score_standardized_list, grammar_score_list)\n prs_1, _ = pearsonr(gec_score_unstandarlized_list, grammar_score_list)\n prs_2, _ = pearsonr(error_sum_list, grammar_score_list)\n\n print('gec_score_standardized X grammar_score PRS: {}'.format(prs_0))\n print('gec_score_unstandardized X grammar_score PRS: {}'.format(prs_1))\n print('error_sum X grammar_score PRS: {}'.format(prs_2))\n\n def good_sents_finder(self, excel_path):\n testset = self.read_excel(excel_path)\n\n result = []\n counter = 0\n for case in testset:\n print(counter, flush=True)\n counter += 1\n\n essay = case['essay']\n torch_gec = self.torch_gec\n\n opennlp_url = 'http://10.6.0.146:9093'\n grade_url = 'http://10.6.1.207:8888'\n\n payload = {\"texts\": str([essay])}\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Cache-Control\": \"no-cache\",\n }\n opennlp_res = json.loads(requests.request(\"POST\", opennlp_url, data=payload, headers=headers).text)\n syntaxcheck_res = json.loads(torch_gec.pipeline(essay, rerank=False, trim=True, official=True))\n\n big_payload = {\n \"essay\": essay,\n \"opennlp_results\": json.dumps(opennlp_res),\n \"syntaxcheck_results\": json.dumps(syntaxcheck_res)\n }\n rating = json.loads(requests.post(grade_url, data=json.dumps(big_payload), headers=headers).text)\n good_sents = rating['good_sents']\n case['good_sents'] = good_sents\n result.append(case)\n\n self.save2csv('./result.csv', result)\n\n\ndef run_infer_by_batch():\n s2t_path = './s2t.txt'\n out_path = './result.json'\n diagnostician = Diagnostician()\n dataset = diagnostician.read_dataset(s2t_path)\n diagnostician.infer_by_batch(dataset, out_path)\n\n\ndef run_diagnose():\n excel_path = './asr.xlsx'\n diagnostician = Diagnostician()\n diagnostician.diagnose(excel_path)\n\n\ndef run_good_sents_finder():\n excel_path = './asr.xlsx'\n diagnostician = Diagnostician()\n diagnostician.good_sents_finder(excel_path)\n\n\nif __name__ == '__main__':\n run_good_sents_finder()\n","sub_path":"tests/diagnostician.py","file_name":"diagnostician.py","file_ext":"py","file_size_in_byte":16090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"356648371","text":"# ------------------------------------------------------------------------------\n#\n# Project: Master Inventory \n# Authors: Fabian Schindler \n#\n# ------------------------------------------------------------------------------\n# Copyright (C) 2016 European Space Agency\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies of this Software or works derived from this Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n# ------------------------------------------------------------------------------\n\n\nfrom optparse import make_option\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import transaction\nfrom django.db.utils import IntegrityError\n\nfrom minv.commands import MinvCommand\nfrom minv.inventory import models\n\n\nclass Command(MinvCommand):\n option_list = BaseCommand.option_list + (\n make_option(\"-c\", \"--create\",\n action=\"store_const\", dest=\"mode\", const=\"create\", default=\"create\",\n help=\"Set the mode to 'create' (the default).\"\n ),\n make_option(\"-d\", \"--delete\",\n action=\"store_const\", dest=\"mode\", const=\"delete\",\n help=\"Set the mode to 'delete'.\"\n ),\n make_option(\"-l\", \"--list\",\n action=\"store_const\", dest=\"mode\", const=\"list\",\n help=\"Set the mode to 'list'.\"\n ),\n make_option(\"-o\", \"--oads\",\n action=\"append\", dest=\"oads_list\", default=None,\n help=(\n \"For mode 'create' only. Define a new OADS url for the new \"\n \"collection.\"\n )\n ),\n make_option(\"-n\", \"--nga\",\n action=\"append\", dest=\"nga_list\", default=None,\n help=(\n \"For mode 'create' only. Define a new ngA url for the new \"\n \"collection.\"\n )\n )\n )\n\n require_group = \"minv_g_app_engineers\"\n\n args = (\n 'MISSION/FILE-TYPE [ -c | -d | -l ] '\n '[ -o [ -o ... ]] '\n '[ -n [ -n ... ]] '\n )\n\n help = (\n 'Create or delete or list collections. '\n 'Requires membership of group \"minv_g_app_engineers\".'\n )\n\n @transaction.atomic\n def handle_authorized(self, *args, **options):\n mode = options[\"mode\"] or \"create\"\n\n mission = None\n file_type = None\n\n if mode in (\"create\", \"delete\"):\n if not args:\n raise CommandError(\n \"For mode create and delete a collection identifier is \"\n \"necessary.\"\n )\n\n try:\n mission, file_type = args[0].split(\"/\")\n except:\n raise CommandError(\"Invalid Collection specifier '%s'\" % args[0])\n\n if mode == \"create\":\n oads_list = options[\"oads_list\"] or []\n nga_list = options[\"nga_list\"] or []\n\n try:\n collection = models.Collection.objects.create(\n mission=mission, file_type=file_type\n )\n print(\"Adding collection '%s'.\" % collection)\n except IntegrityError:\n raise CommandError(\n \"A collection with mission '%s' and file type '%s' already \"\n \"exists.\" % (mission, file_type)\n )\n\n for url in nga_list:\n location = models.Location.objects.create(\n collection=collection, location_type=\"nga\", url=url\n )\n print(\"Adding location '%s' to collection.\" % location)\n\n for url in oads_list:\n location = models.Location.objects.create(\n collection=collection, location_type=\"oads\", url=url\n )\n print(\"Adding location '%s' to collection.\" % location)\n\n elif mode == \"delete\":\n try:\n collection = models.Collection.objects.get(\n mission=mission, file_type=file_type\n )\n\n except models.Collection.DoesNotExist:\n raise CommandError(\n \"No such collection with mission '%s' and file type '%s'.\"\n % (mission, file_type)\n )\n\n print(\"Deleting collection '%s'\" % collection)\n collection.delete()\n if options.get(\"purge\"):\n # TODO: delete configuration folder as-well\n pass\n\n elif mode == \"list\":\n for collection in models.Collection.objects.all():\n print(collection)\n","sub_path":"minv/inventory/management/commands/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":5546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"537923689","text":"\"\"\"\n 1. Создать функцию, которая выводит на экран цифру, введенную пользоватлем в консоли.\n\n 2. Написать программу, которая принимает 5 значений, введенных пользователем из консоли, сохранит их в список,\n затем передаст значения в фукцию, которая выводит на экран сумму значений списка.\n\n 3. Написать программу, которая:\n - выводит следующее меню на экран\n 1. Ввести значения а и b\n 2. Умножить значения а и b\n 3. Делить а на b\n 4. Выход\n - реализует каждую опцию как фукцию\n - реализует все ошибки и исключения.\n\"\"\"\n\n\n\n\n# 1\ndef function (value):\n return value\n\nprint('Введите значение: ')\na = int(input())\nprint(function(a))\n\n\n# 2\n\ndef function2(array):\n total = 0\n for element in range(len(array)):\n total += array[element]\n\n return total\n\nd = []\ncount, i = 0, 0\nwhile i < 5:\n n = int(input('Введите число'))\n i += 1\n d.append(n)\n\n\nprint(function2(d))\n\n# 3\ndef user_input():\n A = int(input('a: '))\n B = int(input('b: '))\n\n return A, B\n\n\ndef multiplication(A, B):\n return A * B\n\n\ndef divider(A, B):\n return A / B\n\n\ndef quit_pr():\n return True\n\n\na = 0\nb = 0\n\nwhile True:\n\n print('''1. Ввести значения а и b\n2. Умножить значения а и b\n3. Делить а на b\n4. Выход''')\n\n try:\n user_choice = int(input('>>> '))\n\n if user_choice != 4:\n if user_choice == 1:\n a, b = user_input()\n print(f'a: {a}, b: {b}')\n elif user_choice == 2:\n print(f'a * b = {multiplication(a, b)}')\n elif user_choice == 3:\n print(f'a / b = {divider(a, b)}')\n else:\n raise ValueError\n else:\n if quit_pr() is True:\n print('Выход из программы...')\n break\n except (ValueError, ZeroDivisionError):\n print('Допущена ошибка.')\n","sub_path":"3 функции.py","file_name":"3 функции.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411014461","text":"import logging\nimport os\nimport itertools\nimport datetime\n\nimport numpy as np\nimport simulacra as si\nfrom simulacra.units import *\n\nimport ionization as ion\n\nFILE_NAME = os.path.splitext(os.path.basename(__file__))[0]\nOUT_DIR = os.path.join(os.getcwd(), \"out\", FILE_NAME)\nSIM_LIB = os.path.join(OUT_DIR, \"SIMLIB\")\n\nLOGMAN = si.utils.LogManager(\"simulacra\", \"ionization\", stdout_level=logging.INFO)\n\nPLOT_KWARGS = dict(target_dir=OUT_DIR, img_format=\"png\", fig_dpi_scale=6)\n\n\ndef run_spec(spec):\n with LOGMAN as logger:\n sim = si.utils.find_or_init_sim(spec, search_dir=SIM_LIB)\n\n sim.info().log()\n if sim.status != si.Status.FINISHED:\n sim.run_simulation()\n sim.save(save_mesh=True, target_dir=SIM_LIB)\n sim.info().log()\n\n sim.plot_wavefunction_vs_time(show_vector_potential=False, **PLOT_KWARGS)\n\n sim.plot_radial_probability_current_vs_time__combined(\n r_upper_limit=15 * bohr_radius,\n time_lower_limit=-3 * sim.spec.electric_potential[0].pulse_width,\n **PLOT_KWARGS,\n )\n\n return sim\n\n\nif __name__ == \"__main__\":\n with LOGMAN as logger:\n pulse_type = ion.potentials.GaussianPulse\n\n pulse_widths = np.array([50, 100, 200, 400, 800]) * asec\n fluences = np.array([0.1, 1, 10, 20]) * Jcm2\n phases = [0, pi / 4, pi / 2]\n number_of_cycles = [2]\n\n pulse_time_bound = 5\n sim_time_bound = 6\n extra_end_time = 2\n\n dt = 1 * asec\n r_bound = 100 * bohr_radius\n r_points_per_br = 10\n l_bound = 500\n\n specs = []\n for pw, flu, cep, n_cycles in itertools.product(\n pulse_widths, fluences, phases, number_of_cycles\n ):\n pulse = pulse_type.from_number_of_cycles(\n pulse_width=pw,\n fluence=flu,\n phase=cep,\n number_of_cycles=n_cycles,\n number_of_pulse_widths=3,\n window=ion.potentials.LogisticWindow(\n window_time=pulse_time_bound * pw, window_width=0.2 * pw\n ),\n )\n\n specs.append(\n ion.SphericalHarmonicSpecification(\n f\"{pulse_type.__name__}__Nc={n_cycles}_pw={pw / asec:3f}as_flu={flu / Jcm2:3f}jcm2_cep={cep / pi:3f}pi__R={r_bound / bohr_radius:3f}br_ppbr={r_points_per_br}_L={l_bound}_dt={dt / asec:3f}as\",\n r_bound=r_bound,\n r_points=r_points_per_br * r_bound / bohr_radius,\n l_bound=l_bound,\n time_step=dt,\n time_initial=-sim_time_bound * pw,\n time_final=(sim_time_bound + extra_end_time) * pw,\n mask=ion.RadialCosineMask(0.8 * r_bound, r_bound),\n electric_potential=pulse,\n electric_potential_dc_correction=True,\n use_numeric_eigenstates=True,\n numeric_eigenstate_max_energy=20 * eV,\n numeric_eigenstate_max_angular_momentum=20,\n checkpoints=True,\n checkpoint_dir=SIM_LIB,\n checkpoint_every=datetime.timedelta(minutes=1),\n store_radial_probability_current=True,\n )\n )\n\n si.utils.multi_map(run_spec, specs, processes=4)\n","sub_path":"science/probability_current/radial_probability_current__gaussian_pulses.py","file_name":"radial_probability_current__gaussian_pulses.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332257707","text":"\"\"\"\nIn English, present participle is formed by adding suffix -ing to infinite form: go -\n> going. A simple set\nof heuristic rules can be given as follows:\nIf the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee,\netc.)\nIf the verb ends in ie, change ie to y and add ingFor words consisting of consonant-vowel-consonant, double the final letter before\nadding ing\nBy default just add ing\nYour task in this exercise is to define a function make_ing_form() which given a verb\nin infinitive form\nreturns its present participle form. Test your function with words such as lie, see,\nmove and hug.\n\"\"\"\n\n\n\n\ndef make_ing_form(verb):\n v3 = verb[-2:]\n x=verb[-2:]\n y=verb[-1:]\n # return verb[-3],verb[-2],verb[-1]\n consonants = 'bcdfghjklmnpqrstvwxyz'\n vowels='aeiou'\n\n if v3 == 'ee':\n return verb + 'ing'\n\n elif x == 'ie': \n new=verb[:-2]\n return new+'ying'\n\n elif y=='e':\n new=verb[:-1]\n return new+'ing'\n\n elif verb[-1] == 'y':\n return verb+'ing'\n\n elif verb[-3] in consonants and verb[-2] in vowels and verb[-1] in consonants:\n return verb+verb[-1]+'ing'\n\n else:\n return verb+'ing'\n\n# x='die'\n# x='be'\n# x='move'\n# x='study'\n# x='see'\nx=['lie', 'see', 'move', 'hug', 'study','work','lunch','write','watch','play','enjoy','fancy','wait','hold','stop','add']\nfor str in x:\n print(make_ing_form(str))\n","sub_path":"python_assignments/Lab Assignments/making__ing__form.py","file_name":"making__ing__form.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400958320","text":"from json import JSONEncoder, load, dump\nfrom os import sep\nfrom Carte import Carte, Borne, Ouvrier, Tache, Obstacle, Robot, Atelier\n\n\nclass CarteEncoder(JSONEncoder):\n def default(self, o):\n return o.__dict__\n\n\ndef exporter(carte: Carte, path: str = \"\"):\n \"\"\"\n :param path: Chemin finissant par /\n :param carte:\n :return:\n \"\"\"\n with open(f'{path}{carte.nom}.json', 'w') as outfile:\n dump(carte, outfile, cls=CarteEncoder)\n print(f'{path}/{carte.nom}.json')\n\n\ndef importer(chemin: str):\n \"\"\"\n importe une Carte\n Produit une erreur si le fichier est inconnu ou n'est pas une carte\n :param chemin: Le chemin de la carte, fichier json inclus\n :return: Le premier objet carte du fichier chemin\n \"\"\"\n with open(chemin, 'r') as infile:\n dico_carte = load(infile)\n\n for i in range(len(dico_carte['liste_obstacle'])):\n dico_carte['liste_obstacle'][i] = typifier(dico_carte['liste_obstacle'][i], Obstacle)\n dico_carte['liste_obstacle'][i].pos1 = tuple(dico_carte['liste_obstacle'][i].pos1)\n dico_carte['liste_obstacle'][i].pos2 = tuple(dico_carte['liste_obstacle'][i].pos2)\n\n for i in range(len(dico_carte['liste_robot'])):\n dico_carte['liste_robot'][i] = typifier(dico_carte['liste_robot'][i], Robot)\n dico_carte['liste_robot'][i].tache = typifier(dico_carte['liste_robot'][i].tache, Tache)\n dico_carte['liste_robot'][i].tache.depart = tuple(dico_carte['liste_robot'][i].tache.depart)\n dico_carte['liste_robot'][i].tache.fin = tuple(dico_carte['liste_robot'][i].tache.fin)\n dico_carte['liste_robot'][i].pos = tuple(dico_carte['liste_robot'][i].pos)\n\n for i in range(len(dico_carte['liste_atelier'])):\n dico_carte['liste_atelier'][i] = typifier(dico_carte['liste_atelier'][i], Atelier)\n dico_carte['liste_atelier'][i].pos1 = tuple(dico_carte['liste_atelier'][i].pos1)\n dico_carte['liste_atelier'][i].pos2 = tuple(dico_carte['liste_atelier'][i].pos2)\n\n for i in range(len(dico_carte['liste_borne'])):\n dico_carte['liste_borne'][i] = typifier(dico_carte['liste_borne'][i], Borne)\n dico_carte['liste_borne'][i].pos1 = tuple(dico_carte['liste_borne'][i].pos1)\n dico_carte['liste_borne'][i].pos2 = tuple(dico_carte['liste_borne'][i].pos2)\n\n for i in range(len(dico_carte['liste_ouvrier'])):\n dico_carte['liste_ouvrier'][i] = typifier(dico_carte['liste_ouvrier'][i], Ouvrier)\n\n for i in range(len(dico_carte['liste_tache'])):\n dico_carte['liste_tache'][i] = typifier(dico_carte['liste_tache'][i], Tache)\n\n return typifier(dico_carte, Carte)\n\n\ndef typifier(objet: dict, typer: type):\n \"\"\"\n Création d'un objet à partir de ses attributs. Repose sur le fonctionnement très bas niveau de Python\n :param objet: __dict__ d'un objet\n :param typer: classe d'un objet\n :return: un Objet de type type et obj.__dict__ == objet\n \"\"\"\n obj = typer.__new__(typer, \"obj\")\n obj.__dict__ = objet\n return obj\n\n# class Save2:\n#\n# def importer(self, carte: Carte):\n# \"\"\"\n# Transformation du contenue des fichiers json compris dans le dossier 'nomCarte' en objet carte\n# avec la liste des obstacles remplies , la taille et son nom definie\n# :parametre: une carte a remplir et deja enregistrer\n# :return: un objet carte remplit\n# \"\"\"\n#\n# chemin = os.path.join(__file__, carte.nom)\n# if (os.path.exists(chemin)):\n# with open(chemin+'/taille.json' , 'r') as json_data:\n# Taille = json.load(json_data)\n# carte.x = Taille[\"x\"]\n# carte.y = Taille[\"y\"]\n# liste_obstacle = []\n#\n# with open(chemin+'/borne.json','r') as json_data:\n# liste = json.load(json_data)\n# for j in liste[\"Borne\"]:\n# b = Borne(j[\"id\"] , j[\"pos1\"] , j[\"pos2\"])\n# carte.liste_obstacle.append(b)\n#\n# with open(chemin+'/atelier.json','r') as json_data:\n# liste = json.load(json_data)\n# for j in liste[\"Atelier\"]:\n# b = Atelier(j[\"id\"] , j[\"pos1\"] , j[\"pos2\"] , j[\"utilite\"] , j[\"tache\"])\n# carte.liste_obstacle.append(b)\n#\n# with open(chemin+'/obstacle.json','r') as json_data:\n# liste = json.load(json_data)\n# for j in liste[\"Obstacle\"]:\n# b = Obstacle(j[\"id\"] , j[\"pos1\"] ,j[\"pos2\"])\n# carte.liste_obstacle.append(b)\n#\n# with open(chemin+'/Robot.json','r') as json_data:\n# liste = json.load(json_data)\n# for j in liste[\"Robot\"]:\n# b = Robot(j[\"id\"] , j[\"transport\"] , j[\"assemblage\"] , j[\"pos\"] , j[\"vitesse\"])\n# carte.liste_robot.append(b)\n#\n#\n# def enregistrer(self,carte:Carte):\n# \"\"\"\n# Transforme une carte et une liste de robot en fichier json\n# Prend en paramètre une carte et la liste des robot dans la carte\n# :parametre: un objet carte\n# \"\"\"\n#\n# chemin = os.path.join(__file__)\n# if not(os.path.exists(chemin+carte.nom)):\n# os.mkdir(os.path.join(__file__ , carte.nom))\n# chemin = os.path.join(__file__ , carte.nom)\n# o = []\n# b = []\n# a = []\n#\n# with open(chemin+'/taille.json' , 'w+') as json_data:\n# Taille = {\"x\" : carte.x , \"y\" : carte.y}\n# json.dump(Taille, json_data , indent=4)\n#\n# for j in carte.listeObstacle:\n# if type(j) is Borne :\n# b.append({ \"id\" : j.id , \"pos1\" : j.pos1 , \"pos2\" : j.pos2})\n#\n# if type(j) is Atelier :\n# a.append({ \"id\" : j.id , \"pos1\" : j.pos1 , \"pos2\" : j.pos2 ,\n# \"utilite\" : j.utilite , \"tache\" : j.tache})\n#\n# else :\n# o.append({ \"id\" : j.id , \"pos1\" : j.pos1 , \"pos2\" : j.pos2})\n#\n# with open(chemin+\"/obstacle.json\" , \"w+\") as json_data:\n# obstacles = dict({\"Obstacle\" : o})\n# json.dump(obstacles, json_data , indent=4)\n#\n# with open(chemin+\"/borne.json\" , \"w+\") as json_data:\n# bornes = dict({\"Borne\" : b})\n# json.dump(bornes, json_data , indent=4)\n#\n# with open(chemin+\"/atelier.json\" , \"w+\") as json_data:\n# ateliers = dict({\"Atelier\" : a})\n# json.dump(ateliers, json_data , indent=4)\n#\n# r = []\n# for j in carte.listeRobot:\n# r.append({\"id\" : j.id , \"transport\" : j.transport , \"assemblage\" : j.assemblage ,\n# \"pos\" : j.pos , \"vitesse\" : j.vitesse})\n# with open(chemin+\"/robot.json\" , \"w+\") as json_data:\n# robots = dict({\"Robot\" : r})\n# json.dump(robots, json_data , indent=4)\n\n\nif __name__ == '__main__':\n cartet = Carte(\"cartet\", 20, 20)\n cartet.ajouter_robot(True, True, (1, 1), 1)\n cartet.ajouter_obstacle((1, 2), (2, 4))\n cartet.ajouter_obstacle((5, 6), (10, 11))\n cartet.ajouter_obstacle((3, 11), (4, 15))\n cartet.ajouter_obstacle((13, 13), (14, 16))\n cartet.ajouter_obstacle((11, 11), (16, 12))\n cartet.ajouter_borne((15, 15))\n\n print(cartet.liste_borne[0].__dict__)\n exporter(cartet)\n # print(json.dumps(cartet, cls=CarteEncoder))\n c = importer(\"cartet.json\")\n print(c.liste_borne[0].__dict__)\n","sub_path":"src/Save.py","file_name":"Save.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589890897","text":"# Write a short Python function that takes a positive integer n and returns\n# the sum of the squares of all the positive integers smaller than n.\n\ndef sum_of_squares(n):\n total_sum = 0\n n -= 1\n current_square = 0\n # suqare next thing less than n\n # and add it to sum\n while n is not 0:\n current_square = n ** 2\n total_sum += current_square\n n -= 1\n\n return total_sum\n\n# Get input\nn = input(\"Please enter a positive integer: \")\n\n# error check\nif (int(n) < 0): \n print(str(n) + \" is not a positive integer.\")\nelse:\n print(sum_of_squares(int(n)))","sub_path":"01 - Basics/04-sum_of_squares.py","file_name":"04-sum_of_squares.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327587008","text":"import numpy as np\nimport logging\nimport random\nimport cv2\nimport matplotlib.pyplot as plt\nimport time \nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)\n\nSINGLE = np.dtype(\"single\")\n\n\ndef load_to_buffer(capture, frames_left, frame_count, buffer, buffer_offset, width=None, height=None):\n buffer_size = buffer.shape[0]\n\n if not width:\n width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\n if not height:\n height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n w = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)/2 - width/2)\n h = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)/2 - height/2)\n\n w = h = 0\n\n end_of_video = False\n for i in range(frame_count):\n # read frame\n ret, frame = cap.read()\n if ret and frames_left > 0:\n index = (buffer_offset + i) % buffer_size\n frame = frame[w: w+width, h: h+height]\n buffer[index] = np.average(frame, axis=2, weights=[1, .0, .0])\n \n # print([buffer[index].flatten()[x] for x in range(20)])\n\n frames_left -= 1\n else:\n end_of_video = True\n frame_count = i\n capture.release()\n break\n\n \n logging.info(f\"Loaded {frame_count} frames into buffer {buffer_offset} - {buffer_offset+frame_count-1}\")\n if end_of_video: logging.info(\"End of video.\")\n\n\n return end_of_video, frame_count\n\n\ndef chunk_analysis(buffer, buffer_offset, chunk_size, fft_mag_accum, ccc_vector, tau_vector):\n \"\"\"\n Handles DDM analysis on a single\n\n :param buffer: main data array [#frame, width, height]\n :param buffer_offset: frame offset for analysis\n :param chunk_size: #frame for analysis chunk\n :param fft_mag_accum: Accumulated fourier-transform data array [tau_index, width, height]\n :param ccc_vector: Number of frames that have contributed to fft_mag_accum\n :param tau_vector: Vector containing tau values\n \"\"\"\n if chunk_size <= 0:\n return\n\n\n buffer_size = buffer.shape[0]\n\n pixel_count = buffer.shape[1] * buffer.shape[2]\n norm_factor = 1 / pixel_count\n\n logging.info(f\"Analysing buffer frames {buffer_offset}-{buffer_offset+chunk_size-1}\")\n\n for tau_idx, tau in enumerate(tau_vector):\n # Currently only take of each tau value per chunk\n for x in range(50):\n index_1 = buffer_offset #+ random.randint(0, chunk_size - 1 - tau) # random is likely a bottle neck\n\n temp_diff = buffer[index_1 % buffer_size] - buffer[(index_1 + tau) % buffer_size]\n \n # print(tau, [temp_diff.flatten()[x] for x in range(20)])\n \n fft_temp_diff = np.fft.fft2(temp_diff) * norm_factor\n \n #plt.pcolor(temp_diff)\n #plt.show()\n\n fft_mag_accum[tau_idx] += np.abs(fft_temp_diff) ** 2\n\n # plt.pcolor(fft_mag_accum[tau_idx])\n # plt.show()\n\n # print(tau, [fft_mag_accum[tau_idx].flatten()[x] for x in range(10)])\n\n ccc_vector[tau_idx] += 50\n\n\ndef gen_radius_masks(q_num, width, height):\n radius_mask = np.zeros((q_num, width, height))\n radius_mask_px_count = np.zeros(q_num)\n\n q_vector = np.array(range(1, 20))\n\n\n for q_index in range(q_num):\n logging.info(f\"Radial mask {q_index}\")\n for x in range(width):\n for y in range(height):\n r = np.linalg.norm([x - width / 2, y - height / 2])\n # print(r, q[q_index])\n if 1 <= r / q_vector[q_index] <= 1.2:\n radius_mask[q_index, x, y] = 1\n radius_mask_px_count[q_index] += 1\n #plt.pcolor(radius_mask[q_index])\n #plt.show()\n radius_mask[q_index] = np.fft.fftshift(radius_mask[q_index])\n # print(np.array2string(q_vector, separator=', '))\n # print(np.array2string(q_vector, separator=', '))\n # print(q_vector.size)\n\n return radius_mask, q_vector, radius_mask_px_count\n\n\ndef analyse_fft_mag_accum(fft_mag_accum, ccc_vector, radius_masks, q_vector, radius_mask_px_count):\n tau_count = ccc_vector.size\n q_count = q_vector.size\n\n iqtau = np.zeros((q_count, tau_count))\n\n for tau_index in range(tau_count):\n fft_mag_accum[tau_index] = fft_mag_accum[tau_index] / ccc_vector[tau_index]\n\n for q_index in range(q_count):\n if radius_mask_px_count[q_index] == 0:\n iqtau[q_index, tau_index] = np.NaN\n else:\n iqtau[q_index, tau_index] = np.sum(radius_masks[q_index] * fft_mag_accum[tau_index]) \\\n / radius_mask_px_count[q_index]\n\n return q_vector, iqtau\n\n\ndef ddm_circ(capture, video_width, video_height, tau_vector, frames):\n buffer_size = 1000\n chunk_size = 50\n\n analysis_offset = 0\n load_in_offset = 0\n q_count = 19\n\n t1 = time.time()\n\n buffer = np.zeros((buffer_size, video_width, video_height), SINGLE)\n fft_mag_accum = np.zeros((tau_vector.size, video_width, video_height), SINGLE)\n ccc_vector = np.zeros(tau_vector.size)\n\n # Load in two video chunks\n finished, gen_chunk_size = load_to_buffer(capture, frames, chunk_size, buffer, load_in_offset, video_width, video_height)\n frames -= chunk_size\n load_in_offset = (load_in_offset + gen_chunk_size) % buffer_size\n\n while not finished:\n chunk_analysis(buffer, analysis_offset, gen_chunk_size, fft_mag_accum, ccc_vector, tau_vector)\n frames -= chunk_size\n analysis_offset = (analysis_offset + gen_chunk_size) % buffer_size\n\n finished, gen_chunk_size = load_to_buffer(capture, frames, chunk_size, buffer, load_in_offset, video_width, video_height)\n load_in_offset = (load_in_offset + gen_chunk_size) % buffer_size\n\n chunk_analysis(buffer, analysis_offset, gen_chunk_size, fft_mag_accum, ccc_vector, tau_vector)\n\n # print([fft_mag_accum.flatten()[x*100] for x in range(100)]) \n\n logging.info(\"Initial analysis complete.\")\n t2 = time.time()\n print(t2-t1)\n\n # Analyse\n radius_masks, q_vector, radius_mask_px_count = gen_radius_masks(q_count, video_width, video_height)\n logging.info(\"Got radius masks\")\n\n out = analyse_fft_mag_accum(fft_mag_accum, ccc_vector, radius_masks, q_vector, radius_mask_px_count)\n logging.info(\"Full analysis complete.\")\n return out\n\nif __name__ == '__main__':\n # Playing video from file:\n cap = cv2.VideoCapture(\"/media/ghaskell/Slow Drive/colloid_vids/red_colloids_0_5um11Feb2021152731.mp4\")\n\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # note this isn't actually super accurate\n\n #over write\n width = 1024\n height = 1024\n frames = 1500\n\n\n size = min(width, height) # divide 4 to reduce analysed area - remove for real implementation\n size = int(2 ** np.floor(np.log2(size)))\n\n print(f\"Width: {width}, Height: {height}, Frames: {frames}, Analysed Size: {size}\")\n\n tau_vec = np.array(range(2, 15))\n\n q_vector, iqtau = ddm_circ(cap, size, size, tau_vec, frames)\n q_vector = q_vector[1:]\n iqtau = iqtau[1:,:]\n\n for tau in range(1, iqtau.shape[1]):\n # plotting the points\n plt.plot(q_vector, iqtau[:, tau])\n plt.xlabel(\"qs\")\n plt.show()\n\n for qi in range(iqtau.shape[0]):\n # plotting the points\n plt.plot(tau_vec, iqtau[qi], label=f\"q = {q_vector[qi]}\")\n plt.xlabel(\"Tau\")\n plt.legend(loc=\"upper left\")\n plt.show()\n\n","sub_path":"python/ddm.py","file_name":"ddm.py","file_ext":"py","file_size_in_byte":7518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"444206826","text":"class Song(object):\n\n#instance function\n def __init__(self,papa):\n self.lyrics = papa #instance attribute\n# class function\n def sing_me_a_song(self):\n for line in self.lyrics:\n print(line)\njumla = [\"Today is my birthday\",\"She has my birthday\"]\n\nhappy_bday = Song(jumla)\n\nbulls_on_parade = Song([\"WOOOOOEW\",\"JIOJIOJIO\",\"PIOPIOPIOP\"])\n\nhappy_bday.sing_me_a_song()\nbulls_on_parade.sing_me_a_song()\n","sub_path":"ex40.py","file_name":"ex40.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"618916018","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport os\nimport sys\n\nfrom model import build_model, load_trace\nfrom forecasting import compute_forecast\n\n\ndef loss_and_optimize(ending_returns, lam=1.0):\n '''\n Defines the loss optimization problem to solve with cvxpy, and returns the solution.\n '''\n import cvxpy as cp\n\n # Setup the loss function\n ndim = ending_returns.shape[1]\n w = cp.Variable(ndim)\n loss = cp.sum( -1.0*cp.exp( -lam*( ending_returns @ w ) ) )\n prob = cp.Problem(cp.Maximize(loss), \n [cp.sum(w) == 1, \n w >= 0])\n \n # Solve the problem\n prob.solve(solver=cp.SCS, max_iters=5000, eps=1e-6)\n print(\"Solved the problem!\")\n sol = w.value\n\n # Save solution\n names = [\"Algo{}\".format(i) for i in range(ndim)]\n weight_dict = dict(zip(names, sol))\n\n os.chdir(sys.path[0])\n with open('optimal_weights.csv', 'w') as f:\n f.truncate(0)\n for key in weight_dict.keys():\n f.write(\"%s,%s\\n\"%(key,weight_dict[key]))\n \n return None\n\ndef batch_eval_loss(w, ending_returns, lam=1.0):\n '''\n Evaluates the loss function on array of input weights. You want this to be speedy, since it gets called repeatedly by the optimizer.\n You can in theory throw in whatever kinds of penalizing terms you want.\n \n Here I've implemented the loss function that Thomas Wiecki showed in his Thalesians talk. Lambda controls\n the level of risk aversion. Loss is essentially E[-exp(-lam*r)].\n '''\n \n loss = (-1.0*np.exp(-lam*np.matmul(ending_returns, w))).sum(axis=0)\n return loss\n\ndef visualize_loss(lams=[0.1, 0.4, 0.7, 1.0], xmin=-3.0, xmax=3.0, npoints=1000):\n '''\n Helps visualize the loss function.\n '''\n fig, axs = plt.subplots(1, 2, figsize=(13,8))\n \n # subplot 1\n dom = np.linspace(xmin, xmax, npoints)/100\n for lam in lams:\n y = - np.exp(-lam*dom)\n axs[0].plot(dom, y, label=\"lambda = {}\".format(lam))\n axs[0].set_xlabel(\"Portfolio Return\")\n axs[0].set_ylabel(\"Loss Function Given Portfolio Return\")\n axs[0].set_title(\"Small-scale Loss Function\")\n axs[0].legend()\n \n # subplot 2\n dom = np.linspace(xmin, xmax, npoints)\n for lam in lams:\n y = - np.exp(-lam*dom)\n axs[1].plot(dom, y, label=\"lambda = {}\".format(lam))\n axs[1].set_xlabel(\"Portfolio Return\")\n axs[1].set_ylabel(\"Loss Function Given Portfolio Return\")\n axs[1].set_title(\"Large-scale Loss Function\")\n axs[1].legend()\n \n os.chdir(sys.path[0])\n plt.savefig(\"loss_visualization.png\", dpi=250)\n\n\n\nif __name__ == \"__main__\":\n \n # Create loss function visualization\n visualize_loss(lams=[0.1, 0.4, 0.7, 1.0, 2.0, 3.0])\n\n # Load data\n os.chdir(sys.path[0])\n log_rets = pd.read_csv(\"log_returns.csv\", index_col=\"Date\", parse_dates=True)\n data = log_rets.values\n\n # Build model\n model = build_model(data)\n\n # Get trace\n trace = load_trace(model)\n\n # Calculate forecast\n fdays=100\n raw_returns, cum_returns, ending_returns = compute_forecast(trace, fdays=fdays)\n\n # Run optimizer\n lam = 10.0 # This sets risk penalizer\n loss_and_optimize(ending_returns, lam=lam)\n ","sub_path":"Portfolio Allocation/stoch_vol_student_t/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"573654348","text":"#*****************************************************************************\n# Copyright 2019 yoga suhas\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#******************************************************************************\n\nimport os\nimport glob\nimport pandas as pd\nimport numpy as np\nfrom functools import partial\nfrom keras.models import Sequential\nfrom keras.layers import BatchNormalization\nfrom keras.layers import Flatten, LSTM, Conv1D, MaxPooling1D, Dropout, Dense\nfrom keras.utils import to_categorical\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report\n\nlength = 1000\nnum_epoch = 50\nbatch_size = 32\ntest_size_t = 0.3\nindex = iter(range(5))\nNTC_LABELS = {}\n\ndef pad_normalize(s):\n \"\"\"Collect 1000 bytes from packet payload. If payload length is less than\n 1000 bytes, pad zeroes at the end. Then convert to integers and normalize.\"\"\"\n\n if len(s) < length:\n s += '0' * (length-len(s))\n else:\n s = s[:length]\n return [float(int(s[i], 16)/255) for i in range(0, length)]\n\n\ndef fetch_file(file_name, label):\n df = pd.read_csv(file_name, index_col=None, header=0)\n df.columns = ['data']\n df['label'] = label\n return df\n\n\ndef preprocess(path):\n files = glob.glob(os.path.join(path, '*.txt'))\n list_ = []\n for f in files:\n label = f.split('/')[-1].split('.')[0]\n NTC_LABELS[label] = next(index)\n labelled_df = partial(fetch_file, label=NTC_LABELS[label])\n list_.append(labelled_df(f))\n df = pd.concat(list_, ignore_index=True)\n return df\n\n\ndef build_model(X_train, y_train, X_test, y_test, num_epoch, batch_size):\n activation = 'relu'\n num_classes = len(NTC_LABELS)\n model = Sequential()\n model.add(Conv1D(32, strides=1, \n input_shape=(length, 1), \n activation=activation, \n kernel_size=3, padding='valid'))\n model.add(BatchNormalization())\n model.add(Conv1D(64, \n strides=1, activation=activation, \n kernel_size=3, padding='valid'))\n model.add(BatchNormalization())\n model.add(LSTM(100,return_sequences=True))\n model.add(Dense(100, activation=activation))\n model.add(Dense(108, activation=activation))\n model.add(Flatten())\n model.add(Dense(num_classes, activation='softmax'))\n model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n print(model.summary())\n model.fit(X_train, y_train, verbose=1, epochs=num_epoch, batch_size=batch_size, validation_data=(X_test, y_test))\n return model\n\n\ndef main():\n df = preprocess(path='Dataset')\n df['data'] = df['data'].apply(pad_normalize)\n X_train, X_test, y_train, y_test = train_test_split(df['data'], df['label'],test_size = test_size_t, random_state=4)\n X_train = X_train.apply(pd.Series)\n X_test = X_test.apply(pd.Series)\n X_train = X_train.values.reshape(X_train.shape[0], X_train.shape[1], 1)\n X_test = X_test.values.reshape(X_test.shape[0], X_test.shape[1], 1)\n\n \n model = build_model(X_train, y_train, X_test, y_test, num_epoch, batch_size)\n\n # predict crisp classes for test set\n y_pred_t = model.predict(X_test, batch_size=32, verbose=1)\n y_pred_bool = np.argmax(y_pred_t, axis=1)\n y_pred = model.predict_classes(X_test)\n\n\n # accuracy: (tp + tn) / (p + n)\n accuracy = accuracy_score(y_test, y_pred)\n print('Accuracy: %f' % accuracy)\n # precision tp / (tp + fp)\n precision = precision_score(y_test, y_pred, average='weighted',labels=np.unique(y_pred))\n print('Precision: %f' % precision)\n # recall: tp / (tp + fn)\n recall = recall_score(y_test, y_pred,average='weighted')\n print('Recall: %f' % recall)\n # f1: 2 tp / (2 tp + fp + fn)\n f1 = f1_score(y_test, y_pred, average='weighted',labels=np.unique(y_pred))\n print('F1 score: %f' % f1)\n \n print(classification_report(y_test, y_pred_bool))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"4_cnn_rnn_2_with_f1.py","file_name":"4_cnn_rnn_2_with_f1.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83190459","text":"from keras.models import Model\nfrom keras.layers import Input\ndigit_input = Input(shape=(1,28,28))\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation,Conv2D,MaxPooling2D,Flatten,Dropout\nmodel = Sequential()\nmodel.add(Conv2D(64,(3,3),activation='relu',input_shape =(100,100,32)))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dense(256,activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Flatten)\nmodel.add(Conv2D(32,(3,3),activation='relu',input_shape=(224,224,3)))\nmodel.compile(loss='binary_crossentropy',optimizer='rmsprop')\nfrom keras.optimizers import SGD\nsgd = SGD(lr=0.01,decay=1e-6,momentum=0.9,nesterov=True)\nmodel.compile(loss='categorical_crossentropy',optimizer=sgd)\nmodel.fit(x_train,y_train,batch_size=32,epochs=10,validation_data=(x_val,y_val))","sub_path":"sparktest/task_mysql/tensorflow_test/UQER/keras_test.py","file_name":"keras_test.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493969883","text":"#compare the speed of bubble and insetion at various lists\nimport time\n\nstart_time = time.time()\n\n#Bubble sort\nnumberList = [5,10,2,1,10,2,1,100,199952,0,6]\nswapped = True\n#while the list is not sorted:\nwhile swapped == True:\n swapped = False\n #for each number in the list, except the last one:\n for i in range(0, len(numberList) - 1):\n #if it is bigger than the one to the right\n if numberList[i] > numberList[i+1]:\n #swap them\n temp = numberList[i]\n numberList[i] = numberList[i+1]\n numberList[i+1] = temp\n swapped = True\n\nfor i in range(0, len(numberList)):\n print(numberList[i], end = \" \")\nprint()\n\nbubble_time = time.time() - start_time\n\nstart_time = time.time()\n\n#python implementation of insertion sort algorithm\nnumberList = [5,10,2,1,10,2,1,100,199952,0,6]\nfor i in range(1, len(numberList)):\n position = i\n while position>0 and numberList[position-1]>numberList[position]:\n temp = numberList[position]\n numberList[position] = numberList[position-1]\n numberList[position-1] = temp\n position -= 1\n\nfor i in range(0, len(numberList)):\n print(numberList[i], end = \" \")\nprint()\n\ninsertion_time = time.time() - start_time\n\nprint(\"Both completed, Bubble_Sort: %f, Insertion_Sort: %f\" % (bubble_time, insertion_time))\n","sub_path":"python/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640262301","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls.defaults import patterns, include, url\nfrom django.conf import settings\n\n\nurlpatterns = patterns('',\n url(r'^WebUi/', include('WebUi.urls')),\n)\n\nif settings.DEBUG:\n from django.views.static import serve\n urlpatterns += patterns('',\n url(r'^static/(?P.*)$',\n serve, {\n 'document_root':settings.STATIC_ROOT,\n 'show_indexes': True}\n ),\n\n url(r'^media/(?P.*)$',\n serve, {\n 'document_root':settings.MEDIA_ROOT,\n 'show_indexes': True}\n ),\n)\n","sub_path":"project/urls/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"464655563","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom pwn import *\n\ncontext(arch=\"i386\", os=\"linux\")\n\nSHELLCODE = asm(shellcraft.findpeersh())\n\nr = remote('localhost', 20001)\nr.readline()\n\n# Canary = %134$\n# ebp (0xffd2da98) = %137$\n# ret addr (0x56557d4b) = %138$\n# socket = %139$\n\n# fmt base (0x56557000) = ret_addr - 0xd4b\n# buffer addr (0xffd2d86c) = ebp - 556\n# addr of ret (0xffd2da7c) = ebp - 28\n\nr.sendline(flat(\n '%134$08x', # Canary\n '%137$08x', # EBP\n '%138$08x', # ret addr\n '%139$08x' # socket\n))\n\ncanary = int(r.recv(8), 16)\nebp = int(r.recv(8), 16)\nret = int(r.recv(8), 16)\nsocket = int(r.recv(8), 16)\nfmt_base = ret - 0xd4b\nbuffer = ebp - 556\nret_addr = ebp - 28\nr.recvline()\n\nprint('canary 0x{:08x}'.format(canary ))\nprint('ebp 0x{:08x}'.format(ebp ))\nprint('ret 0x{:08x}'.format(ret ))\nprint('socket 0x{:08x}'.format(socket ))\nprint('fmt_base 0x{:08x}'.format(fmt_base ))\nprint('buffer 0x{:08x}'.format(buffer ))\nprint('ret_addr 0x{:08x}'.format(ret_addr ))\n","sub_path":"presentations/04-advanced-exploitation/assignments/solutions/opgave_1.py","file_name":"opgave_1.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583971677","text":"nk=input()\nnk=nk.split()\nn,k=int(nk[0]),int(nk[1])\nconfict={}\nfor line in range(k):\n line=input()\n tempstr=line.split()\n stu1,stu2=int(tempstr[0]),int(tempstr[1])\n confict[stu1]=confict.get(stu1,set())\n confict[stu1].add(stu2)\n confict[stu2]=confict.get(stu2,set())\n confict[stu2].add(stu1)\nstus=[i+1 for i in range(n)]\nres=[]\ndef permutation(path,rest):\n if not rest:return res.append(path)\n for i in range(len(rest)):\n if path and rest[i] in confict.get(path[-1],set()):continue\n permutation(path+[rest[i]],rest[:i]+rest[i+1:])\npermutation([],stus)\n# print(confict)\nfor i in range(len(res)):\n temp=map(lambda x:str(x),res[i])\n print(\"\".join(temp))\n","sub_path":"wangyi/Permutation.py","file_name":"Permutation.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"51053083","text":"import numpy as np\nfrom imgaug import augmenters as iaa\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom config import Config\n\n\nclass OrderedDataset():\n def __init__(self):\n self.x = np.load(Config.train_x)\n self.y = np.load(Config.train_y)\n assert len(self.x) == len(self.y)\n self.len = len(self.x)\n\n self.indice_map = {key: [] for key in range(10)}\n for i in range(self.len):\n self.indice_map[self.y[i]].append(i)\n\n def getItemsForLabel(self, label, data_size):\n assert label in range(10)\n indices = np.random.choice(self.indice_map[label],\n size=data_size,\n replace=False)\n return [[self.x[i]]\n for i in indices], [self.y[i] for i in indices]\n\n\nclass TripletDataProvider:\n def __init__(self, size_per_class):\n self.size_per_class = size_per_class\n self.batch_size = size_per_class * 10\n self.dataset = OrderedDataset()\n\n self.len = self.dataset.len\n self.batch_num = self.len // self.batch_size\n\n sometimes = lambda aug: iaa.Sometimes(0.8, aug)\n self.aug = iaa.Sequential([\n sometimes(iaa.Affine(\n scale=(0.75, 1.25),\n translate_percent=(-0.25, 0.25),\n rotate=(-10, 10),\n shear=(-10, 10),\n )),\n ])\n\n def next(self):\n imgs = []\n labels = []\n for label in range(10):\n sub_imgs, sub_labels = self.dataset.getItemsForLabel(\n label, self.size_per_class)\n imgs.extend(sub_imgs)\n labels.extend(sub_labels)\n# imgs = self.aug.augment_images(np.array(imgs))\n imgs = np.array(imgs)\n return torch.from_numpy(imgs), torch.tensor(labels)\n","sub_path":"DataProvider_triplet.py","file_name":"DataProvider_triplet.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"365732700","text":"import os\nfrom lib.deviantart import DeviantArtAPI\nfrom lib import utils\n\nclass Config:\n\n api = DeviantArtAPI()\n\n def __init__(self, file_path):\n self.file_path = file_path\n self._data = utils.load_json(file_path)\n self._data[\"save_directory\"] = os.path.normpath(self._data[\"save_directory\"])\n\n def print(self):\n utils.print_json(self._data)\n\n def update(self):\n utils.write_json(self._data, self.file_path)\n\n @property\n def save_dir(self):\n return self._data[\"save_directory\"]\n\n @save_dir.setter\n def save_dir(self, save_dir):\n save_dir = os.path.normpath(save_dir)\n self._data[\"save_directory\"] = save_dir\n\n def update_artist(self, artist_id, value):\n self._data[\"artists\"][artist_id] = value\n\n @property\n def artists(self):\n return self._data[\"artists\"]\n\n def add_artists(self, artist_ids):\n for id in artist_ids:\n try:\n self.api.gallery(id)\n self.artists.setdefault(id, None)\n except:\n print(f\"Artist {id} does not exist\")\n\n def delete_artists(self, artist_ids):\n if \"all\" in artist_ids:\n artist_ids = self.artists.keys()\n for id in artist_ids:\n if id in self.artists.keys():\n self.artists.pop(id, None)\n artist_name = self.api.gallery(id)[\"artist_name\"]\n utils.remove_dir(self.save_dir, artist_name)\n else:\n print(f\"Artist {id} does not exist\")\n\n def clear_artists(self, artist_ids):\n if \"all\" in artist_ids:\n artist_ids = self.artists.keys()\n for id in artist_ids:\n if id in self.artists.keys():\n self.artists[id] = None\n artist_name = self.api.gallery(id)[\"artist_name\"]\n utils.remove_dir(self.save_dir, artist_name)\n else:\n print(f\"Artist {id} does not exist\")","sub_path":"lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"453000327","text":"# -*- coding: utf-8 -*-\nimport math\n\nn=int(input('Informe a quantidade de elementos da lista: '))\nlista=[]\nfor i in range(0,n,1):\n elemento=int(input('Informe os elementos da lista: '))\n lista.append(elemento)\n\nsoma=0\nfor i in range(0, len(lista),1):\n soma=soma+lista[i]\nmedia=soma/len(lista)\n\ndesvPad=0\nfor i in range(0, len(lista),1):\n desvPad=desvPad+((lista[i]-media)**2)\ndesvioPadrao=(desvPad/(len(lista-1)))**0.5\n\nprint('%.2f' %lista[0])\nprint('%.2f' %lista[-1])\nprint('%.2f' %media)\nprint('%.2f' %desvioPadrao)\n \n","sub_path":"moodledata/vpl_data/95/usersdata/213/57167/submittedfiles/desvpad.py","file_name":"desvpad.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"89692821","text":"\"\"\"\n背包问题\n\"\"\"\nimport math\n\n\nclass Item:\n def __init__(self, name, value, weight):\n self.name = name\n self.value = value\n self.weight = weight\n\n def __str__(self):\n return '[商品:%s; 价值:%s; 重量:%s]' % (self.name, self.value, self.weight)\n\n\ndef bei_bao(bag_limit, items):\n \"\"\"\n :param bag_limit: 背包最大容量\n :param items: 商品列表\n :return:\n \"\"\"\n # 找到重量最小的物品,以他为最小粒度将背包分割为小背包\n min1 = min(items, key=lambda product: product.weight)\n little_bag_num = int(math.ceil(bag_limit / min1.weight))\n bags = [Item([], 0, 0) for x in range(little_bag_num)]\n\n for item in items:\n for index in range(0, len(bags), 1):\n bag_limit = (index + 1) * min1.weight\n current_bag = bags[index]\n if item.weight <= bag_limit:\n # 准备放入当前背包的东西\n added_item = Item([item.name], item.value, item.weight)\n # 当前背包可以放下,比较前一个小背包的最大价值和当前背包+空背包的最大价值和\n if item.weight < bag_limit:\n # 查询空余空背包的价值\n blank_bag_index = math.floor((bag_limit - item.weight) / min1.weight)\n if blank_bag_index > 0:\n blank_bag_value = bags[blank_bag_index - 1]\n if item.name not in blank_bag_value.name:\n # 空背包中不能放过当前商品\n added_item.name += blank_bag_value.name\n added_item.value += blank_bag_value.value\n added_item.weight += blank_bag_value.weight\n if current_bag.value < added_item.value:\n # 刷新当前背包的最大价值\n bags[index] = added_item\n\n return bags\n\n\nif __name__ == '__main__':\n items1 = [Item('吉他', 1500, 0.5),\n Item('笔记本电脑', 2000, 2.7),\n Item('aa', 4000, 3.1),\n Item('bb', 1000, 0.5),\n Item('音响', 4000, 2.7),]\n bao1 = bei_bao(4, items1)\n for x in bao1:\n print(x)\n","sub_path":"算法/other/beibao.py","file_name":"beibao.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"48866806","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('website', '0007_userprofile_publicity_photos'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='userprofile',\n name='main_photo',\n field=models.ForeignKey(related_name=b'main_uploaded_photo', blank=True, to='website.UploadedImage', null=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='userprofile',\n name='publicity_photos',\n field=models.ManyToManyField(related_name=b'uploaded_publicity_photos', to=b'website.UploadedImage'),\n ),\n ]\n","sub_path":"website/migrations/0008_auto_20150101_1846.py","file_name":"0008_auto_20150101_1846.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"276801826","text":"from django.contrib.postgres.search import TrigramDistance, TrigramSimilarity\nfrom django.test import modify_settings\n\nfrom . import PostgreSQLTestCase\nfrom .models import CharFieldModel, TextFieldModel\n\n\n@modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'})\nclass TrigramTest(PostgreSQLTestCase):\n Model = CharFieldModel\n\n @classmethod\n def setUpTestData(cls):\n cls.Model.objects.bulk_create([\n cls.Model(field='Matthew'),\n cls.Model(field='Cat sat on mat.'),\n cls.Model(field='Dog sat on rug.'),\n ])\n\n def test_trigram_search(self):\n self.assertQuerysetEqual(\n self.Model.objects.filter(field__trigram_similar='Mathew'),\n ['Matthew'],\n transform=lambda instance: instance.field,\n )\n\n def test_trigram_similarity(self):\n search = 'Bat sat on cat.'\n self.assertQuerysetEqual(\n self.Model.objects.filter(\n field__trigram_similar=search,\n ).annotate(similarity=TrigramSimilarity('field', search)).order_by('-similarity'),\n [('Cat sat on mat.', 0.625), ('Dog sat on rug.', 0.333333)],\n transform=lambda instance: (instance.field, instance.similarity),\n ordered=True,\n )\n\n def test_trigram_similarity_alternate(self):\n self.assertQuerysetEqual(\n self.Model.objects.annotate(\n distance=TrigramDistance('field', 'Bat sat on cat.'),\n ).filter(distance__lte=0.7).order_by('distance'),\n [('Cat sat on mat.', 0.375), ('Dog sat on rug.', 0.666667)],\n transform=lambda instance: (instance.field, instance.distance),\n ordered=True,\n )\n\n\nclass TrigramTextFieldTest(TrigramTest):\n \"\"\"\n TextField has the same behavior as CharField regarding trigram lookups.\n \"\"\"\n Model = TextFieldModel\n","sub_path":"desktop/core/ext-py/Django-1.11/tests/postgres_tests/test_trigram.py","file_name":"test_trigram.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"515672465","text":"#!/usr/bin/env python3\n\nimport logging\nimport argparse\nvalid_logging_levels = {\n \"DEBUG\",\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"CRITICAL\",\n}\nparser = argparse.ArgumentParser(description=\"consolidates javascript files\")\nparser.add_argument(\n action=\"store\",\n choices=valid_logging_levels,\n *(\"-l\", \"--log\"),\n dest=\"logging_level\",\n default=\"DEBUG\",\n metavar=\"LEVEL\",\n help=\"sets the logging level\"\n)\nparser.add_argument(\n action=\"store\",\n nargs=\"+\",\n dest=\"directories\",\n metavar=\"DIRECTORY\",\n help=\"a directory where to find the source files\"\n)\n\ndef main (arg0, argv):\n import consolidator\n args = parser.parse_args(argv)\n logging.basicConfig(level=getattr(logging, args.logging_level))\n\n sourcefiles = consolidator.consolidate(args.directories)\n for sourcefile in sourcefiles:\n print(\"//\", \"-\"*40)\n print(\"//\", sourcefile.filepath)\n print(\"//\", \"-\"*40)\n\n print(sourcefile.content)\n\nif __name__ == \"__main__\":\n import sys\n try:\n c = main(sys.argv[0], sys.argv[1:])\n except KeyboardInterrupt:\n c = 1\n if c:\n sys.exit(c)\n","sub_path":"projects/micro/jsdepend/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"550340208","text":"import wx\nimport wx.xrc\nfrom ObjectListView import ObjectListView, ColumnDefn\nfrom datetime import datetime\n\nfrom db.get_events import getEvents\nfrom db.save_event import editEvent, deleteEvent\n# import sys\n# sys.path.insert(0, r'/F:/PythonApps/Kangangu')\n\n###########################################################################\n# Class ViewEvents\n###########################################################################\n\n\nclass ViewEvents(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(669, 428),\n style=wx.TAB_TRAVERSAL)\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n self.m_staticText17 = wx.StaticText(self, wx.ID_ANY, u\"All Events\", wx.DefaultPosition, wx.DefaultSize,\n wx.ALIGN_CENTRE)\n self.m_staticText17.Wrap(-1)\n self.m_staticText17.SetFont(wx.Font(14, 70, 90, 92, False, wx.EmptyString))\n\n container.Add(self.m_staticText17, 0, wx.TOP | wx.EXPAND, 25)\n\n horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n left_sizer = wx.BoxSizer(wx.HORIZONTAL)\n OLV_sizer = wx.BoxSizer(wx.VERTICAL)\n\n #\n # Events Object list View\n # ----------------------------------------------------------------\n # Search\n # ----------------------------------------------------------------\n search_container = wx.BoxSizer(wx.HORIZONTAL)\n\n self.refresh_btn = wx.BitmapButton(self, wx.ID_ANY,\n wx.Bitmap(u\"images/reload_16x16.bmp\", wx.BITMAP_TYPE_ANY),\n wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW)\n\n self.refresh_btn.SetBitmapHover(wx.Bitmap(u\"images/reload_16x16_rotated.bmp\", wx.BITMAP_TYPE_ANY))\n search_container.Add(self.refresh_btn, 0, wx.BOTTOM | wx.LEFT | wx.RIGHT, 5)\n\n self.m_staticText53 = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.m_staticText53.Wrap(-1)\n search_container.Add(self.m_staticText53, 1, wx.ALL, 5)\n\n self.search_events = wx.SearchCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,\n wx.TE_PROCESS_ENTER)\n self.search_events.ShowSearchButton(True)\n self.search_events.ShowCancelButton(False)\n search_container.Add(self.search_events, 0, wx.BOTTOM, 8)\n\n self.search_events.Bind(wx.EVT_TEXT, self.searchEvents)\n self.search_events.Bind(wx.EVT_TEXT_ENTER, self.searchEvents)\n\n OLV_sizer.Add(search_container, 0, wx.EXPAND, 5)\n #\n #\n # ----------------------------------------------------------------\n # Table\n # ----------------------------------------------------------------\n self.events = getEvents()\n\n self.eventsOLV = ObjectListView(self, wx.ID_ANY, style=wx.LC_REPORT | wx.SUNKEN_BORDER)\n self.setEventsData()\n\n OLV_sizer.Add(self.eventsOLV, 1, wx.EXPAND | wx.ALL, 5)\n\n # ----------------------------------------------------------------\n #\n #\n\n left_btns_sizer = wx.BoxSizer(wx.VERTICAL)\n\n self.edit_event_btn = wx.Button(self, wx.ID_ANY, u\"Edit Event\", wx.DefaultPosition, wx.DefaultSize, 0)\n self.edit_event_btn.Bind(wx.EVT_BUTTON, self.getEventInfo)\n left_btns_sizer.Add(self.edit_event_btn, 0, wx.ALL | wx.EXPAND, 5)\n\n self.delete_event_btn = wx.Button(self, wx.ID_ANY, u\"Delete\", wx.DefaultPosition, wx.DefaultSize, 0)\n self.delete_event_btn.Bind(wx.EVT_BUTTON, self.deleteEvent)\n left_btns_sizer.Add(self.delete_event_btn, 0, wx.ALL | wx.EXPAND, 5)\n\n #\n #\n left_sizer.Add(OLV_sizer, 5, wx.EXPAND | wx.ALL, 5)\n left_sizer.Add(left_btns_sizer, 1, wx.ALL, 5)\n\n horizontal_sizer.Add(left_sizer, 1, wx.EXPAND, 5)\n\n right_sizer = wx.BoxSizer(wx.VERTICAL)\n\n self.edit_event_panel = EditEvent(self)\n\n #\n #\n #\n right_sizer.Add(self.edit_event_panel, 1, wx.EXPAND)\n\n horizontal_sizer.Add(right_sizer, 1, wx.EXPAND, 5)\n\n container.Add(horizontal_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n self.SetSizer(container)\n self.Layout()\n\n # Connect Events\n self.refresh_btn.Bind(wx.EVT_BUTTON, self.refreshTable)\n\n def setEventsData(self, data=None):\n self.eventsOLV.SetColumns([\n ColumnDefn(\"ID\", \"left\", 50, \"event_id\"),\n ColumnDefn(\"Name\", \"center\", 120, \"event_name\"),\n ColumnDefn(\"Date\", \"center\", 75, \"event_date\"),\n ColumnDefn(\"Description\", \"center\", 300, \"event_desc\"),\n ])\n\n self.eventsOLV.SetObjects(self.events)\n\n def updateEventsOLV(self, event): # Refresh events table\n \"\"\"\"\"\"\n data = getEvents()\n self.eventsOLV.SetObjects(data)\n\n def refreshTable(self, event):\n self.updateEventsOLV(\"\")\n\n def searchEvents(self, event):\n search = self.search_events.GetLineText(0)\n data = getEvents(search)\n self.eventsOLV.SetObjects(data)\n\n def getEventInfo(self, event): # In order to edit\n if not self.eventsOLV.GetSelectedObject():\n dlg = wx.MessageDialog(None, \"Click on a row in order to edit event.\",\n 'Error Message.',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n else:\n self.rowData = self.eventsOLV.GetSelectedObject()\n rowObj = self.eventsOLV.GetSelectedObject()\n\n self.edit_event_panel.event_id.SetValue(str(rowObj['event_id']))\n\n self.edit_event_panel.event_name.SetValue(rowObj['event_name'])\n self.edit_event_panel.event_desc.SetValue(rowObj['event_desc'])\n\n # get wxPython datetime format\n day = rowObj['event_date'].day\n month = rowObj['event_date'].month\n year = rowObj['event_date'].year\n\n # -1 because the month counts from 0, whereas people count January as month #1.\n dateFormatted = wx.DateTimeFromDMY(day, month - 1, year)\n\n self.edit_event_panel.event_date.SetValue(dateFormatted)\n\n self.edit_event_panel.Show()\n\n def deleteEvent(self, event):\n if self.eventsOLV.GetSelectedObject():\n rowObj = self.eventsOLV.GetSelectedObject()\n\n dlg = wx.MessageDialog(None, \"Confirm delete\", 'Warning Message.', wx.YES_NO | wx.ICON_WARNING)\n retCode = dlg.ShowModal()\n dlg.Destroy()\n\n if retCode == wx.ID_YES:\n if deleteEvent(rowObj[\"event_id\"]):\n dlg = wx.MessageDialog(None, \"Event deleted successfully.\", 'Success Message.',\n wx.OK | wx.ICON_EXCLAMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n self.updateEventsOLV(\"\")\n else:\n rowObj=\"\"\n\n else:\n dlg = wx.MessageDialog(None, \"Click on a row to delete an event.\", 'Error Message.',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n\n\nclass EditEvent(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(579, 436),\n style=wx.TAB_TRAVERSAL)\n self.parent = parent\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n outer_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n outer_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)\n\n outer_form_sizer = wx.BoxSizer(wx.VERTICAL)\n\n sbSizer2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u\"Edit Event Form\"), wx.VERTICAL)\n\n #\n # hidden event_id\n #\n event_id_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.event_id = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.event_id.Hide()\n event_id_sizer.Add(self.event_id, 4, wx.ALL, 10)\n\n sbSizer2.Add(event_id_sizer, 1, wx.ALL | wx.EXPAND, 10)\n #\n #\n #\n\n event_name_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.event_name_label = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Event Name\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.event_name_label.Wrap(-1)\n event_name_sizer.Add(self.event_name_label, 1, wx.ALL, 10)\n\n self.event_name = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n event_name_sizer.Add(self.event_name, 4, wx.ALL, 10)\n\n sbSizer2.Add(event_name_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n event_date_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.event_date_label = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Event Date\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.event_date_label.Wrap(-1)\n event_date_sizer.Add(self.event_date_label, 1, wx.ALL, 10)\n\n self.event_date = wx.DatePickerCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.DefaultDateTime, wx.DefaultPosition,\n wx.DefaultSize, wx.DP_DEFAULT | wx.DP_DROPDOWN)\n event_date_sizer.Add(self.event_date, 4, wx.ALL, 10)\n\n sbSizer2.Add(event_date_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n events_desc_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.event_desc_label = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Description\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.event_desc_label.Wrap(-1)\n events_desc_sizer.Add(self.event_desc_label, 1, wx.ALL, 10)\n\n self.event_desc = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, wx.TE_MULTILINE)\n events_desc_sizer.Add(self.event_desc, 4, wx.ALL, 10)\n\n sbSizer2.Add(events_desc_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n btns_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.m_staticText22 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.m_staticText22.Wrap(-1)\n btns_sizer.Add(self.m_staticText22, 1, wx.ALL, 5)\n\n self.cancel_edit_btn = wx.Button(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Cancel\", wx.DefaultPosition, wx.DefaultSize,\n 0)\n btns_sizer.Add(self.cancel_edit_btn, 0, wx.ALL, 10)\n\n self.save_edit_event = wx.Button(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Save\", wx.DefaultPosition, wx.DefaultSize, 0)\n btns_sizer.Add(self.save_edit_event, 0, wx.ALL, 10)\n\n sbSizer2.Add(btns_sizer, 3, wx.ALL | wx.EXPAND, 10)\n\n outer_form_sizer.Add(sbSizer2, 0, 0, 50)\n\n self.m_staticText301 = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.m_staticText301.Wrap(-1)\n self.m_staticText301.SetFont(wx.Font(30, 70, 90, 90, False, wx.EmptyString))\n\n outer_form_sizer.Add(self.m_staticText301, 0, wx.ALL | wx.EXPAND, 5)\n\n outer_sizer.Add(outer_form_sizer, 1, wx.ALL | wx.EXPAND, 5)\n\n outer_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)\n\n container.Add(outer_sizer, 1, wx.EXPAND, 5)\n\n self.SetSizer(container)\n self.Layout()\n\n # Connect Events\n self.cancel_edit_btn.Bind(wx.EVT_BUTTON, self.cancelEditEvent)\n self.save_edit_event.Bind(wx.EVT_BUTTON, self.saveEditEvent)\n\n def __del__(self):\n pass\n\n # Virtual event handlers, overide them in your derived class\n def cancelEditEvent(self, event):\n self.event_id.SetValue(\"\")\n self.event_name.SetValue(\"\")\n self.event_desc.SetValue(\"\")\n\n td = datetime.today()\n\n # get wxPython datetime format\n day = td.day\n month = td.month\n year = td.year\n\n # -1 because the month counts from 0, whereas people count January as month #1.\n tdFormatted = wx.DateTimeFromDMY(day, month - 1, year)\n\n self.event_date.SetValue(tdFormatted)\n\n def saveEditEvent(self, event):\n self.save_edit_event.Enable(False)\n\n event_id = self.event_id.GetValue()\n event_name = self.event_name.GetValue()\n event_date = self.event_date.GetValue()\n event_desc = self.event_desc.GetValue()\n\n if event_id != \"\":\n # ---------- VALIDATION ----------\n error = \"\"\n\n if event_name == \"\":\n error = error + \"The Event Name field is required.\\n\"\n\n if event_desc == \"\":\n error = error + \"The Description field is required.\\n\"\n\n # check that date has been changed\n td = datetime.today()\n\n # get wxPython datetime format\n day = td.day\n month = td.month\n year = td.year\n\n # -1 because the month counts from 0, whereas people count January as month #1.\n tdFormatted = wx.DateTimeFromDMY(day, month - 1, year)\n if str(event_date) == str(tdFormatted):\n error = error + \"The Event Date field is required.\\n\"\n\n if error:\n dlg = wx.MessageDialog(None, error, 'Validation Error', wx.OK | wx.ICON_WARNING)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n event_data = {\n 'event_id': event_id,\n 'event_name': event_name,\n 'event_date': event_date,\n 'event_desc': event_desc,\n }\n\n if editEvent(event_data):\n dlg = wx.MessageDialog(None, \"Event Added Successfully.\", 'Success Message',\n wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n self.cancelEditEvent(\"\")\n dlg.Destroy()\n self.parent.updateEventsOLV(\"\")\n else:\n dlg = wx.MessageDialog(None, \"Event Not Saved. Try Again.\", 'Failed',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n dlg = wx.MessageDialog(None, \"Click on a row to edit an event.\", 'Validation Error', wx.OK | wx.ICON_WARNING)\n dlg.ShowModal()\n dlg.Destroy()\n\n self.save_edit_event.Enable(True)","sub_path":"ViewEvents.py","file_name":"ViewEvents.py","file_ext":"py","file_size_in_byte":14772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613227728","text":"import ArrowSentinel\n\n#class CollectionSentinel(ArrowSentinel):\nclass CollectionSentinel(object):\n\tdef __init__(self, funcs):\n\t\t#super().__init__(funcs)\n\t\tself.names = list(funcs.keys())\n\t\tself.funcs = funcs\n\n\tdef generatePipelessTasks(self):\n\t\timport asyncio\n\n\t\tpipelessTasks = []\n\t\tfor k,v in self.funcs.items():\n\t\t\tif (v[1] is None):\n\t\t\t\tasyncFunc = v[0] \n\t\t\t\tfuture = asyncio.ensure_future(asyncFunc())\n\t\t\t\tpipelessTasks.append((k, future))\n\t\t\t\tif (self.names == []):\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tself.names.remove(k)\n\n\t\ttaskNames, taskFutures = zip(*pipelessTasks)\n\t\treturn taskNames, asyncio.gather(*taskFutures)\n\n\t\"\"\"\n\tdef generatePipedTasks(self, piper):\n\t\timport asyncio\n\n\t\tpipedTasks = []\n\t\tfor k,v in self.funcs.items():\n\t\t\tif (v[1] is not None and v[1] == piper):\n\t\t\t\tasyncFunc = v[0] \n\t\t\t\tfuture = asyncio.ensure_future(asyncFunc())\n\t\t\t\tpipedTasks.append(((k, v[2]), future))\n\t\t\t\tif (self.names == []):\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tself.names.remove(k)\n\n\t\ttaskData, taskFutures = zip(*pipedTasks)\n\t\treturn taskData, asyncio.gather(*taskFutures)\n\n\tdef generateAllCollectionTasks(self):\n\t\tpipeless = self.generatePipelessTasks()\n\t\tpiped = [self.generatePipedTasks(p) for p in pipeless[0]]\n\t\t\n\t\t#print(self.names)\n\t\t#while self.names != []:\n\t\tfor func in self.names:\n\t\t\tif (self.names == []):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tcontinue\n\n\n\t\t#print(pipeless, piped)\n\t\"\"\"\n\n\n\n\n\n","sub_path":"Algotrading/Arrow/CollectionSentinel 2.py","file_name":"CollectionSentinel 2.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"156750769","text":"from python import python\nfrom flask import request\nimport sqlite3\nfrom python.index import Index\nfrom python.portfoliodao import PortfolioDAO\n\n@python.route('/portfoliosubmit', methods=['GET', 'POST'])\ndef portfoliosubmit():\n\n message = \"Success\"\n portfoliodao = PortfolioDAO()\n index = Index()\n\n sType = request.form['sType']\n symbol = request.form['symbol']\n price = request.form['price']\n perct = request.form['perct']\n pname = request.form['pname']\n\n try:\n tprice = index.getStockPrice(sType, symbol)\n conn = sqlite3.connect(\"stock.db\")\n portfoliodao.insertPortfolio(conn, sType, symbol, price, perct, pname)\n except Exception as e:\n print(e.args)\n message = \"Failure\"\n return message\n\n@python.route('/delportfolio', methods=['GET', 'POST'])\ndef delportfolio():\n\n message = \"Success\"\n portfoliodao = PortfolioDAO()\n\n symbol = request.form['symbol']\n\n try:\n conn = sqlite3.connect(\"stock.db\")\n portfoliodao.delPortfolio(conn, symbol)\n except Exception as e:\n print(e.args)\n message = \"Failure\"\n return message\n\n@python.route('/getportfolio', methods=['GET', 'POST'])\ndef getportfolio():\n\n message = \"Portfolio List\" + \"\\n\"\n portfoliodao = PortfolioDAO()\n index = Index()\n\n try:\n conn = sqlite3.connect(\"stock.db\")\n cursor = portfoliodao.selectPortfolio(conn)\n for trade in cursor:\n message = message + trade[1] + \"\\n\"\n except Exception as e:\n print(e.args)\n message = \"Failure\"\n return message\n\n@python.route('/enterportfolio', methods=['GET', 'POST'])\ndef enterportfolio():\n user = {'nickname': 'Starting Point'} # fake user\n return '''\n\n \n Enter Portfolio\n \n \n
    \n

    Enter Portfolio

    \n \n

    \n \n

    \n \n

    \n \n

    \n \n

    \n

    \n
    \n
    \n

    GET Portfolio

    \n

    \n
    \n
    \n

    Delete Portfolio

    \n \n

    \n

    \n
    \n \n\n'''\n","sub_path":"enterportfolio.py","file_name":"enterportfolio.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"214819036","text":"from datetime import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport slayerSNN as snn\nfrom fusion import *\n \nnetParams = snn.params('network.yaml')\n\ndevice = torch.device('cuda')\n\nnet = Network(netParams, 'emg', 'dvsCropped').to(device)\n\nnet.load_state_dict(torch.load('Trained/fusionGesture.pt'))\n\ntestingSet = fusionDataset(\n samples =np.loadtxt('test.txt').astype(int),\n samplingTime=netParams['simulation']['Ts'],\n sampleLength=netParams['simulation']['tSample'],\n )\ntestLoader = DataLoader(dataset=testingSet, batch_size=1, shuffle=True, num_workers=1)\n\nstats = snn.utils.stats()\n\nfor trials in range(10):\n for i, (emgInput, dvsInput, target, label) in enumerate(testLoader, 0):\n net.eval()\n with torch.no_grad():\n emgInput = emgInput.to(device)\n dvsInput = dvsInput.to(device)\n target = target.to(device) \n\n output = net.forward(emgInput, dvsInput)\n\n stats.testing.correctSamples += torch.sum( snn.predict.getClass(output) == label ).data.item()\n stats.testing.numSamples += len(label)\n\n # loss = error.numSpikes(output, target)\n # stats.testing.lossSum += loss.cpu().data.item()\n stats.print(\n trials, i\n )\n stats.update()\n\nprint(\n f'Accuracy: {np.mean(np.array(stats.testing.accuracyLog)):.4g} \\\\pm {np.std(np.array(stats.testing.accuracyLog)):.4g}'\n)\n\ngenLoihiParams(net)\nplt.show()","sub_path":"crossValidation03/genLoihiParams.py","file_name":"genLoihiParams.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"6683191","text":"# USAGE\n# python video_facial_landmarks.py --shape-predictor shape_predictor_68_face_landmarks.dat\n# python video_facial_landmarks.py --shape-predictor shape_predictor_68_face_landmarks.dat --picamera 1\n\n# import the necessary packages\nfrom imutils.video import VideoStream\nfrom imutils import face_utils\nimport datetime\nimport argparse\nimport imutils\nimport time\nimport dlib\nimport cv2\nimport threading\nimport numpy as np\nfrom makeup import *\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-p\", \"--shape-predictor\", required=True,\n help=\"path to facial landmark predictor\")\nargs = vars(ap.parse_args())\n \n# initialize dlib's face detector (HOG-based) and then create\n# the facial landmark predictor\nprint(\"[INFO] loading facial landmark predictor...\")\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(args[\"shape_predictor\"])\n\n# initialize the video stream and allow the cammera sensor to warmup\nprint(\"[INFO] camera sensor warming up...\")\nvs = cv2.VideoCapture(0)\ntime.sleep(2.0)\n\nfill = False\nblur = False\n#alpha = 0.5\n\n#minit()\na = mu()\n\nlip_color = (255, 96, 96)\neyeshadow_color = (161, 125, 108)\nblush_color = (255, 216, 226)\n\ndef nothing(x):\n pass\n\nlip_color = (lip_color[2], lip_color[1], lip_color[0])\neyeshadow_color = (eyeshadow_color[2], eyeshadow_color[1], eyeshadow_color[0])\nblush_color = (blush_color[2], blush_color[1], blush_color[0])\n\n\ncv2.namedWindow('frame')\ncv2.createTrackbar('R','frame',255,255,nothing)\ncv2.createTrackbar('G','frame',96,255,nothing)\ncv2.createTrackbar('B','frame',96,255,nothing)\n\ncv2.createTrackbar('R2','frame',161,255,nothing)\ncv2.createTrackbar('G2','frame',125,255,nothing)\ncv2.createTrackbar('B2','frame',108,255,nothing)\n\nswitch = '0 : OFF \\n1 : ON'\ncv2.createTrackbar(switch, 'frame',0,1,nothing)\n# loop over the frames from the video stream\nwhile True:\n # grab the frame from the threaded video stream, resize it to\n # have a maximum width of 400 pixels, and convert it to\n # grayscale\n _, frame = vs.read()\n #frame = imutils.resize(frame, width=400)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # detect faces in the grayscale frame\n rects = detector(gray, 0)\n\n # loop over the face detections\n for rect in rects:\n # determine the facial landmarks for the face region, then\n # convert the facial landmark (x, y)-coordinates to a NumPy\n # array\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n # loop over the (x, y)-coordinates for the facial landmarks\n # and draw them on the image\n #for (x, y) in shape:\n # cv2.circle(frame, (x, y), 1, (0, 0, 255), -1)\n\n #for i in range(16):\n # cv2.line(frame, (shape[i][0], shape[i][1]), (shape[i+1][0], shape[i+1][1]), (0, 255, 0))\n\n if fill:\n a.add_lip(frame, gray, np.concatenate((shape[48:55], shape[60:65][::-1])), lip_color)\n\n a.add_lip(frame, gray, np.concatenate((shape[54:60], [shape[48]], [shape[60]], shape[64:68][::-1])), lip_color)\n\n a.add_eyeshadow(frame, gray, shape[36:40],\n np.int32([np.int32((shape[40][0]+shape[41][0])/2), np.int32((shape[40][1]+shape[41][1])/2)]),\n eyeshadow_color)\n\n a.add_eyeshadow(frame, gray, shape[42:46],\n np.int32([np.int32((shape[46][0]+shape[47][0])/2), np.int32((shape[46][1]+shape[47][1])/2)]),\n eyeshadow_color)\n\n\n #cv2.addWeighted(overlay, alpha, frame, 1 - alpha, 0, frame)\n\n if blur:\n\n dr = np.linalg.norm(shape[14]-shape[33])/3\n dl = np.linalg.norm(shape[2]-shape[33])/3\n d = np.linalg.norm(shape[14]-shape[35])/2.5\n\n m = np.int32((shape[31][0]-d*1.5, shape[31][1]-d*dl/(dl+dr)))\n a.add_blush(frame, gray, m, np.int32(d), blush_color)\n #cv2.circle(frame, (shape[2][0], shape[2][1]), 1, (0, 0, 255), -1)\n #cv2.circle(frame, (shape[31][0], shape[31][1]), 1, (0, 0, 255), -1)\n\n m = np.int32((shape[35][0]+d*1.5, shape[35][1]-d*dr/(dl+dr)))\n a.add_blush(frame, gray, m, np.int32(d), blush_color)\n #cv2.circle(frame, (shape[14][0], shape[14][1]), 1, (0, 0, 255), -1)\n #cv2.circle(frame, (shape[35][0], shape[35][1]), 1, (0, 0, 255), -1)\n\n\n # show the frame\n cv2.imshow(\"frame\", frame)\n\n r = cv2.getTrackbarPos('R','frame')\n g = cv2.getTrackbarPos('G','frame')\n b = cv2.getTrackbarPos('B','frame')\n r2 = cv2.getTrackbarPos('R2','frame')\n g2 = cv2.getTrackbarPos('G2','frame')\n b2 = cv2.getTrackbarPos('B2','frame')\n s = cv2.getTrackbarPos(switch,'frame')\n\n if s>0:\n lip_color = (b, g, r)\n eyeshadow_color = (b2, g2, r2)\n\n key = cv2.waitKey(1) & 0xFF\n\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n elif key == ord(\"a\"):\n fill = not fill\n elif key == ord(\"s\"):\n blur = not blur\n\n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.release()","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"246575093","text":"\nfrom bs4 import *\nimport unittest\nfrom testfixtures import ShouldRaise\n\n\nclass beautifulsoupTest(unittest.TestCase):\n def test_insert(self):\n \"\"\"\n Tag.insert() is a modifying function in the beauitfulsoup library ,which is used to insert any string or tag element in a given position in side an html or xml file.It take two arguments,the newly inserted string or tag and a numeric position to which place in the parent tag to be inserted.\n\n \"\"\"\n # example html\n markup = 'I linked thebeautifulsoup.com'\n soup = BeautifulSoup(markup, 'html.parser')\n tag = soup.a\n # testing -inserting a text inside a tag in a given position\n tag.insert(0, \"to the library\")\n self.assertEqual(str(tag.contents[0]), 'to the library')\n # testing -inserting an empty string inside a tag in a given position\n tag.insert(0, \"\")\n self.assertEqual(str(tag.contents[0]), '')\n # testing outside range position of the string to be inserted\n tag.insert(6, \"adding at the last\")\n self.assertEqual(\n str(tag.contents[len(tag.contents)-1]), 'adding at the last')\n # testing- insert a new span element with a text in position one\n tag1 = soup.new_tag(\"span\")\n tag1.string = \"a new span\"\n soup.a.insert(1, tag1)\n tag = soup.a\n self.assertEqual(str(tag.contents[1]), 'a new span')\n\n def test_extend(self):\n \"\"\"\n Tag.extend() is a modifying function in the beauitfulsoup library ,which is used to insert a given list of string into a tag.\n \"\"\"\n # example html\n markup = 'linked beautifulsoup.com'\n soup = BeautifulSoup(markup, 'html.parser')\n tag = soup.a\n # testing if extend method works with a number of string inside list\n tag.extend(['This', 'is', 'the', 'link to', 'beautifulsoup.'])\n\n self.assertEqual(str(tag.contents[2]), 'This')\n self.assertEqual(str(tag.contents[3]), 'is')\n self.assertEqual(str(tag.contents[4]), 'the')\n self.assertEqual(str(tag.contents[5]), 'link to')\n self.assertEqual(str(tag.contents[6]), 'beautifulsoup.')\n\n # testing if it an empty input\n tag.extend([''])\n self.assertEqual(str(tag.contents[7]), '')\n\n # testing if it integer as a string\n tag.extend(['bs', '4'])\n # print(tag.prettify())\n self.assertEqual(str(tag.contents[9]), '4')\n\n def test_decompose(self):\n \"\"\"\n .decompose() removes a tag from the tree,which may be unnecessarily added ,that is it alters the parsed tree by destroying all together the given tag ,and it have a decomposed property which return true or false after doing the modification.Testing for the return of true or false and verifying that the operation has been done successfully is a good point to test.\n\n \"\"\"\n # example test input\n markup = 'Google linkGoogle.com'\n soup = BeautifulSoup(markup, 'html.parser')\n a_tag = soup.a\n i_tag = soup.i\n # testing the basic operation ,removing a i tag in our example tree\n i_tag.decompose()\n self.assertTrue(i_tag.decomposed, True)\n # testing by deleting the root element in our case ,the a tag\n a_tag.decompose()\n self.assertTrue(a_tag.decomposed, True)\n\n def test_insert_after_before(self):\n \"\"\"\n Those function are greatly related to the insert function ,test this function will also test thoroughly the main insert function.\n \"\"\"\n # example test input\n soup = BeautifulSoup(\"expecting \", 'html.parser')\n tag = soup.new_tag(\"i\")\n tag.string = \"This is a new i tag \"\n # testing the inserting_before method with a new tag and string input\n soup.b.string.insert_before(tag)\n self.assertEqual(\n str(soup.b.contents[0]), \"This is a new i tag \")\n # testing with an empty string input\n tag_i = soup.i\n tag_b = soup.b\n tag_i.insert_before('')\n self.assertEqual(str(tag_b.contents[0]), '')\n # testing the insert_after method with a new tag and string\n tag_h = soup.new_tag(\"h1\")\n tag_h.string = \"insert after method\"\n tag_i.insert_after(tag_h)\n self.assertEqual(str(soup.h1.contents[0]), 'insert after method')\n # testing for only string input\n tag_i.insert_after('inside i tag')\n self.assertEqual(str(soup.b.contents[2]), 'inside i tag')\n # testing for empty input string\n tag_i.insert_after('')\n self.assertEqual(str(soup.b.contents[2]), '')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_bs4_insert.py","file_name":"test_bs4_insert.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"8330","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 29 16:45:36 2016\n\n@author: Comiconomist\n\nScript to retrieve any files in Fallout 4's folders that are more recent than\ncurrent copies in mod working folder\n\nOnly copies files with .ba2 and .esp file types for now.\n\n\"\"\"\n\nimport os\nimport datetime\nimport shutil\n\nacceptableFileTypes = ['.ba2', '.esp']\n\n# Current direcoty:\n\n# Go to Fallout 4 folder of mod working directory:\nprint(os.getcwd())\nos.chdir('..')\nprojDir = os.getcwd()\nprojName = projDir.split(\"\\\\\")[-1]\n\nos.chdir('./Fallout 4')\nmodWorkfo4Dir = os.getcwd()\n#modWorkfo4Dir = 'C:\\\\Games\\\\fo4_modding\\\\Projects\\\\instituteChair\\\\Fallout 4'\n\n# True fallout 4 directory:\nfo4Dir = 'C:\\\\Steam\\\\steamapps\\\\common\\\\Fallout 4'\n\n# Get list of files in working directory with relative paths\nfileRelPathList = []\nfor dir_, _, files in os.walk(modWorkfo4Dir):\n for fileName in files:\n relDir = os.path.relpath(dir_, modWorkfo4Dir)\n relFile = os.path.join(relDir, fileName)\n if relFile[-4:] in acceptableFileTypes:\n fileRelPathList.append(relFile)\n\n# Add to the list possible .esp and .ba2 files:\nfileRelPathList.append('Data\\\\' + projName + '.ba2')\nfileRelPathList.append('Data\\\\' + projName + '.esp')\n\n# Loop over files in my mod working directory: if a more recent copy exists in\n# the fallout 4 root directory I have probably used the creation kit, so copy\n# the more recent one\nfor myFile in fileRelPathList:\n if os.path.isfile(fo4Dir + '\\\\' + myFile):\n if os.path.isfile(modWorkfo4Dir + '\\\\' + myFile):\n # Fallout 4 root directory time:\n fo4Time = os.path.getmtime(fo4Dir + '\\\\' + myFile)\n fo4TimeStr = datetime.datetime.fromtimestamp(fo4Time).strftime('%Y-%m-%d %H:%M:%S')\n # New mod time:\n modTime = os.path.getmtime(modWorkfo4Dir + '\\\\' + myFile)\n modTimeStr = datetime.datetime.fromtimestamp(modTime).strftime('%Y-%m-%d %H:%M:%S')\n print(myFile + ' fo4Time: ' + fo4TimeStr + ' modTime: ' + modTimeStr)\n if fo4Time > modTime :\n print('Copying ' + myFile + ' from fo4 to mod working directory')\n shutil.copyfile(fo4Dir + '\\\\' + myFile, modWorkfo4Dir + '\\\\' + myFile)\n else:\n print(myFile + 'only exists in fo4 directory')\n print('Copying ' + myFile + ' from fo4 to mod working directory')\n shutil.copyfile(fo4Dir + '\\\\' + myFile, modWorkfo4Dir + '\\\\' + myFile)\n \n \nprint('Copying complete')","sub_path":"UtilityScripts/retrieve.py","file_name":"retrieve.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"559815620","text":"# -*- coding: utf-8 -*-\r\n''' Fort Pierce Geocode Addresses\r\nUses a custom locator to geocode\r\naddress from a csv file\r\n\r\nLocator: \r\n Style: US Address—Single House Subaddress\r\n Reference data: Fort Pierce Address Point // Primary Table\r\n Field map: Point Address ID // OBJECTID\r\n House Number // HouseNumber\r\n Prefix Direction // Prefix\r\n Street Name // StreetName\r\n Suffix Type // Suffix\r\n Suffix Direction // Direction\r\n SubAddr Unit // Unit\r\n Sity or Place // CityState\r\n ZIP Code // ZipCode\r\n\r\nUpdates published service, AnimalControl_CodeEnforcement,\r\nin the Fort Pierce AGO\r\n\r\n Python 3.x\r\n'''\r\n\r\nimport arcpy\r\nimport arcgis\r\nfrom arcgis.gis import GIS\r\nimport logging\r\nimport json\r\nimport os\r\nfrom os import path\r\nimport zipfile\r\n\r\n\r\narcpy.env.overwriteOutput = True\r\n\r\ndef geocodeCSV(csv, loc, out_ws):\r\n\r\n pub_geocode_add = out_ws + r'\\published\\GeocodedAddresses.gdb\\AnimalControl_geocoded'\r\n\r\n # convert csv to table for field calculation\r\n logging.info('Converting table...')\r\n add_table = arcpy.TableToTable_conversion(csv, 'in_memory', 'address_table')\r\n\r\n # remove records that are already geocoded\r\n pub_incidentid = list(set([x[0] for x in arcpy.da.SearchCursor(pub_geocode_add, ['Incidentid'])]))\r\n new_incidentid = list(set([x[0] for x in arcpy.da.SearchCursor(add_table, ['Incidentid'])]))\r\n\r\n del_ids = [n for n in new_incidentid if n in pub_incidentid]\r\n\r\n q = '\"Incidentid\" IN ({})'.format(str(del_ids).replace('[','').replace(']',''))\r\n del_rows = arcpy.SelectLayerByAttribute_management(add_table, 'NEW_SELECTION', q)\r\n in_rows = arcpy.DeleteRows_management(del_rows)\r\n\r\n if arcpy.GetCount_management(in_rows)[0] != '0':\r\n\r\n arcpy.AddField_management(in_rows, 'full_add_temp', 'TEXT')\r\n\r\n add_num = 'Locationstreetnumber'\r\n st_dir = 'Locationstreetdir'\r\n st_name = 'Locationstreetname'\r\n st_type = 'Locationstreettype'\r\n\r\n logging.info('Calculating field...')\r\n exp = \"' '.join([str(!{0}!),str(!{1}!),str(!{2}!), str(!{3}!)]).replace('None', '').replace(' ', ' ').replace(' ', ' ').strip()\".format(add_num, st_dir, st_name, st_type)\r\n arcpy.CalculateField_management(in_rows, 'full_add_temp', exp, 'PYTHON')\r\n\r\n # geocode\r\n field_match = \"'Address or Place' full_add_temp VISIBLE NONE;\" \\\r\n + \"'City' Locationcity VISIBLE NONE;\" \\\r\n + \"'County' Locationcounty VISIBLE NONE;\" \\\r\n + \"'State' Locationstate VISIBLE NONE;\" \\\r\n + \"'ZIP' Locationpostal VISIBLE NONE;\" \\\r\n + \"'Country' Locationctry VISIBLE NONE\"\r\n\r\n logging.info('Geocoding...')\r\n geocode_add = arcpy.GeocodeAddresses_geocoding(in_rows, loc, field_match, out_ws + r'\\to_append\\GeocodedAddresses_append.gdb\\GeocodedAddresses', output_fields='LOCATION_ONLY')\r\n \r\n # clean up\r\n arcpy.DeleteField_management(geocode_add, 'full_add_temp')\r\n\r\n logging.info('Updating Animal Control feature with new incidents...')\r\n arcpy.Append_management(geocode_add, pub_geocode_add, 'NO_TEST')\r\n\r\n logging.info('Clean up, aisle 9')\r\n arcpy.Delete_management('in_memory')\r\n del(add_table, pub_incidentid, new_incidentid, del_ids, q, \r\n del_rows, in_rows, add_num, st_dir, st_name, \r\n st_type, exp, field_match)\r\n\r\n logging.info('Sweet success! Ready to publish...')\r\n return(1, geocode_add, pub_geocode_add)\r\n\r\n else:\r\n\r\n logging.info('No new cases to geocode...')\r\n return(0, '', '')\r\n\r\ndef updateService(un, pw, org_url, fs_url, uploads, local):\r\n\r\n # connect to org/portal\r\n gis = GIS(org_url, un, pw)\r\n logging.info('Logged in as {}'.format(un))\r\n\r\n fl = arcgis.features.FeatureLayer(fs_url, gis)\r\n\r\n hosted_count = fl.query(return_count_only=True)\r\n local_count = int(arcpy.GetCount_management(local)[0])\r\n\r\n if hosted_count < local_count:\r\n\r\n logging.info('New rows found, creating json...')\r\n json_local = out_data_ws + r'\\updates.json'\r\n json_update = arcpy.FeaturesToJSON_conversion(uploads, json_local)\r\n fs = arcgis.features.FeatureSet.from_json(open(json_local).read())\r\n\r\n logging.info('Appending new rows...')\r\n fl.edit_features(adds=fs)\r\n logging.info('Success!')\r\n\r\n logging.info('Removing json file...')\r\n os.remove(json_local)\r\n\r\n logging.info('Done!')\r\n \r\n elif hosted_count == local_count:\r\n logging.info('Feature service already has same record count as local AnimalControl_geocoded feature class... investigate!')\r\n\r\n else:\r\n logging.info('Feature service has MORE records than local AnimalControl_geocoded feature class... PROBLEM!')\r\n\r\n # cleanup\r\n del(gis, hosted_count, local_count, fl, json_update, fs)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n\r\n # logging\r\n logfile = (path.abspath(path.join(path.dirname(__file__), '..', r'logs\\geocode-addresses.txt')))\r\n logging.basicConfig(filename=logfile,\r\n level=logging.INFO,\r\n format='%(levelname)s: %(asctime)s %(message)s',\r\n datefmt='%m/%d/%Y %I:%M:%S')\r\n\r\n # inputs for geocoding\r\n workspace = r'C:\\data\\gtg-data\\projects\\fl-fort-pierce\\geocode-address-task'\r\n csv = workspace + r'\\orig-data\\testForAddresses.csv'\r\n locator = workspace + r'\\locator\\FtPierceLocator_AP_PRO'\r\n out_data_ws = workspace + r'\\data'\r\n\r\n # get creds\r\n text = open(workspace + r'\\data\\ago-creds.json').read()\r\n json_array = json.loads(text)\r\n # inputs for update service\r\n orgURL = json_array['orgURL']\r\n # Username of an account in the org/portal that can access and edit all services listed below\r\n username = json_array['username']\r\n # Password corresponding to the username provided above\r\n password = json_array['password']\r\n\r\n # AnimalControl_CodeEnforcement\r\n featureservice = 'https://services1.arcgis.com/oDRzuf2MGmdEHAbQ/ArcGIS/rest/services/AnimalControl_CodeEnforcement/FeatureServer/0'\r\n # itemid = 'd596511e92e94a61870265df538664e4'\r\n\r\n try: \r\n logging.info('\\n\\n-----------------------------------------------------------------')\r\n logging.info('Starting run...')\r\n publish, upload, local_fc = geocodeCSV(csv, locator, out_data_ws)\r\n if publish == 1:\r\n logging.info('Beginning to update service...')\r\n updateService(username, password, orgURL, featureservice, upload, local_fc)\r\n\r\n except Exception as e:\r\n logging.error(\"EXCEPTION OCCURRED\", exc_info=True)\r\n logging.error(e)\r\n","sub_path":"arcgispro-geocode-addresses-FS-update.py","file_name":"arcgispro-geocode-addresses-FS-update.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52078987","text":"import sys\n# print (\"This is the name of the script: \", sys.argv[0])\n# print (\"Number of arguments: \", len(sys.argv))\n# print (\"The arguments are: \" , str(sys.argv))\n# try:\nuserFileName = sys.argv[1] \n# line = userFileName.readline()\n# except ValueError:\n# print(\"Could not convert data to an integer.\")\n# except:\n# print(\"Unexpected error:\", sys.exc_info()[0])\n# raise\ndef getSequence(inputFilename):\n sequence = ''\n file = open(inputFilename, \"r\")\n for line in file:\n if \">\" not in line:\n sequence += line\n sequence = sequence.replace('\\n','')\n return (sequence)\n\ndef getSpecies(inputFilename):\n species = ''\n file = open(inputFilename, \"r\")\n for line in file:\n if \">\" in line:\n species += line\n species = species.replace('\\n','')\n return (species)\n # with open(inputFilename) as fp:\n # for record in genomeSequence:\n # name, sequence = record.id, str(record.seq) \n # return(sequence)\ndef TranslateDNA(translateSequence):\n nucleotideTable = {\n 'ata':'I', 'atc':'I', 'att':'I', 'atg':'START',\n 'aca':'T', 'acc':'T', 'acg':'T', 'act':'T', 'acn' : 'T',\n 'aac':'N', 'aat':'N', 'aaa':'K', 'aag':'K',\n 'agc':'S', 'agt':'S', 'aga':'R', 'agg':'R',\n 'cta':'L', 'ctc':'L', 'ctg':'L', 'ctt':'L', 'ctn' : 'L',\n 'cca':'P', 'ccc':'P', 'ccg':'P', 'cct':'P', 'ccn' : 'P',\n 'cac':'H', 'cat':'H', 'caa':'Q', 'cag':'Q', \n 'cga':'R', 'cgc':'R', 'cgg':'R', 'cgt':'R',\n 'gta':'V', 'gtc':'V', 'gtg':'V', 'gtt':'V', 'gtn' : 'V',\n 'gca':'A', 'gcc':'A', 'gcg':'A', 'gct':'A', 'gcn' : 'A',\n 'gac':'D', 'gat':'D', 'gaa':'E', 'gag':'E', \n 'gga':'G', 'ggc':'G', 'ggg':'G', 'ggt':'G', 'ggn' : 'G',\n 'tca':'S', 'tcc':'S', 'tcg':'S', 'tct':'S', 'tcn' : 'S',\n 'ttc':'F', 'ttt':'F', 'tta':'L', 'ttg':'L',\n 'tac':'Y', 'tat':'Y', 'taa':'STOP', 'tag':'STOP', \n 'tgc':'C', 'tgt':'C', 'tga':'STOP', 'tgg':'W',\n '':'STOP'\n } \n DNA = translateSequence\n # DNA = \"tttatggcaattaaaattggtatcaatggttttggtcgtatcggccgtatcgtattctagttttttttttttatggcaattaaaattggtatcaatggttttggtcgtatcggccgtatcgtattctagttttttttt\"\n # DNA = translateSequence\n tmpProtein = \"\"\n finalSequence = []\n #Index through the string until the end of DNA, increment of 3 \n for index in range(0, len(DNA), 3):\n #If we've found a Start codon\n try:\n if nucleotideTable[DNA[index:index+3]] == \"START\" :\n # tmpProtein += nucleotideTable[DNA[index:index + 3]]\n tmpProtein += \"M\"\n index += 3\n while (nucleotideTable[DNA[index:index + 3]] != \"STOP\"):\n if DNA[index:index + 3] in nucleotideTable:\n tmpProtein += nucleotideTable[DNA[index:index + 3]]\n index += 3\n finalSequence.append(tmpProtein) \n tmpProtein = \"\"\n except KeyError:\n tmpProtein += \"X\"\n \n return (finalSequence) \ndef TranslateORF(frames):\n longestORF = 0\n correctFrame = [0,0]\n translatedFrames = [0] * 6\n\n for frame in frames:\n sequence = getSequence(userFileName)\n\n if (frame == 1):\n translatedSequence = TranslateDNA(sequence) \n translatedFrames[frame-1] = translatedSequence\n maxLen = max([len(index) for index in translatedSequence])\n if maxLen > longestORF:\n longestORF = maxLen\n correctFrame[0] = frame\n correctFrame[1] = \"3'5 Frame 1\" \n elif (frame == 2):\n sequence = sequence[1:] + sequence[0]\n translatedSequence = TranslateDNA(sequence) \n translatedFrames[frame-1] = translatedSequence\n maxLen = max([len(index) for index in translatedSequence])\n if maxLen > longestORF:\n longestORF = maxLen\n correctFrame[0] = frame\n correctFrame[1] = \"3'5 Frame 2\"\n elif (frame == 3):\n sequence = getSequence(userFileName)\n sequence = sequence[2:] + sequence[0:2]\n translatedSequence = TranslateDNA(sequence) \n translatedFrames[frame-1] = translatedSequence\n maxLen = max([len(index) for index in translatedSequence])\n if maxLen > longestORF:\n longestORF = maxLen\n correctFrame[0] = frame\n correctFrame[1] = \"3'5 Frame 3\"\n elif (frame == 4):\n sequence = SequenceComplement(sequence[::-1])\n translatedSequence = TranslateDNA(sequence) \n translatedFrames[frame-1] = translatedSequence\n maxLen = max([len(index) for index in translatedSequence])\n if maxLen > longestORF:\n longestORF = maxLen\n correctFrame[0] = frame\n correctFrame[1] = \"3'5 Frame 1\"\n elif (frame == 5):\n sequence = sequence[1:] + sequence[0]\n sequence = SequenceComplement(sequence[::-1])\n translatedSequence = TranslateDNA(sequence) \n translatedFrames[frame-1] = translatedSequence\n maxLen = max([len(index) for index in translatedSequence])\n if maxLen > longestORF:\n longestORF = maxLen\n correctFrame[0] = frame\n correctFrame[1] = \"3'5 Frame 2\"\n elif (frame == 6):\n sequence = sequence[2:] + sequence[0:2]\n sequence = SequenceComplement(sequence[::-1])\n translatedSequence = TranslateDNA(sequence) \n translatedFrames[frame-1] = translatedSequence\n maxLen = max([len(index) for index in translatedSequence])\n if maxLen > longestORF:\n longestORF = maxLen\n correctFrame[0] = frame\n correctFrame[1] = \"3'5 Frame 3\"\n\n # print (\"Longest ORF: \" + str(longestORF) + \" amino acids\" ) \n # print (\"The correct frame is frame : \" + correctFrame[1] + \" (\" + str(correctFrame[0])\n # + \")\") \n return(translatedFrames)\n\n\n\ndef SequenceComplement(sequence):\n switcher = {\n \"a\": \"t\",\n \"t\": \"a\",\n \"c\": \"g\",\n \"g\": \"c\",\n \"n\": \"n\"\n }\n complementSequence = ''\n for nucleotide in sequence:\n complementSequence += switcher[nucleotide]\n return (complementSequence)\n\ndef PrintToFile(outputFile, framedSequence):\n numberOfFrames = len(framedSequence)\n # outputFile = \"outputFile.txt\"\n\n with open(outputFile, 'w') as f:\n \n # print('Filename:', outputFile, file=f) \n for frameNumber, frames in enumerate(framedSequence):\n frameNumber = framedSequence.index(frames) #change index\n for openReadingFrame, aminoAcids in enumerate(frames):\n print (\">CLAUD_F\" + str(frameNumber+1) + \"_\" + str(openReadingFrame+1).zfill(4), file=f)\n print (aminoAcids, file=f)\n \nfinalFrames = 0\nfinalFrames = TranslateORF(range(1,7))\n# print (finalFrames)\nPrintToFile(\"outputFile.txt\", finalFrames)\n","sub_path":"1-ORF-Finder/translateORF.py","file_name":"translateORF.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543458721","text":"\n#%%\n\n\ndef write_output(filename, output):\n \"\"\"\n writes a list of strings to a .out file\n\n parameters: \n - output: list of strings \n - filename: string\n \"\"\"\n \n filepath = 'data/output_{}.out'.format(filename)\n print('saving file to {}'.format(filepath))\n print(output)\n\n with open(filepath, \"w\") as outfile:\n outfile.write(\"\\n\".join(output))\n\n return \n\n\n\n#%%\n\ndef read_data(filename):\n \n pizzas = []\n with open('data/{}'.format(filename), 'r') as infile: \n\n number_of_pizzas, teams_of_two, teams_of_three, teams_of_four = map(int, infile.readline().split())\n\n for _ in range(number_of_pizzas):\n pizza = list(infile.readline().split())\n pizzas.append(pizza)\n\n problem = {\n 'team_2': teams_of_two,\n 'team_3': teams_of_three,\n 'team_4': teams_of_four,\n 'pizzas': pizzas\n }\n\n return problem \n\n\n#%%\n\n# read data\n\n#filename = 'd_many_pizzas.in'\nfilename = 'e_many_teams.in'\nproblem = read_data(filename)\n\n\n# %%\n# setup problem \n\n\nproblem['pizzas_formated'] = []\nfor i, data in enumerate(problem['pizzas']):\n\n problem['pizzas_formated'].append({\n 'number_of_pizzas': int(data[0]),\n 'ingredients': data[1:],\n 'pizza_id': i\n })\n\n\n\nproblem['pizzas'] = problem['pizzas_formated']\ndel problem['pizzas_formated']\nproblem\n\n#%%\n\npizza_stack = []\n\nfor pizza in problem['pizzas']:\n pizza_stack.append({\n 'pizza_id': pizza['pizza_id'],\n 'ingredients': pizza['ingredients']})\n\n\npizza_stack = sorted(pizza_stack, key=len, reverse=True)\npizza_stack\n\n#%%\nimport pandas as pd \n\npizzas = pd.DataFrame(pizza_stack)\n\npizzas.set_index('pizza_id')\npizzas\n\n#%%\n\ningredient_dummies = pd.get_dummies(pizzas['ingredients'].apply(pd.Series).stack()).sum(level=0)\npizzas = pizzas.merge(ingredient_dummies, left_index=True, right_index=True)\nall_ingredients = list(ingredient_dummies.columns)\npizzas['n_ingredients'] = pizzas.apply(lambda x: len(x['ingredients']), axis = 1) \n\npizzas\n\n\n\n#%%\n\nteam_stack = []\n\nfor _ in range(problem['team_2']):\n team_stack.append({\n 'needs': 2,\n 'pizzas': []\n })\n\nfor _ in range(problem['team_3']):\n team_stack.append({\n 'needs': 3,\n 'pizzas': []\n })\n\nfor _ in range(problem['team_4']):\n team_stack.append({\n 'needs': 4,\n 'pizzas': []\n })\n\n\nteam_stack\n\n#%%\n\n# danach eventuell alle teams nicht satt\n# --> nimm random pizzen so viel wie geht\n# --> nimm teams pizzen weg falls keine mehr da\nfrom copy import deepcopy\n\ndef run(team, pizzas=pizzas, all_ingredients=all_ingredients):\n initial_need = team['needs']\n temp_pizzas = deepcopy(pizzas)\n team['missing_ingredients'] = all_ingredients\n while team['needs'] > 0:\n #temp_pizzas['score'] = temp_pizzas.apply(lambda x: sum(x[team['missing_ingredients']]) / len(x['ingredients']), axis = 1)\n #temp_pizzas['score'] = pizzas[team['missing_ingredients']].apply(sum)\n\n pizza = temp_pizzas.loc[temp_pizzas.apply(lambda x: sum(x[team['missing_ingredients']]) / len(x['ingredients']), axis = 1).idxmax()]\n\n team['pizzas'].append(pizza['pizza_id'])\n\n team['missing_ingredients'] = list(set(team['missing_ingredients']) - set(pizza['ingredients'])) \n\n team['needs'] -= 1\n\n # temp_pizza_stack = [p for p in temp_pizza_stack if p['ingredients'] != pizza['ingredients']]\n temp_pizzas = temp_pizzas.drop(pizza['pizza_id'])\n\n if temp_pizzas.empty:\n print(\"temp leer\")\n break\n\n if(team['needs'] > 0):\n team['needs'] = initial_need\n team['pizzas'] = []\n\n # missing ing event\n else:\n pizzas = temp_pizzas\n # pizza_stack = [p for p in pizza_stack if p not in team['pizzas']]\n if pizzas.empty:\n print(\"keine pizzen mehr\")\n return team\n \n#for team in team_stack:\n# a = run(team)\n# print(a) \n \n\n# %%\nfrom multiprocessing import Pool, cpu_count\n\nA = []\ndef mycallback(x):\n A.append(x)\n\nresults = []\n\nif __name__ == '__main__': \n pool = Pool(processes = cpu_count())\n for team in team_stack:\n output = pool.apply_async(run, (team, pizzas), callback=mycallback)\n results.append(output)\n for r in results:\n r.wait()\n\nprint(A)\n\n\n#%%\n\n# output\n\nteams_served = [team for team in A if team['needs'] == 0]\n\noutput = []\noutput.append(str(len(teams_served)))\nfor team in teams_served:\n line = str(len(team['pizzas'])) + ' '\n line += ' '.join([str(pizza) for pizza in team['pizzas']])\n output.append(line)\n\n\nwrite_output(filename, output)\n\n#%%\n\n\n \n# %%\n","sub_path":"2021/practice_round/practice_m.py","file_name":"practice_m.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400392320","text":"import sys\r\nsys.setrecursionlimit(100005)\r\n\r\ndef dfs(u):\r\n visited[u] = 1\r\n Flag = False\r\n for v in adj[u]:\r\n if visited[v] == 1:\r\n return True\r\n if visited[v] == 0:\r\n Flag = Flag or dfs(v)\r\n visited[u] = 2\r\n return Flag\r\n \r\ntestcase = int(input())\r\nfor _ in range(testcase):\r\n n, m = map(int, input().split())\r\n adj = [[] for i in range(n + 1)]\r\n for i in range(m):\r\n u, v = map(int, input().split())\r\n adj[u].append(v)\r\n\r\n visited = [0] * (n + 1)\r\n res = 0\r\n Flag = False\r\n for i in range(1, n + 1):\r\n if (visited[i] == 0):\r\n res += 1\r\n Flag = dfs(i) or Flag\r\n if (Flag == True):print(\"YES\")\r\n else :print(\"NO\")\r\n \r\n","sub_path":"Lecture07/DuduServiceMaker.py","file_name":"DuduServiceMaker.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511533366","text":"from constants import *\nfrom PySFML import sf\nclass Board:\n\tdef __init__(self, blue, red):\n\t\tself.grid = []\n\t\tself.blue = blue\n\t\tself.red = red\n\t\tself.invalid = set()\n\t\tfor i in range(num_rows):\n\t\t\tself.grid.append([])\n\t\t\tfor j in range(num_cols):\n\t\t\t\tself.grid[i].append(None)\n\n\tdef draw(self, window):\n\t\tstartx = win_width/2\n\t\tstarty = win_height/2\n\t\tstartx, starty = window.ConvertCoords(startx, starty)\n\t\tstartx -= num_cols * box_width/2\n\t\tstarty -= num_rows * box_height/2\n\n\t\tstartx, starty = (400, 200)\n\t\tfor i, row in enumerate(self.grid):\n\t\t\ty = starty + (i * box_height)\n\t\t\tfor j, square in enumerate(row):\n\t\t\t\tx = startx + (j * box_width)\n\t\t\t\tcolor = sf.Color(255, 255, 255)\n\t\t\t\tif j == 0:\n\t\t\t\t\tcolor = red\n\t\t\t\telif j == num_cols - 1:\n\t\t\t\t\tcolor = blue\n\n\t\t\t\tbg_color = sf.Color(0, 0, 0)\n\t\t\t\tif (i, j) in self.invalid:\n\t\t\t\t\tbg_color = sf.Color(150, 25, 25)\n\t\t\t\t\n\t\t\t\tbox = sf.Shape.Rectangle(x, y, x + box_width, y + box_height, bg_color, 1, color)\n\n\t\t\t\twindow.Draw(box)\n\n\t\t\t\tif self.grid[i][j]:\n\t\t\t\t\tself.grid[i][j].draw(window, x, y)\n\n\tdef snap(self, window, token):\n\t\tstartx = win_width/2\n\t\tstarty = win_height/2\n\t\tstartx, starty = window.ConvertCoords(startx, starty)\n\t\tstartx -= num_cols * box_width/2\n\t\tstarty -= num_rows * box_height/2\n\n\t\tcx, cy = token.get_center()\n\t\tcx, cy = int(cx), int(cy)\n\n\n\t\tstartx, starty = (400, 200)\n\t\tfor i, row in enumerate(self.grid):\n\t\t\ty = starty + (i * box_height)\n\t\t\tfor j, square in enumerate(row):\n\t\t\t\tx = startx + (j * box_width)\n\n\t\t\t\trect = sf.IntRect(x, y, x + box_width, y + box_height)\n\t\t\t\tif not self.grid[i][j] and rect.Contains(cx, cy):\n\t\t\t\t\tself.grid[i][j] = token\n\t\t\t\t\ttoken.i = i\n\t\t\t\t\ttoken.j = j\n\n\t\t\t\t\treturn\n\n\n\tdef is_end_point(self, node, color):\n\t\tif color == 'blue' and node[1] == num_cols - 1:\n\t\t\treturn True\n\t\tif color == 'red' and node[1] == 0:\n\t\t\treturn True\n\t\treturn False\n\n\tdef neighbors(self, root):\n\t\tright = (root[0] + 1, root[1])\t\n\t\tleft = (root[0] - 1, root[1])\t\n\t\ttop = (root[0], root[1] + 1)\t\n\t\tbottom = (root[0], root[1] - 1)\t\n\n\t\tneighbors = []\n\t\tfor node in (right, left, top, bottom):\n\t\t\tif node[0] >= 0 and node[1] >= 0 and node[0] <= num_cols - 1 and node[1] <= num_cols - 1 and (not self.grid[node[0]][node[1]] or self.grid[node[0]][node[1]].type != 'rect'):\n\t\t\t\tneighbors.append(node)\n\n\t\treturn neighbors\n\n\tdef find_paths(self, path, color):\n\t\tpaths = []\n\t\tif self.is_end_point(path[-1], color):\n\t\t\treturn path\n\n\t\tfor node in self.neighbors(path[-1]):\n\t\t\tif not node in path:\n\t\t\t\tpath.append(node)\n\t\t\t\tpaths += self.find_paths(path, color)\n\n\t\treturn paths\n\n\tdef get_valid_paths(self):\n\t\tpaths = []\t\n\n\t\tstart = (self.red.i, self.red.j)\n\n\t\treturn self.find_paths([start], 'red')\n\n\tdef find_critical_nodes(self, paths):\n\t\tif not paths:\n\t\t\treturn set()\n\t\tresult = set(paths[0])\n\t\tfor path in paths:\n\t\t\tset_path = set(path)\n\t\t\tresult &= set_path\n\n\t\treturn result\n\t\t\t\n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"648695854","text":"# -*- config: utf-8 -*-\n\"\"\"\nMovement scripting.\n\"\"\"\n\nimport time\nimport yaml\nimport sys\nfrom copy import copy\n\n__all__ = [\n 'Script',\n 'Movement',\n 'ScriptError',\n]\n\n\nclass ScriptError(Exception):\n pass\n\n\nclass Movement(yaml.YAMLObject):\n yaml_tag = '!Movement'\n\n def __init__(self, **kvargs):\n self.joints = [] # (joints, deg, rad, pos)\n self.update(**kvargs)\n\n def update(self, **kvargs):\n self.time = float(kvargs.pop('time', 0))\n self.wait = float(kvargs.pop('wait', 0))\n\n for k, v in kvargs.iteritems():\n try:\n joint, measure = k.rsplit('_', 1)\n except ValueError:\n joint, measure = k, 'pos'\n\n if measure in ['deg', 'degrees']:\n move = (joint, float(v), None, None)\n elif measure in ['rad', 'radians']:\n move = (joint, None, float(v), None)\n elif measure in ['pos', 'position']:\n move = (joint, None, None, int(v))\n else:\n raise ScriptError('unknown measure \"{0}\" for servo \"{1}\"'.format(measure, joint))\n\n self.joints.append(move)\n\n def run(self, ssc, time_):\n for move in self.joints:\n joint_name, deg, rad, pos = move\n joint = ssc[joint_name]\n if deg is not None:\n joint.degrees = deg\n elif rad is not None:\n joint.radians = rad\n else:\n joint.position = pos\n\n time_i = self.time if self.time else time_\n time_i = int(time_i * 1000)\n\n ssc.commit(time=time_i)\n while not ssc.is_done():\n time.sleep(0.01)\n time.sleep(self.wait)\n\n def __cmp__(self, obj):\n if not isinstance(obj, Movement):\n return False\n return cmp(self.joints, obj.joints)\n\n def __getstate__(self):\n d = {'time': self.time,\n 'wait': self.time}\n for joint, deg, rad, pos in self.joints:\n if deg is not None:\n mv = {'deg': deg}\n elif rad is not None:\n mv = {'rad': rad}\n else:\n mv = {'pos': pos}\n d[joint] = mv\n return d\n\n def __setstate__(self, data):\n self.joints = []\n self.time = float(data.pop('time', 0))\n self.wait = float(data.pop('wait', 0))\n \n if sys.version_info >= (3, 0):\n items = data.items()\n else:\n items = data.iteritems()\n \n for k, v in items:\n self.joints.append((k,\n v.pop('deg', None),\n v.pop('rad', None),\n v.pop('pos', None)))\n\n\n def __repr__(self):\n return ''.format(\n self.time, self.wait, self.joints)\n\n\nclass Script(yaml.YAMLObject):\n yaml_tag = '!Script'\n\n def __init__(self, time=None):\n self.time = time\n self.movements = []\n self.on_movement_done = lambda pn, movement: None\n\n def add(self, **kvargs):\n self.movements.append(Movement(**kvargs))\n\n def run(self, ssc):\n autocommit = ssc.autocommit\n ssc.autocommit = None\n ml = len(self.movements)\n for no, move in enumerate(self.movements):\n move.run(ssc, self.time)\n self.on_movement_done((no+1, ml), move)\n ssc.autocommit = autocommit\n\n def __call__(self, ssc):\n self.run(ssc)\n\n def __cmp__(self, obj):\n if not isinstance(obj, Script):\n return False\n return cmp(self.time, obj.time) and \\\n cmp(self.movements, obj.movements)\n\n def __add__(self, obj):\n cls = Script(time=self.time)\n cls.movements = copy(self.movements)\n\n if isinstance(obj, dict):\n cls.add(**obj)\n elif isinstance(obj, Movement):\n cls.movements.append(obj)\n elif isinstance(obj, Script):\n cls.movements += obj.movements\n elif isinstance(obj, (tuple, list)):\n for i in obj:\n self.__add__(i)\n else:\n raise ValueError('Unsupported type')\n\n return cls\n\n def __getstate__(self):\n return {'time': self.time,\n 'movements': self.movements}\n\n def __setstate__(self, data):\n self.time = data.pop('time', 0)\n self.movements = data.pop('movements', [])\n\n def __repr__(self):\n return '