diff --git "a/2672.jsonl" "b/2672.jsonl" new file mode 100644--- /dev/null +++ "b/2672.jsonl" @@ -0,0 +1,743 @@ +{"seq_id":"544474319","text":"#!/usr/bin/env python\n\n# Family size distribution of tags which were aligned to the reference genome\n#\n# Author: Monika Heinzl, Johannes-Kepler University Linz (Austria)\n# Contact: monika.heinzl@edumail.at\n#\n# Takes at least one TABULAR file with tags before the alignment to the SSCS\n# and a TXT with tags of reads that overlap the regions of the reference genome as input.\n# The program produces a plot which shows the distribution of family sizes of the tags from the input files and\n# a CSV file with the data of the plot.\n\n# USAGE: python FSD_regions_1.6_FINAL.py --inputFile filenameSSCS --inputName1 filenameSSCS --ref_genome filenameRefGenome --sep \"characterWhichSeparatesCSVFile\" --output_csv outptufile_name_csv --output_pdf outptufile_name_pdf\n\nimport numpy\nimport matplotlib.pyplot as plt\nimport argparse\nimport sys\nimport os\nfrom matplotlib.backends.backend_pdf import PdfPages\n\ndef readFileReferenceFree(file, delim):\n with open(file, 'r') as dest_f:\n data_array = numpy.genfromtxt(dest_f, skip_header=0, delimiter=delim, comments='#', dtype='string')\n return(data_array)\n\ndef make_argparser():\n parser = argparse.ArgumentParser(description='Family Size Distribution of tags which were aligned to regions of the reference genome')\n parser.add_argument('--inputFile',\n help='Tabular File with three columns: ab or ba, tag and family size.')\n parser.add_argument('--inputName1')\n parser.add_argument('--ref_genome',\n help='TXT File with tags of reads that overlap the region.')\n parser.add_argument('--output_pdf', default=\"data.pdf\", type=str,\n help='Name of the pdf and csv file.')\n parser.add_argument('--output_csv', default=\"data.csv\", type=str,\n help='Name of the pdf and csv file.')\n parser.add_argument('--sep', default=\",\",\n help='Separator in the csv file.')\n return parser\n\ndef compare_read_families_refGenome(argv):\n parser = make_argparser()\n args = parser.parse_args(argv[1:])\n\n firstFile = args.inputFile\n name1 = args.inputName1\n name1 = name1.split(\".tabular\")[0]\n refGenome = args.ref_genome\n title_file = args.output_pdf\n title_file2 = args.output_csv\n sep = args.sep\n\n if type(sep) is not str or len(sep) > 1:\n print(\"Error: --sep must be a single character.\")\n exit(3)\n\n with open(title_file2, \"w\") as output_file, PdfPages(title_file) as pdf:\n data_array = readFileReferenceFree(firstFile, \"\\t\")\n\n mut_array = readFileReferenceFree(refGenome, \" \")\n length_regions = len(mut_array)\n\n seq = numpy.array(data_array[:, 1])\n tags = numpy.array(data_array[:, 2])\n quant = numpy.array(data_array[:, 0]).astype(int)\n group = numpy.array(mut_array[:, 0])\n\n all_ab = seq[numpy.where(tags == \"ab\")[0]]\n all_ba = seq[numpy.where(tags == \"ba\")[0]]\n quant_ab = quant[numpy.where(tags == \"ab\")[0]]\n quant_ba = quant[numpy.where(tags == \"ba\")[0]]\n\n seqDic_ab = dict(zip(all_ab, quant_ab))\n seqDic_ba = dict(zip(all_ba, quant_ba))\n\n seq_mut = numpy.array(mut_array[:, 1])\n\n groupUnique, group_index = numpy.unique(group, return_index=True)\n groupUnique = groupUnique[numpy.argsort(group_index)]\n\n lst_ab = []\n for i in seq_mut:\n lst_ab.append(seqDic_ab.get(i))\n\n lst_ba = []\n for i in seq_mut:\n lst_ba.append(seqDic_ba.get(i))\n\n quant_ab = numpy.array(lst_ab)\n quant_ba = numpy.array(lst_ba)\n\n quantAfterRegion = []\n for i in groupUnique:\n dataAB = quant_ab[numpy.where(group == i)[0]]\n dataBA = quant_ba[numpy.where(group == i)[0]]\n bigFamilies = numpy.where(dataAB > 20)[0]\n dataAB[bigFamilies] = 22\n bigFamilies = numpy.where(dataBA > 20)[0]\n dataBA[bigFamilies] = 22\n\n quantAll = numpy.concatenate((dataAB, dataBA))\n quantAfterRegion.append(quantAll)\n\n maximumX = numpy.amax(numpy.concatenate(quantAfterRegion))\n minimumX = numpy.amin(numpy.concatenate(quantAfterRegion))\n\n ### PLOT ###\n plt.rc('figure', figsize=(11.69, 8.27)) # A4 format\n plt.rcParams['axes.facecolor'] = \"E0E0E0\" # grey background color\n plt.rcParams['xtick.labelsize'] = 14\n plt.rcParams['ytick.labelsize'] = 14\n plt.rcParams['patch.edgecolor'] = \"black\"\n fig = plt.figure()\n plt.subplots_adjust(bottom=0.3)\n\n colors = [\"#6E6E6E\", \"#0431B4\", \"#5FB404\", \"#B40431\", \"#F4FA58\", \"#DF7401\", \"#81DAF5\"]\n\n col = []\n for i in range(0, len(groupUnique)):\n col.append(colors[i])\n\n counts = plt.hist(quantAfterRegion, bins=range(minimumX, maximumX + 1), stacked=False, label=groupUnique,\n align=\"left\", alpha=1, color=col, edgecolor=\"black\", linewidth=1)\n ticks = numpy.arange(minimumX - 1, maximumX, 1)\n\n ticks1 = map(str, ticks)\n ticks1[len(ticks1) - 1] = \">20\"\n plt.xticks(numpy.array(ticks), ticks1)\n count = numpy.bincount(map(int, quant_ab)) # original counts\n\n legend = \"max. family size =\\nabsolute frequency=\\nrelative frequency=\\n\\ntotal nr. of reads=\"\n plt.text(0.15, 0.105, legend, size=11, transform=plt.gcf().transFigure)\n\n legend = \"AB\\n{}\\n{}\\n{:.5f}\\n\\n{:,}\" \\\n .format(max(map(int, quant_ab)), count[len(count) - 1], float(count[len(count) - 1]) / sum(count),\n sum(numpy.array(data_array[:, 0]).astype(int)))\n plt.text(0.35, 0.105, legend, size=11, transform=plt.gcf().transFigure)\n\n count2 = numpy.bincount(map(int, quant_ba)) # original counts\n\n legend = \"BA\\n{}\\n{}\\n{:.5f}\" \\\n .format(max(map(int, quant_ba)), count2[len(count2) - 1], float(count2[len(count2) - 1]) / sum(count2))\n plt.text(0.45, 0.15, legend, size=11, transform=plt.gcf().transFigure)\n\n legend1 = \"total nr. of tags=\"\n legend2 = \"total numbers * \\n{:,}\".format(length_regions)\n plt.text(0.6, 0.2, legend1, size=11, transform=plt.gcf().transFigure)\n plt.text(0.75, 0.2, legend2, size=11, transform=plt.gcf().transFigure)\n legend4 = \"* In the plot, both family sizes of the ab and ba strands were used.\\nWhereas the total numbers indicate only the single count of the tags per region.\\n\"\n plt.text(0.1, 0.02, legend4, size=11, transform=plt.gcf().transFigure)\n\n space = numpy.arange(0, len(groupUnique), 0.02)\n for i, s, count in zip(groupUnique, space, quantAfterRegion):\n plt.text(0.6, 0.05 + s, \"{}=\\n\".format(i), size=11, transform=plt.gcf().transFigure)\n plt.text(0.75, 0.05 + s, \"{:,}\\n\".format(len(count) / 2), size=11, transform=plt.gcf().transFigure)\n\n plt.legend(loc='upper right', fontsize=14, bbox_to_anchor=(0.9, 1), frameon=True)\n #plt.title(name1, fontsize=14)\n plt.xlabel(\"Family size\", fontsize=14)\n plt.ylabel(\"Absolute Frequency\", fontsize=14)\n plt.grid(b=True, which=\"major\", color=\"#424242\", linestyle=\":\")\n plt.margins(0.01, None)\n\n # plt.savefig(\"{}_regions.pdf\".format(title_file), bbox_inch=\"tight\")\n pdf.savefig(fig, bbox_inch=\"tight\")\n plt.close()\n\n output_file.write(\"Dataset:{}{}\\n\".format(sep, name1))\n output_file.write(\"{}AB{}BA\\n\".format(sep, sep))\n output_file.write(\"max. family size:{}{}{}{}\\n\".format(sep, max(map(int, quant_ab)), sep, max(map(int, quant_ba))))\n output_file.write(\"absolute frequency:{}{}{}{}\\n\".format(sep, count[len(count) - 1], sep, count2[len(count2) - 1]))\n output_file.write(\"relative frequency:{}{:.3f}{}{:.3f}\\n\\n\".format(sep, float(count[len(count) - 1]) / sum(count), sep, float(count2[len(count2) - 1]) / sum(count2)))\n output_file.write(\"total nr. of reads{}{}\\n\".format(sep, sum(numpy.array(data_array[:, 0]).astype(int))))\n output_file.write(\"\\n\\nValues from family size distribution\\n\")\n output_file.write(\"{}\".format(sep))\n for i in groupUnique:\n output_file.write(\"{}{}\".format(i,sep))\n output_file.write(\"\\n\")\n j=0\n for fs in counts[1][0:len(counts[1])-1]:\n if fs == 21:\n fs = \">20\"\n else:\n fs = \"={}\".format(fs)\n output_file.write(\"FS{}{}\".format(fs,sep))\n for n in range(len(groupUnique)):\n output_file.write(\"{}{}\".format(int(counts[0][n][j]), sep))\n output_file.write(\"\\n\")\n j+=1\n output_file.write(\"sum{}\".format(sep))\n for i in counts[0]:\n output_file.write(\"{}{}\".format(int(sum(i)), sep))\n output_file.write(\"\\n\")\n output_file.write(\"\\n\\nIn the plot, both family sizes of the ab and ba strands were used.\\nWhereas the total numbers indicate only the single count of the tags per region.\\n\")\n output_file.write(\"Region{}total nr. of tags per region\\n\".format(sep))\n for i, count in zip(groupUnique, quantAfterRegion):\n output_file.write(\"{}{}{}\\n\".format(i,sep,len(count) / 2))\n output_file.write(\"sum of tags{}{}\\n\".format(sep,length_regions))\n\n print(\"Files successfully created!\")\n #print(\"Files saved under {}.pdf and {}.csv in {}!\".format(title_file, title_file, os.getcwd()))\n\nif __name__ == '__main__':\n sys.exit(compare_read_families_refGenome(sys.argv))\n","sub_path":"tools/fsd_regions/fsd_regions.py","file_name":"fsd_regions.py","file_ext":"py","file_size_in_byte":9481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"123775476","text":"#coding: utf-8\n\n# https://github.com/coomlata1/pythonista-scripts/blob/master/PhotosToDropbox.py\n\n'''\nPhotoToDropbox.py\n@coomlata1\n\nv1.0: 01/28/2015-Created\n\nv1.1: 02/01/2015-Fixed bug in 'GetDimensions()'\nfunction for square photos.\n\nv1.2: 02/05/2015-Added code to geo-tag photos with\ndate, time, and place that photo was taken & a\ntimer function to track the processing time for\nscript.\n\nv1.3: 02/09/2015-Reduced geo-tag font size for\nsmaller photos.\n\nv1.4: 02/09/2015-Many thanks to cclaus for detailed\ncode cleanup & insightful comments.\n\nv1.5: 02/22/2015-More code cleanup & better string\nformatting\n\nv1.6: 03/25/2015-Fixed bug in main()\nwhere photo with no geotag was not being appended\nto 'no_gps' list.\n\nv1.7: 04/13/2015-Code tightening with help & thanks\nto @cclauss.\n\nv1.8: 08/20/2015-Fixed several bugs in geo-tag\nfunction\n\nv1.9: 01/01/2016-Resize photo before geo-tag stamp\nrather than after, for more consistent placement &\nfont size for tag.\n\nv2.0: 01/22/2016-Added code to disable auto timer\nto prevent script from stalling on large photo transfers.\nInspiration for this comes from @cclauss.\n\nv2.1: 01/30/2016-Added code and a pyui file to support\nthe selection of dropbox photo directory, sizing, geotag,\nand metadata options via a form.\n\nThis Pythonista script will RESIZE,\nRENAME, GEO-TAG & UPLOAD all selected\nphotos in the iPhone camera roll to new\nfolders in your Dropbox account. The main\nfolder will be named after the year the\nphoto was taken in the format 'yyyy', &\nthe subfolders will be named for the date\nthe photo was taken in the format\nmm.dd.yyyy. The photos themselves will\nhave the exact time the photo was taken\namended to the front of their names in the\nformat hh.mm.ss.XXXX.jpg, where XXXX is\nthe original name. All metadata in the\noriginal photo will be copied to the\nresized & renamed copy if desired. The\nscript allows you to select your desired\nphoto scaling options.\n\nScript requires that the pexif module,\navailable at https://github.com\nbennoleslie/pexif, be imported into\nPythonista. Just copy pexif.py into the\nPythonista script dir. Pexif allows for\nboth reading from and writing to the\nmetadata of image files. Many thanks to\nBen Leslie for maintaining the pexif\nmodule at github.\n\nScript also requires DropboxLogin.py, available at\nhttps://gist.github.com/omz/4034526, which allows\nlogin access to dropbox.\n'''\nfrom __future__ import print_function\nimport console\nimport location\nimport photos\nimport re\nimport string\nimport sys\nimport time\nimport pexif\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nfrom dropboxlogin import get_client\nimport ui\n\n# Global variables for pyui file\nglobal fifty\nglobal custom\nglobal none\n\n# Global arrays for photos that will require manual processing\nno_exif = []\nno_resize = []\nno_gps = []\n\n# Global processing flags\nresizeOk = True\nminumum_size = True\nresizePercent = 0\n\ndef button_tapped(sender):\n\t'@type sender: ui.Button'\n\tglobal fifty\n\tglobal custom\n\tglobal none\n\t\n\tif sender.name == 'fifty':\n\t\tfifty = True\n\t\tv.close()\n\tif sender.name == 'custom':\n\t\tcustom = True\n\t\tv.close()\n\tif sender.name == 'none':\n\t\tnone = True\n\t\tv.close()\n\t\t\ndef GetDateTime(meta):\n\t# The defaults\n\ttheYear = theDate = theTime = ''\n\t# Added default\n\texif = meta.get('{Exif}', None)\n\tif exif:\n\t\ttry:\n\t\t\ttheDate,theTime = str(exif.get('DateTimeOriginal')).split()\n\t\t\ttheDate = theDate.split(':')\n\t\t\ttheYear = theDate[0]\n\t\t\ttheDate = '{}.{}.{}'.format(theDate[1],theDate[2],theYear)\n\t\t\ttheTime = theTime.replace(':','.')\n\t\texcept: # ccc: you should specify the errors you expect...\n\t\t\tpass # https://realpython.com/blog/python/the-most-diabolical-python-antipattern\n\treturn theYear, theDate, theTime\n\t\ndef GetDimensions(meta, scale, img_name, min):\n\t# Add default for exif\n\texif = meta.get('{Exif}', None)\n\t#print exif\n\t# Original dimensions\n\tw = int(exif.get('PixelXDimension'))\n\th = int(exif.get('PixelYDimension'))\n\t\n\t# Minumum dimensions\n\tmin_w = 1600 if min else 0\n\tmin_h = 1200 if min else 0\n\t\n\tif scale == 1:\n\t\t# If scaled at 100%...no resize\n\t\tno_resize.append(img_name)\n\t\tresizeOk = False\n\t# Square\n\telif w == h:\n\t# Don't resize square photos with a height smaller than height of desired minumum size\n\t\tif h < min_h:\n\t\t\tno_resize.append(img_name)\n\t\t\tresizeOk = False\n\t\telse:\n\t\t\tresizeOk = True\n\t# Don't resize a non-square photo smaller than the desired minumum size.\n\telif int(scale * (w)) * int(scale * (h)) < int(min_w * min_h):\n\t\tno_resize.append(img_name)\n\t\tresizeOk = False\n\telse:\n\t\tresizeOk = True\n\t\t\n\tnew_w = int(scale * w) if resizeOk else w\n\tnew_h = int(scale * h) if resizeOk else h\n\t\n\t# Return new & original dimensions, & resize flag\n\treturn new_w, new_h, w, h, resizeOk\n\t\ndef CopyMeta(meta_src, meta_dst, x, y):\n\t'''\n\tCopy metadata from original photo to a\n\tresized photo that has no media metadata\n\tand write the results to a new photo\n\tthat is resized with the media metadata.\n\t'''\n\t# Source photo\n\timg_src = pexif.JpegFile.fromFile(meta_src)\n\t# Destination photo\n\timg_dst = pexif.JpegFile.fromFile(meta_dst)\n\timg_dst.import_metadata(img_src)\n\t# Results photo\n\t'''\n\tAfter importing metadata from source\n\twe need to update the metadata to the\n\tnew resize dimensions. Thanks to Ben\n\tLeslie for updating Pexif to\n\taccomodate this.\n\t'''\n\timg_dst.exif.primary.ExtendedEXIF.PixelXDimension = [x]\n\timg_dst.exif.primary.ExtendedEXIF.PixelYDimension = [y]\n\t\n\t# Now write the updated metadata to the resized photo\n\timg_dst.writeFile('meta_resized.jpg')\n\t\n# ccc: rewrite to use dict.get() with default...returns degreesToRotate, orientation\ndef GetDegreesToRotate(d):\n\trotate_dict = {'1':(0,'landscape'),\n\t'3':(-180,'landscape'),\n\t'6':(-90,'portrait'),\n\t'8': (90,'portrait')}\n\treturn rotate_dict.get(str(d), (0, 'unknown'))\n\t\ndef GetLocation(meta):\n\tgps = meta.get('{GPS}', None)\n\t\n\tif gps:\n\t\tlat = gps.get('Latitude',0.0)\n\t\tlon = gps.get('Longitude',0.0)\n\t\tlat_ref = gps.get('LatitudeRef', '')\n\t\tlon_ref = gps.get('LongitudeRef', '')\n\t\t# Southern hemisphere\n\t\tif lat_ref == 'S':\n\t\t\tlat = -lat\n\t\t# Western hemisphere\n\t\tif lon_ref == 'W':\n\t\t\tlon = -lon\n\t\t\t\n\t\tcoordinates = {'latitude':lat, 'longitude':lon}\n\t\t\n\t\t# Dictionary of location data\n\t\t# ccc: pick results[0] right away\n\t\tresults = location.reverse_geocode(coordinates)[0]\n\t\t\n\t\tname = results['Name']\n\t\ttry:\n\t\t\tstreet = results['Thoroughfare']\n\t\texcept KeyError:\n\t\t\tstreet = ''\n\t\ttry:\n\t\t\tcity = results['City']\n\t\texcept KeyError:\n\t\t\tcity = ''\n\t\ttry:\n\t\t\tstate = results['State']\n\t\texcept KeyError:\n\t\t\tstate = ''\n\t\ttry:\n\t\t\tzipcode = results['ZIP']\n\t\texcept KeyError:\n\t\t\tzipcode = ''\n\t\t\t\n\t\t# If name is an address then use street name only\n\t\tif find_number(name):\n\t\t\tname = street\n\t\t\t\n\t\ttheLocation = '{}, {} {} @ {}'.format(city, state, zipcode, name)\n\telse:\n\t\ttheLocation = ''\n\t\t\n\treturn theLocation\n\t\ndef find_number(a):\n\treturn re.findall(r'^\\.?\\d+',a)\n\t\ndef Timer(start, end, count):\n\t\"\"\"\n\tCalculates the time it takes to run\n\tprocess, based on start and finish\n\t\"\"\"\n\t# Add 5 seconds to time for each photo's dropbox upload pause\n\telapsed = (end - start) + (5 * count)\n\t# Convert process time, if needed\n\tif elapsed < 60:\n\t\ttime = '{:.2f}'.format(elapsed) + \" seconds\\n\"\n\telif elapsed < 3600:\n\t\tmin = elapsed / 60\n\t\ttime = '{:.2f}'.format(min) + \" minutes\\n\"\n\telse: # elapsed >= 3600:\n\t\thour = elapsed / 3600\n\t\ttime = '{:.2f}'.format(hour) + \" hours\\n\"\n\t\t\n\treturn time\n\t\ndef main(choose, keepMeta, geoTag, dest_dir, size):\n\tminumum_size = True\n\tresizePercent = 0\n\t\n\tif size == 'fifty':\n\t\tscale = float(50) / 100\n\telif size == 'custom':\n\t\tmsg = 'Enter desired reduction percent for selected photo(s): '\n\t\ttry:\n\t\t\tscale = float(console.input_alert(msg,'Numbers only','35')) / 100\n\t\t\t# No minumums here...reduce all photos no matter what their size.\n\t\t\tminumum_size = False\n\t\texcept KeyboardInterrupt:\n\t\t\tsys.exit('Script cancelled.')\n\telif size == 'none':\n\t\tscale = 1\n\t\t\n\t#john = dialogs.form_dialog(title = 'Photo Options',fields=[{'type':'switch','title':'Geotag'}, {'type':'switch','title':'Keep Metadata'}])\n\t\n\t# Disable idle timer to cover working with a large batch of photos\n\tconsole.set_idle_timer_disabled(True)\n\t\n\tstart = time.clock()\n\t\n\t# Create an instance of Dropbox client\n\tdrop_client = get_client()\n\t\n\tans = ''\n\t'''\n\tWhen metadata is returned with photo\n\tthe photo is a tuple, with one the\n\timage, and the other the media\n\tmetadata.\n\t'''\n\tfor count, photo in enumerate(choose):\n\t\t# Raw data string and Metadata\n\t\timg, meta = photo\n\t\t#print meta\n\t\t#sys.exit()\n\t\t\n\t\tprint('\\nProcessing photo...')\n\t\t# Get date & time photo was taken\n\t\ttheYear, theDate, theTime = GetDateTime(meta)\n\t\t\n\t\t# Formulate file name for photo\n\t\told_filename = str(meta.get('filename'))\n\t\t\n\t\tif theDate:\n\t\t\tfolder_name = '{}/{}'.format(theYear, theDate)\n\t\t\tnew_filename = '{}.{}'.format(theTime, old_filename)\n\t\telse:\n\t\t\tfolder_name = 'NoDates'\n\t\t\tnew_filename = old_filename\n\t\t\tkeepMeta = False\n\t\t\t\n\t\tnew_filename = '{}/{}/{}'.format(dest_dir, folder_name, new_filename)\n\t\t\n\t\tif folder_name == 'NoDates':\n\t\t\tno_exif.append(new_filename)\n\t\t\t\n\t\t# Get dimensions for resize based on size of original photo\n\t\tnew_w, new_h, w, h, resizeOk = GetDimensions(meta, scale, new_filename, minumum_size)\n\t\t\n\t\tfmt = '\\nOriginal Name: {}\\nNew Name: {}'\n\t\t\n\t\tprint(fmt.format(old_filename, new_filename))\n\t\t\n\t\tfmt = '\\nOriginal Size: {}x{}\\nNew Size: {}x{}'\n\t\tprint(fmt.format(w, h, new_w, new_h))\n\t\t\n\t\taddToMsg = 'with' if keepMeta else 'without'\n\t\t\n\t\tif resizeOk:\n\t\t\tmsg = '\\nCreating resized copy of original photo {} the metadata from original.'\n\t\telse:\n\t\t\tmsg = '\\nCreating copy of original photo {} the metadata from original.'\n\t\t\t\n\t\tprint(msg.format(addToMsg))\n\t\t\n\t\t# Write string image of original photo to Pythonista script dir\n\t\twith open('with_meta.jpg', 'wb') as out_file:\n\t\t\tout_file.write(img)\n\t\t\t\n\t\t# Open image, resize it, and write new image to scripts dir\n\t\timg = Image.open('with_meta.jpg')\n\t\timg = img.resize((new_w, new_h),Image.ANTIALIAS)\n\t\t\n\t\tif geoTag:\n\t\t\t# Get geo-tagging info\n\t\t\ttheLocation = GetLocation(meta)\n\t\t\t\n\t\t\tif theLocation:\n\t\t\t\tprint('\\nGeo-tagging photo...')\n\t\t\t\t\n\t\t\t\t# Find out if photo is oriented for landscape or portrait\n\t\t\t\torientation = meta.get('Orientation') # ccc: add a default?\n\t\t\t\t'''\n\t\t\t\tGet degrees needed to rotate photo\n\t\t\t\tfor it's proper orientation. See\n\t\t\t\twww.impulsesdventue.com/photo\n\t\t\t\texif-orientation.html for more\n\t\t\t\tdetails.\n\t\t\t\t'''\n\t\t\t\tdegrees, oriented = GetDegreesToRotate(orientation)\n\t\t\t\t\n\t\t\t\tprint('\\nThe orientation for photo is {}.'.format(oriented))\n\t\t\t\t\n\t\t\t\ttheTime = theTime.replace('.',':')\n\t\t\t\ttheLocation = '{} @ {} in {}'.format(theDate, theTime, theLocation)\n\t\t\t\t\n\t\t\t\t# Rotate so tag is on bottom of photo regardless of orientation\n\t\t\t\timg = img.rotate(degrees).convert('RGBA')\n\t\t\t\t# Tuple\n\t\t\t\tw, h = img.size\n\t\t\t\tdraw = ImageDraw.Draw(img)\n\t\t\t\t\n\t\t\t\t# Font for geo-tag will be 28 pt Helvetica\n\t\t\t\t#fontsize = 56 if w > 1300 else 28\n\t\t\t\tfontsize = 28\n\t\t\t\tfont = ImageFont.truetype('Helvetica', fontsize)\n\t\t\t\t\n\t\t\t\t# Determine y axis for geotag\n\t\t\t\t#if h < 1000:\n\t\t\t\t#y = h - 35\n\t\t\t\t#else:\n\t\t\t\t#y = h - 75\n\t\t\t\ty = h - 35\n\t\t\t\t\n\t\t\t\t# Put red text @ bottom left of photo\n\t\t\t\tdraw.text((25, y), theLocation,(255, 0, 0), font = font)\n\t\t\t\t\n\t\t\t\t# Rotate back to original position\n\t\t\t\timg = img.rotate(-degrees)\n\t\t\telse:\n\t\t\t\tprint('\\nNo gps metadata for photo.')\n\t\t\t\tno_gps.append(new_filename)\n\t\telse:\n\t\t\tprint('\\nPhoto will not be geotagged. Flag is set to false.')\n\t\t\t\n\t\tmeta = ''\n\t\t#img = img.resize((new_w, new_h),Image.ANTIALIAS)\n\t\t# Save new image\n\t\timg.save('without_meta.jpg')\n\t\t\n\t\tif keepMeta:\n\t\t\t'''\n\t\t\tCopy metadata from 'with_meta.jpg'\n\t\t\tto 'without_meta.jpg and call this\n\t\t\treprocessed image file\n\t\t\t'meta_resized.jpg'.\n\t\t\t'''\n\t\t\tCopyMeta('with_meta.jpg', 'without_meta.jpg', new_w, new_h)\n\t\t\t\n\t\t\tjpgFile = 'meta_resized.jpg'\n\t\t\t\n\t\telse:\n\t\t\t# Use resized photo that has not had metadata added back into it\n\t\t\tjpgFile = 'without_meta.jpg'\n\t\t\t\n\t\tprint('\\nUploading photo to Dropbox...')\n\t\t\n\t\t'''\n\t\tUpload resized photo with or without\n\t\toriginal metadata to Dropbox...use\n\t\twith statement to open file so file\n\t\tcloses automatically at end of with.\n\t\t'''\n\t\twith open(jpgFile,'r') as img:\n\t\t\tresponse = drop_client.put_file(new_filename, img)\n\t\t\t\n\t\t\t# Give Dropbox server time to process\n\t\t\ttime.sleep(5)\n\t\tresponse = jpgFile = theLocation = img = theDate = theTime = theYear = new_filename = old_filename = ''\n\t\tprint('\\nUpload successful.')\n\t\t\n\tfinish = time.clock()\n\tprint('{} photos processed in {}'.format(count + 1, Timer(start, finish, count + 1)))\n\t\n\tif no_exif:\n\t\tprint('\\nPhotos with no DateTimeOriginal tag in their metadata and will need categorizing manually:')\n\t\tprint('\\n'.join(no_exif))\n\t\t\n\tif no_resize:\n\t\tprint('\\nPhotos that did not get resized because either you chose not to resize, or they were smaller than the minumum size of 1600x1200:')\n\t\tprint('\\n'.join(no_resize))\n\t\t\n\tif no_gps:\n\t\tprint('\\nPhotos that did not get geo-tagged because there was no gps info in the photo\\'s metadata:')\n\t\tprint('\\n'.join(no_gps))\n\t\t\nif __name__ == '__main__':\n\tconsole.clear()\n\t# Make sure photos are available...\n\tif photos.get_count() != 0:\n\t\t'''\n\t\tHere we are picking photos from the\n\t\tcamera roll which, in Pythonista,\n\t\tallows us access to extra media data\n\t\tin photo's metafile. Because raw data\n\t\tis set to true, the image is a string\n\t\trepresenting the image object, not the\n\t\tobject itself.\n\t\t'''\n\t\tchoose = photos.pick_image(show_albums = True, multi = True, original = True, raw_data = True, include_metadata = True)\n\telse:\n\t\tsys.exit('No photos available.')\n\t\t\n\tphoto_count = 0\n\t\n\tfor count, photo in enumerate(choose):\n\t\t# Make sure a photo has been selected...Test first photo\n\t\tif photo_count < 1:\n\t\t\ttry:\n\t\t\t\t# Raw data string and Metadata\n\t\t\t\timg, meta = photo\n\t\t\t\t# Increment counter\n\t\t\t\tphoto_count = photo_count + 1\n\t\t\t# if we get an error there was no photo to test\n\t\t\texcept TypeError:\n\t\t\t\tsys.exit('No photos selected.')\n\t\t\t\t\n\t# Default pic sizes\n\tfifty = False\n\tcustom = False\n\tnone = False\n\t\n\t# Load pyui file\n\tv = ui.load_view('PhotosToDropbox')\n\t\n\tmeta = v['toggle_meta']\n\tgeo = v['toggle_geotag']\n\t\n\t# Display ui and wait till user selects something from it\n\tv.present()\n\tv.wait_modal()\n\t\n\t# Get option choices for keeping metadata and geotagging photos\n\tmeta = meta.value\n\tgeo = geo.value\n\tdest_dir = v['photo_dir'].text\n\t\n\t# Go with default if textbox is blank\n\tif len(dest_dir) == 0:\n\t\tdest_dir = '/Photos'\n\t# Check syntax\n\telif dest_dir[:1] != '/':\n\t\tdest_dir = '/' + dest_dir\n\t\t\n\t# If user pressed the close button then cancel script\n\tif fifty == custom == none == False:\n\t\tsys.exit('Script Cancelled')\n\t# Otherwise store resizing choice in a variable to pass to main()\n\telif fifty:\n\t\tsize = 'fifty'\n\telif custom:\n\t\tsize = 'custom'\n\telif none:\n\t\tsize = 'none'\n\t\t\n\tmain(choose, meta, geo, dest_dir, size)\n\n","sub_path":"dropbox/PhotosToDropbox_coomlata1.py","file_name":"PhotosToDropbox_coomlata1.py","file_ext":"py","file_size_in_byte":14768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"403002652","text":"import cv2\nimport numpy as np\nfrom polarization.camera import PolarizationCamera\nfrom polarization.polarization import Polarization\n\ndef get_degree_of_polarization(cams):\n frames = cams\n result = np.zeros(list(frames[0].shape) + [3], np.uint8) # H x W x C\n\n sort = np.argsort(frames, axis=0) # Sort by Ascending order, C x H x W\n _max = sort[-1]\n _min = sort[0]\n \n for row in range(result.shape[0]):\n for col in range(result.shape[1]):\n\n min_value = frames[_min[row, col]][row][col]\n max_value = frames[_max[row, col]][row][col]\n\n degree_of_polarization = (int(max_value) - int(min_value)) / (int(max_value) + int(min_value)) # 0 to 1\n degree_of_polarization = int(degree_of_polarization * 255) # 0 to 255\n\n result[row, col] = [degree_of_polarization, degree_of_polarization, degree_of_polarization]\n\n return result\n\ncap_0_degree = cv2.VideoCapture(1)\ncap_45_degree = cv2.VideoCapture(2)\ncap_90_degree = cv2.VideoCapture(3)\ncap_135_degree = cv2.VideoCapture(4)\n\n\ncap_list = [cap_0_degree, cap_45_degree, cap_90_degree, cap_135_degree]\n\nfor cap in cap_list:\n assert(cap.isOpened())\n # cap.set(3, 256) \n # cap.set(4, 256)\n\nwhile True:\n\n _, frame1 = cap_0_degree.read()\n _, frame2 = cap_45_degree.read()\n _, frame3 = cap_90_degree.read()\n _, frame4 = cap_135_degree.read()\n\n cv2.imshow('0', frame1)\n cv2.imshow('1', frame2)\n cv2.imshow('2', frame3)\n cv2.imshow('3', frame4)\n\n\n if cv2.waitKey(1) == 27:\n cv2.imwrite('0_degree.jpg', frame1)\n cv2.imwrite('45_degree.jpg', frame2)\n cv2.imwrite('90_degree.jpg', frame3)\n cv2.imwrite('135_degree.jpg', frame4)\n break\n\n\nfor cap in cap_list:\n cap.release()\n\ncv2.destroyAllWindows()\n ","sub_path":"src/capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649928484","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n\turl(r'^apply/$', views.apply, name='apply'),\n\turl(r'^lists/$', views.lists, name='lists'),\n\turl(r'^successfully/$', views.successfully, name='successfully'),\n]","sub_path":"stud_app/studreq/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"593368758","text":"#Various analyses \nimport json\nfrom pyscf import lib,gto,scf,mcscf,fci,lo,ci,cc\nfrom pyscf.scf import ROHF,UHF,ROKS\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pyscf2qwalk import print_qwalk_mol\nfrom functools import reduce \n\n#for mol_spin in [1,3]:\n#for r in [1.725,1.963925]:\n#for method in ['ROHF','B3LYP','PBE0']:\n#for basis in ['vdz','vtz']:\n\n#Gather IAOs\nf='b3lyp_iao_b.pickle'\na=np.load(f)\nprint(a.shape)\nfor mol_spin in [1]:\n for r in [1.963925]:\n for method in ['B3LYP']:\n for basis in ['vtz']:\n for el in ['Cu']:\n for charge in [0]:\n chkfile=\"../chkfiles/\"+el+basis+\"_r\"+str(r)+\"_c\"+str(charge)+\"_s\"+str(mol_spin)+\"_\"+method+\".chk\"\n mol=lib.chkfile.load_mol(chkfile)\n \n if(\"U\" in method): m=UHF(mol)\n else: m=ROHF(mol)\n m.__dict__.update(lib.chkfile.load(chkfile, 'scf'))\n\n #Highest 3 MOs transformed into IAO basis \n s=m.get_ovlp()\n act=np.zeros(s.shape[1])\n act[10:14]=1\n H1=np.diag(act*m.mo_energy)\n e1=reduce(np.dot,(a.T,s,m.mo_coeff,H1,m.mo_coeff.T,s.T,a))*27.2114\n e1=(e1+e1.T)/2.\n\n labels=[\"3s\",\"4s\",\"3px\",\"3py\",\"3pz\",\"3dxy\",\"3dyz\",\"3dz2\",\"3dxz\",\"3dx2y2\",\"2s\",\"2px\",\"2py\",\"2pz\"]\n #plt.title(f.split(\".\")[0]+\" S=\"+str(mol_spin)+\" H1\")\n plt.matshow(e1,cmap=plt.cm.bwr,vmax=-1.7,vmin=1.7)\n plt.xticks(np.arange(len(labels)),labels,rotation=90)\n plt.yticks(np.arange(len(labels)),labels)\n plt.colorbar()\n plt.show()\n exit(0)\n\n #Build RDM on IAO basis \n s=m.get_ovlp()\n mo_occ=np.array([np.ceil(m.mo_occ-m.mo_occ/2),np.floor(m.mo_occ/2)])\n M=m.mo_coeff[:,mo_occ[0]>0]\n M=reduce(np.dot,(a.T,s,M))\n dm_u=np.dot(M,M.T)\n M=m.mo_coeff[:,mo_occ[1]>0]\n M=reduce(np.dot,(a.T,s,M))\n dm_d=np.dot(M,M.T)\n \n #plt.title(\"S=\"+str(mol_spin))\n #plt.matshow(dm_u+dm_d - np.diag(np.diag(dm_u+dm_d)),vmin=-1,vmax=1,cmap=plt.cm.bwr)\n #plt.show()\n\n #Check traces\n act=np.array([1,5,6,7,8,9,11,12,13])\n labels=[\"3s\",\"4s\",\"3px\",\"3py\",\"3pz\",\"3dxy\",\"3dyz\",\"3dz2\",\"3dxz\",\"3dx2y2\",\"2s\",\"2px\",\"2py\",\"2pz\"]\n print('Full trace: ', np.trace(dm_u),np.trace(dm_d)) #Full Trace\n if(dm_u.shape[0]>12):\n print('Active trace: ',sum(np.diag(dm_u)[act]),sum(np.diag(dm_d)[act])) #Active Trace\n print(np.diag(dm_u)[act],np.diag(dm_d)[act])\n print(labels)\n\n ''' \n #b3lyp_iao \n Full trace: 8.840832814616048 7.841332423958144\n Full trace: 8.840832814609485 7.841332423951078\n Full trace: 8.981529038120833 6.940653762730744\n \n #b3lyp_iao_full\n Full trace: 8.841268343773583 7.84196451387073\n\t Full trace: 8.841268343767048 7.841964513863693\n\t Full trace: 8.981573438252646 6.941070240064234 \n \n #b3lyp_iao_b \n\t Full trace: 12.994552212911534 11.995048752791913\n\t Active trace: 7.997022606928624 6.997526898722619\n\t Full trace: 12.9945522129124 11.995048752792275\n\t Active trace: 7.99702260692954 6.997526898723032\n\t Full trace: 13.966681984807854 10.992999814606678\n\t Active trace: 8.967423623715172 5.995491490895137\n \n #b3lyp_iao_b_full\n\t Full trace: 12.996185405502084 11.996681924440646\n\t Active trace: 8.018456851447063 7.019016832528233\n\t Full trace: 12.996185405503008 11.996681924441067\n\t Active trace: 8.018456851447853 7.019016832528523\n\t Full trace: 13.96730922290277 10.99363331140566\n\t Active trace: 8.968252085875948 6.020952811406707\n '''\n\n #Check e matrix\n s=m.get_ovlp()\n H1=np.diag(m.mo_energy)\n e1=reduce(np.dot,(a.T,s,m.mo_coeff,H1,m.mo_coeff.T,s.T,a))*27.2114\n e1=(e1+e1.T)/2.\n labels=[\"3s\",\"4s\",\"3px\",\"3py\",\"3pz\",\"3dxy\",\"3dyz\",\"3dz2\",\"3dxz\",\"3dx2y2\",\"2s\",\"2px\",\"2py\",\"2pz\"]\n \n fig=plt.figure()\n ax=fig.add_subplot(111)\n cax=ax.matshow(e1,vmin=-1,vmax=1,cmap=plt.cm.bwr)\n ax.set_xticks(np.arange(len(labels)))\n ax.set_yticks(np.arange(len(labels)))\n ax.set_xticklabels(labels,rotation=90)\n ax.set_yticklabels(labels)\n plt.show()\n \n '''\n #Rotated H1 matrix\n plt.title(f.split(\".\")[0]+\" S=\"+str(mol_spin)+\" H1\")\n plt.matshow(e1-np.diag(np.diag(e1)),cmap=plt.cm.bwr,vmax=-1.7,vmin=1.7)\n plt.xticks(np.arange(len(labels)),labels,rotation=90)\n plt.yticks(np.arange(len(labels)),labels)\n plt.colorbar()\n plt.savefig(f.split(\".\")[0]+\"_s\"+str(mol_spin)+\"_h1.pdf\",bbox_inches='tight')\n '''\n \n #Eigenvalue comparison\n '''\n w,__=np.linalg.eigh(e1)\n plt.plot(m.mo_energy[:len(w)]*27.2114,'go',label='MO')\n plt.plot(w,'b*',label='IAO')\n plt.xlabel('Eigenvalue')\n plt.ylabel('Energy (eV)')\n plt.title(f.split(\".\")[0]+\" S=\"+str(mol_spin)+\" DFT eigenvalues\")\n plt.savefig(f.split(\".\")[0]+\"_s\"+str(mol_spin)+\"_evals.pdf\",bbox_inches='tight')\n plt.close()\n '''\n\n '''\n #Plot orbitals\n for i in range(a.shape[1]):\n m.mo_coeff[:,i]=a[:,i] \n print_qwalk_mol(mol,m,basename=\"../orbs/\"+el+basis+\"_r\"+str(r)+\"_c\"+str(charge)+\"_s\"+str(mol_spin)+\"_\"+f.split(\".\")[0]) \n exit(0)\n '''\n","sub_path":"pyscf/attic/analysis/iao_analysis.py","file_name":"iao_analysis.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522756534","text":"from decimal import Decimal\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n#окружность\nx0 = 3\ny0 = 8\nr = 3\nangle = np.linspace(0, 2 * np.pi, 1000)\nx = r * np.cos(angle) + x0\ny = r * np.sin(angle) + y0\nplt.plot(x, y)\n\n#эллипс\nx0 = 1\ny0 = -2\na = 8\nb = 4\nangle = np.linspace(0, 2*np.pi, 1000)\nx1 = a * np.cos(angle) + x0\ny1 = b * np.sin(angle) + y0\nplt.plot(x1, y1)\n\n#гипербола\nx = []\ny = []\ny1 = []\nxx1 = []\nx_ = 0.\na = 0.3\nb = 3\nwhile x_ <= 10:\n x_ = x_ + 0.001\n if (x_**2/a**2 - 1) > 0:\n x.append(x_)\n xx1.append(((- 1) * x_))\n y1.append(math.sqrt((x_**2/a**2 - 1) / b**2))\n y.append(-math.sqrt((x_**2/a**2 - 1) / b**2))\n\n plt.plot(x, y1)\n plt.plot(x, y)\n plt.plot(xx1, y1)\n plt.plot(xx1, y)\n\n\nplt.axis('scaled')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid(True)\n#plt.show()\nplt.savefig('task3_fig1.png')\n","sub_path":"lesson3/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"489904849","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom collections import OrderedDict\nimport os\nimport re\nfrom typing import (\n Dict,\n Mapping,\n MutableMapping,\n MutableSequence,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n cast,\n)\n\nfrom google.api_core import client_options as client_options_lib\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import gapic_v1\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.exceptions import MutualTLSChannelError # type: ignore\nfrom google.auth.transport import mtls # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\nfrom google.cloud.orchestration.airflow.service_v1beta1 import (\n gapic_version as package_version,\n)\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\nfrom google.api_core import operation # type: ignore\nfrom google.api_core import operation_async # type: ignore\nfrom google.longrunning import operations_pb2\nfrom google.protobuf import empty_pb2 # type: ignore\nfrom google.protobuf import field_mask_pb2 # type: ignore\nfrom google.protobuf import timestamp_pb2 # type: ignore\n\nfrom google.cloud.orchestration.airflow.service_v1beta1.services.environments import (\n pagers,\n)\nfrom google.cloud.orchestration.airflow.service_v1beta1.types import (\n environments,\n operations,\n)\n\nfrom .transports.base import DEFAULT_CLIENT_INFO, EnvironmentsTransport\nfrom .transports.grpc import EnvironmentsGrpcTransport\nfrom .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport\nfrom .transports.rest import EnvironmentsRestTransport\n\n\nclass EnvironmentsClientMeta(type):\n \"\"\"Metaclass for the Environments client.\n\n This provides class-level methods for building and retrieving\n support objects (e.g. transport) without polluting the client instance\n objects.\n \"\"\"\n\n _transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]]\n _transport_registry[\"grpc\"] = EnvironmentsGrpcTransport\n _transport_registry[\"grpc_asyncio\"] = EnvironmentsGrpcAsyncIOTransport\n _transport_registry[\"rest\"] = EnvironmentsRestTransport\n\n def get_transport_class(\n cls,\n label: Optional[str] = None,\n ) -> Type[EnvironmentsTransport]:\n \"\"\"Returns an appropriate transport class.\n\n Args:\n label: The name of the desired transport. If none is\n provided, then the first transport in the registry is used.\n\n Returns:\n The transport class to use.\n \"\"\"\n # If a specific transport is requested, return that one.\n if label:\n return cls._transport_registry[label]\n\n # No transport is requested; return the default (that is, the first one\n # in the dictionary).\n return next(iter(cls._transport_registry.values()))\n\n\nclass EnvironmentsClient(metaclass=EnvironmentsClientMeta):\n \"\"\"Managed Apache Airflow Environments.\"\"\"\n\n @staticmethod\n def _get_default_mtls_endpoint(api_endpoint):\n \"\"\"Converts api endpoint to mTLS endpoint.\n\n Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\n \"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.\n Args:\n api_endpoint (Optional[str]): the api endpoint to convert.\n Returns:\n str: converted mTLS api endpoint.\n \"\"\"\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P[^.]+)(?P\\.mtls)?(?P\\.sandbox)?(?P\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"composer.googleapis.com\"\n DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore\n DEFAULT_ENDPOINT\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n EnvironmentsClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_info(info)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n EnvironmentsClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(filename)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @property\n def transport(self) -> EnvironmentsTransport:\n \"\"\"Returns the transport used by the client instance.\n\n Returns:\n EnvironmentsTransport: The transport used by the client\n instance.\n \"\"\"\n return self._transport\n\n @staticmethod\n def environment_path(\n project: str,\n location: str,\n environment: str,\n ) -> str:\n \"\"\"Returns a fully-qualified environment string.\"\"\"\n return (\n \"projects/{project}/locations/{location}/environments/{environment}\".format(\n project=project,\n location=location,\n environment=environment,\n )\n )\n\n @staticmethod\n def parse_environment_path(path: str) -> Dict[str, str]:\n \"\"\"Parses a environment path into its component segments.\"\"\"\n m = re.match(\n r\"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)$\",\n path,\n )\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_billing_account_path(\n billing_account: str,\n ) -> str:\n \"\"\"Returns a fully-qualified billing_account string.\"\"\"\n return \"billingAccounts/{billing_account}\".format(\n billing_account=billing_account,\n )\n\n @staticmethod\n def parse_common_billing_account_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a billing_account path into its component segments.\"\"\"\n m = re.match(r\"^billingAccounts/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_folder_path(\n folder: str,\n ) -> str:\n \"\"\"Returns a fully-qualified folder string.\"\"\"\n return \"folders/{folder}\".format(\n folder=folder,\n )\n\n @staticmethod\n def parse_common_folder_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a folder path into its component segments.\"\"\"\n m = re.match(r\"^folders/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_organization_path(\n organization: str,\n ) -> str:\n \"\"\"Returns a fully-qualified organization string.\"\"\"\n return \"organizations/{organization}\".format(\n organization=organization,\n )\n\n @staticmethod\n def parse_common_organization_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a organization path into its component segments.\"\"\"\n m = re.match(r\"^organizations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_project_path(\n project: str,\n ) -> str:\n \"\"\"Returns a fully-qualified project string.\"\"\"\n return \"projects/{project}\".format(\n project=project,\n )\n\n @staticmethod\n def parse_common_project_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a project path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_location_path(\n project: str,\n location: str,\n ) -> str:\n \"\"\"Returns a fully-qualified location string.\"\"\"\n return \"projects/{project}/locations/{location}\".format(\n project=project,\n location=location,\n )\n\n @staticmethod\n def parse_common_location_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a location path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)/locations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @classmethod\n def get_mtls_endpoint_and_cert_source(\n cls, client_options: Optional[client_options_lib.ClientOptions] = None\n ):\n \"\"\"Return the API endpoint and client cert source for mutual TLS.\n\n The client cert source is determined in the following order:\n (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not \"true\", the\n client cert source is None.\n (2) if `client_options.client_cert_source` is provided, use the provided one; if the\n default client cert source exists, use the default one; otherwise the client cert\n source is None.\n\n The API endpoint is determined in the following order:\n (1) if `client_options.api_endpoint` if provided, use the provided one.\n (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is \"always\", use the\n default mTLS endpoint; if the environment variable is \"never\", use the default API\n endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise\n use the default API endpoint.\n\n More details can be found at https://google.aip.dev/auth/4114.\n\n Args:\n client_options (google.api_core.client_options.ClientOptions): Custom options for the\n client. Only the `api_endpoint` and `client_cert_source` properties may be used\n in this method.\n\n Returns:\n Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the\n client cert source to use.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If any errors happen.\n \"\"\"\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n use_client_cert = os.getenv(\"GOOGLE_API_USE_CLIENT_CERTIFICATE\", \"false\")\n use_mtls_endpoint = os.getenv(\"GOOGLE_API_USE_MTLS_ENDPOINT\", \"auto\")\n if use_client_cert not in (\"true\", \"false\"):\n raise ValueError(\n \"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`\"\n )\n if use_mtls_endpoint not in (\"auto\", \"never\", \"always\"):\n raise MutualTLSChannelError(\n \"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`\"\n )\n\n # Figure out the client cert source to use.\n client_cert_source = None\n if use_client_cert == \"true\":\n if client_options.client_cert_source:\n client_cert_source = client_options.client_cert_source\n elif mtls.has_default_client_cert_source():\n client_cert_source = mtls.default_client_cert_source()\n\n # Figure out which api endpoint to use.\n if client_options.api_endpoint is not None:\n api_endpoint = client_options.api_endpoint\n elif use_mtls_endpoint == \"always\" or (\n use_mtls_endpoint == \"auto\" and client_cert_source\n ):\n api_endpoint = cls.DEFAULT_MTLS_ENDPOINT\n else:\n api_endpoint = cls.DEFAULT_ENDPOINT\n\n return api_endpoint, client_cert_source\n\n def __init__(\n self,\n *,\n credentials: Optional[ga_credentials.Credentials] = None,\n transport: Optional[Union[str, EnvironmentsTransport]] = None,\n client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n ) -> None:\n \"\"\"Instantiates the environments client.\n\n Args:\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n transport (Union[str, EnvironmentsTransport]): The\n transport to use. If set to None, a transport is chosen\n automatically.\n client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the\n client. It won't take effect if a ``transport`` instance is provided.\n (1) The ``api_endpoint`` property can be used to override the\n default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT\n environment variable can also be used to override the endpoint:\n \"always\" (always use the default mTLS endpoint), \"never\" (always\n use the default regular endpoint) and \"auto\" (auto switch to the\n default mTLS endpoint if client certificate is present, this is\n the default value). However, the ``api_endpoint`` property takes\n precedence if provided.\n (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable\n is \"true\", then the ``client_cert_source`` property can be used\n to provide client certificate for mutual TLS transport. If\n not provided, the default SSL client certificate will be used if\n present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is \"false\" or not\n set, no client certificate will be used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport\n creation failed for any reason.\n \"\"\"\n if isinstance(client_options, dict):\n client_options = client_options_lib.from_dict(client_options)\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n client_options = cast(client_options_lib.ClientOptions, client_options)\n\n api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(\n client_options\n )\n\n api_key_value = getattr(client_options, \"api_key\", None)\n if api_key_value and credentials:\n raise ValueError(\n \"client_options.api_key and credentials are mutually exclusive\"\n )\n\n # Save or instantiate the transport.\n # Ordinarily, we provide the transport, but allowing a custom transport\n # instance provides an extensibility point for unusual situations.\n if isinstance(transport, EnvironmentsTransport):\n # transport is a EnvironmentsTransport instance.\n if credentials or client_options.credentials_file or api_key_value:\n raise ValueError(\n \"When providing a transport instance, \"\n \"provide its credentials directly.\"\n )\n if client_options.scopes:\n raise ValueError(\n \"When providing a transport instance, provide its scopes \"\n \"directly.\"\n )\n self._transport = transport\n else:\n import google.auth._default # type: ignore\n\n if api_key_value and hasattr(\n google.auth._default, \"get_api_key_credentials\"\n ):\n credentials = google.auth._default.get_api_key_credentials(\n api_key_value\n )\n\n Transport = type(self).get_transport_class(transport)\n self._transport = Transport(\n credentials=credentials,\n credentials_file=client_options.credentials_file,\n host=api_endpoint,\n scopes=client_options.scopes,\n client_cert_source_for_mtls=client_cert_source_func,\n quota_project_id=client_options.quota_project_id,\n client_info=client_info,\n always_use_jwt_access=True,\n api_audience=client_options.api_audience,\n )\n\n def create_environment(\n self,\n request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None,\n *,\n parent: Optional[str] = None,\n environment: Optional[environments.Environment] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Create a new environment.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_create_environment():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.CreateEnvironmentRequest(\n )\n\n # Make the request\n operation = client.create_environment(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest, dict]):\n The request object. Create a new environment.\n parent (str):\n The parent must be of the form\n \"projects/{projectId}/locations/{locationId}\".\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment):\n The environment to create.\n This corresponds to the ``environment`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`\n An environment for running orchestration tasks.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent, environment])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.CreateEnvironmentRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.CreateEnvironmentRequest):\n request = environments.CreateEnvironmentRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n if environment is not None:\n request.environment = environment\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.create_environment]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.Environment,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def get_environment(\n self,\n request: Optional[Union[environments.GetEnvironmentRequest, dict]] = None,\n *,\n name: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> environments.Environment:\n r\"\"\"Get an existing environment.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_get_environment():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.GetEnvironmentRequest(\n )\n\n # Make the request\n response = client.get_environment(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest, dict]):\n The request object. Get an environment.\n name (str):\n The resource name of the environment\n to get, in the form:\n\n \"projects/{projectId}/locations/{locationId}/environments/{environmentId}\"\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.orchestration.airflow.service_v1beta1.types.Environment:\n An environment for running\n orchestration tasks.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.GetEnvironmentRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.GetEnvironmentRequest):\n request = environments.GetEnvironmentRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.get_environment]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def list_environments(\n self,\n request: Optional[Union[environments.ListEnvironmentsRequest, dict]] = None,\n *,\n parent: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> pagers.ListEnvironmentsPager:\n r\"\"\"List environments.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_list_environments():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.ListEnvironmentsRequest(\n )\n\n # Make the request\n page_result = client.list_environments(request=request)\n\n # Handle the response\n for response in page_result:\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest, dict]):\n The request object. List environments in a project and\n location.\n parent (str):\n List environments in the given\n project and location, in the form:\n\n \"projects/{projectId}/locations/{locationId}\"\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager:\n The environments in a project and\n location.\n Iterating over this object will yield\n results and resolve additional pages\n automatically.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.ListEnvironmentsRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.ListEnvironmentsRequest):\n request = environments.ListEnvironmentsRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.list_environments]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # This method is paged; wrap the response in a pager, which provides\n # an `__iter__` convenience method.\n response = pagers.ListEnvironmentsPager(\n method=rpc,\n request=request,\n response=response,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def update_environment(\n self,\n request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None,\n *,\n name: Optional[str] = None,\n environment: Optional[environments.Environment] = None,\n update_mask: Optional[field_mask_pb2.FieldMask] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Update an environment.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_update_environment():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.UpdateEnvironmentRequest(\n )\n\n # Make the request\n operation = client.update_environment(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest, dict]):\n The request object. Update an environment.\n name (str):\n The relative resource name of the\n environment to update, in the form:\n\n \"projects/{projectId}/locations/{locationId}/environments/{environmentId}\"\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment):\n A patch environment. Fields specified by the\n ``updateMask`` will be copied from the patch environment\n into the environment under update.\n\n This corresponds to the ``environment`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n Required. A comma-separated list of paths, relative to\n ``Environment``, of fields to update. For example, to\n set the version of scikit-learn to install in the\n environment to 0.19.0 and to remove an existing\n installation of argparse, the ``updateMask`` parameter\n would include the following two ``paths`` values:\n \"config.softwareConfig.pypiPackages.scikit-learn\" and\n \"config.softwareConfig.pypiPackages.argparse\". The\n included patch environment would specify the\n scikit-learn version as follows:\n\n ::\n\n {\n \"config\":{\n \"softwareConfig\":{\n \"pypiPackages\":{\n \"scikit-learn\":\"==0.19.0\"\n }\n }\n }\n }\n\n Note that in the above example, any existing PyPI\n packages other than scikit-learn and argparse will be\n unaffected.\n\n Only one update type may be included in a single\n request's ``updateMask``. For example, one cannot update\n both the PyPI packages and labels in the same request.\n However, it is possible to update multiple members of a\n map field simultaneously in the same request. For\n example, to set the labels \"label1\" and \"label2\" while\n clearing \"label3\" (assuming it already exists), one can\n provide the paths \"labels.label1\", \"labels.label2\", and\n \"labels.label3\" and populate the patch environment as\n follows:\n\n ::\n\n {\n \"labels\":{\n \"label1\":\"new-label1-value\"\n \"label2\":\"new-label2-value\"\n }\n }\n\n Note that in the above example, any existing labels that\n are not included in the ``updateMask`` will be\n unaffected.\n\n It is also possible to replace an entire map field by\n providing the map field's path in the ``updateMask``.\n The new value of the field will be that which is\n provided in the patch environment. For example, to\n delete all pre-existing user-specified PyPI packages and\n install botocore at version 1.7.14, the ``updateMask``\n would contain the path\n \"config.softwareConfig.pypiPackages\", and the patch\n environment would be the following:\n\n ::\n\n {\n \"config\":{\n \"softwareConfig\":{\n \"pypiPackages\":{\n \"botocore\":\"==1.7.14\"\n }\n }\n }\n }\n\n **Note:** Only the following fields can be updated:\n\n - ``config.softwareConfig.pypiPackages``\n\n - Replace all custom custom PyPI packages. If a\n replacement package map is not included in\n ``environment``, all custom PyPI packages are\n cleared. It is an error to provide both this mask\n and a mask specifying an individual package.\n\n - ``config.softwareConfig.pypiPackages.``\\ packagename\n\n - Update the custom PyPI package *packagename*,\n preserving other packages. To delete the package,\n include it in ``updateMask``, and omit the mapping\n for it in\n ``environment.config.softwareConfig.pypiPackages``.\n It is an error to provide both a mask of this form\n and the ``config.softwareConfig.pypiPackages``\n mask.\n\n - ``labels``\n\n - Replace all environment labels. If a replacement\n labels map is not included in ``environment``, all\n labels are cleared. It is an error to provide both\n this mask and a mask specifying one or more\n individual labels.\n\n - ``labels.``\\ labelName\n\n - Set the label named *labelName*, while preserving\n other labels. To delete the label, include it in\n ``updateMask`` and omit its mapping in\n ``environment.labels``. It is an error to provide\n both a mask of this form and the ``labels`` mask.\n\n - ``config.nodeCount``\n\n - Horizontally scale the number of nodes in the\n environment. An integer greater than or equal to 3\n must be provided in the ``config.nodeCount``\n field. Supported for Cloud Composer environments\n in versions composer-1.\\ *.*-airflow-*.*.*.\n\n - ``config.webServerNetworkAccessControl``\n\n - Replace the environment's current\n WebServerNetworkAccessControl.\n\n - ``config.softwareConfig.airflowConfigOverrides``\n\n - Replace all Apache Airflow config overrides. If a\n replacement config overrides map is not included\n in ``environment``, all config overrides are\n cleared. It is an error to provide both this mask\n and a mask specifying one or more individual\n config overrides.\n\n - ``config.softwareConfig.airflowConfigOverrides.``\\ section-name\n\n - Override the Apache Airflow config property *name*\n in the section named *section*, preserving other\n properties. To delete the property override,\n include it in ``updateMask`` and omit its mapping\n in\n ``environment.config.softwareConfig.airflowConfigOverrides``.\n It is an error to provide both a mask of this form\n and the\n ``config.softwareConfig.airflowConfigOverrides``\n mask.\n\n - ``config.softwareConfig.envVariables``\n\n - Replace all environment variables. If a\n replacement environment variable map is not\n included in ``environment``, all custom\n environment variables are cleared.\n\n - ``config.softwareConfig.imageVersion``\n\n - Upgrade the version of the environment in-place.\n Refer to ``SoftwareConfig.image_version`` for\n information on how to format the new image\n version. Additionally, the new image version\n cannot effect a version downgrade, and must match\n the current image version's Composer and Airflow\n major versions. Consult the `Cloud Composer\n version\n list `__\n for valid values.\n\n - ``config.softwareConfig.schedulerCount``\n\n - Horizontally scale the number of schedulers in\n Airflow. A positive integer not greater than the\n number of nodes must be provided in the\n ``config.softwareConfig.schedulerCount`` field.\n Supported for Cloud Composer environments in\n versions composer-1.\\ *.*-airflow-2.*.*.\n\n - ``config.softwareConfig.cloudDataLineageIntegration``\n\n - Configuration for Cloud Data Lineage integration.\n\n - ``config.databaseConfig.machineType``\n\n - Cloud SQL machine type used by Airflow database.\n It has to be one of: db-n1-standard-2,\n db-n1-standard-4, db-n1-standard-8 or\n db-n1-standard-16. Supported for Cloud Composer\n environments in versions\n composer-1.\\ *.*-airflow-*.*.*.\n\n - ``config.webServerConfig.machineType``\n\n - Machine type on which Airflow web server is\n running. It has to be one of:\n composer-n1-webserver-2, composer-n1-webserver-4\n or composer-n1-webserver-8. Supported for Cloud\n Composer environments in versions\n composer-1.\\ *.*-airflow-*.*.*.\n\n - ``config.maintenanceWindow``\n\n - Maintenance window during which Cloud Composer\n components may be under maintenance.\n\n - ``config.workloadsConfig``\n\n - The workloads configuration settings for the GKE\n cluster associated with the Cloud Composer\n environment. Supported for Cloud Composer\n environments in versions\n composer-2.\\ *.*-airflow-*.*.\\* and newer.\n\n - ``config.environmentSize``\n\n - The size of the Cloud Composer environment.\n Supported for Cloud Composer environments in\n versions composer-2.\\ *.*-airflow-*.*.\\* and\n newer.\n\n This corresponds to the ``update_mask`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`\n An environment for running orchestration tasks.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name, environment, update_mask])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.UpdateEnvironmentRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.UpdateEnvironmentRequest):\n request = environments.UpdateEnvironmentRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n if environment is not None:\n request.environment = environment\n if update_mask is not None:\n request.update_mask = update_mask\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.update_environment]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.Environment,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def delete_environment(\n self,\n request: Optional[Union[environments.DeleteEnvironmentRequest, dict]] = None,\n *,\n name: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Delete an environment.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_delete_environment():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.DeleteEnvironmentRequest(\n )\n\n # Make the request\n operation = client.delete_environment(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest, dict]):\n The request object. Delete an environment.\n name (str):\n The environment to delete, in the\n form:\n\n \"projects/{projectId}/locations/{locationId}/environments/{environmentId}\"\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated\n empty messages in your APIs. A typical example is to\n use it as the request or the response type of an API\n method. For instance:\n\n service Foo {\n rpc Bar(google.protobuf.Empty) returns\n (google.protobuf.Empty);\n\n }\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.DeleteEnvironmentRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.DeleteEnvironmentRequest):\n request = environments.DeleteEnvironmentRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.delete_environment]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n empty_pb2.Empty,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def restart_web_server(\n self,\n request: Optional[Union[environments.RestartWebServerRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Restart Airflow web server.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_restart_web_server():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.RestartWebServerRequest(\n )\n\n # Make the request\n operation = client.restart_web_server(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest, dict]):\n The request object. Restart Airflow web server.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`\n An environment for running orchestration tasks.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.RestartWebServerRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.RestartWebServerRequest):\n request = environments.RestartWebServerRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.restart_web_server]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.Environment,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def check_upgrade(\n self,\n request: Optional[Union[environments.CheckUpgradeRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Check if an upgrade operation on the environment will\n succeed.\n In case of problems detailed info can be found in the\n returned Operation.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_check_upgrade():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.CheckUpgradeRequest(\n )\n\n # Make the request\n operation = client.check_upgrade(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest, dict]):\n The request object. Request to check whether image\n upgrade will succeed.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be :class:`google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check\n operation.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.CheckUpgradeRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.CheckUpgradeRequest):\n request = environments.CheckUpgradeRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.check_upgrade]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.CheckUpgradeResponse,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def execute_airflow_command(\n self,\n request: Optional[\n Union[environments.ExecuteAirflowCommandRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> environments.ExecuteAirflowCommandResponse:\n r\"\"\"Executes Airflow CLI command.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_execute_airflow_command():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.ExecuteAirflowCommandRequest(\n )\n\n # Make the request\n response = client.execute_airflow_command(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest, dict]):\n The request object. Execute Airflow Command request.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse:\n Response to\n ExecuteAirflowCommandRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.ExecuteAirflowCommandRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.ExecuteAirflowCommandRequest):\n request = environments.ExecuteAirflowCommandRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.execute_airflow_command]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def stop_airflow_command(\n self,\n request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> environments.StopAirflowCommandResponse:\n r\"\"\"Stops Airflow CLI command execution.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_stop_airflow_command():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.StopAirflowCommandRequest(\n )\n\n # Make the request\n response = client.stop_airflow_command(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest, dict]):\n The request object. Stop Airflow Command request.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse:\n Response to\n StopAirflowCommandRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.StopAirflowCommandRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.StopAirflowCommandRequest):\n request = environments.StopAirflowCommandRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.stop_airflow_command]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def poll_airflow_command(\n self,\n request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> environments.PollAirflowCommandResponse:\n r\"\"\"Polls Airflow CLI command execution and fetches logs.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_poll_airflow_command():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.PollAirflowCommandRequest(\n )\n\n # Make the request\n response = client.poll_airflow_command(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest, dict]):\n The request object. Poll Airflow Command request.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse:\n Response to\n PollAirflowCommandRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.PollAirflowCommandRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.PollAirflowCommandRequest):\n request = environments.PollAirflowCommandRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.poll_airflow_command]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def save_snapshot(\n self,\n request: Optional[Union[environments.SaveSnapshotRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Creates a snapshots of a Cloud Composer environment.\n As a result of this operation, snapshot of environment's\n state is stored in a location specified in the\n SaveSnapshotRequest.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_save_snapshot():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.SaveSnapshotRequest(\n )\n\n # Make the request\n operation = client.save_snapshot(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest, dict]):\n The request object. Request to create a snapshot of a\n Cloud Composer environment.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotResponse`\n Response to SaveSnapshotRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.SaveSnapshotRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.SaveSnapshotRequest):\n request = environments.SaveSnapshotRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.save_snapshot]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.SaveSnapshotResponse,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def load_snapshot(\n self,\n request: Optional[Union[environments.LoadSnapshotRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Loads a snapshot of a Cloud Composer environment.\n As a result of this operation, a snapshot of\n environment's specified in LoadSnapshotRequest is loaded\n into the environment.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_load_snapshot():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.LoadSnapshotRequest(\n )\n\n # Make the request\n operation = client.load_snapshot(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest, dict]):\n The request object. Request to load a snapshot into a\n Cloud Composer environment.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotResponse`\n Response to LoadSnapshotRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.LoadSnapshotRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.LoadSnapshotRequest):\n request = environments.LoadSnapshotRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.load_snapshot]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.LoadSnapshotResponse,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def database_failover(\n self,\n request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Triggers database failover (only for highly resilient\n environments).\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_database_failover():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.DatabaseFailoverRequest(\n )\n\n # Make the request\n operation = client.database_failover(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest, dict]):\n The request object. Request to trigger database failover\n (only for highly resilient\n environments).\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverResponse`\n Response for DatabaseFailoverRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.DatabaseFailoverRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.DatabaseFailoverRequest):\n request = environments.DatabaseFailoverRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.database_failover]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n environments.DatabaseFailoverResponse,\n metadata_type=operations.OperationMetadata,\n )\n\n # Done; return the response.\n return response\n\n def fetch_database_properties(\n self,\n request: Optional[\n Union[environments.FetchDatabasePropertiesRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> environments.FetchDatabasePropertiesResponse:\n r\"\"\"Fetches database properties.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud.orchestration.airflow import service_v1beta1\n\n def sample_fetch_database_properties():\n # Create a client\n client = service_v1beta1.EnvironmentsClient()\n\n # Initialize request argument(s)\n request = service_v1beta1.FetchDatabasePropertiesRequest(\n environment=\"environment_value\",\n )\n\n # Make the request\n response = client.fetch_database_properties(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest, dict]):\n The request object. Request to fetch properties of\n environment's database.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse:\n Response for\n FetchDatabasePropertiesRequest.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a environments.FetchDatabasePropertiesRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, environments.FetchDatabasePropertiesRequest):\n request = environments.FetchDatabasePropertiesRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[\n self._transport.fetch_database_properties\n ]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(\n ((\"environment\", request.environment),)\n ),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def __enter__(self) -> \"EnvironmentsClient\":\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"Releases underlying transport's resources.\n\n .. warning::\n ONLY use as a context manager if the transport is NOT shared\n with other clients! Exiting the with block will CLOSE the transport\n and may cause errors in other clients!\n \"\"\"\n self.transport.close()\n\n def list_operations(\n self,\n request: Optional[operations_pb2.ListOperationsRequest] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operations_pb2.ListOperationsResponse:\n r\"\"\"Lists operations that match the specified filter in the request.\n\n Args:\n request (:class:`~.operations_pb2.ListOperationsRequest`):\n The request object. Request message for\n `ListOperations` method.\n retry (google.api_core.retry.Retry): Designation of what errors,\n if any, should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n Returns:\n ~.operations_pb2.ListOperationsResponse:\n Response message for ``ListOperations`` method.\n \"\"\"\n # Create or coerce a protobuf request object.\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n if isinstance(request, dict):\n request = operations_pb2.ListOperationsRequest(**request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method.wrap_method(\n self._transport.list_operations,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def get_operation(\n self,\n request: Optional[operations_pb2.GetOperationRequest] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operations_pb2.Operation:\n r\"\"\"Gets the latest state of a long-running operation.\n\n Args:\n request (:class:`~.operations_pb2.GetOperationRequest`):\n The request object. Request message for\n `GetOperation` method.\n retry (google.api_core.retry.Retry): Designation of what errors,\n if any, should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n Returns:\n ~.operations_pb2.Operation:\n An ``Operation`` object.\n \"\"\"\n # Create or coerce a protobuf request object.\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n if isinstance(request, dict):\n request = operations_pb2.GetOperationRequest(**request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method.wrap_method(\n self._transport.get_operation,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def delete_operation(\n self,\n request: Optional[operations_pb2.DeleteOperationRequest] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> None:\n r\"\"\"Deletes a long-running operation.\n\n This method indicates that the client is no longer interested\n in the operation result. It does not cancel the operation.\n If the server doesn't support this method, it returns\n `google.rpc.Code.UNIMPLEMENTED`.\n\n Args:\n request (:class:`~.operations_pb2.DeleteOperationRequest`):\n The request object. Request message for\n `DeleteOperation` method.\n retry (google.api_core.retry.Retry): Designation of what errors,\n if any, should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n Returns:\n None\n \"\"\"\n # Create or coerce a protobuf request object.\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n if isinstance(request, dict):\n request = operations_pb2.DeleteOperationRequest(**request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method.wrap_method(\n self._transport.delete_operation,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n\nDEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=package_version.__version__\n)\n\n\n__all__ = (\"EnvironmentsClient\",)\n","sub_path":"packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":92880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244055141","text":"from dataclasses import dataclass\nfrom typing import Optional\n\nimport numpy as np\n\nfrom fedot.core.repository.operation_types_repository import OperationTypesRepository\nfrom fedot.core.repository.tasks import TaskTypesEnum\n\n\n@dataclass\nclass SupplementaryData:\n \"\"\"\n A class that stores variables for for internal purposes in core during fit\n and predict. For instance, to manage dataflow properties.\n \"\"\"\n # Is it data in the main branch\n is_main_target: bool = True\n # Amount of nodes, which Data visited\n data_flow_length: int = 0\n # Masked features for data\n features_mask: Optional[dict] = None\n # Last visited nodes\n previous_operations: Optional[list] = None\n\n def calculate_data_flow_len(self, outputs):\n \"\"\" Method for calculating data flow length (amount of visited nodes)\n\n :param outputs: list with OutputData\n \"\"\"\n data_flow_lens = [output.supplementary_data.data_flow_length for output in outputs]\n\n if len(data_flow_lens) == 1:\n data_flow_len = data_flow_lens[0]\n else:\n data_flow_len = max(data_flow_lens)\n\n # Update amount of nodes which this data have visited\n self.data_flow_length = data_flow_len + 1\n\n def prepare_parent_mask(self, outputs):\n \"\"\" The method for outputs from multiple parent nodes prepares a field\n with encoded values. This allow distinguishing from which ancestor the\n data was attached to. For example, a mask for two ancestors, each of\n which gives predictions in the form of a tabular data with two columns\n will look like this:\n {'input_ids': [0, 0, 1, 1],\n 'flow_lens': [1, 1, 0, 0]}\n\n :param outputs: list with OutputData\n :return features_mask: dict with mask for features. A composite ID of\n two lists is used\n - id of parent operation order\n - amount of nodes, which data have visited\n \"\"\"\n\n # For each parent output prepare mask\n input_ids = []\n flow_lens = []\n input_id = 0\n for output in outputs:\n predicted_values = np.array(output.predict)\n # Calculate columns\n table_shape = predicted_values.shape\n\n # Calculate columns\n if len(table_shape) == 1:\n features_amount = 1\n else:\n features_amount = table_shape[1]\n # Order of ancestral operations\n id_mask = [input_id] * features_amount\n input_ids.extend(id_mask)\n\n # Number of nodes visited by the data\n flow_mask = [output.supplementary_data.data_flow_length] * features_amount\n flow_lens.extend(flow_mask)\n\n # Update input id\n input_id += 1\n\n self.features_mask = {'input_ids': input_ids, 'flow_lens': flow_lens}\n\n def get_compound_mask(self):\n \"\"\" The method allows to combine a mask with features in the form of\n an one-dimensional array.\n \"\"\"\n\n input_ids = np.array(self.features_mask.get('input_ids'), dtype=str)\n flow_lens = np.array(self.features_mask.get('flow_lens'), dtype=str)\n comp_list = np.core.defchararray.add(input_ids, flow_lens)\n return comp_list\n\n def get_flow_mask(self) -> list:\n return self.features_mask.get('flow_lens')\n\n def define_parents(self, unique_features_masks: np.array, task: TaskTypesEnum):\n \"\"\" Define which parent should be \"Data parent\" and \"Model parent\"\n for decompose operation\n\n :param unique_features_masks: unique values for mask\n :param task: task to solve\n \"\"\"\n if not isinstance(self.previous_operations, list) or len(self.previous_operations) == 1:\n raise ValueError(f'Data was received from one node but at least two nodes are required')\n\n data_operations, _ = OperationTypesRepository('data_operation').suitable_operation(task_type=task)\n\n # Which data operations was in pipeline before decompose operation\n previous_data_operation = None\n for prev_operation in self.previous_operations:\n if prev_operation in data_operations:\n previous_data_operation = prev_operation\n # Take first data operation as \"Data parent\"\n break\n\n if previous_data_operation is not None:\n # Lagged operation by default is \"Data parent\"\n data_ids = np.ravel(np.argwhere(np.array(self.previous_operations) == previous_data_operation))\n data_parent_id = data_ids[0]\n model_ids = np.ravel(np.argwhere(np.array(self.previous_operations) != previous_data_operation))\n model_parent_id = model_ids[0]\n else:\n model_parent_id = 0\n data_parent_id = 1\n\n data_parent = unique_features_masks[data_parent_id]\n model_parent = unique_features_masks[model_parent_id]\n\n return model_parent, data_parent\n","sub_path":"fedot/core/data/supplementary_data.py","file_name":"supplementary_data.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68153080","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nimport struct\nimport datetime\nimport decimal\nfrom pymysql.constants import FIELD_TYPE\n\nENCODING_TYPE = \"utf-8\"\n\n\ndef convert_float_to_bytes(value: object):\n return bytearray(struct.pack(\"d\", value))\n\n\ndef convert_int_to_bytes(value: object):\n return bytearray(struct.pack(\"i\", value))\n\n\ndef convert_long_long(value: int):\n \"\"\" Range of bigint in Pg is the same with long long in c,\n although python type is int, but need to pack the value in long long format \"\"\"\n return bytearray(struct.pack(\"q\", value))\n\n\ndef convert_str(value: str):\n return bytearray(str(value).encode(ENCODING_TYPE))\n\n\ndef bytes_to_bytearray(value):\n \"\"\"\n If value is type , then we convert to a bytearray\n \"\"\"\n return bytearray(list(value))\n\n\ndef convert_decimal(value: decimal.Decimal):\n \"\"\" We convert the decimal to string representation,\n it will hold all the data before and after the decimal point \"\"\"\n return bytearray(str(decimal.Decimal(value)).encode(ENCODING_TYPE))\n\n\ndef to_bytes(value: object, field_type: int):\n \"\"\"\n Converts the given MySQL object to string and then to bytes\n \"\"\"\n return bytearray(repr(value).encode(ENCODING_TYPE))\n\n\ndef convert_date(value: datetime.date):\n # Separate date and time\n date_val = value.isoformat().replace(\"T\", \" \")\n return bytearray(date_val.encode(ENCODING_TYPE))\n\n\ndef convert_time(value: datetime.time):\n # Separate date and time\n time_val = value.isoformat().replace(\"T\", \" \")\n return bytearray(time_val.encode(ENCODING_TYPE))\n\n\ndef convert_datetime(value: datetime.datetime):\n # Separate date and time\n datetime_val = value.isoformat().replace(\"T\", \" \")\n return bytearray(datetime_val.encode(ENCODING_TYPE))\n\n\nMYSQL_DATATYPE_WRITER_MAP = {\n FIELD_TYPE.BIT: lambda value: to_bytes(value, FIELD_TYPE.BIT),\n FIELD_TYPE.TINY: convert_int_to_bytes,\n FIELD_TYPE.SHORT: convert_int_to_bytes,\n FIELD_TYPE.LONG: convert_int_to_bytes,\n FIELD_TYPE.FLOAT: convert_float_to_bytes,\n FIELD_TYPE.DOUBLE: convert_float_to_bytes,\n FIELD_TYPE.LONGLONG: convert_long_long,\n FIELD_TYPE.INT24: convert_int_to_bytes,\n FIELD_TYPE.YEAR: convert_int_to_bytes,\n FIELD_TYPE.TIMESTAMP: convert_datetime,\n FIELD_TYPE.DATETIME: convert_datetime,\n FIELD_TYPE.TIME: convert_time,\n FIELD_TYPE.DATE: convert_date,\n FIELD_TYPE.NEWDATE: convert_date,\n FIELD_TYPE.SET: lambda value: to_bytes(value, FIELD_TYPE.SET),\n FIELD_TYPE.BLOB: convert_str,\n FIELD_TYPE.TINY_BLOB: convert_str,\n FIELD_TYPE.MEDIUM_BLOB: convert_str,\n FIELD_TYPE.LONG_BLOB: convert_str,\n FIELD_TYPE.STRING: convert_str,\n FIELD_TYPE.VAR_STRING: convert_str,\n FIELD_TYPE.VARCHAR: convert_str,\n FIELD_TYPE.DECIMAL: convert_decimal,\n FIELD_TYPE.NEWDECIMAL: convert_decimal,\n FIELD_TYPE.GEOMETRY: convert_str,\n FIELD_TYPE.ENUM: convert_str\n}\n","sub_path":"ossdbtoolsservice/converters/mysql_converters/any_to_bytes_converters.py","file_name":"any_to_bytes_converters.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"564410718","text":"def KMPSearch(pat, txt):\n M = len(pat)\n N = len(txt)\n lps = [None for x in range(M)]\n j = 0\n computeLPSArray(pat, M, lps)\n i = 0\n while (i < N):\n if (pat[j] == txt[i]):\n i += 1\n j += 1\n if (j == M):\n print(\n f'Encontrado patron ({pat}) en el indice {(i-j)} - {(i-j)+M-1}')\n j = lps[j-1]\n elif (i < N and pat[j] != txt[i]):\n if j != 0:\n j = lps[j-1]\n else:\n i += 1\n\n\ndef computeLPSArray(pat, M, lps):\n tam = 0\n i = 1\n lps[0] = 0\n while(i < M):\n if (pat[i] == pat[tam]):\n tam += 1\n lps[i] = tam\n i += 1\n else:\n if (tam != 0):\n tam = lps[tam-1]\n else:\n lps[i] = tam\n i += 1\n\n\ndef variousSearchs(arr, txt):\n for i in range(len(arr)):\n KMPSearch(arr[i], txt)\n\n\ntxt = 'anita lava la tina'\narr = ['anita', 'la']\nvariousSearchs(arr, txt)\n","sub_path":"Codigos estudiantes por lenguaje/PY/Bryann Valderrama/Strings/KMPSearch.py","file_name":"KMPSearch.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452135742","text":"# Need to run \"pip install discord\" for packages to work\n\nimport discord\nimport datetime\nfrom discord import player\nfrom discord.ext import commands\nfrom datetime import date\nimport time\nimport asyncio\nimport random\nfrom displayCard import displayCard\nfrom getBlackJackTotal import getBlackJackTotal\n\n\ndef main():\n client = commands.Bot(command_prefix='$')\n\n @client.event\n async def on_ready():\n channel = client.get_channel('CHANNEL_ID_TO_POST_MESSAGE_IN')\n\n await channel.send('Bot online!')\n\n @client.command(name='blackjack', pass_context=True)\n @commands.has_role('Admin')\n async def blackjack(ctx):\n await ctx.message.delete()\n num_of_cards_in_hand = 0\n play_game = True\n card_to_draw = random.randint(1, 52)\n player_blackjack_count = 0\n dealer_blackjack_count = 0\n dealer_has_busted = False\n player_will_stay = False\n card_number = ''\n\n list_of_cards = ['Aclub.png', '2club.png', '3club.png', '4club.png', '5club.png', '6club.png', '7club.png', '8club.png',\n '9club.png', 'Tclub.png', 'Jclub.png', 'Qclub.png', 'Kclub.png', 'Adiamonds.png', '2diamonds.png', '3diamonds.png', '4diamonds.png', '5diamonds.png', '6diamonds.png', '7diamonds.png', '8diamonds.png', '9diamonds.png', 'Tdiamonds.png', 'Jdiamonds.png', 'Qdiamonds.png', 'Kdiamonds.png', 'Ahearts.png', '2hearts.png', '3hearts.png', '4hearts.png', '5hearts.png', '6hearts.png', '7hearts.png', '8hearts.png', '9hearts.png', 'Thearts.png', 'Jhearts.png', 'Qhearts.png', 'Khearts.png', 'Aspades.png', '2spades.png', '3spades.png', '4spades.png', '5spades.png', '6spades.png', '7spades.png', '8spades.png', '9spades.png', 'Tspades.png', 'Jspades.png', 'Qspades.png', 'Kspades.png']\n\n card_names = ['Ace of club', '2 of club', '3 of club', '4 of club', '5 of club', '6 of club', '7 of club', '8 of club', '9 of club', '10 of club', 'Jack of club', 'Queen of club', 'King of club', 'Ace of diamonds', '2 of diamonds', '3 of diamonds', '4 of diamonds', '5 of diamonds', '6 of diamonds', '7 of diamonds', '8 of diamonds', '9 of diamonds', '10 of diamonds', 'Jack of diamonds', 'Queen of diamonds', 'King of diamonds',\n 'Ace of hearts', '2 of hearts', '3 of hearts', '4 of hearts', '5 of hearts', '6 of hearts', '7 of hearts', '8 of hearts', '9 of hearts', '10 of hearts', 'Jack of hearts', 'Queen of hearts', 'King of hearts', 'Ace of spades', '2 of spades', '3 of spades', '4 of spades', '5 of spades', '6 of spades', '7 of spades', '8 of spades', '9 of spades', '10 of spades', 'Jack of spades', 'Queen of spades', 'King of spades', ]\n\n cards_in_hand = []\n\n cards_in_deck = len(list_of_cards)\n\n await ctx.send('------------------------------------------------')\n\n await ctx.send('The dealer will play first')\n\n while play_game == True:\n card_to_draw = random.randint(1, cards_in_deck)\n\n # await displayCard(ctx, list_of_cards, card_to_draw)\n cards_in_hand.append(card_names[card_to_draw])\n\n #print(f'Value for card_to_draw: {card_to_draw}')\n card_name = list_of_cards[card_to_draw]\n list_of_cards.remove(card_name)\n #print(f'Length of list_of_cards: {len(list_of_cards)}')\n card_number = list_of_cards[card_to_draw][0]\n\n num_of_cards_in_hand += 1\n cards_in_deck -= 1\n\n if cards_in_deck > 0:\n await ctx.send('The dealer will now play')\n\n if player_blackjack_count <= 21:\n await ctx.send('Here is my card')\n await displayCard(ctx, list_of_cards, card_to_draw)\n dealer_blackjack_count = await getBlackJackTotal(card_number, dealer_blackjack_count)\n await ctx.send(f'Cards left in deck: {cards_in_deck}\\n\\nPlayer Blackjack count: {player_blackjack_count}\\nDealer Blackjack count: {dealer_blackjack_count}\\n')\n\n if player_will_stay == False:\n await ctx.send('What would you like to do?\\nA. Hit\\nB. View cards in hand\\nC. Stand\\nD. Quit')\n else:\n # Need to possibly make all this a function that can be called\n continue\n\n def check(msg):\n return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ['a', 'b', 'c', 'd']\n\n msg = await client.wait_for('message', check=check)\n\n if msg.content.lower() == 'a':\n await ctx.send('Here is your card')\n await displayCard(ctx, list_of_cards, card_to_draw)\n player_blackjack_count = await getBlackJackTotal(card_number, player_blackjack_count)\n await asyncio.sleep(2)\n elif msg.content.lower() == 'b':\n stay_in_menu = True\n await ctx.send('Cards in hand currently:')\n for i in range(num_of_cards_in_hand):\n await ctx.send(f'{cards_in_hand[i]}')\n\n while stay_in_menu == True:\n await ctx.send('What would you like to do?\\nA. Hit\\nB. View cards in hand again\\nC. Stay')\n player_will_stay = True\n\n def check(msg):\n return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ['a', 'b', 'c']\n\n msg = await client.wait_for('message', check=check)\n\n if msg.content.lower() == 'a':\n stay_in_menu == False\n break\n elif msg.content.lower() == 'b':\n await ctx.send('Cards in hand currently:')\n for i in range(num_of_cards_in_hand):\n await ctx.send(f'{cards_in_hand[i]}')\n elif msg.content.lower() == 'c':\n stay_in_menu == False\n break\n elif msg.content.lower() == 'c':\n # Need to possibly make all this a function that can be called\n player_will_stay = True\n await ctx.send('I will continue to hit')\n while player_will_stay == True:\n await ctx.send('Here is my card')\n await displayCard(ctx, list_of_cards, card_to_draw)\n dealer_blackjack_count = await getBlackJackTotal(card_number, dealer_blackjack_count)\n await ctx.send(f'Cards left in deck: {cards_in_deck}\\n\\nPlayer Blackjack count: {player_blackjack_count}\\nDealer Blackjack count: {dealer_blackjack_count}\\n')\n\n if dealer_blackjack_count >= 21:\n player_will_stay == False\n await ctx.send('The dealer hit over 21. That\\'s a bust for me. You win!')\n play_game = False\n\n elif msg.content.lower() == 'd':\n await ctx.send('Have a good day!')\n play_game = False\n break\n elif dealer_blackjack_count > 21:\n await ctx.send('The dealer hit over 21. That\\'s a bust for me. You win!')\n play_game == False\n break\n elif player_blackjack_count > 21:\n await ctx.send('You hit over 21. That\\'s a bust for you. You lose!')\n play_game == False\n break\n else:\n await ctx.send('The deck is empty.')\n await ctx.send('Have a good day!')\n play_game = False\n break\n\n @client.command(name='tempban', pass_context=True)\n @commands.has_role('Admin')\n async def tempban(ctx, member: discord.Member, duration: int, *, reason=None):\n channel = client.get_channel('CHANNEL_ID_TO_POST_MESSAGE_IN')\n # num_of_days = duration * 86400 # converts number you enter from seconds to days\n num_of_minutes = duration * 60\n time_banned = duration\n today = date.today()\n\n embed_msg = discord.Embed(title='User Receiving Temporary Ban:', description=str(\n member.display_name), color=0xF1E94B)\n embed_msg.add_field(name='Reason:',\n value=str(reason), inline=False)\n embed_msg.add_field(name='Number of days banned:',\n value=int(time_banned), inline=False)\n embed_msg.add_field(name='Date:',\n value=str(today), inline=False)\n await channel.send(embed=embed_msg)\n await member.send(f'You have been temporarily banned from the server for {time_banned} day(s). The reason for this ban is because {reason}.')\n await member.ban()\n await ctx.message.delete()\n # await client.delete_message(ctx.message)\n await asyncio.sleep(num_of_minutes)\n await member.unban()\n await channel.send(f'User {member.display_name} has been unbanned.')\n\n @client.command(name='ban', pass_context=True)\n @commands.has_role('Admin')\n async def ban(ctx, member: discord.Member, *, reason=None):\n channel = client.get_channel('CHANNEL_ID_TO_POST_MESSAGE_IN')\n today = date.today()\n\n embed_msg = discord.Embed(title='User Receiving Permanent Ban:', description=str(\n member.display_name), color=0xEE1717)\n embed_msg.add_field(name='Reason:',\n value=str(reason), inline=False)\n embed_msg.add_field(name='Date:',\n value=str(today), inline=False)\n await channel.send(embed=embed_msg)\n await member.send(f'You have been banned from the server. The reason for this ban is because {reason}.')\n await member.ban()\n await ctx.message.delete()\n\n @client.command(name='warn', pass_context=True)\n @commands.has_role('Admin')\n async def warn(ctx, member: discord.Member, *, reason=None):\n channel = client.get_channel('CHANNEL_ID_TO_POST_MESSAGE_IN')\n today = date.today()\n\n embed_msg = discord.Embed(title='User Receiving Warning:', description=str(\n member.display_name), color=0xE6DF2E)\n embed_msg.add_field(name='Reason:',\n value=str(reason), inline=False)\n embed_msg.add_field(name='Date:',\n value=str(today), inline=False)\n await channel.send(embed=embed_msg)\n await member.send(f'You are receiving a warning for {reason}. Please do not do this again. Thank you!')\n await ctx.message.delete()\n\n @client.command(name='detain', pass_context=True)\n @commands.has_role('Admin')\n async def detain(ctx, member: discord.Member, *, reason=None):\n channel = client.get_channel('CHANNEL_ID_TO_POST_MESSAGE_IN')\n today = date.today()\n\n #role = discord.utils.get(member.guild.roles, name='approved')\n # await member.remove_roles(role)\n role = discord.utils.get(member.guild.roles, name='Muted')\n await member.add_roles(role)\n\n embed_msg = discord.Embed(title='User sent to cell:', description=str(\n member.display_name), color=0x41ECDB)\n embed_msg.add_field(name='Reason:',\n value=str(reason), inline=False)\n embed_msg.add_field(name='Date:',\n value=str(today), inline=False)\n await channel.send(embed=embed_msg)\n await member.send(f'You have been detained on the server. Please see the channel so a mod can discuss the reason why you were sent there. Thank you!')\n await ctx.message.delete()\n\n @client.command(name='undetain', pass_context=True)\n @commands.has_role('Admin')\n async def undetain(ctx, member: discord.Member, *, reason=None):\n channel = client.get_channel('CHANNEL_ID_TO_POST_MESSAGE_IN')\n today = date.today()\n\n role = discord.utils.get(member.guild.roles, name='Muted')\n await member.remove_roles(role)\n #role = discord.utils.get(member.guild.roles, name='approved')\n # await member.add_roles(role)\n\n embed_msg = discord.Embed(title='User removed from cell:', description=str(\n member.display_name), color=0xD84DFF)\n embed_msg.add_field(name='Date:',\n value=str(today), inline=False)\n await channel.send(embed=embed_msg)\n await member.send(f'You have been undetained on the us-politixxxs server and should have access to general chat now. Have a nice day!')\n await ctx.message.delete()\n\n @client.command(name='addrole', pass_context=True)\n # @commands.has_role('Admin')\n async def addrole(ctx, role: discord.Role):\n member = ctx.author\n\n if (role.id == 'Administrator' or role.id == 'Moderator'):\n await ctx.send('Unable to add role ' + str(role) + ' to user ' + str(member) + '.')\n else:\n await member.add_roles(role)\n await ctx.send('Role added to user ' + str(member) + ': ' + str(role))\n\n @client.command(name='removerole', pass_context=True)\n # @commands.has_role('Admin')\n async def removerole(ctx, role: discord.Role):\n member = ctx.author\n\n if (role.id == 'Administrator' or role.id == 'Moderator'):\n await ctx.send('Unable to remove role ' + str(role) + ' from user ' + str(member) + '.')\n else:\n await member.remove_roles(role)\n await ctx.send('Role removed from user ' + str(member) + ': ' + str(role))\n\n @client.command(name='approve', pass_context=True)\n # @commands.has_role('Moderators')\n @commands.has_permissions(manage_roles=True)\n async def approve(ctx, *members: discord.Member):\n await ctx.message.delete()\n role_id = 'ROLE_ID_HERE'\n role = discord.utils.get(ctx.guild.roles, id=role_id)\n i = 0\n\n for member in members:\n i += 1\n\n await ctx.send('Adding the approved role to ' + str(i) + ' users. Please wait!')\n await asyncio.sleep(1)\n\n for member in members:\n await member.add_roles(role)\n await ctx.send(str(member) + ' has been approved!')\n await asyncio.sleep(1)\n\n @client.command(name='shutdown', pass_context=True)\n @commands.has_role('Admin')\n async def shutdown(ctx):\n await ctx.send('I am logging off now. Goodbye!')\n await client.close()\n\n # Beginning of the role reaction commands\n reaction_title = \"\"\n reactions = {}\n reaction_message_id = \"\"\n\n @client.command(name=\"createreactpost\")\n async def createreactpost(ctx):\n embed_msg = discord.Embed(title='Add your roles here!', color=0x6d49d0)\n embed_msg.add_field(\n name=\"Set Title\", value=\"$setposttitle \\\"New Title\\\"\", inline=False)\n embed_msg.add_field(\n name=\"Add Role\", value=\"$addrolereact @Role EMOJI_HERE\", inline=False)\n embed_msg.add_field(\n name=\"Remove Role\", value=\"$removerolereact @Role\", inline=False)\n embed_msg.add_field(\n name=\"Send Creation Post\", value=\"$sendreactpost\", inline=False)\n\n await ctx.send(embed=embed_msg)\n await ctx.message.delete()\n\n @client.command(name=\"setposttitle\")\n async def setreactiontitle(ctx, new_title):\n\n global reaction_title\n reaction_title = new_title\n await ctx.send(\"The title for the message is now `\" + reaction_title + \"`!\")\n await ctx.message.delete()\n\n @client.command(name=\"addrolereact\")\n async def addrolereaction(ctx, role: discord.Role, reaction):\n\n if role != None:\n reactions[role.name] = reaction\n await ctx.send(\"Role `\" + str(role.name) + \"` has been added with the emoji \" + str(reaction))\n await ctx.message.delete()\n else:\n await ctx.send(\"Please try again!\")\n\n @client.command(name=\"removerolereact\")\n async def removerolereaction(ctx, role: discord.Role):\n\n if role.name in reactions:\n del reactions[role.name]\n await ctx.send(\"Role `\" + str(role.name) + \"` has been deleted!\")\n await ctx.message.delete()\n else:\n await ctx.send(\"That role was not added!\")\n\n @client.command(name=\"sendreactpost\")\n async def sendreactionpost(ctx):\n global reaction_title\n\n description = \"React to add your roles here!\\n\\n\"\n\n for role in reactions:\n description += \"`\" + str(role) + \"` - \" + \\\n str(reactions[role]) + \"\\n\"\n\n embed_msg = discord.Embed(\n title=reaction_title, description=description, color=0x6d49d0)\n\n message = await ctx.send(embed=embed_msg)\n\n global reaction_message_id\n reaction_message_id = str(message.id)\n\n for role in reactions:\n await message.add_reaction(reactions[role])\n\n await ctx.message.delete()\n\n @client.event\n async def on_reaction_add(reaction, user):\n global reaction_message_id\n\n if not user.bot:\n message = reaction.message\n\n if str(message.id) == reaction_message_id:\n role_to_give = \"\"\n\n for role in reactions:\n if reactions[role] == reaction.emoji:\n role_to_give = role\n\n role_for_reaction = discord.utils.get(\n user.guild.roles, name=role_to_give)\n await user.add_roles(role_for_reaction)\n\n @client.command(name=\"playgame\")\n async def playgame(ctx):\n await ctx.send('What game would you like to play?')\n await asyncio.sleep(1)\n await ctx.send('A. Pick a number\\nB. Heads or tails\\nC. Quit\\nType a letter to select an option!')\n\n def check(msg):\n return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ['a', 'b', 'c']\n\n msg = await client.wait_for('message', check=check)\n\n if msg.content.lower() == 'a':\n user_did_win = False\n correct_number = random.randint(1, 10)\n\n await ctx.send('Enter a number between 1 and 10.\\nIf you guess the right number you win!')\n\n while user_did_win == False:\n def check(msg):\n return msg.author == ctx.author and msg.channel == ctx.channel and int(msg.content) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n msg = await client.wait_for('message', check=check)\n\n if int(msg.content) == correct_number:\n await ctx.send('You guess right! You win.')\n user_did_win = True\n else:\n await ctx.send('You guessed wrong. Try again!')\n await asyncio.sleep(1)\n elif msg.content.lower() == 'b':\n correct_number = random.randint(1, 2)\n await ctx.send('I will flip a coin and you will guess if it landed on heads or tails.')\n await ctx.send('Flipping coin now')\n await asyncio.sleep(3)\n await ctx.send('Alright, guess which side landed face up!')\n await asyncio.sleep(1)\n await ctx.send('A. Heads\\nB. Tails\\nType a letter to select an option!')\n\n #user_did_win = False\n\n # while user_did_win == False:\n def check(msg):\n return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ['a', 'b']\n\n msg = await client.wait_for('message', check=check)\n\n if correct_number == 1:\n if msg.content.lower() == 'a':\n await ctx.send('You guessed right! You win.')\n user_did_win = True\n else:\n await ctx.send('You guessed wrong. You lose!')\n await asyncio.sleep(1)\n elif correct_number == 2:\n if msg.content.lower() == 'b':\n await ctx.send('You guessed right! You win.')\n user_did_win = True\n else:\n await ctx.send('You guessed wrong. You lose!')\n await asyncio.sleep(1)\n elif msg.content.lower() == \"c\":\n await ctx.send('Well I didn\\'t want to play anymore games with you anyways!')\n else:\n await ctx.send('I\\'m sorry, I don\\'t understand what you said.')\n\n # End of the role reaction commands\n\n @client.event\n async def on_message(message):\n channel = message.channel\n if message.content == 'hello octus' or message.content == 'Hello octus' or message.content == 'Hello Octus':\n await message.channel.send(f'Hello {message.author}!')\n\n await client.process_commands(message)\n\n client.run('YOUR_API_KEY_HERE')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Octus Discord Bot Test.py","file_name":"Octus Discord Bot Test.py","file_ext":"py","file_size_in_byte":21221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"161828303","text":"import cv2\nimport numpy as np\nfrom numpy.linalg import inv\nfrom numpy.linalg import norm\nfrom numpy.linalg import det\nfrom scipy.ndimage import map_coordinates as interp2\nfrom scipy.optimize import least_squares as ls\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport os\nimport random\nimport glob\nimport math\nfrom math import floor\nfrom operator import itemgetter\n\nimport ReadCameraModel\nimport UndistortImage\n\n\n\ndef sift_feat(und1, und2):\n '''\n gives out the feature matches\n :param und1: undistorted image 1\n :param und2: undistorted image 2\n :return: matches : obtained matches\n '''\n\n img1 = und1\n img2 = und2\n sift = cv2.xfeatures2d.SIFT_create()\n\n # find the keypoints and descriptors with SIFT\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n\n # Find point matches\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n search_params = dict(checks=50)\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1, des2, k=2)\n\n # Apply Lowe's SIFT matching ratio test\n good = []\n pt=[]\n for m, n in matches:\n if m.distance < 0.2 * n.distance:\n good.append(m)\n pt.append([m,n])\n# if abs(m.distance-n.distance) < 0.01 * m.distance:\n# good.append(m)\n# pt.append([m,n])\n\n #####################\n img_match = np.empty((max(img1.shape[0], img2.shape[0]), img1.shape[1] + img2.shape[1], 3), dtype=np.uint8)\n cv2.drawMatchesKnn(img1, kp1, img2, kp2, pt,outImg=img_match, matchColor=None, singlePointColor=(255, 255, 255), flags=2)\n\n dim = (int(img1.shape[0]/2), int(img1.shape[1]/2))\n img_match=cv2.resize(img_match,dim,interpolation = cv2.INTER_AREA)\n# cv2.imshow(\"flann matching\", img_match)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n #######################\n src_pts = np.asarray([kp1[m[0].queryIdx].pt for m in pt])\n dst_pts = np.asarray([kp2[m[0].trainIdx].pt for m in pt])\n\n # print(src_pts[0])\n\n # Constrain matches to fit homography\n retval, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 100.0)\n mask = mask.ravel()\n\n # We select only inlier points\n list_1 = src_pts[mask == 1]\n list_2 = dst_pts[mask == 1]\n list_1=np.hstack((list_1,np.ones((np.shape(list_1)[0],1))))\n list_2=np.hstack((list_2,np.ones((np.shape(list_1)[0],1))))\n\n all_matches = [list_1, list_2]\n\n return all_matches\n\ndef estimate_fundamental_matrix(x_i, x_i_dash):\n '''\n generate the fundamental matrix from correspondences\n :param x_i, x_i_dash: correspondences from image1 and image2\n :return: f_matrix : estimated fundamental matrix\n '''\n A=[]\n for j in range(len(x_i)):\n r =np.array([x_i[j][0]*x_i_dash[j][0], x_i[j][0]*x_i_dash[j][1], x_i[j][0], x_i[j][1]*x_i_dash[j][0], x_i[j][1]*x_i_dash[j][1], x_i[j][1], x_i_dash[j][0], x_i_dash[j][1],1])\n A.append(r)\n A =np.asarray(A)\n\n ## Obtaining F Estimate\n u, s, vh = np.linalg.svd(A)\n F_est = vh[:,vh.shape[0]-1]\n F_est=np.reshape(F_est,(3,3)).T\n\n ## Correcting the F_estimate\n u_,s_,vh_ = np.linalg.svd(F_est)\n s_[s_.shape[0]-1] = 0\n s_corrected = np.diag(s_)\n\n ## Corrected F\n F_tilde = np.matmul(u_, np.matmul(s_corrected, vh_))\n\n return F_tilde\n\n\ndef estimate_Norm_fundamental_matrix(x_i, x_i_dash):\n '''\n generate the fundamental matrix from correspondences\n :param x_i, x_i_dash: correspondences from image1 and image2\n :return: f_matrix : estimated fundamental matrix\n '''\n\n\n\n points1 = np.asarray(x_i)\n points2 = np.asarray(x_i_dash)\n\n x_i = np.asarray(x_i)\n x_i_dash = np.asarray(x_i_dash)\n\n dist1 = np.sqrt((points1[:,0]- np.mean(points1[:,0]))**2 + (points1[:,1]- np.mean(points1[:,1]))**2)\n dist2 = np.sqrt((points2[:,0]- np.mean(points2[:,0]))**2 + (points2[:,1]- np.mean(points2[:,1]))**2)\n\n m_dist1 = np.mean(dist1)\n m_dist2 = np.mean(dist2)\n\n scale1 = np.sqrt(2)/m_dist1\n scale2 = np.sqrt(2)/m_dist2\n\n x_i[:,0] = (points1[:,0] - np.mean(points1[:,0]))*scale1\n x_i[:,1] = (points1[:,1] - np.mean(points1[:,1]))*scale1\n x_i_dash[:,0] = (points2[:,0] - np.mean(points2[:,0]))*scale2\n x_i_dash[:,1] = (points2[:,1] - np.mean(points2[:,1]))*scale2\n\n A=[]\n for j in range(len(x_i)):\n r =np.array([x_i[j][0]*x_i_dash[j][0], x_i[j][0]*x_i_dash[j][1], x_i[j][0], x_i[j][1]*x_i_dash[j][0], x_i[j][1]*x_i_dash[j][1], x_i[j][1], x_i_dash[j][0], x_i_dash[j][1],1])\n A.append(r)\n A =np.asarray(A)\n\n ## Obtaining F Estimate\n u, s, vh = np.linalg.svd(A)\n F_est = vh[:,vh.shape[0]-1]\n F_est=np.reshape(F_est,(3,3)).T\n\n ## Correcting the F_estimate\n u_,s_,vh_ = np.linalg.svd(F_est)\n s_[s_.shape[0]-1] = 0\n s_corrected = np.diag(s_)\n\n ## Corrected F\n F_tilde = np.matmul(u_, np.matmul(s_corrected, vh_))\n\n return F_tilde\n\ndef RANSAC(all_matches):\n '''\n take all the matches and give out the best matches after rejecting outliers\n :param matches: all the matches obtained from sift feature mapping\n :return: inliers : all the inliers after outlier rejection\n '''\n n=8\n m=10000\n inliers=[]\n Epsilon=0.3\n b = 0\n outliers=[]\n s=[]\n\n for i in range(0,m-1):\n rand_points=random.sample(range(0,len(all_matches[0])),8)\n x_i = list(itemgetter(*rand_points)(all_matches[0]))\n x_i_dash = list(itemgetter(*rand_points)(all_matches[1]))\n F_tilde = estimate_fundamental_matrix(x_i, x_i_dash)\n # F_tilde = estimate_Norm_fundamental_matrix(x_i, x_i_dash)\n\n for j in range(0,n):\n if abs(np.matmul(np.transpose(x_i_dash[j]),np.matmul(F_tilde,x_i[j]))) 0.8:\n# inliers.append(s)\n if b0:\n positive+=1\n # print('number of positives', positive)\n # print('R', R)\n # print('C', C)\n\n if positive > prev:\n correct_poses = [R,C]\n prev = positive\n\n Obtained_homogeneous_matrix = np.eye(4,4)\n Obtained_homogeneous_matrix[0:3, 0:3] = correct_poses[0]\n Obtained_homogeneous_matrix[0:3, 3:4] = np.reshape(correct_poses[1], (3,1))\n\n x_old = Homogeneous_matrix_new[0][3]\n y_old = Homogeneous_matrix_new[1][3]\n z_old = Homogeneous_matrix_new[2][3]\n\n x_new = Obtained_homogeneous_matrix[0][3]\n y_new = Obtained_homogeneous_matrix[1][3]\n z_new = Obtained_homogeneous_matrix[2][3]\n\n Homogeneous_matrix_new = np.matmul(Homogeneous_matrix_new, Obtained_homogeneous_matrix)\n\n # Trajectories.append([[x_old, y_old, z_old],[x_new, y_new, z_new]])\n Trajectories.append([x_old, y_old, z_old,x_new, y_new, z_new])\n\n frame_count+=1\n\n print('frame count after exiting ',frame_count)\n\n np.save('trajectories3.npy', Trajectories)\n\n\n\n\n\n","sub_path":"src/visual_odom.py","file_name":"visual_odom.py","file_ext":"py","file_size_in_byte":15374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598357713","text":"from keras.models import Model, load_model\n\nimport pickle\n\nmodel_h5 = 'dae_ecgsim.h5'\ndata = 'ecgsim.dat'\n\nmodel = load_model(model_h5)\n(sigs, sigs_noisy, param_sig, param_nn, x_train, y_train) = pickle.load(open(data, 'rb'))\n\nfor m in range(4):\n for n in range(4):\n idx = n*4+m\n if idx >= 50:\n break\n ax = plt.subplot2grid((4,4),(m,n))\n ax.plot(predicted[idx])\n ax.plot(sigs[idx+predicted][input_dim:])\n ax.plot(sigs_noisy[idx+predicted][input_dim:])\nplt.show()\n","sub_path":"dae_ecgsim_showcase.py","file_name":"dae_ecgsim_showcase.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"39670056","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 29 17:22:22 2015\n\n@author: Hugo\n\"\"\"\n\n#Thermomètre\nimport sys\nif sys.version_info < (3,0) :\n from Tkinter import *\nelse :\n from tkinter import *\nfrom change_color import *\nclass Thermometre:\n def __init__(self, canvas, temp, temp_max,x1, y1, x2, y2):\n self.canvas = canvas\n self.temp_max = temp_max\n self.temp = temp\n self.x1 = x1\n self.x2 = x2\n self.y1 = y1\n self.y2 = y2\n\n def changer_temperature(self, temp):\n self.temp = temp\n self.canvas.delete(self.bar)\n self.bar = self.canvas.create_rectangle(self.x1,self.y2-(self.temp/self.temp_max)*(self.y2-self.y1),self.x2,self.y2,width = 2, fill = change_color('temp', value = temp, valuemin = 0, valuemax = 50), tags = 'thermometre')\n\n def afficher(self):\n self.fond = self.canvas.create_rectangle(self.x1,self.y1,self.x2,self.y2, fill = 'white', width = 2.0)\n self.bar = self.canvas.create_rectangle(self.x1,self.y2-(self.temp/self.temp_max)*(self.y2-self.y1),self.x2,self.y2, width = 2, fill = change_color('temp', value = self.temp, valuemin = 0, valuemax = 50), tags = 'thermometre')\n def cacher(self):\n self.canvas.delete(self.fond)\n self.canvas.delete(self.bar)\n\n#fen = Tk()\n#can = Canvas(fen, height = 300, width = 300)\n#ther = Thermometre(can, 75, 100,10,10,20,200 )\n#ther.afficher()\n#can.pack()\n#fen.mainloop()\n","sub_path":"Affichage/Thermometre.py","file_name":"Thermometre.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192959840","text":"\"\"\"\n2021-3-27\n\n\"\"\"\n\nimport os\nimport numpy as np\nimport jieba\nfrom math import log\nimport logging\nimport pandas as pd\nimport pickle\nimport re\nimport nltk\nimport string\nimport json\nfrom tqdm import tqdm\nimport warnings\nimport logging\nfrom textdistance import levenshtein\nfrom nltk.corpus import stopwords\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils import data\n\n# from transformers import BertTokenizer\n\n# from test_hyperlinks import cal_subject_semantic\nfrom utils.utils import convert_token2id, glove_token2id\n\n# from data_process import Keras_Bert_Vocabulary\n\nlogging.basicConfig(level=logging.info)\nwarnings.filterwarnings(\"ignore\")\n\n\ndef del_string_punc(s):\n return ''.join([x for x in list(s) if x not in string.punctuation])\n\n\nclass DataSet(data.Dataset):\n def __init__(self, root, surface, windows, doc_num, body_num, val, test, tokenizer, dataset):\n '''\n :param root:\n :param windows:\n :param doc_num:\n :param body_num:\n :param val:\n :param test:\n '''\n self.root = root\n self.windows = 50\n self.surface = 4\n self.doc_num = 100\n self.body_num = 200\n self.EMBEDING_SIZE = 300\n self.train = None\n self.test = test\n if val:\n if dataset == \"ace2004\":\n self.document_dict = pd.read_pickle('./ace2004/ace2004_doc_mentions_entity.pkl')\n self.doc_list = pd.read_pickle('./ace2004/ace2004_doc_list.pkl')\n self.id_text = pd.read_pickle('./ace2004/ace2004_id_text.pkl')\n self.local_sp_path = './sp_albert/ace2004'\n self.local_hyperlinks_path = './hyperlinks/dev/'\n self.m2e = pd.read_pickle('./ace2004/men_id_candidates_10_entity.pkl')\n self.m2e_prior = pd.read_pickle('./ace2004/men2cand_prior.pkl')\n self.id2entity = pd.read_pickle('./ace2004/id2cand.pkl')\n elif dataset == \"aquaint\":\n self.document_dict = pd.read_pickle('./aquaint/aquaint_doc_mentions_entity.pkl')\n self.doc_list = pd.read_pickle('./aquaint/aquaint_doc_list.pkl')\n self.id_text = pd.read_pickle('./aquaint/aquaint_id_text.pkl')\n self.local_sp_path = './sp_albert/aquaint'\n self.local_hyperlinks_path = './hyperlinks/dev/'\n self.m2e = pd.read_pickle('./aquaint/men_id_candidates_10_entity.pkl')\n self.m2e_prior = pd.read_pickle('./aquaint/men2cand_prior.pkl')\n self.id2entity = pd.read_pickle('./aquaint/id2cand.pkl')\n elif dataset == \"msnbc\":\n self.document_dict = pd.read_pickle('./msnbc/msnbc_doc_mentions_entity.pkl')\n self.doc_list = pd.read_pickle('./msnbc/msnbc_doc_list_entity.pkl')\n self.id_text = pd.read_pickle('./msnbc/msnbc_id_text_entity.pkl')\n self.local_sp_path = './sp_albert/msnbc'\n self.local_hyperlinks_path = './hyperlinks/dev/'\n self.m2e = pd.read_pickle('./msnbc/men_id_candidates_10_entity.pkl')\n self.m2e_prior = pd.read_pickle('./msnbc/men2cand_prior.pkl')\n self.id2entity = pd.read_pickle('./msnbc/id2cand.pkl')\n elif dataset == \"clueweb\":\n self.document_dict = pd.read_pickle('./clueweb/clueweb_doc_mentions_entity.pkl')\n self.doc_list = pd.read_pickle('./clueweb/clueweb_doc_list.pkl')\n self.id_text = pd.read_pickle('./clueweb/clueweb_id_text.pkl')\n self.local_sp_path = './sp_albert/clueweb'\n self.local_hyperlinks_path = './hyperlinks/dev/'\n self.m2e = pd.read_pickle('./clueweb/men_id_candidates_10_entity.pkl')\n self.m2e_prior = pd.read_pickle('./clueweb/men2cand_prior.pkl')\n self.id2entity = pd.read_pickle('./clueweb/id2cand.pkl')\n elif dataset == \"wikipedia\":\n self.document_dict = pd.read_pickle('./wikipedia/wikipedia_doc_mentions_entity.pkl')\n self.doc_list = pd.read_pickle('./wikipedia/wikipedia_doc_list.pkl')\n self.id_text = pd.read_pickle('./wikipedia/wikipedia_id_text.pkl')\n self.local_sp_path = './sp_albert/wikipedia'\n self.local_hyperlinks_path = './hyperlinks/dev/'\n self.m2e = pd.read_pickle('./wikipedia/men_id_candidates_10_entity.pkl')\n self.m2e_prior = pd.read_pickle('./wikipedia/men2cand_prior.pkl')\n self.id2entity = pd.read_pickle('./wikipedia/id2cand.pkl')\n else:\n self.document_dict = pd.read_pickle('./aida_train/aida_doc_mentions_entity.pkl')\n self.doc_list = pd.read_pickle('./aida_train/aida_doc_list.pkl')\n self.id_text = pd.read_pickle('./aida_train/aida_id_text.pkl')\n self.local_sp_path = './sp_albert/train'\n self.local_hyperlinks_path = './hyperlinks/train/'\n self.m2e = pd.read_pickle('./aida_train/men_id_candidates_10_entity.pkl')\n self.m2e_prior = pd.read_pickle('./aida_train/men2cand_prior3.pkl')\n self.id2entity = pd.read_pickle('./data/enwiki_id2title2.pkl')\n\n self.get_entity_doc = pd.read_pickle('./data/kb_id_text_update_entire.pkl')\n\n self.tokenizer = tokenizer\n\n self.entity_embedding = pd.read_pickle('./entity_embedding/bert/entity_embedding_dict_new_entire.pkl')\n self.entity_vocab = pd.read_pickle('./entity_embedding/albert/entity_vocab_new_entire.pkl')\n\n self.document_embedding = pd.read_pickle('./document_embedding/bert/document_embedding_dict_new_entire.pkl')\n self.document_vocab = pd.read_pickle('./document_embedding/bert/document_vocab_new_entire.pkl')\n\n self.enwiki_id2title = pd.read_pickle('./data/enwiki_id2title2.pkl')\n\n self.hyperlinks_dict = pd.read_pickle('./data/hyperlinks_dict.pkl')\n self.hyperlinks_from = pd.read_pickle('./data/hyperlinks_dict_from_id4.pkl')\n\n vocab_path = './data/glove_word_vocab.pkl'\n self.word_vocabulary = pd.read_pickle(vocab_path)\n\n def cal_subject_semantic(self, subject_i, subject_j):\n \"\"\"利用超链接计算两个实体之间的语义相似度\"\"\"\n # W = len(self.hyperlinks_dict.keys())\n W = 5811754\n\n if subject_i not in self.hyperlinks_from.keys() or subject_j not in self.hyperlinks_from.keys():\n return 0.0\n link_subject_i = self.hyperlinks_from[subject_i]\n link_subject_j = self.hyperlinks_from[subject_j]\n\n if len(link_subject_i) == 0:\n return 0.0\n if len(link_subject_j) == 0:\n return 0.0\n\n U_1 = set(link_subject_i)\n U_2 = set(link_subject_j)\n\n U_1_count = len(U_1)\n U_2_count = len(U_2)\n\n max_count = max(U_1_count, U_2_count)\n min_count = min(U_1_count, U_2_count)\n\n inter_count = len(U_1.intersection(U_2))\n\n if inter_count == 0:\n return 0.0\n\n scores = 1 - ((log(max_count) - log(inter_count)) / (log(W) - log(min_count)))\n return scores\n\n def getHandsFeature(self, mention, candidates, doc_text, str_sim=True, lowercase=True):\n feature_list = []\n mention = mention.lower().title()\n doc_text = doc_text.lower().title()\n cand_list = candidates\n for cand_id in cand_list:\n cand = self.id2entity[cand_id].replace(\"_\", \" \")\n features = []\n if str_sim:\n if lowercase: cand = cand.lower().title()\n features.append(1 if cand in doc_text else 0)\n feature_list.append(features)\n return feature_list\n\n def __getitem__(self, index):\n \"\"\"create mention、context、document vector\"\"\"\n text_id = self.doc_list[index]\n document = self.document_dict[text_id]\n doc_text = self.id_text[text_id]\n\n mentions, gold_entities_ids, offsets, length, context = zip(*document)\n\n mentions2entities = [self.m2e[text_id + '|||' + x] for i, x in enumerate(mentions)]\n\n mentions2entities_copy = []\n entity_mask = []\n for i in range(len(mentions2entities)):\n entity_id = [self.entity_vocab[x.split('|||')[-1]] + 1 for x in mentions2entities[i]]\n mentions2entities_copy.append(entity_id)\n mask = [1] * len(entity_id)\n entity_mask.append(mask)\n\n max_len = 0\n for e in mentions2entities:\n e_len = len(e)\n if e_len > max_len:\n max_len = e_len\n for i, ent in enumerate(mentions2entities):\n if len(ent) < max_len:\n mentions2entities_copy[i].extend([0] * (max_len - len(ent)))\n entity_mask[i].extend([0] * (max_len - len(ent)))\n assert len(mentions2entities_copy[i]) == max_len\n assert len(entity_mask[i]) == max_len\n\n total_entities = []\n related_entities = []\n e2e01_idx = []\n idx_0 = 0\n idx_1 = idx_0\n for ind, x in enumerate(mentions2entities):\n for value in x:\n # to distinguish same mention in one document\n related_entities.append(value + '|~!@# $ %^&*|' + str(offsets[ind]))\n total_entities.append(value)\n idx_1 += 1\n e2e01_idx.append((idx_0, idx_1))\n idx_0 = idx_1\n\n assert len(total_entities) == len(related_entities)\n\n # men2cand_prior\n m2c_prior = []\n men2cand_prior = self.m2e_prior\n for i, m in enumerate(mentions):\n es = self.m2e[text_id + '|||' + m]\n for v in es:\n prior = float(men2cand_prior[text_id + '|||' + m + '|||' + v])\n m2c_prior.append(prior)\n assert len(m2c_prior) == len(related_entities)\n\n # 构建全局实体之间的语义相关性(利用百度百科知识库的超链接)\n entity_sr = [[0 for i in range(len(related_entities))] for j in range(len(related_entities))]\n\n sparse_features = {}\n\n # hands_feature\n hands_feature = []\n for i, m in enumerate(mentions):\n hand_fea_list = self.getHandsFeature(m, mentions2entities[i], doc_text)\n hands_feature.extend(hand_fea_list)\n assert len(hands_feature) == len(related_entities)\n\n gold_entities = []\n for line in gold_entities_ids:\n # line = [e for e in line if e.strip() != '']\n gold_entities.append(line)\n gold_entities_ind = [[0 for i in range(len(related_entities))] for j in range(len(mentions))]\n for i, entity_l in enumerate(gold_entities):\n ne = str(entity_l) + '|~!@# $ %^&*|' + str(offsets[i])\n if ne not in related_entities:\n print('file error')\n print(document)\n print(ne)\n print(text_id, mentions[i])\n\n gold_entities_ind[i][related_entities.index(ne)] = 1\n\n # extract mention vector\n # logging.info('#######Surface vector...#######')\n mentions_surface = []\n mentions_strings = mentions\n for m in mentions_strings:\n tokens = nltk.tokenize.word_tokenize(m.lower())\n # word_ind = [vocab.convert2id(x) for x in tokens]\n # convert mention surface to ids\n word_ind = glove_token2id(self.word_vocabulary, tokens)\n mentions_surface.append(word_ind)\n\n # extract Context vector...\n # logging.info('#######Context vector...#######')\n mask_context = []\n mentions_con = context\n mentions_context = []\n new_contexts = []\n for ind, text in enumerate(mentions_con):\n men_context = [x.lower() for x in nltk.tokenize.word_tokenize(text.lower()) if x not in string.punctuation]\n # men_context = [c for c in men_context if c not in stopwords.words(\"english\")]\n new_contexts.append(glove_token2id(self.word_vocabulary, men_context))\n men_contex = glove_token2id(self.word_vocabulary, men_context)\n mask_c = [1] * len(men_contex)\n if len(men_contex) < self.windows:\n men_contex.extend([0] * (self.windows - len(men_contex)))\n mask_c.extend([0] * (self.windows - len(mask_c)))\n else:\n men_contex[:] = men_contex[:self.windows]\n mask_c = mask_c[:self.windows]\n mask_context.append(mask_c)\n\n mentions_context.append(men_contex)\n\n # extract Document vector\n # logging.info('#######Document vector...#######')\n bert_document_vec = self.document_embedding[text_id]\n doc_cont = self.id_text[text_id]\n doc_words = [x.lower() for x in nltk.tokenize.word_tokenize(doc_cont.lower()) if x not in string.punctuation]\n # doc_words = [c for c in doc_words if c not in stopwords.words(\"english\")]\n # convert to str as parameters\n document_vec = glove_token2id(self.word_vocabulary, doc_words)\n mask_document = [1] * len(document_vec)\n if len(document_vec) < self.doc_num:\n document_vec.extend([0] * (self.doc_num - len(document_vec)))\n mask_document.extend([0] * (self.doc_num - len(mask_document)))\n else:\n document_vec = document_vec[:self.doc_num]\n mask_document = mask_document[:self.doc_num]\n\n mask_men_surface = []\n new_mentions = mentions\n new_mentions_surface = []\n for i, m in enumerate(mentions_surface):\n new_mentions_surface.append([])\n for id in m:\n new_mentions_surface[i].append(int(id))\n mask_m = [1] * len(new_mentions_surface[i])\n if len(new_mentions_surface[i]) < self.surface:\n new_mentions_surface[i].extend([0] * ((self.surface - len(new_mentions_surface[i]))))\n mask_m.extend([0] * (self.surface - len(mask_m)))\n else:\n new_mentions_surface[i] = new_mentions_surface[i][:self.surface]\n mask_m = mask_m[:self.surface]\n mask_men_surface.append(mask_m)\n\n new_mentions_context = mentions_context\n new_document_vec = [document_vec]\n new_bert_doc_vec = torch.tensor(bert_document_vec).unsqueeze(0)\n\n new_mask_men = mask_men_surface\n new_mask_context = mask_context\n\n new_document_vec = Variable(torch.LongTensor(new_document_vec))\n new_mentions_surface = Variable(torch.LongTensor(new_mentions_surface))\n new_mentions_context = Variable(torch.LongTensor(new_mentions_context))\n\n # extract Entity title and document\n # logging.info('#######Entity Title and Document #######')\n # Entity vector\n new_related_entites = related_entities\n\n entities_Tvec = []\n entities_Bvec = []\n\n # mask_entities_Tvec = []\n mask_entities_Bvec = []\n albert_Bvec = []\n\n for e in new_related_entites:\n entity_name = e.split('|~!@# $ %^&*|')[0]\n title = self.enwiki_id2title[entity_name].replace(\"'\", \"\").lower().title()\n # title = title.replace(' ', '_')\n # title = entity_name\n body = self.get_entity_doc[entity_name]\n title_tokens = nltk.tokenize.word_tokenize(title.lower())\n title_vec = glove_token2id(self.word_vocabulary, title_tokens)\n mask_T = [1] * len(title_vec)\n\n # body_tokens = nltk.tokenize.word_tokenize(body.lower())\n body_tokens = [x.lower() for x in nltk.tokenize.word_tokenize(body.lower()) if x not in string.punctuation]\n body_vec = glove_token2id(self.word_vocabulary, body_tokens)\n mask_B = [1] * len(body_vec)\n\n if len(title_vec) < self.surface:\n title_vec.extend([0 for i in range((self.surface - len(title_vec)))])\n mask_T.extend([0 for i in range((self.surface - len(mask_T)))])\n else:\n title_vec = title_vec[:self.surface]\n mask_T = mask_T[:self.surface]\n if len(body_vec) < self.body_num:\n body_vec.extend([0 for i in range((self.body_num - len(body_vec)))])\n mask_B.extend([0 for i in range((self.body_num - len(mask_B)))])\n else:\n body_vec = body_vec[:self.body_num]\n mask_B = mask_B[:self.body_num]\n\n # entities_Tvec.append(title_vec)\n entities_Tvec.append(self.entity_embedding[str(entity_name)].tolist())\n entities_Bvec.append(body_vec)\n # mask_entities_Tvec.append(mask_T)\n mask_entities_Bvec.append(mask_B)\n\n new_entities_Tvec = Variable(torch.FloatTensor(entities_Tvec))\n new_entities_Bvec = Variable(torch.LongTensor(entities_Bvec))\n\n new_mentions2entities = [[0 for i in range(len(new_related_entites))] for j in range(len(new_mentions))]\n for i, m in enumerate(mentions2entities):\n for x in m:\n new_mentions2entities[i][new_related_entites.index(x + '|~!@# $ %^&*|' + str(offsets[i]))] = 1\n\n new_entities2entities = [[1 for i in range(len(new_related_entites))] for j in range(len(new_related_entites))]\n for ind, m in enumerate(mentions):\n ind_a, ind_b = e2e01_idx[ind]\n len_ab = ind_b - ind_a\n for xxx_ind in range(ind_a, ind_b):\n for jjj_ind in range(ind_a, ind_b):\n new_entities2entities[xxx_ind][jjj_ind] = 0\n\n for i, e in enumerate(new_entities2entities):\n new_entities2entities[i][i] = 0\n\n gold_entities_ind = torch.FloatTensor(gold_entities_ind)\n\n new_mentions2entities = torch.Tensor(new_mentions2entities)\n new_entities2entities = torch.Tensor(new_entities2entities)\n\n new_total_entities = total_entities\n\n new_m2c_prior = torch.FloatTensor(m2c_prior)\n\n new_entity_sr = torch.FloatTensor(entity_sr)\n return new_mentions, gold_entities_ind, text_id, new_mentions_surface, new_mentions_context, new_document_vec, new_entities_Tvec, new_entities_Bvec, new_mentions2entities, new_entities2entities, sparse_features, new_total_entities, new_m2c_prior, new_entity_sr, mentions2entities, new_contexts, hands_feature, new_bert_doc_vec\n\n def __len__(self):\n return len(self.document_dict.keys())\n\n\ndef collate_fn(data):\n return data\n\n\ndef get_loader(root, surface, windows, doc_num, body_num, val, test, shuffle, num_workers, tokenizer, dataset):\n data = DataSet(root, surface, windows, doc_num, body_num, val, test, tokenizer, dataset)\n\n # Data loader for gold_el dataset\n # test表示是否是测试, 和shuffle互异\n\n data_loader = torch.utils.data.DataLoader(dataset=data, # 批大小\n batch_size=1,\n # 若dataset中的样本数不能被batch_size整除的话,最后剩余多少就使用多少\n shuffle=shuffle, # 是否随机打乱顺序\n num_workers=num_workers, # 多线程读取数据的线程数\n collate_fn=collate_fn\n )\n\n return data_loader\n","sub_path":"Entity_Linking/hsm/data_loader/data_glove_loader_f.py","file_name":"data_glove_loader_f.py","file_ext":"py","file_size_in_byte":19356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"273892616","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\n# @CreationDate: 2020-12-26 16:48:10\n# @Author: xiaochuan\n# @Description: 字母异位词分组\n\n# 思路:字符串元素排序,将其转变为不可变的元组之后,作为字典的键,原本值作为键对应的值存入字典中\nclass Solution:\n def groupAnagrams(self, strs):\n dict = {}\n for item in strs:\n key = tuple(sorted(item))\n dict[key] = dict.get(key, []) + [item]\n return [i for i in dict.values()]\n \nif __name__ == \"__main__\":\n print(Solution().groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))","sub_path":"Week_02/2.5.2 哈希映射集合 字母异位词分组.py","file_name":"2.5.2 哈希映射集合 字母异位词分组.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296288865","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 Akretion France (http://www.akretion.com/)\n# @author: Alexis de Lattre \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import models, _\nfrom odoo.exceptions import UserError\n\n\nclass AccountMoveBacktodraft(models.TransientModel):\n _name = 'account.move.backtodraft'\n _description = 'Account Move Unpost'\n\n def backtodraft(self):\n assert self._context.get('active_model') == 'account.move'\n amo = self.env['account.move']\n moves = amo.browse(self._context.get('active_ids'))\n moves_backtodraft = moves.filtered(lambda x: x.state == 'posted')\n if not moves_backtodraft:\n raise UserError(_(\n 'There is no journal items in posted state to unpost.'))\n moves_backtodraft.button_cancel()\n return True\n","sub_path":"account_usability/wizard/account_move_backtodraft.py","file_name":"account_move_backtodraft.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398019966","text":"import sys\r\nsys.setrecursionlimit(10 ** 9) #再帰回数の限界を変更\r\n\r\ndef dfs(A):\r\n global ans\r\n # 数列の長さが N に達したら計算\r\n\r\n if len(A) == N:\r\n score = 0\r\n for i in range(Q):\r\n if A[L[i][1]-1]-A[L[i][0]-1]==L[i][2]:\r\n score += L[i][3]\r\n ans = max(ans,score)\r\n return\r\n for v in range(A[-1],M+1):\r\n dfs(A+[v])\r\n\r\nN,M,Q = map(int, input().split())\r\nL = []\r\nfor i in range(Q):\r\n L.append(list(map(int, input().split())))\r\nans = 0\r\ndfs([1])\r\nprint(ans)\r\n","sub_path":"atcoder/mizuiro_h20/bitzentansaku/ABC165C_Many_Requirements/reused/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129845968","text":"import argparse\n\nfrom pythainlp import corpus, cli\n\n\nclass App:\n def __init__(self, argv):\n parser = argparse.ArgumentParser(**cli.make_usage(\"corpus\"))\n\n parser.add_argument(\n \"--name\",\n type=str,\n help=\"corpus's name\",\n )\n\n parser.add_argument(\n \"command\",\n type=str,\n default=\"\",\n nargs=\"?\",\n help=\"[download|remove]\"\n )\n\n args = parser.parse_args(argv[2:])\n\n cli.exit_if_empty(args.command, parser)\n command = args.command\n\n if hasattr(App, command):\n getattr(App, command)(args)\n else:\n print(\"No command available: %s\" % command)\n\n @staticmethod\n def download(args):\n corpus.download(args.name)\n\n @staticmethod\n def remove(args):\n corpus.remove(args.name)\n","sub_path":"pythainlp/cli/corpus.py","file_name":"corpus.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335586630","text":"\"\"\"\r\nLuu Vinh Trung\r\nAugust 16th 2020\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.metrics import accuracy_score, roc_auc_score\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom xgboost import XGBClassifier\r\nfrom sklearn.metrics import r2_score\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import GridSearchCV\r\nimport seaborn as sns\r\nfrom datetime import datetime\r\nfrom dateutil.relativedelta import relativedelta\r\nimport re\r\n\r\ndef get_full_data():\r\n \"\"\"\r\n Returns a processed dataset as dataframe from dataset.csv file input. The output including derived features of month purchase count and amount.\r\n \"\"\"\r\n try:\r\n df = pd.read_csv(\"dataset.csv\")\r\n count_lst = np.array([])#to store the number of viewed products of each transaction\r\n purchase_amount_lst = np.array([])\r\n for index,row in df.iterrows():\r\n purchase_list = row['transaction_info']\r\n purchase_count = purchase_list.count('}, {')+1 #purchase count of the record\r\n purchase_amount = get_total_amount(purchase_list) #purchase amount of the record\r\n count_lst = np.append(count_lst,purchase_count)#derived column data\r\n purchase_amount_lst = np.append(purchase_amount_lst,purchase_amount)#derived column data\r\n #create new columns for the dataset to train model\r\n df['purchase_count'] = count_lst.tolist()\r\n df['purchase_amount'] = purchase_amount_lst.tolist()\r\n df['month_year'] = pd.to_datetime(df['date']).dt.to_period('M')#as there are only Feb, Mar, Apr, May, June of 2018, it is better to convert them into month only\r\n df = df.drop(['transaction_info','date'],axis=1)\r\n #df = pd.pivot_table(df, index=[\"csn\"],columns=[\"month_year\"],values=[\"purchase_amount\",\"purchase_count\"],aggfunc= np.sum)#.reset_index(level=[0])\r\n df_purchase_amount = pd.pivot_table(df, index=[\"csn\"],columns=[\"month_year\"],values=[\"purchase_amount\"],aggfunc= np.sum)#pivot to group purchase amount by csn\r\n df_purchase_amount.columns = df_purchase_amount.columns.get_level_values(1)\r\n df_purchase_amount = df_purchase_amount.add_prefix('purchase_amount_')\r\n df_purchase_count = pd.pivot_table(df, index=[\"csn\"],columns=[\"month_year\"],values=[\"purchase_count\"],aggfunc= np.sum)#pivot to group purchase count by csn\r\n df_purchase_count.columns = df_purchase_count.columns.get_level_values(1)\r\n df_purchase_count = df_purchase_count.add_prefix('purchase_count_')\r\n except Exception as exception:\r\n print(exception)\r\n return None\r\n return df_purchase_amount, df_purchase_count#two independent dataset to facilitate the analysis\r\n\r\ndef get_total_amount(purchase_list):\r\n \"\"\"\r\n Returns total amount of money spent on a list of purchase in a record.\r\n \"\"\"\r\n try:\r\n purchase_listed = purchase_list.split('}, {')\r\n total_amount = 0\r\n for purchase in purchase_listed:\r\n purchase_detail = purchase.split(',')\r\n str = (purchase_detail[1].split(':'))[1]\r\n quantity = float(str)\r\n str = purchase_detail[2].split(':')[1]\r\n str = str.strip(\"]}\")\r\n price = float(str)\r\n total_amount+=quantity*price\r\n except Exception as exception:\r\n print(exception)\r\n return None\r\n return total_amount\r\n\r\ndef get_month_data_to_predict(df, month):\r\n \"\"\"\r\n Returns a processed dataset as dataframe including data of the month to predict, and the two previous month data\r\n \"\"\"\r\n try:\r\n df.drop(df.columns[month-1:month+1], axis=1, inplace=True)#data of the month to predict must be available for every row\r\n df.dropna(subset=[df.columns[0], df.columns[1]], inplace=True, how='all')#at least one of two previous month data must be available\r\n df = df.fillna(0)#as it is requested to predict who will make at least 1 purchase, the labels can be classified to be\r\n df.loc[df[df.columns[2]] > 0, df.columns[2]] = 1#0: no purchase and 1: purchase\r\n except Exception as exception:\r\n print(exception)\r\n return None\r\n return df\r\n\r\ndef remove_correlative_feature(data, corr, threshold):\r\n \"\"\"\r\n Returns a processed dataset as dataframe not including the removed feature due to the feature correlation.\r\n The removal decision is based on a correlation threshold through scanning the correlation matrix corr.\r\n \"\"\"\r\n try:\r\n columns = np.full((corr.shape[0],), True, dtype=bool)\r\n for i in range(corr.shape[0]):\r\n for j in range(i + 1, corr.shape[0]):\r\n if corr.iloc[i, j] >= threshold:\r\n if columns[j]:\r\n columns[j] = False\r\n selected_columns = data.columns[columns]\r\n data = data[selected_columns]\r\n except Exception as exception:\r\n print(exception)\r\n return None\r\n return data\r\n\r\ndef get_specific_month_data_to_predict(month):\r\n \"\"\"\r\n Returns a processed dataset as a combined dataframe from get_month_data_to_predict()\r\n for both purchase amount and count.\r\n \"\"\"\r\n try:\r\n df_purchase_amount, df_purchase_count = get_full_data()\r\n df_purchase_amount = get_month_data_to_predict(df_purchase_amount,month)\r\n df_purchase_count = get_month_data_to_predict(df_purchase_count,month)\r\n purchase_data = pd.concat([df_purchase_count, df_purchase_amount], axis=1, join='inner')#full and original dataset\r\n except Exception as exception:\r\n print(exception)\r\n return None\r\n return purchase_data\r\n\r\ndef get_training_and_test_sets(purchase_data):\r\n \"\"\"\r\n Returns X_train, y_train, X_test, y_test to train and valid data.\r\n \"\"\"\r\n try:\r\n y = purchase_data.iloc[:, 5]\r\n purchase_data.drop(purchase_data.columns[[2, 5]], axis=1, inplace=True)\r\n X = purchase_data\r\n except Exception as exception:\r\n print(exception)\r\n return None\r\n return train_test_split(X, y, test_size=0.25, random_state=0)\r\n\r\ndef random_forest_classifier_predict(purchase_data):\r\n \"\"\"\r\n Implements Random Forest Classifier with optimized hyperparams by GridSearchCV, shows f1 and roc_auc scores of the prediction on test set\r\n \"\"\"\r\n try:\r\n X_train, X_test, y_train, y_test = get_training_and_test_sets(purchase_data)\r\n clf = RandomForestClassifier(random_state=42, max_features='auto', n_estimators=20, max_depth=4, criterion='gini')\r\n clf.fit(X_train, y_train)\r\n y_pred = clf.predict(X_test)\r\n print(accuracy_score(y_test, y_pred))#0.74\r\n print(roc_auc_score(y_test, y_pred))#0.74\r\n\r\n # param_grid = {\r\n # 'n_estimators': [10, 20, 30, 50, 100],\r\n # 'max_features': ['auto', 'sqrt', 'log2'],\r\n # 'max_depth' : [4,6,8,10],\r\n # 'criterion' :['gini', 'entropy']\r\n # }\r\n\r\n # CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 5)\r\n # CV_clf.fit(X_train, y_train)\r\n # print(CV_clf.best_params_)\r\n # print(CV_clf.best_score_)\r\n except Exception as exception:\r\n print(exception)\r\n\r\ndef xgboost_classifier_predict(purchase_data):\r\n \"\"\"\r\n Implements XGBoosting Classifier with optimized hyperparams by GridSearchCV, shows r2 and roc_auc scores of the prediction on test set\r\n \"\"\"\r\n try:\r\n X_train, X_test, y_train, y_test = get_training_and_test_sets(purchase_data)\r\n estimator = XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\r\n colsample_bynode=1, colsample_bytree=1, gamma=0, gpu_id=-1,\r\n importance_type='gain', interaction_constraints='',\r\n learning_rate=0.05, max_delta_step=0, max_depth=5,\r\n min_child_weight=1, monotone_constraints='()',\r\n n_estimators=60, n_jobs=4, nthread=4, num_parallel_tree=1,\r\n random_state=42, reg_alpha=0, reg_lambda=1, scale_pos_weight=1,\r\n seed=42, subsample=1, tree_method='exact', validate_parameters=1,\r\n verbosity=None)\r\n estimator.fit(X_train, y_train)\r\n y_pred = estimator.predict(X_test)\r\n print(r2_score(y_test, y_pred))#-0.03252337791244386 the negative score shows the disadvantage of the model\r\n print(roc_auc_score(y_test, y_pred))#0.7410161555741303\r\n\r\n # parameters = {\r\n # 'max_depth': range(5, 10, 1),\r\n # 'n_estimators': range(60, 80, 140),\r\n # 'learning_rate': [0.2, 0.01, 0.05]\r\n # }\r\n #\r\n # CV_clf = GridSearchCV(estimator=estimator, param_grid=parameters, scoring = 'roc_auc', n_jobs = 10, cv = 10, verbose=True)\r\n # CV_clf.fit(X_train, y_train)\r\n # print(CV_clf.best_estimator_)\r\n # print(CV_clf.best_params_)\r\n # print(CV_clf.best_score_)\r\n\r\n #y_pred = CV_clf.predict(X_test)\r\n #print(CV_clf.best_score_)\r\n except Exception as exception:\r\n print(exception)\r\n\r\ndef eda_purchase_count(data):\r\n \"\"\"\r\n Show plot of the difference between Purchase and No Purchase count for data analysis, and the difference is little,\r\n that means the prediction accuracy should be quite higher than 50%\r\n \"\"\"\r\n try:\r\n fig, ax = plt.subplots(figsize=(6,4))\r\n sns.countplot(x=data.columns[5], data=data)\r\n plt.title(\"Count of Purchases\")\r\n plt.show()\r\n except Exception as exception:\r\n print(exception)\r\n\r\ndef eda_purchase_var_correlation(corr):\r\n \"\"\"\r\n Show plot of the correlation between feature of X\r\n \"\"\"\r\n try:\r\n fig, ax = plt.subplots(figsize=(8, 8))\r\n plt.title(\"Purchase var correlation\")\r\n sns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), cmap=sns.diverging_palette(220, 10, as_cmap=True), square=True, ax=ax)\r\n plt.show()\r\n except Exception as exception:\r\n print(exception)\r\n\r\ndef eda_purchase_and_average(data):\r\n \"\"\"\r\n Show plot of the correlation between median of purchase count/amount and the purchase decision in the month to predict\r\n \"\"\"\r\n try:\r\n for col in data.columns:\r\n fig, ax = plt.subplots(1, figsize=(8, 6))\r\n sns.boxplot(x=data.columns[4], y=col, data=data)\r\n ax.set_ylim(0,100)#(0,300000)\r\n plt.title(\"Purchase and Avg correlation\")\r\n plt.show()\r\n except Exception as exception:\r\n print(exception)\r\n\r\n\r\npurchase_data = get_specific_month_data_to_predict(4)#assume that we choose April to predict the purchase decision of customers\r\n\r\n#eda_purchase_count(purchase_data)\r\n\r\n# purchase_data.drop(purchase_data.columns[2], axis=1, inplace=True)\r\n# eda_purchase_and_average(purchase_data)\r\n\r\n# purchase_data.drop(purchase_data.columns[[2, 5]], axis=1, inplace=True)\r\n# corr = purchase_data.corr(method='pearson')\r\n# print(np.asmatrix(corr))\r\n# eda_purchase_var_correlation(corr)\r\n# X = remove_correlative_feature(purchase_data, corr, 0.85)#0.85 as threshold of correlation to remove the feature\r\n# X.to_csv(\"reduced_dataset.csv\")\r\n\r\n#random_forest_classifier_predict(purchase_data)\r\n\r\nxgboost_classifier_predict(purchase_data)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"OMT.py","file_name":"OMT.py","file_ext":"py","file_size_in_byte":11499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"40978494","text":"import logging\r\n\r\n# logger = logging.getLogger()\r\n# handler = logging.StreamHandler()\r\n# fh = logging.FileHandler('print.log')\r\n# fh.setLevel(logging.)\r\n# formatter = logging.Formatter(\r\n# '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\r\n# handler.setFormatter(formatter)\r\n# logger.addHandler(handler)\r\n# logger.setLevel(logging.DEBUG)\r\n\r\n\r\ndef save_to_logging(contents):\r\n logging.basicConfig(\r\n filename='print.log',\r\n level=logging.DEBUG,\r\n format='%(levelname)s:%(asctime)s:%(message)s'\r\n )\r\n logging.info(contents)","sub_path":"app/analyse/set_logging.py","file_name":"set_logging.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"184594230","text":"import abc\nimport importlib\nimport os\nimport pkgutil\nimport re\n\nimport pandas as pd\n\nfrom plogpy.type import LogType\n\n\nclass NoMatchedError(Exception):\n pass\n\n\nclass LogRegisterInfo:\n def __init__(self, log_type, patterns):\n self.log_type = log_type\n self.patterns = patterns\n\n\nclass PerfLogParser(abc.ABC):\n \"\"\"\n Base class of parser.\n Each log parser class must inherit this class.\n \"\"\"\n\n @staticmethod\n @abc.abstractmethod\n def regiter_info() -> LogRegisterInfo:\n \"\"\"\n (unique_log_type, [regex, ...])\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def parse(self, path: str) -> pd.DataFrame:\n \"\"\"\n Parse file of specifed path.\n Returns pd.DataFrame.\n \"\"\"\n raise NotImplementedError\n\n\n# key=id, value=([regex,...], parser)\nLOG_PARSER_DICT: dict = {}\nregexes_set = set()\n\n\ndef __init_log_parsers():\n parser_classes = __get_parser_classes()\n for cls_ref in parser_classes:\n reg_info = cls_ref.regiter_info()\n log_type = reg_info.log_type\n patterns = reg_info.patterns\n # Check duplication\n if log_type in LOG_PARSER_DICT:\n raise Exception(f\"Log type '{log_type}' already exists.\")\n # Add log a parser entry\n LOG_PARSER_DICT[log_type] = (patterns, cls_ref())\n for pattern in patterns:\n for t, rs in LOG_PARSER_DICT.items():\n if pattern in rs:\n raise Exception(\n f\"Duplicated '{pattern}'. Log type=({log_type}, {t})\"\n )\n regexes_set.add(pattern)\n\n\n# TODO: common.py is not suitable root path for checking parser classes???\ndef __get_parser_classes() -> list:\n \"\"\"\n Collect list of PerfLogParser class from current path of the module (that is common.py).\n \"\"\"\n # get modules\n path = os.path.dirname(__file__)\n mod_names = [modname for _, modname, _ in pkgutil.iter_modules(path=[path])]\n modules = [\n importlib.import_module(\".\" + modname, __package__) for modname in mod_names\n ]\n\n # get parser classes in each module\n parser_classes = []\n for module in modules:\n class_names = dir(module)\n for classname in class_names:\n cl = getattr(module, classname)\n if __is_parser_class(cl):\n parser_classes.append(cl)\n return parser_classes\n\n\ndef __is_parser_class(class_ref) -> bool:\n \"\"\"\n Check if the class is the subclass of PerLogParser\n \"\"\"\n try:\n if issubclass(class_ref, PerfLogParser) and class_ref is not PerfLogParser:\n return True\n except TypeError:\n pass\n return False\n\n\ndef get_matched_parser(target_file: str) -> PerfLogParser:\n log_type = __detect_log_type(target_file)\n return get_parser(log_type)\n\n\ndef get_supported_list() -> list:\n return sorted(LOG_PARSER_DICT.keys())\n\n\ndef __detect_log_type(target_file: str, scan_line_num: int = 5) -> LogType:\n \"\"\"\n Scan the target_file until scan_line_num and detect the log type.\n Return LogType.\n Throws Exception if no appropriate log type is found.\n \"\"\"\n MAX_ONE_LINE_BYTE_NUM = 4096\n with open(target_file) as f:\n i = 0\n while True:\n i += 1\n line = f.readline(MAX_ONE_LINE_BYTE_NUM)\n if i == scan_line_num:\n break\n for log_type, (patterns, _) in LOG_PARSER_DICT.items():\n for pattern in patterns:\n if re.search(pattern, line):\n return log_type\n raise NoMatchedError(\"No matched type found:\" + target_file)\n\n\ndef get_parser(log_type: LogType) -> PerfLogParser:\n if log_type in LOG_PARSER_DICT:\n _, parser = LOG_PARSER_DICT.get(log_type)\n return parser\n raise Exception(\"Undefined log type:\" + str(log_type))\n\n\n__init_log_parsers()\n","sub_path":"plogpy/plogpy/parser/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393651488","text":"# encoding:utf-8\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# jupytext_version: 1.13.4\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\n\"\"\"\n配置处理器(ConfigParser)相关的功能函数\n\"\"\"\n\nimport re\nimport os\nfrom pathlib import Path\nfrom configparser import ConfigParser, DuplicateSectionError, DuplicateOptionError\nimport pathmagic\n\nwith pathmagic.context():\n from func.first import getdirmain, touchfilepath2depth\n from func.logme import log\n from func.sysfunc import not_IPython\n\n\ndef dropdup4option(opcontent:str):\n \"\"\"\n manuplicate the content(str), which is such as 'option'='value',\n then return clean option/value contents in list object, drop the duplicated\n options, keep the first value\n \"\"\"\n ptno = re.compile(\"(\\w+)\\s*=\\s*(\\w*)\") # = pairs pattern\n opdict = dict() # result container in dict\n fdlst = re.findall(ptno, opcontent)\n for item in fdlst:\n if item[0] in opdict.keys():\n log.critical(f\"出现option名称重复:\\t{item[0]},取用最新的数据\")\n opdict.update(dict({item[0]: item[1]}))\n # make = pairs list\n rstlst = [' = '.join(list(x)) for x in list(zip(opdict.keys(), opdict.values()))]\n # add two new lines at head and tail\n return '\\n' + '\\n'.join(rstlst) + '\\n\\n'\n\n\ndef dropdup4section(fcontent):\n ftn = re.compile(r\"\\[\\w+\\]\")\n sectionlst = re.findall(ftn, fcontent)\n optionlst = re.split(ftn, fcontent)\n resultdict = dict()\n for i in range(len(sectionlst)):\n sname = sectionlst[i]\n if sname in resultdict.keys():\n thislen = len(resultdict[sname])\n thatlen = len(optionlst[i + 1])\n log.critical(f\"存在重复的section:\\t{sname}\\t{thislen}\\t{thatlen}\")\n if thislen > thatlen:\n continue\n cleanopcontent = dropdup4option(optionlst[i + 1])\n resultdict.update({sname: cleanopcontent})\n rstlst = [x for y in list(zip(resultdict.keys(), resultdict.values())) for x in y]\n correctcontent = ''.join(rstlst)\n\n return correctcontent\n\n\ndef fixinifile(inipath):\n with open(inipath, 'r') as f:\n fcontent = f.read()\n with open(str(inipath) + '.bak', 'w') as writer:\n writer.write(fcontent)\n correctcontent = dropdup4section(fcontent)\n with open(str(inipath), 'w') as writer:\n writer.write(correctcontent)\n return correctcontent\n\n\ndef removesection(cfpfilename: str, sectionname: str):\n \"\"\"\n 删除指定section,默认清除其下面的所有option\n \"\"\"\n cfpin, cfpinpath = getcfp(cfpfilename)\n if cfpin.has_section(sectionname):\n cfpin.remove_section(sectionname)\n cfpin.write(open(cfpinpath, 'w', encoding='utf-8'))\n log.critical(f\"成功清除{sectionname}下的所有option!!!\")\n\n\ndef getcfp(cfpfilename: str):\n cfpson = ConfigParser()\n inipathson = Path(getdirmain()) / 'data' / (cfpfilename + '.ini')\n touchfilepath2depth(inipathson)\n try:\n cfpson.read(inipathson, encoding='utf-8')\n except (DuplicateSectionError, DuplicateOptionError) as dse:\n log.critical(f\"ini文件《{inipathson}》中存在重复的section或option名称,备份文件并试图修复文件……{dse}\")\n fixinifile(inipathson)\n except Exception as eee:\n log.critical(eee)\n try:\n cfpson.read(inipathson, encoding='utf-8')\n log.critical(f\"ini文件《{inipathson}》修复成功!!!\")\n except Exception as e:\n log.critical(f\"读取配置文件《{inipathson}》时失败!!!{e}\")\n log.critical(f\"试图强制删除该配置文件《{inipathson}》\")\n os.remove(inipathson)\n log.critical(f\"配置文件《{inipathson}》被强制删除!!!\")\n return\n\n return cfpson, inipathson\n\n\ndef setcfpoptionvalue(cfpfilename: str, sectionname: str, optionname: str, optionvalue):\n cfpin, cfpinpath = getcfp(cfpfilename)\n if not cfpin.has_section(sectionname):\n cfpin.add_section(sectionname)\n cfpin.write(open(cfpinpath, 'w', encoding='utf-8'))\n cfpin.set(sectionname, optionname, optionvalue)\n cfpin.write(open(cfpinpath, 'w', encoding='utf-8'))\n\n\ndef getcfpoptionvalue(cfpfilename: str, sectionname: str, optionname: str):\n \"\"\"\n return option value for certain optionname, under given ssction, all for indicated cfp filename\n if section is not exsited, create it, then return None; if the option is not exsiteds, just return None.\n \"\"\"\n cfpin, cfpinpath = getcfp(cfpfilename)\n if not cfpin.has_section(sectionname):\n print(f\"seticon {sectionname} is not exists. Then creating it now ...\")\n cfpin.add_section(sectionname)\n cfpin.write(open(cfpinpath, 'w', encoding='utf-8'))\n return\n if not cfpin.has_option(sectionname, optionname):\n print(f\"option {optionname} is not exists under section [{sectionname}]\")\n return\n\n targetvalue = str(cfpin.get(sectionname, optionname))\n\n # 处理布尔值\n if targetvalue.strip().lower() == 'true':\n return True\n\n if targetvalue.strip().lower() == 'false':\n return False\n\n # 处理整数\n ptn = re.compile(r\"^[+-]?[0-9]+$\")\n result = ptn.match(targetvalue)\n if result:\n targetvalue = int(result.group())\n return targetvalue\n\n # 处理小数\n ptn = re.compile(r\"^[+-]?[0-9]+\\.[0-9]+$\")\n result = ptn.match(targetvalue)\n if result:\n targetvalue = float(result.group())\n return targetvalue\n\n return targetvalue\n\n\ndef getcfpsectionvalue(cfpfilename: str, sectionname: str):\n \"\"\"\n return section value(which is list including tuple) for certain section name,, all for indicated cfp filename\n if section is not exsited, create it, then return None.\n \"\"\"\n cfpin, cfpinpath = getcfp(cfpfilename)\n if not cfpin.has_section(sectionname):\n print(f\"seticon {sectionname} is not exists. Then creating it now ...\")\n cfpin.add_section(sectionname)\n cfpin.write(open(cfpinpath, 'w', encoding='utf-8'))\n return\n else:\n return cfpin.items(f'{sectionname}')\n\n\nis_log_details = getcfpoptionvalue('everinifromnote', 'everwork', 'logdetails') \n# cfp, inifilepath = getcfp('everwork')\n# cfpdata, inidatanotefilepath = getcfp('everdatanote')\n# cfplife, inilifepath = getcfp('everlife')\n# cfpzysm, inizysmpath = getcfp('everzysm')\n# cfpworkplan, iniworkplanpath = getcfp('everworkplan')\n\n\nif __name__ == '__main__':\n if not_IPython() and is_log_details:\n print(f'开始测试文件\\t{__file__}')\n# cp, cppath = getcfp('everwork')\n# print(cp, cppath)\n cfpapiname = 'everapi'\n inipathson = Path(getdirmain()) / 'data' / (cfpapiname + '.ini')\n name = '[notestore]'\n cp, cppath = getcfp(cfpapiname)\n print(cp)\n# removesection(cfpapiname, nssectionname)\n# ict = fixinifile(inipathson)\n seccontent = getcfpsectionvalue('everwork', 'evernote')\n print(seccontent)\n if not_IPython() and is_log_details:\n print('Done.')\n","sub_path":"func/configpr.py","file_name":"configpr.py","file_ext":"py","file_size_in_byte":7109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243567160","text":"\"\"\"Adds a backend for storing documents as flat files.\n\nTo use add this to settings.local:\n\n NORMALIZED_PROCESSING = ['storage']\n RAW_PROCESSING = ['storage']\n\"\"\"\n\nimport os\nimport json\n\nfrom scrapi.processing.base import BaseProcessor\n\n\nclass StorageProcessor(BaseProcessor):\n NAME = 'storage'\n\n def process_raw(self, raw):\n filename = 'archive/{}/{}/raw.{}'.format(raw['source'], raw['docID'], raw['filetype'])\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n\n with open(filename, 'w') as f:\n f.write(json.dumps(raw.attributes, indent=4))\n\n def process_normalized(self, raw, normalized):\n filename = 'archive/{}/{}/normalized.json'.format(raw['source'], raw['docID'], raw['filetype'])\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n\n with open(filename, 'w') as f:\n f.write(json.dumps(normalized.attributes, indent=4))\n","sub_path":"scrapi/processing/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"564100883","text":"from django.shortcuts import get_object_or_404\nfrom websites.models import Website\n\n\ndef cart_contents(request):\n \"\"\"\n Ensures that the cart contents are available when rendering\n every page\n \"\"\"\n cart = request.session.get('cart', {})\n\n cart_items = []\n total = 0\n website_count = 0\n\n for id, quantity in cart.items():\n website = get_object_or_404(Website, pk=id)\n total += quantity * website.price\n website_count += quantity\n cart_items.append({'id': id, 'quantity': quantity, 'website': website})\n\n return {\n 'cart_items': cart_items,\n 'total': total, 'website_count': website_count\n }\n","sub_path":"cart/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"106092516","text":"#!/usr/bin/env python3\n#coding: utf-8\n\n'''\n根据关键词将文本分割,并保存为单独的文件.\nusage:运行脚本,依次输入待分割文件->分割关键词->输出文件名\nAuthor@LiYihang\n\n'''\n\nimport re\nimport linecache\nimport pandas as pd\n\ndef fileParse():\n inputFile = input('Input SourcFile:')\n fp = open(inputFile, 'r')\n\n _cell_length_a = []\n _cell_length_b = []\n _cell_length_c = []\n _cell_angle_alpha = []\n _cell_angle_beta = []\n _cell_angle_gamma = []\n _symmetry_Int_Tables_number = []\n _symmetry_space_group_name_ = []\n _symmetry_cell_setting = []\n _pauling_file_object_repr = []\n _pauling_file_object_version = []\n _pauling_file_entry = []\n _pauling_file_entry_reference = []\n _pauling_file_phase = []\n _pauling_file_phase_reference = []\n\n dataInfo = ['_cell_length_a','_cell_length_b','_cell_length_c',\n '_cell_angle_alpha','_cell_angle_beta','_cell_angle_gamma',\n '_symmetry_Int_Tables_number','_symmetry_space_group_name_',\n '_symmetry_cell_setting','_pauling_file_object_repr',\n '_pauling_file_entry','_pauling_file_phase',\n '_pauling_file_entry_reference','_pauling_file_phase_reference']\n\n for eachLine in fp:\n eachLine = eachLine.strip('\\n')\n\n if re.search('_cell_length_a', eachLine) is not None:\n a = re.compile(r'(_cell_length_a)\\s+(.*)').search(eachLine)\n _cell_length_a.append(a.group(2))\n\n elif re.search('_cell_length_b', eachLine) is not None:\n b = re.compile(r'(_cell_length_b)\\s+(.*)').search(eachLine)\n _cell_length_b.append(b.group(2))\n\n elif re.search('_cell_length_c', eachLine) is not None:\n c = re.compile(r'(_cell_length_c)\\s+(.*)').search(eachLine)\n _cell_length_c.append(c.group(2))\n\n elif re.search('_cell_angle_alpha', eachLine) is not None:\n alpha = re.compile(r'(_cell_angle_alpha)\\s+(.*)').search(eachLine)\n _cell_angle_alpha.append(alpha.group(2))\n\n elif re.search('_cell_angle_beta', eachLine) is not None:\n beta = re.compile(r'(_cell_angle_beta)\\s+(.*)').search(eachLine)\n _cell_angle_beta.append(beta.group(2))\n\n elif re.search('_cell_angle_gamma', eachLine) is not None:\n gamma = re.compile(r'(_cell_angle_gamma)\\s+(.*)').search(eachLine)\n _cell_angle_gamma.append(gamma.group(2))\n\n elif re.search('_symmetry_Int_Tables_number', eachLine) is not None:\n number = re.compile(r'(_symmetry_Int_Tables_number)\\s+(\\d+)').search(eachLine)\n _symmetry_Int_Tables_number.append(number.group(2))\n\n elif re.search('_symmetry_space_group_name_H-M', eachLine) is not None:\n space_group_name = re.compile(r'(_symmetry_space_group_name_H-M)\\s(.*)').search(eachLine)\n _symmetry_space_group_name_.append(space_group_name.group(2))\n\n elif re.search('_symmetry_cell_setting', eachLine) is not None:\n cell_setting = re.compile(r'(_symmetry_cell_setting)\\s+(\\w+)').search(eachLine)\n _symmetry_cell_setting.append(cell_setting.group(2))\n\n elif re.search('_pauling_file_object_repr', eachLine) is not None:\n repr = re.compile(r'(_pauling_file_object_repr)\\s+(.*)').search(eachLine)\n _pauling_file_object_repr.append(repr.group(2))\n\n elif re.search('_pauling_file_entry ', eachLine) is not None:\n entry = re.compile(r'(_pauling_file_entry)\\s+(.*)').search(eachLine)\n _pauling_file_entry.append(entry.group(2))\n\n elif re.search('_pauling_file_phase ', eachLine) is not None:\n phase = re.compile(r'(_pauling_file_phase)\\s+(.*)').search(eachLine)\n _pauling_file_phase.append(phase.group(2))\n\n elif re.search('_pauling_file_entry_reference', eachLine) is not None:\n entry_reference = re.compile(r'(_pauling_file_entry_reference)\\s+(.*)').search(eachLine)\n _pauling_file_entry_reference.append(entry_reference.group(2))\n\n elif re.search('_pauling_file_phase_reference', eachLine) is not None:\n phase_reference = re.compile(r'(_pauling_file_phase_reference)\\s+(.*)').search(eachLine)\n _pauling_file_phase_reference.append(phase_reference.group(2))\n\n else:\n continue\n\n fp.close()\n\n df = pd.DataFrame({'_cell_length_a':pd.Series(_cell_length_a),\n '_cell_length_b':pd.Series(_cell_length_b),\n '_cell_length_c':pd.Series(_cell_length_c),\n '_cell_angle_alpha':pd.Series(_cell_angle_alpha),\n '_cell_angle_beta':_cell_angle_beta,\n '_cell_angle_gamma':_cell_angle_gamma,\n '_symmetry_Int_Tables_number':pd.Series(_symmetry_Int_Tables_number),\n '_symmetry_space_group_name_':pd.Series(_symmetry_space_group_name_),\n '_symmetry_cell_setting':pd.Series(_symmetry_cell_setting),\n '_pauling_file_object_repr':pd.Series(_pauling_file_object_repr),\n '_pauling_file_entry':pd.Series(_pauling_file_entry),\n '_pauling_file_phase':pd.Series(_pauling_file_phase),\n '_pauling_file_entry_reference':pd.Series(_pauling_file_entry_reference),\n '_pauling_file_phase_reference':pd.Series(_pauling_file_phase_reference)})\n df.to_excel('spinel0.xlsx', sheet_name='cif', na_rep=\"NULL\")\n\n\nif __name__ == \"__main__\":\n fileParse()\n","sub_path":"提取cif信息.py","file_name":"提取cif信息.py","file_ext":"py","file_size_in_byte":5597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109612244","text":"import torch\nfrom torchvision import datasets, transforms\nimport argparse\nimport numpy as np\nfrom PIL import Image\nimport json\n\ndef argparse_train():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"data_directory\", help=\"set directory to get the data from\")\n parser.add_argument(\"--save_dir\", help=\"set directory to save checkpoints\", default = \"./\")\n parser.add_argument(\"--arch\", help=\"choose model architecture\", default=\"densenet121\")\n parser.add_argument(\"--prob_dropout\",type=float, help=\"choose dropout probability in hidden layer\", default=0.3)\n parser.add_argument(\"--learning_rate\",type=float , help=\"choose learning rate\", default=0.001)\n parser.add_argument(\"--hidden_units\", type=int, help=\"choose hidden units\", default=512)\n parser.add_argument(\"--epochs\", type=int, help=\"choose epochs\", default=10)\n parser.add_argument('--gpu', action='store_true', default=False, dest='gpu', help='set gpu-training to True')\n\n\n results = parser.parse_args()\n print('data_directory = {!r}'.format(results.data_directory))\n print('save_dir = {!r}'.format(results.save_dir))\n print('arch = {!r}'.format(results.arch))\n print('prob_dropout = {!r}'.format(results.prob_dropout))\n print('learning_rate = {!r}'.format(results.learning_rate))\n print('hidden_units = {!r}'.format(results.hidden_units))\n print('epochs = {!r}'.format(results.epochs))\n print('gpu_training = {!r}'.format(results.gpu))\n \n return results\n\ndef argparse_predict():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"image_path\", help=\"set path to image for prediction\")\n parser.add_argument(\"checkpoint\", help=\"set checkpoint to load the model from\")\n parser.add_argument(\"--top_k\", type=int, help=\"return top K most likely classes\", default=5)\n parser.add_argument(\"--category_names\", help=\"use a mapping of categories to real names\", default=None)\n parser.add_argument('--gpu', action='store_true', default=False, dest='gpu', help='set gpu-training to True')\n\n results = parser.parse_args()\n print('image_path = {!r}'.format(results.image_path))\n print('checkpoint = {!r}'.format(results.checkpoint))\n print('top_k = {!r}'.format(results.top_k))\n print('category_names = {!r}'.format(results.category_names))\n print('gpu_training = {!r}'.format(results.gpu))\n \n return results\n\ndef load_data(data_directory):\n train_dir = data_directory + '/train'\n valid_dir = data_directory + '/valid'\n test_dir = data_directory + '/test'\n # Define transforms for the training, validation, and testing sets\n data_transforms = {'train': transforms.Compose([transforms.Resize((250,250)),\n transforms.RandomCrop((224,224)),\n transforms.RandomRotation(20),\n transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),\n 'valid': transforms.Compose([transforms.Resize((224,224)),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),\n 'test': transforms.Compose([transforms.Resize((224,224)),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),\n }\n\n # Load the datasets with ImageFolder\n image_datasets = {'train': datasets.ImageFolder(train_dir, transform = data_transforms['train']),\n 'valid': datasets.ImageFolder(train_dir, transform = data_transforms['valid']),\n 'test': datasets.ImageFolder(train_dir, transform = data_transforms['test'])\n }\n\n # Using the image datasets and the trainforms, define the dataloaders\n dataloaders = {'train': torch.utils.data.DataLoader(image_datasets['train'], batch_size = 64, shuffle=True),\n 'valid': torch.utils.data.DataLoader(image_datasets['valid'], batch_size = 64, shuffle=True),\n 'test': torch.utils.data.DataLoader(image_datasets['test'], batch_size = 64, shuffle=True),\n }\n \n return image_datasets, dataloaders\n\ndef preprocess_image(image_path):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n # Load image\n image = Image.open(image_path)\n \n # scale image\n size = 256, 256\n image.thumbnail(size)\n \n # center crop\n width, height = image.size # Get dimensions\n new_width = 224\n new_height = 224\n left = (width - new_width)/2\n \n top = (height - new_height)/2\n right = (width + new_width)/2\n bottom = (height + new_height)/2\n image = image.crop((left, top, right, bottom))\n \n np_image = np.array(image)\n \n # Normalize\n means = np.array([0.485, 0.456, 0.406])\n stdev = np.array([0.229, 0.224, 0.225])\n \n np_image = (np_image/255 - means)/stdev\n \n image_transposed = np_image.transpose(2,0,1)\n \n return image_transposed\n\n\ndef import_mapping(category_names):\n with open(category_names, 'r') as f:\n cat_to_name = json.load(f)\n \n return cat_to_name","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"523989394","text":"class Box:\n def myInit(mySelf, boxname, size, color):\n mySelf.boxname = boxname\n mySelf.size = size\n mySelf.color = color # 自己写一个初始化函数,一样奏效,甚至不用self命名。其它函数当中用标准self\n return mySelf # 返回给实例化过程一个对象!神奇!并且含有对象属性/字典\n\n # def __init__(self, boxname, size, color):\n # self.boxname = boxname\n # self.size = size\n # self.color = color #注释掉原来标准的初始化\n\n def open(self, myself):\n print(self)\n print(myself)\n print('-->用自己的myself,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))\n print('-->用类自己的self,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))\n\n def close(self):\n print('-->关闭%s,谢谢' % self.boxname)\n\n\n# 经过改造,运行结果和标准初始化没区别\n\nb = Box().myInit('魔盒', '14m', '红色')\n# b = Box('魔盒', '14m', '红色')#注释掉原来标准的初始化方法\nb.close()\nb.open(b) # 本来就会自动传一个self,现在传入b,就会让open多得到一个实例对象本身,print看看是什么。\nprint(b.__dict__) # 这里返回的就是self本身,self存储属性,没有动作。","sub_path":"GreatWord/newone.py","file_name":"newone.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"508013046","text":"###########################################################\n#\n# Copyright (c) 2005, Southpaw Technology\n# All Rights Reserved\n#\n# PROPRIETARY INFORMATION. This software is proprietary to\n# Southpaw Technology, and is not to be reproduced, transmitted,\n# or disclosed in any way without written permission.\n#\n#\n#\n\n__all__ = [\"NotificationTest\"]\n\nimport tacticenv\nimport unittest\nimport time\n\nfrom pyasm.common import *\nfrom pyasm.security import *\nfrom pyasm.search import Transaction, SearchType, Search\nfrom pyasm.unittest import Person\nfrom pyasm.checkin import FileCheckin\n\nfrom project import *\nfrom snapshot import *\nfrom schema import *\nfrom task import *\nfrom naming import *\nfrom note import Note\nfrom pipeline import Context\nfrom expression import ExpressionParser\nfrom pyasm.unittest import UnittestEnvironment\nfrom pyasm.biz import Notification\nfrom pyasm.command import Trigger\n\nclass NotificationTest(unittest.TestCase):\n\n def test_all(my):\n \n Batch()\n from pyasm.web.web_init import WebInit\n WebInit().execute()\n\n test_env = UnittestEnvironment()\n test_env.create()\n my.transaction = Transaction.get(create=True)\n Project.set_project('unittest')\n try:\n my.person = Person.create( \"Unit\", \"Test\",\n \"ComputerWorld\", \"Fake Unittest Person\")\n my._test_notification()\n\n my.transaction = Transaction.get(create=True)\n my._test_result()\n finally:\n my.transaction.rollback()\n test_env.delete()\n\n return\n\n\n def _test_notification(my):\n \n sobject = SearchType.create(\"sthpw/notification\")\n sobject.set_value('subject', 'TACTIC Unittest 001: a new item has been added.')\n sobject.set_value(\"event\",'insert|unittest/country')\n sobject.commit()\n\n sobject = SearchType.create(\"sthpw/notification\")\n sobject.set_value('subject', 'TACTIC Unittest 002: an item has been updated.')\n sobject.set_value(\"event\",'update|unittest/country')\n sobject.commit()\n\n sobject = SearchType.create(\"sthpw/notification\")\n sobject.set_value('subject', 'TACTIC Unittest 003: New notes added.')\n sobject.set_value(\"event\",'insert|sthpw/note')\n sobject.commit() \n\n sobject = SearchType.create(\"sthpw/notification\")\n sobject.set_value('subject', 'TACTIC Unittest 004: New task assigned.')\n sobject.set_value(\"event\",'change|sthpw/task|status')\n sobject.commit()\n\n sobject = SearchType.create(\"sthpw/notification\")\n sobject.set_value('subject', 'TACTIC Unittest 005: task status has been changed.')\n sobject.set_value(\"event\",'change|sthpw/task|assigned')\n sobject.commit()\n\n sobject = SearchType.create(\"sthpw/notification\")\n sobject.set_value('subject', 'TACTIC Unittest 006: Files are checked in.')\n sobject.set_value(\"event\",'checkin|unittest/country')\n sobject.commit()\n\n # Item added\n my.clear_notification()\n sobject1 = SearchType.create(\"unittest/country\")\n sobject1.set_value('code', 'test_update_trigger')\n sobject1.commit()\n\n # Updated item\n sobject1.set_value('code','success') \n sobject1.commit() \n\n # Note added\n Note.create(my.person, \"test note2\", context='default2')\n\n # Task assigned\n sobject = Task.create(my.person,'hi','hellotest',assigned=\"test assigned\")\n\n # Task status changed\n tasks = Task.get_by_sobject(my.person)\n tasks[0].set_value('process','success')\n tasks[0].commit()\n\n # Files are checked in\n file_path = \"./notification_test_check.txt\"\n for i in range(0,4):\n file = open(file_path, 'w')\n file.write(\"whatever\")\n file.close()\n checkin = FileCheckin(sobject1, file_path, \"main\", context='test', checkin_type='auto')\n checkin.execute()\n Trigger.call_all_triggers()\n\n if os.path.exists(file_path):\n os.remove(file_path)\n \n def _test_result(my):\n\n search = Search('sthpw/notification_log')\n search.add_order_by('timestamp desc')\n search.set_limit(7)\n note = search.get_sobjects()\n message=[]\n for i in range(6):\n temp_value = note[i].get_value('subject')\n message.append(temp_value)\n \n my.assertEquals(\"TACTIC Unittest 001: a new item has been added.\", message[0])\n my.assertEquals(\"TACTIC Unittest 002: an item has been updated.\", message[1])\n my.assertEquals(\"TACTIC Unittest 003: New notes added.\", message[2])\n my.assertEquals(\"TACTIC Unittest 004: New task assigned.\", message[3])\n my.assertEquals(\"TACTIC Unittest 005: task status has been changed.\", message[4])\n my.assertEquals(\"TACTIC Unittest 006: Files are checked in.\", message[5])\n\n def clear_notification(my):\n Notification.clear_cache()\n Container.put(\"Trigger:notifications\", None)\n Container.put(\"triggers:cache\", None)\n Container.put(\"notifications:cache\", None)\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n","sub_path":"pyasm/biz/notification_test.py","file_name":"notification_test.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166276158","text":"#!/usr/bin/env python3\n\nimport sys\nfrom typing import Iterable\n\n\ndef power_consumption(data: Iterable[str]) -> int:\n size = 0\n n_size = 0\n vector = []\n\n for ind, line in enumerate(data):\n if ind == 0:\n n_size = len(line)\n vector = [0] * n_size\n\n for ind in range(n_size):\n if line[ind] == '1':\n vector[ind] += 1\n\n size += 1\n\n value_1, value_2 = '', ''\n\n for ind in range(n_size):\n if vector[ind] > size - vector[ind]:\n value_1 += '1'\n value_2 += '0'\n else:\n value_1 += '0'\n value_2 += '1'\n\n return int(value_1, 2) * int(value_2, 2)\n\n\nclass TestClass():\n\n def test_1(self):\n data = [\n '00100',\n '11110',\n '10110',\n '10111',\n '10101',\n '01111',\n '00111',\n '11100',\n '10000',\n '11001',\n '00010',\n '01010',\n ]\n\n assert power_consumption(data) == 198\n\n\ndef main():\n data = map(lambda x: x.strip(), sys.stdin)\n result = power_consumption(data)\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2021/day_03_binary_diagnostic_1.py","file_name":"day_03_binary_diagnostic_1.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"631016511","text":"#encoding:utf-8\n\"\"\"\nTest CWT coefficients\nAuthor : Gaopengfei\nDate: 2016.6.23\n\"\"\"\nimport os\nimport sys\nimport json\nimport math\nimport pickle\nimport random\nimport pywt\nimport time\nimport glob\nimport pdb\nfrom multiprocessing import Pool\n\nimport numpy as np\n## machine learning methods\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom numpy import pi, r_\nfrom scipy import optimize\n\n# project homepath\n# \ncurfilepath = os.path.realpath(__file__)\ncurfolderpath = os.path.dirname(curfilepath)\nprojhomepath = os.path.dirname(curfolderpath)\nprojhomepath = os.path.dirname(projhomepath)\nsys.path.append(projhomepath)\n# configure file\n# conf is a dict containing keys\n# my project components\n\n\nclass plotRoundStat:\n def __init__(self):\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]\n self.colors = []\n for color_tri in tableau20:\n self.colors.append((color_tri[0]/255.0,color_tri[1]/255.0,color_tri[2]/255.0))\n\n def plot_mean_error(self):\n EvalRoundList = glob.glob(os.path.join(curfolderpath,'EvalInfoRound*'))\n meandict = dict()\n for evalfolder in EvalRoundList:\n jsonfilepath = os.path.join(evalfolder,'ErrStat.json')\n with open(jsonfilepath,'r') as fin:\n errdict = json.load(fin)\n\n # get mean error\n for label,stat in errdict.iteritems():\n if label not in meandict:\n meandict[label] = []\n meandict[label].append(stat['mean'])\n # plot mean error\n plt.figure(1)\n color_ind = 1\n for label,meanlist in meandict.iteritems():\n plt.plot(meanlist,color = self.colors[color_ind],marker = 's',label = label,markersize = 12,lw = 4,alpha = 0.8)\n color_ind += 1\n\n plt.grid(True)\n plt.legend()\n plt.title('mean error in each Round')\n plt.show()\n\n\n def plot_std_error(self):\n EvalRoundList = glob.glob(os.path.join(curfolderpath,'EvalInfoRound*'))\n stddict = dict()\n for evalfolder in EvalRoundList:\n jsonfilepath = os.path.join(evalfolder,'ErrStat.json')\n with open(jsonfilepath,'r') as fin:\n errdict = json.load(fin)\n\n # get mean error\n for label,stat in errdict.iteritems():\n if label not in stddict:\n stddict[label] = []\n stddict[label].append(stat['std'])\n # plot mean error\n plt.figure(1)\n color_ind = 1\n for label,meanlist in stddict.iteritems():\n plt.plot(meanlist,color = self.colors[color_ind],marker = 's',label = label,markersize = 12,lw = 4,alpha = 0.8)\n color_ind += 1\n\n plt.grid(True)\n plt.legend()\n plt.title('std error in each Round')\n plt.show()\n\n\nif __name__ == '__main__':\n roundstat = plotRoundStat()\n roundstat.plot_mean_error()\n #roundstat.plot_std_error()\n","sub_path":"PaperResults/plotQT2LeadResult/MultiLead3/plot_Round_Error.py","file_name":"plot_Round_Error.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343807779","text":"import argparse\nimport cv2\nimport torch\n\nfrom model import SCNN\nfrom utils.prob2lines import getLane\nfrom utils.transforms import *\nimport time\nfrom tqdm import tqdm\n\nimport pdb\n\nimage_resize_width = 512\n\nnet = SCNN(input_size=(image_resize_width, 288), pretrained=False)\nif torch.cuda.is_available():\n net = net.cuda()\n\nmean=(0.3598, 0.3653, 0.3662) # CULane mean, std\nstd=(0.2573, 0.2663, 0.2756)\ntransform = Compose(Resize((image_resize_width, 288)), ToTensor(),\n Normalize(mean=mean, std=std))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--img_path\", '-i', type=str, default=\"demo/demo.jpg\", help=\"Path to demo img\")\n parser.add_argument(\"--weight_path\", '-w', type=str, help=\"Path to model weights\")\n parser.add_argument(\"--visualize\", '-v', action=\"store_true\", default=False, help=\"Visualize the result\")\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n img_path = args.img_path\n weight_path = args.weight_path\n\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n x = transform({'img': img})['img']\n x.unsqueeze_(0)\n\n save_dict = torch.load(weight_path, map_location='cpu')\n\n net.load_state_dict(save_dict['net'])\n net.eval()\n\n if torch.cuda.is_available():\n x = x.cuda()\n \n # start_time = time.time()\n # for i in tqdm(range(100)):\n # seg_pred, exist_pred = net(x)[:2]\n # print(\"Spend time {} seconds for 100 times\".format(time.time() - start_time))\n # CPU spend time 64.43067598342896 seconds for 100 times, --> 640ms\n # GPU spend time 7.734357118606567 seconds for 100 times, --> 70ms\n\n seg_pred, exist_pred = net(x)[:2]\n # pdb.set_trace()\n # (pdb) pp x.shape\n # torch.Size([1, 3, 288, 512])\n\n # (pdb) pp seg_pred.shape\n # torch.Size([1, 5, 288, 512])\n\n # (Pdb) pp seg_pred.min(), seg_pred.max()\n # (tensor(-13.8127, device='cuda:0', grad_fn=),\n # tensor(26.3522, device='cuda:0', grad_fn=))\n\n # (Pdb) pp exist_pred.shape, exist_pred\n # (torch.Size([1, 4]),\n # tensor([[0.9989, 0.9999, 0.9993, 0.9983]], device='cuda:0',\n # grad_fn=))\n\n\n seg_pred = seg_pred.detach().cpu().numpy()\n exist_pred = exist_pred.detach().cpu().numpy()\n seg_pred = seg_pred[0]\n exist = [1 if exist_pred[0, i] > 0.5 else 0 for i in range(4)]\n\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img = cv2.resize(img, (image_resize_width, 288))\n lane_img = np.zeros_like(img)\n color = np.array([[255, 125, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255]], dtype='uint8')\n coord_mask = np.argmax(seg_pred, axis=0)\n for i in range(0, 4):\n if exist_pred[0, i] > 0.5:\n lane_img[coord_mask == (i + 1)] = color[i]\n cv2.imshow(\"lane\", lane_img)\n\n # pdb.set_trace()\n # (Pdb) seg_pred.shape, coord_mask.shape\n # ((5, 288, 512), (288, 512))\n\n img = cv2.addWeighted(src1=lane_img, alpha=0.8, src2=img, beta=1., gamma=0.)\n for x in getLane.prob2lines_CULane(seg_pred, exist):\n print(x)\n\n if args.visualize:\n print([1 if exist_pred[0, i] > 0.5 else 0 for i in range(4)])\n cv2.imshow(\"\", img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n else:\n cv2.imwrite(\"demo/demo_result.jpg\", img)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tusimple_demo.py","file_name":"tusimple_demo.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192961906","text":"import pyspark\nimport argparse\nfrom new_gps_spark_logic import GpsPingFilter\n\n# attempt to read input args from spark-submit job\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--testfile\", help=\"the full path and name to a test file\")\nargs = parser.parse_args()\n\n#fileNameAndPath = \"OOOOPS NOT SET\";\n#if args.testfile:\n# fileNameAndPath = args.testfile\n \n\ngpf = GpsPingFilter()\n\ngpf.init_spark()\n\ngpf.load_daily_feed('local','2020-08-09')\n\ngpf.junk_filter()\n\ngpf.speed_filter()\n\ngpf.linear_filter()\n\ngpf.write_results()","sub_path":"spark/notebooks/gps/PythonMain-KB_test.py","file_name":"PythonMain-KB_test.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157902387","text":"# - Glencoe Software, Inc.\n# - University of Dundee\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport os\nimport sys\nimport keyword\nimport logging\n\n# The generateDS package and our generateds module\n# collide on case-insensitive file systems.\nimport generateDS.generateDS\nfrom ome.modeltools.exceptions import ModelProcessingError\nfrom xml import sax\nfrom xml.etree import ElementTree\nfrom ome.modeltools.model import OMEModel\n\nXschemaHandler = generateDS.generateDS.XschemaHandler\nset_type_constants = generateDS.generateDS.set_type_constants\n\n\ndef parse(opts):\n \"\"\"\n Entry point for XML Schema parsing into an OME Model.\n \"\"\"\n # The following two statements are required to \"prime\" the generateDS\n # code and ensure we have reasonable namespace support.\n filenames = opts.args\n namespace = opts.namespace\n\n schemas = dict()\n\n logging.debug(\"Namespace: %s\" % namespace)\n set_type_constants(namespace)\n generateDS.generateDS.XsdNameSpace = namespace\n logging.debug(\"Type map: %s\" % opts.lang.type_map)\n\n parser = sax.make_parser()\n ch = XschemaHandler()\n parser.setContentHandler(ch)\n for filename in filenames:\n parser.parse(filename)\n\n schemaname = os.path.split(filename)[1]\n schemaname = os.path.splitext(schemaname)[0]\n schema = ElementTree.parse(filename)\n schemas[schemaname] = schema\n\n root = ch.getRoot()\n if root is None:\n raise ModelProcessingError(\n \"No model objects found, have you set the correct namespace?\")\n root.annotate()\n return OMEModel.process(ch, schemas, opts)\n\n\ndef reset():\n \"\"\"\n Since the generateDS module contains many globals and package scoped\n variables we need the ability to reset its state if we are to re-use\n it multiple times in the same process.\n \"\"\"\n generateDS.generateDS.GenerateProperties = 0\n generateDS.generateDS.UseOldGetterSetter = 0\n generateDS.generateDS.MemberSpecs = None\n generateDS.generateDS.DelayedElements = []\n generateDS.generateDS.DelayedElements_subclass = []\n generateDS.generateDS.AlreadyGenerated = []\n generateDS.generateDS.AlreadyGenerated_subclass = []\n generateDS.generateDS.PostponedExtensions = []\n generateDS.generateDS.ElementsForSubclasses = []\n generateDS.generateDS.ElementDict = {}\n generateDS.generateDS.Force = 0\n generateDS.generateDS.Dirpath = []\n generateDS.generateDS.ExternalEncoding = sys.getdefaultencoding()\n\n generateDS.generateDS.NamespacesDict = {}\n generateDS.generateDS.Targetnamespace = \"\"\n\n generateDS.generateDS.NameTable = {\n 'type': 'type_',\n 'float': 'float_',\n }\n for kw in keyword.kwlist:\n generateDS.generateDS.NameTable[kw] = '%sxx' % kw\n\n generateDS.generateDS.SubclassSuffix = 'Sub'\n generateDS.generateDS.RootElement = None\n generateDS.generateDS.AttributeGroups = {}\n generateDS.generateDS.SubstitutionGroups = {}\n #\n # SubstitutionGroups can also include simple types that are\n # not (defined) elements. Keep a list of these simple types.\n # These are simple types defined at top level.\n generateDS.generateDS.SimpleElementDict = {}\n generateDS.generateDS.SimpleTypeDict = {}\n generateDS.generateDS.ValidatorBodiesBasePath = None\n generateDS.generateDS.UserMethodsPath = None\n generateDS.generateDS.UserMethodsModule = None\n generateDS.generateDS.XsdNameSpace = ''\n","sub_path":"xsd-fu/python/ome/modeltools/generateds.py","file_name":"generateds.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451642160","text":"import json\nfrom typing import List, Dict, Any\n\n\ndef _write_to_json(data: Any, location: str):\n with open(location, 'w') as f:\n json.dump(data, f)\n\n\ndef run(train_sentences: List[List[str]],\n valid_sentences: List[List[str]],\n test_sentences: List[List[str]],\n word_lookup: List[str],\n word_embedding: List[List[float]],\n\n train_case_seqs: List[List[int]],\n valid_case_seqs: List[List[int]],\n test_case_seqs: List[List[int]],\n\n train_relations: List[List[str]],\n valid_relations: List[List[str]],\n test_relations: List[List[str]],\n\n folder: str):\n\n # write sentences\n _write_to_json(train_sentences, folder + 'train_sentences.json')\n _write_to_json(valid_sentences, folder + 'valid_sentences.json')\n _write_to_json(test_sentences, folder + 'test_sentences.json')\n _write_to_json(word_lookup, folder + 'word_lookup.json')\n _write_to_json(word_embedding, folder + 'word_embedding.json')\n\n # write case_seqs\n _write_to_json(train_case_seqs, folder + 'train_case_seqs.json')\n _write_to_json(valid_case_seqs, folder + 'valid_case_seqs.json')\n _write_to_json(test_case_seqs, folder + 'test_case_seqs.json')\n\n # write relations\n _write_to_json(train_relations, folder + 'train_relations.json')\n _write_to_json(valid_relations, folder + 'valid_relations.json')\n _write_to_json(test_relations, folder + 'test_relations.json')\n\n # write rtype_lookup\n _write_to_json([\"OrgBased_In\", \"Located_In\", \"Live_In\", \"Kill\", \"Work_For\"], folder + 'rtype_lookup.json')\n\n","sub_path":"uncased-nomc/adjust/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628888522","text":"\"\"\"Display helper for misc stuff.\"\"\"\nfrom pollbot.i18n import i18n\nfrom pollbot.telegram.keyboard.misc import get_help_keyboard\n\n\ndef get_help_text_and_keyboard(user, current_category):\n \"\"\"Create the help message depending on the currently selected help category.\"\"\"\n categories = [\n 'creation',\n 'settings',\n 'notifications',\n 'management',\n 'languages',\n 'bugs',\n ]\n\n text = i18n.t(f'misc.help.{current_category}', locale=user.locale)\n keyboard = get_help_keyboard(user, categories, current_category)\n\n return text, keyboard\n","sub_path":"pollbot/display/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"253874868","text":"import dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom components import NavBar, Header, UserLoginCard, UserLogoutCard\n\n\ndef UsersPortal(username=None):\n if username is None:\n card = UserLoginCard()\n else:\n card = UserLogoutCard(username)\n\n return html.Div([\n Header(username),\n NavBar(),\n html.Br(),\n html.Br(),\n html.Br(),\n dbc.Container(card),\n ])\n","sub_path":"layouts/userportal.py","file_name":"userportal.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72398872","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[11]:\n\n\nimport sklearn\nimport pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scanpy as sc\nimport anndata\nimport re\nimport importlib.util\nspec = importlib.util.spec_from_file_location(\"ScanpyUtilsMT\", os.path.expanduser(\"~/code/pollye/MTsc/utils/ScanpyUtilsMT.py\"))\nsc_utils = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(sc_utils)\n\nheadpath='/wynton/scratch/mtschmitz/macaqueseq/'\nadatapaths=[os.path.join(headpath,x) for x in os.listdir(headpath)]\nsamplenames=[re.sub('_Out','',x) for x in os.listdir(headpath)]\nsubtractive=True\n\nfor adatapath,samplename in zip(np.array(adatapaths),np.array(samplenames)):\n sc.settings.figdir=os.path.expanduser('~/figs/'+str(subtractive)+'/'+samplename)\n if not os.path.exists(sc.settings.figdir):\n os.makedirs(sc.settings.figdir)\n if not os.path.exists(os.path.join(adatapath,'outs/ambientsubtracted'+str(subtractive)+'.h5ad')):\n continue\n adata=sc.read_10x_mtx(os.path.join(adatapath,'outs/filtered_feature_bc_matrix'),cache=True)\n sc.pp.filter_genes(adata, min_cells=10,inplace=True)\n sc.pp.filter_cells(adata,min_counts=5,inplace=True)\n ambinotadata=sc.read_h5ad(os.path.join(adatapath,'outs/ambientsubtracted'+str(subtractive)+'.h5ad'))\n sc.pp.filter_genes(ambinotadata, min_cells=10,inplace=True)\n sc.pp.filter_cells(ambinotadata,min_counts=5,inplace=True)\n cells=list(set(adata.obs.index) & set(ambinotadata.obs.index)) \n genes=list(set(adata.var.index) & set(ambinotadata.var.index)) \n \n ambinotadata._inplace_subset_obs(cells)\n ambinotadata._inplace_subset_var(genes)\n adata._inplace_subset_obs(cells)\n adata._inplace_subset_var(genes)\n sns.distplot(np.log10((adata.X-ambinotadata.X).sum(1).A1+1),kde=False)\n plt.savefig(os.path.join(sc.settings.figdir,'CountDifferences.png'))\n plt.close()\n \n condit='Original'\n sc.pp.normalize_total(adata, target_sum=1e4)\n sc.pp.log1p(adata)\n #vg=sc.pp.highly_variable_genes(adata,adata.shape[0],inplace=False)\n #adata._inplace_subset_var(vg['highly_variable'])\n sc.pp.scale(adata, max_value=10)\n sc.pp.pca(adata)\n sc.pp.neighbors(adata)\n sc.tl.umap(adata)\n sc.tl.leiden(adata)\n sc.pl.umap(adata, color=['leiden'],save=condit+\"Leiden\")\n sc_utils.marker_analysis(adata,variables=['leiden'],markerpath=os.path.expanduser('~/markers.txt'),subclass=True,prefix=condit)\n condit='Ambiaint'\n sc.pp.normalize_total(ambinotadata, target_sum=1e4)\n sc.pp.log1p(ambinotadata)\n #ambinotadata._inplace_subset_var(vg['highly_variable'])\n sc.pp.scale(ambinotadata, max_value=10)\n sc.pp.pca(ambinotadata)\n sc.pp.neighbors(ambinotadata)\n sc.tl.umap(ambinotadata)\n sc.tl.leiden(ambinotadata)\n sc.pl.umap(ambinotadata, color=['leiden'],save=condit+\"Leiden\")\n sc_utils.marker_analysis(ambinotadata,variables=['leiden'],markerpath=os.path.expanduser('~/markers.txt'),subclass=False,prefix=condit) \n pd.DataFrame([sc_utils.get_cluster_metrics(adata,rands=[],silhouettes=['X_umap','X_pca']),sc_utils.get_cluster_metrics(ambinotadata,rands=[],silhouettes=['X_umap','X_pca'])],index=['Original','Ambiaint']).to_csv(os.path.join(sc.settings.figdir,\"SilhouetteScores.csv\"))\n \n \n","sub_path":"notebooks/CompareELALDA.py","file_name":"CompareELALDA.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"225452681","text":"\"\"\"Data handling.\n\nA module which organises the datasets by locating files and filenames,\nreturning filename descriptions of all project input data, along with\npathnames where results should be stored. Additionally cleans data, e.g.,\nremoving errors due to model non-convergence and datasets with insufficient\nsample numbers.\n\"\"\"\n# imports\nimport os\nimport sys\nimport pandas as pd\nimport glob\nfrom pathlib import Path\nfrom datetime import datetime\nif sys.version_info >= (3, 8):\n from typing import TypedDict, Tuple\nelse:\n from typing import Tuple\n from typing_extensions import TypedDict\n\n\n# Helper functions\ndef get_date_time(\n) -> str:\n \"\"\"Gets current date.\n\n Module obtains current date and returns it as a string variable.\n This variable can then be used for outputting results into new\n folders labelled by date.\n \"\"\"\n now = datetime.now() # gets current date\n\n # converts to YYYY-MM-DD format, e.g., 2022-10-31\n dt_string = now.strftime(\"%Y-%m-%d\")\n\n return dt_string\n\n\ndef make_dir(path: Path\n ) -> None:\n \"\"\"Creates directory if it does not exist.\"\"\"\n if not os.path.exists(path):\n os.mkdir(path)\n\n\n# Folder paths\ndef get_path(study: str,\n folder: str\n ) -> Tuple[str, str]:\n \"\"\"Gets data/results folder path of chosen study.\n\n Args:\n study: Study name of interest (e.g., 'SixTestCompounds').\n folder: Folder of interest (e.g., 'results').\n\n Returns:\n Folder path (in string format) for data or results folder\n (as selected by user) related to study of choice.\n \"\"\"\n cwd = os.getcwd()\n path = f\"{cwd}\\\\{folder}\\\\{study}\\\\\"\n\n return path\n\n\n# Data filenames & filepaths\ndef get_files(study: str,\n dataset: str\n ) -> Tuple[list, list]:\n \"\"\"Gets list of filepaths and filenames.\n\n Searches dataset folder within chosen study and returns\n list of filepaths and filenames contained within.\n\n Args:\n study: Study name of interest (e.g., 'SixTestCompounds').\n dataset: Dataset of interest (e.g., '01_signals').\n \"\"\"\n study_data_path = get_path(study, 'data')\n dataset_path = f\"{study_data_path}{dataset}\"\n files = glob.glob(dataset_path + '*\\\\*')\n filenames = [Path(path).stem for path in files]\n\n return files, filenames\n\n\n# File metadata\ndef get_metadata(filename: str,\n files: Path\n ) -> TypedDict('metadata', {'substudy': str,\n 'drug': str,\n 'site': str,\n 'subject': int,\n 'day': int,\n 'signals': pd.DataFrame\n }\n ):\n \"\"\"Extracts study descriptions from filenames.\n\n This function allows the user to extract metadata from\n a filename along with the corresponding dataframe contained\n within the file. Works only when filename is formatted as\n a string containing study descriptors (metadata) separated\n by underscores, i.e.,\n filename = \"compound_site_RatNumber_dayNumber_dataType\"\n e.g., \"Asunaprevir_E_Rat2_2_Signals\"\n\n Args:\n filename: File name of interest.\n files: File of interest.\n\n Returns:\n A dict mapping keys to the corresponding metadata and\n signal data contained in csv file.\n \"\"\"\n filename_elements = filename.split('_')\n metadata = {}\n metadata['substudy'] = filename_elements[0]\n metadata['drug'] = filename_elements[1]\n metadata['site'] = filename_elements[2]\n metadata['subject'] = int(filename_elements[3][3:])\n metadata['day'] = int(filename_elements[4])\n metadata['signals'] = pd.read_csv(files)\n\n return metadata\n\n\n# Subdirectory paths\ndef get_subdir(parentdir: str,\n subdir_name: str\n ) -> str:\n \"\"\"Gets subdirectory path.\n\n Args:\n parentdir: Parent directory where subdirectory\n should be stored.\n subdir_name: Name of subdirectory.\n\n Returns:\n Subdirectory path name in string format.\n \"\"\"\n subdir_path = f\"{parentdir}{subdir_name}\\\\\"\n make_dir(subdir_path)\n\n return subdir_path\n\n\n# Results folders\ndef get_results_folder(study: str,\n folder_name: str,\n subfolder_name: str,\n extra_subfolder_name: str,\n filename: str,\n file_type: str\n ) -> str:\n \"\"\"Obtains results folder and subfolders.\n\n Args:\n study: Study name of interest (e.g., 'SixTestCompounds').\n folder_name: Results folder of interest (e.g., '02_effect_sizes').\n subfolder_name: Results subfolder of interest (e.g., 'figures'). If\n no subfolders are required use None.\n extra_subfolder_name: Extra results subfolder of interest (e.g.,\n 'per_Rat'). If no extra subfolders are required use None.\n filename: Chosen file name.\n file_type: File format, e.g., 'csv'.\n\n Returns:\n Directory path name (in string format) for storing results.\n \"\"\"\n make_dir('results')\n parent_dir = get_path(study, 'results')\n make_dir(parent_dir)\n dt_string = get_date_time()\n date_folder = get_subdir(parent_dir, dt_string)\n output_folder = get_subdir(date_folder, folder_name)\n\n if (subfolder_name is None) & (extra_subfolder_name is None):\n filepath = f\"{output_folder}\\\\{filename}\"\n\n elif (subfolder_name is not None) & (extra_subfolder_name is None):\n subfolder = get_subdir(output_folder, subfolder_name)\n filepath = f\"{subfolder}\\\\{filename}\"\n\n elif (subfolder_name is not None) & (extra_subfolder_name is not None):\n subfolder = get_subdir(output_folder, subfolder_name)\n extra_subfolder = get_subdir(subfolder, extra_subfolder_name)\n filepath = f\"{extra_subfolder}\\\\{filename}\"\n\n save_name = f\"{filepath}.{file_type}\"\n\n return save_name\n\n\n# Data cleaning\ndef remove_data_errors(parameter_data: pd.DataFrame,\n study: str\n ) -> pd.DataFrame:\n \"\"\"Cleans data.\n\n Removes computational fitting errors in biomarker prediction caused by\n non-convergence of the model fitting algorithm, i.e., the output of\n boundary values instead of true values, e.g., gadoxetate extraction\n fraction, E=100%.\n\n Args:\n parameter_data: DataFrame containing estimated parameter variables.\n study: Study name of interest (e.g., 'SixTestCompounds').\n\n Returns:\n Cleaned DataFrame.\n \"\"\"\n data_pivoted = pd.pivot_table(parameter_data,\n values='Value',\n columns=['Symbol'],\n index=['Substudy',\n 'Site',\n 'Drug',\n 'Rat',\n 'Day'])\n\n # Remove computational fitting errors based on subjects where gadoxetate\n # extraction fraction, E is close or equal to 100% (i.e., >= 99%)\n fit_errors = data_pivoted[data_pivoted['E'] >= 99.95]\n fit_errors_removed = (data_pivoted[~data_pivoted\n .index.isin(fit_errors.index)])\n\n # Save index metadata for computational fitting errors\n save_name = get_results_folder(study,\n '01_model_outputs',\n None,\n None,\n 'fit_errors',\n 'txt')\n with open(save_name, \"w\") as output:\n output.write(str(list([fit_errors.index])))\n\n cleaned_parameter_data = fit_errors_removed.stack().reset_index()\n cleaned_parameter_data.rename(columns={0: 'Value'}, inplace=True)\n\n return cleaned_parameter_data\n\n\ndef remove_insufficient_data(parameter_data: pd.DataFrame,\n study: str\n ) -> pd.DataFrame:\n \"\"\"Removes data with insufficient number of observations.\n\n Removes cases where only one acquisition per subject is present\n (i.e., day 1 or day 2 data are missing), or whole substudies\n where data for only 1 subject is present.\n\n Args:\n parameter_data: DataFrame containing estimated parameter variables.\n study: Study name of interest (e.g., 'Reproducibility').\n\n Returns:\n Cleaned DataFrame.\n \"\"\"\n data_pivoted = pd.pivot_table(parameter_data,\n values='Value',\n columns=['Symbol'],\n index=['Substudy',\n 'Drug',\n 'Site',\n 'Fstrength',\n 'Site_Fstrength',\n 'Time_period',\n 'Rat',\n 'Day'])\n # Remove subjects with missing acquisition on day 1 or day 2\n missing_days_removed = (data_pivoted[data_pivoted\n .groupby(['Substudy',\n 'Site',\n 'Rat'])\n .transform('count') > 1]\n .dropna())\n missing_days_removed_clean = missing_days_removed.stack().reset_index()\n missing_days_removed_clean.rename(columns={0: 'Value'}, inplace=True)\n\n # Count number of substudies with only 1 subject\n counts = missing_days_removed_clean.groupby(['Symbol',\n 'Substudy',\n 'Site',\n 'Drug',\n 'Day'])['Rat'].count()\n\n # Remove substudies with only 1 subject\n substudy_to_drop = []\n for i in counts.index:\n if counts[i] == 1:\n substudy_to_drop.append(i[1])\n insufficient_data_removed = (missing_days_removed_clean[~missing_days_removed_clean['Substudy']\n .isin(substudy_to_drop)])\n insufficient_data_removed.reset_index(drop=True, inplace=True)\n\n return insufficient_data_removed\n","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":10585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370821285","text":"# Copyright (c) 2015\n#\n# All rights reserved.\n#\n# This file is distributed under the Clear BSD license.\n# The full text can be found in LICENSE in the root directory.\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\nimport random\nimport re\nimport string\nimport time\n\nwlan_iface = None\n\n\ndef wifi_interface(console):\n \"\"\"This method returns the wifi interface\n\n :param console: CM console object\n :type console: object\n :returns: The wlan_iface of the modem wlan0/ath0 or None\n :rtype: string\n \"\"\"\n global wlan_iface\n\n if wlan_iface is None:\n console.sendline('uci show wireless | grep wireless.*0.*type=')\n i = console.expect([\"type='?mac80211'?\", \"type='?qcawifi'?\"])\n if i == 0:\n wlan_iface = \"wlan0\"\n elif i == 1:\n wlan_iface = \"ath0\"\n else:\n wlan_iface = None\n\n return wlan_iface\n\n\ndef randomSSIDName():\n \"\"\"This method returns the random SSID name used to set on CM\n\n :returns: The SSID generated randomly\n :rtype: string\n \"\"\"\n return 'WIFI-' + ''.join(\n random.sample(string.ascii_lowercase + string.digits, 10))\n\n\ndef uciSetWifiSSID(console, ssid):\n \"\"\"This method sets the WiFi SSID on the CM\n\n :param console: CM console object\n :type console: object\n :param ssid: SSID to be used to set on CM\n :type ssid: string\n \"\"\"\n console.sendline(\n 'uci set wireless.@wifi-iface[0].ssid=%s; uci commit wireless; wifi' %\n ssid)\n console.expect_prompt()\n\n\ndef uciSetWifiMode(console, radio, hwmode):\n \"\"\"This method sets the WiFi hwmode as per the radio over CM\n\n :param console: CM console object\n :type console: object\n :param radio: radio to set hwmode\n :type radio: string\n :param hwmode: hwmode to be set over the CM\n :type hwmode: string\n \"\"\"\n console.sendline('uci set wireless.wifi%s.hwmode=%s; uci commit wireless' %\n (radio, hwmode))\n console.expect_prompt()\n\n\ndef uciSetChannel(console, radio, channel):\n \"\"\"This method sets the channel as per the radio over CM\n\n :param console: CM console object\n :type console: object\n :param radio: radio to set hwmode\n :type radio: string\n :param channel: channel to be set over the CM\n :type channel: string\n \"\"\"\n console.sendline(\n 'uci set wireless.wifi%s.channel=%s; uci commit wireless' %\n (radio, channel))\n console.expect_prompt()\n\n\ndef enable_wifi(board, index=0):\n \"\"\"This method enables the WiFi as per the index specified.\n\n :param board: board object\n :type board: object\n :param index: index to be used to enable, defaults to 0\n :type index: int\n \"\"\"\n board.sendline(\n '\\nuci set wireless.@wifi-device[%s].disabled=0; uci commit wireless' %\n index)\n board.expect('uci set')\n board.expect_prompt()\n board.sendline('wifi')\n board.expect('wifi')\n board.expect_prompt(timeout=50)\n time.sleep(20)\n\n\ndef enable_all_wifi_interfaces(board):\n \"\"\"This method enables all the WiFi interface available over the board\n\n :param board: board object\n :type board: object\n \"\"\"\n board.sendline('\\nuci show wireless | grep disabled')\n board.expect('grep disabled')\n board.expect_prompt()\n \"\"\"\n The following re.findall should return list of settings:\n ['wireless.radio0.disabled', 'wireless.radio1.disabled']\n \"\"\"\n settings = re.findall(r'([\\w\\.]+)=\\d', board.before)\n for s in settings:\n board.sendline('uci set %s=0' % s)\n board.expect_prompt()\n board.sendline('uci commit wireless')\n board.expect_prompt()\n board.sendline('wifi')\n board.expect_prompt(timeout=50)\n\n\ndef disable_wifi(board, wlan_iface=\"ath0\"):\n \"\"\"This method disables the WiFi over the interface specified\n\n :param board: board object\n :type board: object\n :param wlan_iface: the WiFi interface to be disabled defaults to \"ath0\"\n :type wlan_iface: string\n \"\"\"\n board.sendline(\n 'uci set wireless.@wifi-device[0].disabled=1; uci commit wireless')\n board.expect('uci set')\n board.expect_prompt()\n board.sendline('wifi')\n board.expect_prompt()\n board.sendline('iwconfig %s' % wlan_iface)\n board.expect_prompt()\n\n\ndef wifi_on(board):\n \"\"\"This method returns the WiFi enabled status over the CM True if enabled else False\n\n :param board: board object\n :type board: object\n :returns: The WiFi enabled status of the CM\n :rtype: boolean\n \"\"\"\n board.sendline('\\nuci show wireless.@wifi-device[0].disabled')\n try:\n board.expect('disabled=0', timeout=5)\n board.expect_prompt()\n return True\n except:\n return False\n\n\ndef wifi_get_info(board, wlan_iface):\n \"\"\"This method gets the WiFi information about the board like essid, channel, rate, freq\n\n :param board: board object\n :type board: object\n :param wlan_iface: The WiFi interface to be used to get details.\n :type wlan_iface: string\n :raises: Assert Exception\n \"\"\"\n try:\n if \"ath\" in wlan_iface:\n board.sendline('iwconfig %s' % wlan_iface)\n board.expect('ESSID:\"(.*)\"')\n essid = board.match.group(1)\n board.expect(\"Frequency:([^ ]+)\")\n freq = board.match.group(1)\n essid = board.match.group(1)\n board.expect('Bit Rate[:=]([^ ]+) ')\n rate = float(board.match.group(1))\n board.expect_prompt()\n # TODO: determine channel\n channel = -1.0\n elif \"wlan\" in wlan_iface:\n board.sendline(\"iwinfo wlan0 info\")\n board.expect('ESSID: \"(.*)\"')\n essid = board.match.group(1)\n board.expect(r'Channel:\\s*(\\d+)\\s*\\(([\\d\\.]+)\\s*GHz')\n channel = int(board.match.group(1))\n freq = float(board.match.group(2))\n board.expect('Bit Rate: ([^ ]+)')\n try:\n rate = float(board.match.group(1))\n except:\n rate = -1.0\n board.expect_prompt()\n else:\n print(\"Unknown wireless type\")\n except:\n board.sendline('dmesg')\n board.expect_prompt()\n raise\n\n return essid, channel, rate, freq\n\n\ndef wait_wifi_up(board, num_tries=10, sleep=15, wlan_iface=\"ath0\"):\n \"\"\"This method waits for the WiFi Bit Rate to be != 0 default 10 trials with a wait of 15 seconds for each trial.\n\n :param board: board object\n :type board: object\n :param num_tries: number of trials, defaults to 10\n :type num_tries: int\n :param sleep: number of seconds to wait, defaults to 15\n :type sleep: int\n :param wlan_iface: Wireless interface to wait for, defaults to \"ath0\"\n :type wlan_iface: string\n :raises: Assert Exception\n \"\"\"\n for _ in range(num_tries):\n time.sleep(sleep)\n essid, channel, rate, freq = wifi_get_info(board, wlan_iface)\n if \"ath\" in wlan_iface and rate > 0:\n return\n if \"wlan\" in wlan_iface == \"wlan0\" and essid != \"\" and channel != 0 and freq != 0.0:\n return\n\n if rate == 0:\n print(\"\\nWiFi did not come up. Bit Rate still 0.\")\n assert False\n\n\ndef wifi_add_vap(console, phy, ssid):\n \"\"\"This method adds virtual access point on the interface specified as per the ssid provided.\n\n :param console: console object\n :type console: object\n :param phy: physical interface to be used\n :type phy: string\n :param ssid: ssid to be set for VAP\n :type ssid: string\n \"\"\"\n console.sendline('uci add wireless wifi-iface')\n console.expect_prompt()\n console.sendline('uci set wireless.@wifi-iface[-1].device=\"%s\"' % phy)\n console.expect_prompt()\n console.sendline('uci set wireless.@wifi-iface[-1].network=\"lan\"')\n console.expect_prompt()\n console.sendline('uci set wireless.@wifi-iface[-1].mode=\"ap\"')\n console.expect_prompt()\n console.sendline('uci set wireless.@wifi-iface[-1].ssid=\"%s\"' % ssid)\n console.expect_prompt()\n console.sendline('uci set wireless.@wifi-iface[-1].encryption=\"none\"')\n console.expect_prompt()\n console.sendline('uci commit')\n console.expect_prompt()\n\n\ndef wifi_del_vap(console, index):\n \"\"\"This method deletes virtual access point on the interface specified as per the index provided.\n\n :param console: console object\n :type console: object\n :param index: index to be used\n :type index: int\n \"\"\"\n console.sendline('uci delete wireless.@wifi-iface[%s]' % index)\n console.expect_prompt()\n console.sendline('uci commit')\n console.expect_prompt()\n\n\ndef uciSetWifiSecurity(board, vap_iface, security):\n \"\"\"This method sets the WiFi security on the VAP interface on the board\n\n :param board: board object\n :type board: object\n :param vap_iface: interface to be used\n :type vap_iface: string\n :param security: security to be set\n :type security: string\n \"\"\"\n if security.lower() in ['none']:\n print(\"Setting security to none.\")\n board.sendline('uci set wireless.@wifi-iface[%s].encryption=none' %\n vap_iface)\n board.expect_prompt()\n elif security.lower() in ['wpa-psk']:\n print(\"Setting security to WPA-PSK.\")\n board.sendline('uci set wireless.@wifi-iface[%s].encryption=psk+tkip' %\n vap_iface)\n board.expect_prompt()\n board.sendline(\n 'uci set wireless.@wifi-iface[%s].key=1234567890abcdexyz' %\n vap_iface)\n board.expect_prompt()\n elif security.lower() in ['wpa2-psk']:\n print(\"Setting security to WPA2-PSK.\")\n board.sendline(\n 'uci set wireless.@wifi-iface[%s].encryption=psk2+ccmp' %\n vap_iface)\n board.expect_prompt()\n board.sendline(\n 'uci set wireless.@wifi-iface[%s].key=1234567890abcdexyz' %\n vap_iface)\n board.expect_prompt()\n\n\nclass wifi_stub():\n apply_changes_no_delay = True\n\n # The above variable can tweak the behavior of the below functions\n # If it is set to True, it will apply the changes after setting wifi parameters\n # If it is set to False, it will not save any changes & apply_changes() will be skipped\n def enable_wifi(self, *args, **kwargs):\n \"\"\"This method is stub for enabling wifi on CM\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_ssid(self, *args, **kwargs):\n \"\"\"This method is stub to set SSID\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_broadcast(self, *args, **kwargs):\n \"\"\"This method is stub to set boardcast\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_security(self, *args, **kwargs):\n \"\"\"This method is stub to set security\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_password(self, *args, **kwargs):\n \"\"\"This method is stub to set password\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def enable_channel_utilization(self, *args, **kwargs):\n \"\"\"This method is stub to enable channel utilization\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_operating_mode(self, *args, **kwargs):\n \"\"\"This method is stub to set operating mode\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_bandwidth(self, *args, **kwargs):\n \"\"\"This method is stub to set bandwidth\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def set_channel_number(self, *args, **kwargs):\n \"\"\"This method is stub to enable channel utilization\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_wifi_enabled(self, *args, **kwargs):\n \"\"\"This method is stub to get WiFi enabled\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_ssid(self, *args, **kwargs):\n \"\"\"This method is stub to get SSID\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_security(self, *args, **kwargs):\n \"\"\"This method is stub to get security mode\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_password(self, *args, **kwargs):\n \"\"\"This method is stub to get password\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_channel_utilization(self, *args, **kwargs):\n \"\"\"This method is stub to get channel utilization\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_operating_mode(self, *args, **kwargs):\n \"\"\"This method is stub to get operating mode\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_bandwidth(self, *args, **kwargs):\n \"\"\"This method is stub to get bandwidth\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_broadcast(self, *args, **kwargs):\n \"\"\"This method is stub to get the broadcast\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def get_channel_number(self, *args, **kwargs):\n \"\"\"This method is stub to get the channel number\n\n :param self: self object\n :type self: object\n :param args: arguments to be used if any\n :type args: NA\n :param kwargs: extra arguments to be used\n :type kwargs: NA\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def prepare(self):\n \"\"\"This method is stub\n\n :param self: self object\n :type self: object\n \"\"\"\n pass\n\n def cleanup(self):\n \"\"\"This method is stub\n\n :param self: self object\n :type self: object\n \"\"\"\n pass\n\n def apply_changes(self):\n \"\"\"This method is stub used to save the configs to be modified\n\n :param self: self object\n :type self: object\n \"\"\"\n pass\n\n\nclass wifi_client_stub():\n def enable_wifi(self):\n \"\"\"This method is WiFi client stub used to enable WiFi/ make the WiFi interface UP\n\n :param self: self object\n :type self: object\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def disable_wifi(self):\n \"\"\"This method is WiFi client stub used to enable WiFi/ make the WiFi interface DOWN\n\n :param self: self object\n :type self: object\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def disable_and_enable_wifi(self):\n \"\"\"This method is WiFi client stub used to disbale and enable WiFi/ make the WiFi interface DOWN and UP\n\n :param self: self object\n :type self: object\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def wifi_scan(self):\n \"\"\"This method is WiFi client stub used to scan for SSIDs on a particular radio, and return a list of SSID\n\n :param self: self object\n :type self: object\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n \"\"\"\n this code does not execute, but rather serves as an example for the API\n return \"SSID: SSID: ..\"\n \"\"\"\n\n def wifi_check_ssid(self, ssid_name):\n \"\"\"This method is WiFi client stub used to scan for paticular SSID\n\n :param self: self object\n :type self: object\n :param ssid_name: ssid name to be scanned for\n :type ssid_name: string\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n \"\"\"\n this code does not execute, but rather serves as an example for the API\n return True if found\n return False if not found\n \"\"\"\n\n def wifi_connect(self, ssid_name, password, security_mode):\n \"\"\"This method is WiFi client stub used to connect to wifi either with ssid name and password or with ssid name alone\n\n :param self: self object\n :type self: object\n :param ssid_name: ssid name to be scanned for\n :type ssid_name: string\n :param password: password to be used to connect to SSID\n :type password: string\n :param security_mode: security mode of WiFi\n :type security_mode: string\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def wifi_connectivity_verify(self):\n \"\"\"This method is WiFi client stub used to verify wifi connectivity\n\n :param self: self object\n :type self: object\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n \"\"\"\n this code does not execute, but rather serves as an example for the API\n return True or False\n \"\"\"\n\n def wifi_disconnect(self):\n \"\"\"This method is WiFi client stub used to disconnect WiFi\n\n :param self: self object\n :type self: object\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n\n def wifi_change_region(self, country):\n \"\"\"This method is WiFi client stub used to change the country\n\n :param self: self object\n :type self: object\n :param country: country to change to\n :type country: string\n :raises: Exception \"Not implemented\"\n \"\"\"\n raise Exception(\"Not implemented!\")\n","sub_path":"boardfarm/lib/wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":21575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"81195715","text":"from selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom urllib.request import Request, urlopen\n\n# req = Request('http://movie.naver.com/movie/sdb/rank/rmovie.nhn')\n# req = urlopen(req)\n# html = res.read().decode('cp949')\n\n\npath = \"D:\\WebDr\\chromedriver.exe\"\ndriver = webdriver.Chrome(path)\n# driver = webdriver.Firefox()\n# driver = webdriver.Ie()\n\ndriver.set_page_load_timeout(10)\ndriver.get(\"https://www.op.gg/\")\ndriver.find_element_by_name(\"userName\").send_keys(\"필동호랭이\")\ndriver.find_element_by_class_name(\"챔피언 분석\").click()\ntime.sleep(4)\ndriver.quit()\n\ndef ex1():\n bs = BeautifulSoup(html, 'html.parser')\n print(bs, type(bs))\n\n tag = bs.a\n print(tag, type(tag))\ndef ex2():\n bs = BeautifulSoup(html, 'html.parser')\n\n tag = bs.td\n print(tag['class'])\n print(tag['id'])\n print(tag.attrs)\n\n tag = bs.div\n print(tag['id'])\n\ndef ex3():\n bs = BeautifulSoup(html, 'html.parser')\n\n tag = bs.find('div', attrs={'class': 'tit3'})\n print(tag)\n\n tag = bs.find('div')\n print(tag)\n\n tag = bs.find('td', attrs={'class': 'not_exist'})\n print(tag)\n\n tag = bs.find(attrs={'title': '범죄도시'})\n print(tag)\n\n\n\n\n\n","sub_path":"crawling/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109222169","text":"import hashlib\nimport hmac\nfrom Crypto.Random import get_random_bytes\n\nmsg = b'This is the message'\nkey = get_random_bytes(32)\n\n\nblake = hashlib.blake2b(key=key, digest_size=32)\nblake.update(msg)\nprint(\"BLAKE = \" + blake.hexdigest())\n\n####################\n\nmac_object = hmac.new(key, msg, hashlib.sha256)\nhmac_sha256 = mac_object.hexdigest()\nprint(\"HMAC-SHA256 = \" + hmac_sha256)\n\nmsg1 = b'This is the new message'\nmac_object_1 = hmac.new(key, msg1, hashlib.sha256)\nhmac_sha256_1 = mac_object_1.hexdigest()\nprint(\"HMAC-SHA256_1 = \" + hmac_sha256_1)\n\nif hmac.compare_digest(mac_object_1.digest(), mac_object.digest()):\n print(\"HMAC correctly verified: messages are identical\")\nelse:\n print(\"HMAC are different\")\n","sub_path":"AY2021/py-basics/symmetric/live/11.HMAC_hashlib.py","file_name":"11.HMAC_hashlib.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"108761771","text":"#Name: Sharath Byakod\n#Date: 4/10/18\n#Period: 4\n\nimport sys\nimport urllib.request\n\ninput = sys.argv[1]\n\ntry:\n url = urllib.request.urlopen(input).read()\n print(url)\nexcept:\n file = open(input, 'r')\n text = file.read().strip()\n file.close()","sub_path":"Artificial Intelligence/Semester 2/Scrabble:Boggle/util_slurp.py","file_name":"util_slurp.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613721990","text":"# Grace Kaylor\r\n#\r\n# The purpose of this project is to calculate the overall sentiment rating of a\r\n# text document in English. The user is prompted to enter a file name. The\r\n# program then reads the file and parses it into sentences. The sentiment of\r\n# each sentence is then calculated using two support files (positive.txt and\r\n# negative.txt courtesy of: Minqing Hu and Bing Liu. (Mining and Summarizing\r\n# Customer Reviews.\" Proceedings of the ACM SIGKDD International Conference\r\n# on Knowledge Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, \r\n# Washington, USA.)). The sentiment is calculated by giving +1 points to words\r\n# in the positive word list, and -1 points to words in the negative words list,\r\n# and +0 for words in neither. The average result (total points divided by the\r\n# number of words in the sentence) of each sentence is then displayed in a\r\n# scrolled text window using tkinter, along with the average of the entire file.\r\n# The overall sentiment value (positive, negative, neutral) is displayed as well.\r\n# The user is given the option to exit, save the file to any location and by\r\n# any name, or to change the background color (repeatedly). The matplotlib is\r\n# all commented it out, but it can be used to display the graph of the sentences\r\n# and their ratings.\r\n#\r\n# Dependencies:\r\n# finalProjectClean.py\r\n# negative-words.txt\r\n# positive-words.txt\r\n#\r\n# Available Files:\r\n# alice.txt\r\n# declaration.txt\r\n\r\nimport re\r\nimport finalProjectClean\r\nfrom tkinter import *\r\nfrom tkinter.filedialog import asksaveasfile\r\nfrom tkinter.scrolledtext import ScrolledText\r\nimport random\r\n\r\n# Can comment out MatPlotLib \r\n# import matplotlib.pyplot as plt\r\n\r\n\r\ndef main():\r\n # Prompts the user for a file name\r\n getFile = True\r\n while (getFile):\r\n file = input(\"Enter File Name: \")\r\n try:\r\n # http://ptrckprry.com/course/ssd/data/positive-words.txt\r\n p = open('positive-words.txt', 'r')\r\n # http://ptrckprry.com/course/ssd/data/negative-words.txt\r\n n = open('negative-words.txt', 'r')\r\n a = open(file, 'r')\r\n getFile = False\r\n except:\r\n print(\"\\nFile could not be opened.\\n\")\r\n \r\n # Reads the positive and negative word texts, and the users text\r\n positiveWords = p.read()\r\n negativeWords = n.read()\r\n textWords = a.read()\r\n \r\n p.close()\r\n n.close()\r\n a.close()\r\n\r\n # Parses the positive word list\r\n positiveWords = parse(positiveWords)\r\n # Parses the negative word list\r\n negativeWords = parse(negativeWords)\r\n\r\n # Cleans the text words and derives the sentence list\r\n cleanText = finalProjectClean.Clean(textWords)\r\n cleanText.getSentenceList()\r\n \r\n # Removes punction from the list of sentences\r\n sentenceList = cleanText.removePunctuationInSentences()\r\n\r\n # Calculates the sentiment rating of the word list\r\n # Gets back a dictionary of sentences mapped to their averages, and the average rating overall\r\n sentimentDict, average = calculateSentiment(sentenceList, positiveWords, negativeWords)\r\n display(cleanText.originalSentenceList, sentimentDict, average, file)\r\n\r\n# Parses the list of positive and negative texts\r\ndef parse(allWords):\r\n allWords = allWords.split(\"\\n\")\r\n # Removes header\r\n allWords = allWords[30:]\r\n return allWords\r\n\r\n# Caclulates the sentiment rating of the text \r\ndef calculateSentiment(sentenceList, positiveList, negativeList):\r\n sentiment = {}\r\n sentenceTotal = 0\r\n totalSentences = 0\r\n # Splits the sentences on words\r\n for sentence in sentenceList:\r\n sentence = sentence.split(\" \")\r\n total = 0\r\n for i in range (len(sentence)):\r\n word = sentence[i]\r\n # Removes invalid words\r\n if word == \"\" or word == \" \" or word == \"\\n\":\r\n continue\r\n # If word in positive word list\r\n if word in positiveList:\r\n total += 1\r\n # If word in negative word list\r\n elif word in negativeList:\r\n total -= 1\r\n # If word preceded by not, never, or nothing\r\n elif ((word == \"not\") or (word == \"never\") or (word == \"nothing\")) and (sentence[i+1] in positiveList):\r\n # - 1 for not, -1 for next word, skip next word\r\n total -= 2\r\n i = i + 1\r\n # If word preceded by not, never, or nothing\r\n elif ((word == \"not\") or (word == \"never\") or (word == \"nothing\")) and (sentence[i+1] in negativeList):\r\n # +1 for not, +1 for next word, skip next word\r\n total += 2\r\n i = i + 1\r\n else:\r\n total += 0\r\n totalSentences += 1\r\n sentenceTotal += total\r\n # Rejoins the sentences\r\n sentiment[\" \".join(sentence)] = total\r\n \r\n # Caculates the average sentiment rating by diving the sum of all of the\r\n # sentence ratings by the number of sentences\r\n average = sentenceTotal/totalSentences\r\n \r\n return sentiment, average\r\n \r\n# Displays the sentiment data \r\ndef display(originalSentenceList, sentiment, average, file):\r\n tk = Tk()\r\n\r\n # MatPlotLib\r\n # plt.figure()\r\n\r\n #create a scrolled text field\r\n st = ScrolledText(tk)\r\n st.pack()\r\n\r\n fileName = \"FILE NAME: \" + file + \"\\n\"\r\n \r\n # Adds the file name to the text window\r\n st.insert(INSERT, fileName)\r\n \r\n total = \"TOTAL SENTIMENT RATING: \" + str(average) + \"\\n\"\r\n \r\n # Adds the total to the text window\r\n st.insert(INSERT, total)\r\n\r\n # Determines if the average is positive, negative, or neutral\r\n if (average > 0):\r\n overall = \"OVERALL, THIS TEXT IS POSITIVE\\n\\n\"\r\n st.insert(INSERT,overall)\r\n elif (average < 0):\r\n overall = \"OVERALL, THIS TEXT IS NEGATIVE\\n\\n\"\r\n st.insert(INSERT,overall)\r\n else:\r\n overall = \"OVERALL, THIS TEXT IS NETURAL\\n\\n\"\r\n st.insert(INSERT,overall)\r\n \r\n i = 0\r\n for k, v in sentiment.items():\r\n # Adds the setence sentiment total to the text window\r\n value = str(v) + \":\\n\\n\"\r\n st.insert(INSERT,value)\r\n \r\n # Adds the sentence to the text window\r\n key = k + \"\\n\\n\"\r\n st.insert(INSERT,key)\r\n \r\n # Adds the divider to the text window\r\n divider = (\"-\" * 80) + \"\\n\\n\"\r\n st.insert(INSERT,divider)\r\n\r\n # Optional for MatPlotLib\r\n # plt.bar(i, v);\r\n \r\n i += 1\r\n \r\n # Make a quit button\r\n b = Button(\r\n tk,\r\n text='Quit',\r\n command=tk.destroy,\r\n pady = 20,\r\n padx = 88\r\n )\r\n # Display that button\r\n b.pack(side=LEFT)\r\n \r\n # Make a save button\r\n s = Button(\r\n tk,\r\n text = 'Save',\r\n command = lambda : save(st,tk),\r\n pady = 20,\r\n padx = 88\r\n )\r\n # Display button\r\n s.pack(side=LEFT)\r\n \r\n # Make a button to change the background color repeatedly\r\n c = Button(\r\n tk,\r\n text = 'Click Me',\r\n command = lambda : changeBg(st),\r\n pady = 20,\r\n padx = 88\r\n )\r\n # Display the button\r\n c.pack(side=LEFT)\r\n \r\n # Optional code to print out a graph using MatLibPlot\r\n # plt.xlabel(\"Sentence\")\r\n # plt.ylabel(\"Rating\")\r\n # plt.title(\"Sentence Sentiment Rating Averages\")\r\n # plt.show()\r\n \r\n # wait for something to happen\r\n mainloop()\r\n \r\n# Changes the color of the background from the list of options\r\ndef changeBg(st):\r\n # List courtesy of http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter\r\n \r\n colors = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace',\r\n 'linen', 'antique white', 'papaya whip', 'blanched almond', 'bisque', 'peach puff',\r\n 'navajo white', 'lemon chiffon', 'mint cream', 'azure', 'alice blue', 'lavender',\r\n 'lavender blush', 'misty rose', 'dark slate gray', 'dim gray', 'slate gray',\r\n 'light slate gray', 'gray', 'light grey', 'midnight blue', 'navy', 'cornflower blue', 'dark slate blue',\r\n 'slate blue', 'medium slate blue', 'light slate blue', 'medium blue', 'royal blue', 'blue',\r\n 'dodger blue', 'deep sky blue', 'sky blue', 'light sky blue', 'steel blue', 'light steel blue',\r\n 'light blue', 'powder blue', 'pale turquoise', 'dark turquoise', 'medium turquoise', 'turquoise',\r\n 'cyan', 'light cyan', 'cadet blue', 'medium aquamarine', 'aquamarine', 'dark green', 'dark olive green',\r\n 'dark sea green', 'sea green', 'medium sea green', 'light sea green', 'pale green', 'spring green',\r\n 'lawn green', 'medium spring green', 'green yellow', 'lime green', 'yellow green',\r\n 'forest green', 'olive drab', 'dark khaki', 'khaki', 'pale goldenrod', 'light goldenrod yellow',\r\n 'light yellow', 'yellow', 'gold', 'light goldenrod', 'goldenrod', 'dark goldenrod', 'rosy brown',\r\n 'indian red', 'saddle brown', 'sandy brown',\r\n 'dark salmon', 'salmon', 'light salmon', 'orange', 'dark orange',\r\n 'coral', 'light coral', 'tomato', 'orange red', 'red', 'hot pink', 'deep pink', 'pink', 'light pink',\r\n 'pale violet red', 'maroon', 'medium violet red', 'violet red',\r\n 'medium orchid', 'dark orchid', 'dark violet', 'blue violet', 'purple', 'medium purple',\r\n 'thistle', 'snow2', 'snow3',\r\n 'snow4', 'seashell2', 'seashell3', 'seashell4', 'AntiqueWhite1', 'AntiqueWhite2',\r\n 'AntiqueWhite3', 'AntiqueWhite4', 'bisque2', 'bisque3', 'bisque4', 'PeachPuff2',\r\n 'PeachPuff3', 'PeachPuff4', 'NavajoWhite2', 'NavajoWhite3', 'NavajoWhite4',\r\n 'LemonChiffon2', 'LemonChiffon3', 'LemonChiffon4', 'cornsilk2', 'cornsilk3',\r\n 'cornsilk4', 'ivory2', 'ivory3', 'ivory4', 'honeydew2', 'honeydew3', 'honeydew4',\r\n 'LavenderBlush2', 'LavenderBlush3', 'LavenderBlush4', 'MistyRose2', 'MistyRose3',\r\n 'MistyRose4', 'azure2', 'azure3', 'azure4', 'SlateBlue1', 'SlateBlue2', 'SlateBlue3',\r\n 'SlateBlue4', 'RoyalBlue1', 'RoyalBlue2', 'RoyalBlue3', 'RoyalBlue4', 'blue2', 'blue4',\r\n 'DodgerBlue2', 'DodgerBlue3', 'DodgerBlue4', 'SteelBlue1', 'SteelBlue2',\r\n 'SteelBlue3', 'SteelBlue4', 'DeepSkyBlue2', 'DeepSkyBlue3', 'DeepSkyBlue4',\r\n 'SkyBlue1', 'SkyBlue2', 'SkyBlue3', 'SkyBlue4', 'LightSkyBlue1', 'LightSkyBlue2',\r\n 'LightSkyBlue3', 'LightSkyBlue4', 'SlateGray1', 'SlateGray2', 'SlateGray3',\r\n 'SlateGray4', 'LightSteelBlue1', 'LightSteelBlue2', 'LightSteelBlue3',\r\n 'LightSteelBlue4', 'LightBlue1', 'LightBlue2', 'LightBlue3', 'LightBlue4',\r\n 'LightCyan2', 'LightCyan3', 'LightCyan4', 'PaleTurquoise1', 'PaleTurquoise2',\r\n 'PaleTurquoise3', 'PaleTurquoise4', 'CadetBlue1', 'CadetBlue2', 'CadetBlue3',\r\n 'CadetBlue4', 'turquoise1', 'turquoise2', 'turquoise3', 'turquoise4', 'cyan2', 'cyan3',\r\n 'cyan4', 'DarkSlateGray1', 'DarkSlateGray2', 'DarkSlateGray3', 'DarkSlateGray4',\r\n 'aquamarine2', 'aquamarine4', 'DarkSeaGreen1', 'DarkSeaGreen2', 'DarkSeaGreen3',\r\n 'DarkSeaGreen4', 'SeaGreen1', 'SeaGreen2', 'SeaGreen3', 'PaleGreen1', 'PaleGreen2',\r\n 'PaleGreen3', 'PaleGreen4', 'SpringGreen2', 'SpringGreen3', 'SpringGreen4',\r\n 'green2', 'green3', 'green4', 'chartreuse2', 'chartreuse3', 'chartreuse4',\r\n 'OliveDrab1', 'OliveDrab2', 'OliveDrab4', 'DarkOliveGreen1', 'DarkOliveGreen2',\r\n 'DarkOliveGreen3', 'DarkOliveGreen4', 'khaki1', 'khaki2', 'khaki3', 'khaki4',\r\n 'LightGoldenrod1', 'LightGoldenrod2', 'LightGoldenrod3', 'LightGoldenrod4',\r\n 'LightYellow2', 'LightYellow3', 'LightYellow4', 'yellow2', 'yellow3', 'yellow4',\r\n 'gold2', 'gold3', 'gold4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'goldenrod4',\r\n 'DarkGoldenrod1', 'DarkGoldenrod2', 'DarkGoldenrod3', 'DarkGoldenrod4',\r\n 'RosyBrown1', 'RosyBrown2', 'RosyBrown3', 'RosyBrown4', 'IndianRed1', 'IndianRed2',\r\n 'IndianRed3', 'IndianRed4', 'sienna1', 'sienna2', 'sienna3', 'sienna4', 'burlywood1',\r\n 'burlywood2', 'burlywood3', 'burlywood4', 'wheat1', 'wheat2', 'wheat3', 'wheat4', 'tan1',\r\n 'tan2', 'tan4', 'chocolate1', 'chocolate2', 'chocolate3', 'firebrick1', 'firebrick2',\r\n 'firebrick3', 'firebrick4', 'brown1', 'brown2', 'brown3', 'brown4', 'salmon1', 'salmon2',\r\n 'salmon3', 'salmon4', 'LightSalmon2', 'LightSalmon3', 'LightSalmon4', 'orange2',\r\n 'orange3', 'orange4', 'DarkOrange1', 'DarkOrange2', 'DarkOrange3', 'DarkOrange4',\r\n 'coral1', 'coral2', 'coral3', 'coral4', 'tomato2', 'tomato3', 'tomato4', 'OrangeRed2',\r\n 'OrangeRed3', 'OrangeRed4', 'red2', 'red3', 'red4', 'DeepPink2', 'DeepPink3', 'DeepPink4',\r\n 'HotPink1', 'HotPink2', 'HotPink3', 'HotPink4', 'pink1', 'pink2', 'pink3', 'pink4',\r\n 'LightPink1', 'LightPink2', 'LightPink3', 'LightPink4', 'PaleVioletRed1',\r\n 'PaleVioletRed2', 'PaleVioletRed3', 'PaleVioletRed4', 'maroon1', 'maroon2',\r\n 'maroon3', 'maroon4', 'VioletRed1', 'VioletRed2', 'VioletRed3', 'VioletRed4',\r\n 'magenta2', 'magenta3', 'magenta4', 'orchid1', 'orchid2', 'orchid3', 'orchid4', 'plum1',\r\n 'plum2', 'plum3', 'plum4', 'MediumOrchid1', 'MediumOrchid2', 'MediumOrchid3',\r\n 'MediumOrchid4', 'DarkOrchid1', 'DarkOrchid2', 'DarkOrchid3', 'DarkOrchid4',\r\n 'purple1', 'purple2', 'purple3', 'purple4', 'MediumPurple1', 'MediumPurple2',\r\n 'MediumPurple3', 'MediumPurple4', 'thistle1', 'thistle2', 'thistle3', 'thistle4',\r\n 'gray1', 'gray2', 'gray3', 'gray4', 'gray5', 'gray6', 'gray7', 'gray8', 'gray9', 'gray10',\r\n 'gray11', 'gray12', 'gray13', 'gray14', 'gray15', 'gray16', 'gray17', 'gray18', 'gray19',\r\n 'gray20', 'gray21', 'gray22', 'gray23', 'gray24', 'gray25', 'gray26', 'gray27', 'gray28',\r\n 'gray29', 'gray30', 'gray31', 'gray32', 'gray33', 'gray34', 'gray35', 'gray36', 'gray37',\r\n 'gray38', 'gray39', 'gray40', 'gray42', 'gray43', 'gray44', 'gray45', 'gray46', 'gray47',\r\n 'gray48', 'gray49', 'gray50', 'gray51', 'gray52', 'gray53', 'gray54', 'gray55', 'gray56',\r\n 'gray57', 'gray58', 'gray59', 'gray60', 'gray61', 'gray62', 'gray63', 'gray64', 'gray65',\r\n 'gray66', 'gray67', 'gray68', 'gray69', 'gray70', 'gray71', 'gray72', 'gray73', 'gray74',\r\n 'gray75', 'gray76', 'gray77', 'gray78', 'gray79', 'gray80', 'gray81', 'gray82', 'gray83',\r\n 'gray84', 'gray85', 'gray86', 'gray87', 'gray88', 'gray89', 'gray90', 'gray91', 'gray92',\r\n 'gray93', 'gray94', 'gray95', 'gray97', 'gray98', 'gray99']\r\n \r\n # Chooses a random index for the color\r\n i = random.randint(0,len(colors))\r\n st.config(bg=colors[i])\r\n \r\n# Saves the text file to the users computer\r\ndef save(st,tk):\r\n content = st.get(1.0, END)\r\n files = [('All Files', '*.*'), \r\n ('Python Files', '*.py'), \r\n ('Text Document', '*.txt')] \r\n file = asksaveasfile(filetypes = files, defaultextension = files) \r\n # Writes the content of the scrolled text window the screen\r\n outFile = open(file.name, 'w')\r\n outFile.write(content)\r\n outFile.close()\r\n \r\nmain()\r\n","sub_path":"finalProject.py","file_name":"finalProject.py","file_ext":"py","file_size_in_byte":14969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"220785166","text":"'''The following code was adapted from https://ai-su13.artifice.cc/gps.html\n to demonstrate a problem that GPS can't solve optimally'''\n\nfrom gps import gps\nproblem = {\n # the problem can be solved by gps because all the preconditions will be met for the son to get to school\n # and the person driving to still have money when they get to school since the car is working and there is \n # no need to spend money in the repair shop\n \"start\": [\"son at home\", \"have money\", \"car works\"], \n \"finish\": [\"have money\", \"son at school\"],\n\n # the problem can no longer be solved: the person cannot drive their son to school and still have money\n # if the money was spent at the repair shop, so this ends in a plan failure: \n \"start1\": [\"son at home\", \"have money\", \"have phone book\", \"car needs battery\"],\n \"finish1\": [\"have money\",\"son at school\"],\n\n \"ops\": [\n {\n \"action\": \"drive son to school\",\n \"preconds\": [\"son at home\", \"car works\"],\n \"add\": [\"son at school\"],\n \"delete\": [\"son at home\"]\n },\n {\n \"action\": \"shop installs battery\",\n \"preconds\": [\"car needs battery\", \"shop knows problem\", \"shop has money\"],\n \"add\": [\"car works\"],\n \"delete\": []\n },\n {\n \"action\": \"tell shop problem\",\n \"preconds\": [\"in communication with shop\"],\n \"add\": [\"shop knows problem\"],\n \"delete\": []\n },\n {\n \"action\": \"telephone shop\",\n \"preconds\": [\"know phone number\"],\n \"add\": [\"in communication with shop\"],\n \"delete\": []\n },\n {\n \"action\": \"look up number\",\n \"preconds\": [\"have phone book\"],\n \"add\": [\"know phone number\"],\n \"delete\": []\n },\n {\n \"action\": \"give shop money\",\n \"preconds\": [\"have money\"],\n \"add\": [\"shop has money\"],\n \"delete\": [\"have money\"]\n }\n ]\n}\n#\ndef main():\n start = problem['start1']\n finish = problem['finish1']\n ops = problem['ops']\n actionSequence = gps(start, finish, ops)\n if actionSequence is None:\n print(\"plan failure...\")\n return\n for action in actionSequence:\n print(action)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"lab01/lab_3.py","file_name":"lab_3.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337278493","text":"\n\nfrom xai.brain.wordbase.verbs._slog import _SLOG\n\n#calss header\nclass _SLOGGED(_SLOG, ):\n\tdef __init__(self,): \n\t\t_SLOG.__init__(self)\n\t\tself.name = \"SLOGGED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"slog\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_slogged.py","file_name":"_slogged.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"134825112","text":"from transformers import BertJapaneseTokenizer, BertModel, get_linear_schedule_with_warmup\nfrom torch.utils.data import DataLoader, Subset\nfrom allennlp.modules import conditional_random_field\nfrom sklearn.model_selection import train_test_split\nimport argparse\nimport random\nimport sys\nfrom pathlib import Path\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.utils.rnn import pad_sequence\nimport mlflow\nimport numpy as np\nfrom tqdm import tqdm\nimport mojimoji\nimport json\nfrom model import BertCrf\nbase_dir = Path(__file__).resolve().parents[1]\nsys.path.append(str(base_dir))\n\nimport data_utils\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\ndef train(model, train_dataset, val_dataset, max_epoch=20, batch_size=16, outputdir=None):\n data = DataLoader(train_dataset, batch_size=batch_size, collate_fn=data_utils.my_collate_fn)\n\n val_data = DataLoader(val_dataset, batch_size=batch_size, collate_fn=data_utils.my_collate_fn)\n val_loss = [float('inf'), float('inf')]\n\n bert_parameter = list(model.bert.parameters())\n other_parameter = (list(model.hidden_to_output.parameters()) +\n list(model.crf.parameters()))\n optimizer_grouped_parameters = [\n {'params': bert_parameter, 'lr':5e-5},\n {'params': other_parameter, 'lr':0.001}\n ]\n\n optimizer = optim.Adam(optimizer_grouped_parameters)\n\n losses = []\n model.to(device)\n for epoch in tqdm(range(max_epoch)):\n model.train()\n all_loss = 0\n step = 0\n\n for sent, label in data:\n #print(len(label[0]))\n input_x = pad_sequence([torch.tensor(x)\n for x in sent], batch_first=True).to(device)\n input_y = pad_sequence([torch.tensor(y)\n for y in label], batch_first=True).to(device)\n print(input_x.shape)\n print(input_y.shape)\n mask = [[float(i>0) for i in ii] for ii in input_x]\n print(len(mask[0]))\n mask = torch.tensor(mask).to(device)\n\n loss = model(input_x, input_y, mask) * (-1.0)\n all_loss += loss.item()\n\n loss.backward()\n optimizer.step()\n #scheduler.step()\n model.zero_grad()\n\n step += 1\n\n losses.append(all_loss / step)\n mlflow.log_metric(\"loss\", losses[-1], step=epoch)\n\n model.eval()\n all_loss = 0\n step = 0\n\n for sent, label in val_data:\n input_x = pad_sequence([torch.tensor(x)\n for x in sent], batch_first=True).to(device)\n input_y = pad_sequence([torch.tensor(y)\n for y in label], batch_first=True).to(device)\n mask = [[float(i>0) for i in ii] for ii in input_x]\n mask = torch.tensor(mask).to(device)\n\n loss = model(input_x, input_y, mask) * (-1.0)\n all_loss += loss.item()\n\n step += 1\n val_loss.append(all_loss / step)\n mlflow.log_metric(\"val_loss\", val_loss[-1], step=epoch)\n output_path = outputdir + '/checkpoint{}.model'.format(len(val_loss)-1)\n torch.save(model.state_dict(), output_path)\n\n if val_loss[-1] > val_loss[-2] and val_loss[-2] > val_loss[-3]:\n break\n\n #print(val_loss)\n if val is not None:\n min_epoch = np.argmin(val_loss)\n print(min_epoch)\n model_path = outputdir + '/checkpoint{}.model'.format(min_epoch)\n model.load_state_dict(torch.load(model_path))\n\n torch.save(model.state_dict(), outputdir+'/final.model')\n\ndef evaluate(model, x):\n data = data_utils.Batch(x, x, batch_size=8, sort=False)\n\n model.to(device)\n output = []\n model.eval()\n for sent, label in data:\n input_x = pad_sequence([torch.tensor(x)\n for x in sent], batch_first=True).to(device)\n input_y = pad_sequence([torch.tensor(y)\n for y in label], batch_first=True).to(device)\n mask = [[float(i>0) for i in ii] for ii in input_x]\n mask = torch.tensor(mask).to(device)\n\n tags = [m[0] for m in model.decode(input_x, mask)]\n output += tags\n\n return output\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Train BERT')\n parser.add_argument('--train_path', type=str, help='data path')\n parser.add_argument('--val_path', type=str, help='data path')\n parser.add_argument('--batch_size', type=int, help='batch size')\n parser.add_argument('--output_dir', type=str, help='batch size')\n parser.add_argument('--output_path', type=str, help='batch size')\n parser.add_argument('--labels', type=str, help='batch size')\n args = parser.parse_args()\n\n mlflow.start_run()\n\n tokenizer = BertJapaneseTokenizer.from_pretrained(\"cl-tohoku/bert-base-japanese-char\")\n\n label_vocab = data_utils.create_label_vocab_from_file(args.labels)\n itol = {i:w for w, i in label_vocab.items()}\n\n constraints = conditional_random_field.allowed_transitions(\"BIO\", itol)\n train_dataset = data_utils.IobDataset(args.train_path, tokenizer, label_vocab)\n if args.val_path:\n val_dataset = data_utils.IobDataset(args.val_path, tokenizer, label_vocab)\n else:\n # validation setの指定が無い場合、1/10をvalidationにする\n train_size = len(train_dataset)\n val_index = random.sample([i for i in range(train_size)], train_size//10)\n val_dataset = Subset(train_dataset, val_index)\n\n val_index = set(val_index)\n train_index = [i for i in range(train_size) if i not in val_index]\n train_dataset = Subset(train_dataset, train_index)\n\n bert = BertModel.from_pretrained('cl-tohoku/bert-base-japanese-char')\n model = BertCrf(bert, len(label_vocab), constraints)\n\n train(model, train_dataset, val_dataset, outputdir=args.output_dir, batch_size=args.batch_size)\n tags = evaluate(model, input_x_test)\n\n\n mlflow.end_run()\n\n \"\"\"\n # test script\n labels = [[itol[t] for t in tag] for tag in tags]\n input_x_test = [tokenizer.convert_ids_to_tokens(t)[1:] for t in input_x_test]\n input_y_test = [[itol[i] for i in t] for t in input_y_test]\n\n output = []\n for x, t, y in zip(input_x_test, labels, input_y_test):\n output.append('\\n'.join([x1 + '\\t' + str(x2) + '\\t' + str(x3) for x1, x2, x3 in zip(x, y, t)]))\n\n with open(args.output_path, 'w') as f:\n f.write('\\n\\n'.join(output))\n \"\"\"\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"401323743","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/10/12 19:40\n# @Author : RookieDay\n# @Site : \n# @File : data_config.py\n# @Software: PyCharm Community Edition\n\n# 设置全局参数 所要爬取的岗位、城市、区、保存文件\nSPIDER_CONFIG = {\n 'position': '数据分析',\n 'city': '',\n 'district': '',\n 'output_file' : 'lagou_analysis.csv',\n 'rowTitle': ['companyFullName','city','district','positionName',\n 'workYear','jobNature', 'salary','eduction','companySize',\n 'financeStage','industryField','positionAdvantage',\n 'positionLables','industryLables','companyLableList','jobDetail'\n ]\n}","sub_path":"lagouSpiderAnalysis/data_config.py","file_name":"data_config.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112178506","text":"\"\"\"\r\nPython code snippets vol 33:\r\n161-Get city coordinates\r\nstevepython.wordpress.com\r\n\r\nSource:\r\nhttps://pbaumgarten.com/python/requests.html\r\n\"\"\"\r\nimport json\r\nimport requests\r\n\r\ndef get_city_coordinates(location):\r\n \"\"\"Get info from geocode.xyz\"\"\"\r\n\r\n url = \"https://geocode.xyz/\"+location+\"?json=1\"\r\n params = {}\r\n headers = {'Content-Type': 'application/json'}\r\n response = requests.get(url, headers=headers, params=params)\r\n\r\n if response.status_code == 200:\r\n return json.loads(response.content.decode(\"utf-8\"))\r\n else:\r\n print(\"*** ERROR! Response \", response.status_code, \" ***\")\r\n return None\r\n\r\ncity = input(\"Type the name of a city: \")\r\ninfo = get_city_coordinates(city)\r\nprint(\"City: \", info[\"standard\"][\"city\"])\r\nprint(\"Country: \", info[\"standard\"][\"countryname\"])\r\nprint(\"Latitude: \", info[\"latt\"])\r\nprint(\"Longitude: \", info[\"longt\"])\r\n","sub_path":"Python-code-snippets-101-200/161-Get City Coordinates.py","file_name":"161-Get City Coordinates.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"162127869","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom __future__ import division\nimport sys\nimport glob\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\n# My package\nfrom ngskit.utils import dna\n\n\n# Normalize Read counts\n\ndef norm_TC(df, scalar_factor = 1):\n \"\"\"Very basic normalization. Total Counts. scalar_factor = 1\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe with the raw reads.\n scalar_factor : int, float\n Integer or float, can be diversity of the smaples or the avg of read across\n the whole dataset\n\n Returns\n -------\n pandas.DataFrame\n with the colun nReads, Normilized reads\n\n \"\"\"\n df['nReads'] = ( df['Reads'] / df['Reads'].sum() ) * scalar_factor\n\n return df\n\ndef norm_TC_AVG(df):\n \"\"\"Very basic normalization. Total Counts. scalar_factor= Avg of reads\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe with the raw reads.\n scalar_factor : int, float\n Integer or float, can be diversity of the smaples or the avg of read across\n the whole dataset\n\n Returns\n -------\n pandas.DataFrame\n with the colun nReads, Normilized reads\n\n \"\"\"\n scalar_factor = df['Reads'].mean(skipna=True)\n\n df['nReads'] = ( df['Reads'] / df['Reads'].sum() ) * scalar_factor\n\n return df\n\n\ndef norm_TC_COUNTS(df):\n \"\"\"Very basic normalization. Total Counts. scalar_factor is the total of mapped peptides\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe with the raw reads.\n scalar_factor : int, float\n Integer or float, can be diversity of the smaples or the avg of read across\n the whole dataset\n\n Returns\n -------\n pandas.DataFrame\n with the colun nReads, Normilized reads\n\n \"\"\"\n scalar_factor = df['Seq'].unique().shape[0]\n df['nReads'] = ( df['Reads'] / df['Reads'].sum() ) * scalar_factor\n\n return df\n\n\ndef norm_deseq(df, read_columns):\n \"\"\"Scale a dataframe using the deseq scaling.\n\n Uses :func:`scale_factor_deseq`\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe with the raw reads.\n read_columns : list\n list with the columns with the read counts information\n\n Returns\n -------\n pandas.DataFrame\n with the colun nReads, Normilized reads\n \"\"\"\n\n # rename columns to label norm reads\n nreads_colums = ['n'+col_name for col_name in read_columns]\n # get scalar factor to norm reads\n scale_factors = scale_factor_deseq(df, read_columns)\n # norm\n df[nreads_colums] = df[read_columns] / scale_factors\n\n return df\n\n\ndef scale_factor_deseq(df, read_columns):\n \"\"\"Returns the scale factor according to he deseq paper. The columns of the\n dataframe are the samples.\n\n size factor :math:`\\\\hat{s}_{j}` for sample *j* (from DESeq paper).\n\n .. math::\n\n \\\\hat{s}_{j} = median_{i} (\n \\\\frac\n {k_{ij}}\n {\n \\\\left (\n \\\\prod_{v=1}^{m}\n k_{iv}\n \\\\right )^{1/m}\n }\n )\n\n \"\"\"\n # set nan values, if any, to zero\n df[read_columns].fillna('0', inplace=True)\n # calc the genes geometric mean over all samples\n gmean = df[read_columns].apply(sp.stats.gmean, axis=1)\n # keeps only the genes whose geometric mean is > 0\n gmean = gmean[gmean > 0]\n\n sample_factors = {}\n\n # calc the scaling factor for each sample\n for sample, seq in df[read_columns].iteritems():\n\n scale_factor = np.median(seq.loc[gmean.index] / gmean)\n\n sample_factors[sample] = scale_factor\n\n return pd.Series(sample_factors)\n\n# I/O\n\ndef read_preprocessed(file_dir, norm=False, **Kargs):\n \"\"\"read file with sequences already counted.\n\n Parameters\n ----------\n\n Returns\n -------\n Pandas DataFrame ['Seq','Reads'] no Normalized\n Pandas DataFrame ['Seq','Reads', 'nReads'] Normalized\n \"\"\"\n\n df = pd.read_csv(file_dir, names=['Seq','Reads'], **Kargs)\n # very basic normalization\n if norm:\n\n df = norm(df)\n\n return df\n\ndef read_fasta(fasta_file, norm=False, translate2aa=True, **Kargs):\n \"\"\"Read a demultiplexed fasta file and return Dataframe.\n\n Parameters\n ----------\n\n Returns\n -------\n Pandas DataFrame ['Seq','Reads'] no Normalized\n Pandas DataFrame ['Seq','Reads', 'nReads'] Normalized\n \"\"\"\n\n seqs = dict()\n with open(fasta_file, 'r') as input_file:\n for line in input_file:\n if line.startswith('>'):\n pass\n else:\n s = line.strip()\n\n if translate2aa:\n aa = dna.translate2aa(s)\n\n seqs[aa] = seqs.get(aa, 0) + 1\n else:\n\n seqs[s] = seqs.get(s, 0) + 1\n\n df = pd.DataFrame.from_dict(data=seqs, orient='index')\n df.reset_index(inplace=True)\n df.rename(columns={'index':'Seq', 0:'Reads'}, inplace=True)\n\n if norm:\n # Apply normalization function\n\n df = norm(df)\n\n else:\n pass\n\n return df\n\ndef read_bowtie(filename, norm=False, **Kargs):\n \"\"\"Read bowtie output.\n\n Parameters\n ----------\n\n Returns\n -------\n Pandas DataFrame ['Seq','Reads'] no Normalized\n Pandas DataFrame ['Seq','Reads', 'nReads'] Normalized\n\n\n \"\"\"\n df = load_bowtieout(filename)\n # Join by seq, count and sort\n q = df.groupby(['referenceId'], as_index=False)['offset'].agg(len)\n q.sort_values(by='offset', ascending=False, inplace=True)\n q.rename(columns={'offset': 'Reads'}, inplace=True)\n\n if norm:\n # Apply normalization function\n\n q = norm(q)\n\n return q[['referenceId', 'Reads','nReads']]\n else:\n return q[['referenceId', 'Reads']]\n\n\ndef read_blast(filename, aligment_length, norm=False, **Kargs):\n \"\"\"Read blasted file.\n\n Parameters\n ----------\n filename : str\n Fasta output file dir\n\n aligment_length :\n\n norm : Function\n Normalization fucntion\n Returns\n -------\n Pandas DataFrame ['referenceId', 'queryId', 'Reads'] no Normalized\n Pandas DataFrame [''referenceId', 'queryId', 'Reads', 'nReads'] Normalized\n\n\n \"\"\"\n df = load_blastout(filename)\n # filter cutoff identity, aligment length and mismatchCount\n mismatchCount = Kargs.get('mismatchCount', d=0)\n identity = Kargs.get('identity', d=100.0)\n\n df = df[(df['percIdentity'] >= identity)\n & (df['alnLength'] == aligment_length)\n & (df['mismatchCount'] <= mismatchCount)]\n\n # Join by seq, count and sort\n q = df.groupby(['referenceId'], as_index=False)['eVal'].agg(len)\n q.sort_values(by='eVal', ascending=False, inplace=True)\n q.rename(columns={'eVal': 'Reads'}, inplace=True)\n\n if norm:\n # Apply normalization function\n # logg with type is appling\n q = norm(q)\n # q['nReads'] = ( q['Reads'] / q['Reads'].sum() ) * diversity\n\n return q[['referenceId', 'Reads','nReads']]\n else:\n return q[['referenceId', 'Reads']]\n\n# I/O More generic\n\ndef load_blastout(filename):\n \"\"\"load blast output to Dataframe.\n\n\n Parameters\n ----------\n\n Returns\n -------\n\n Notes\n -----\n .: How to generate output blast:\n\n blastall -p blastn -d design_lib.fasta -i smaples_id_demultiplex.fasta -o blastoutput -v1 -b1 -m8\n or\n blastn -db /home/kimlab2/ccorbi/optim_lib/Kim/fasta_libs/optm_library.fasta -query $i -evalue 1 -out $i.out -outfmt '6 qacc sacc pident length mismatch gapopen qstart qend sstart send evalue bitscore'\n\n\n \"\"\"\n df = pd.read_csv(filename, delim_whitespace=True, names=[\n 'queryId',\n 'referenceId',\n 'percIdentity',\n 'alnLength',\n 'mismatchCount',\n 'gapOpenCount',\n 'queryStart',\n 'queryEnd',\n 'subjectStart',\n 'subjectEnd',\n 'eVal',\n 'bitScore',\n ])\n return df\n\n\ndef load_bowtieout(filename):\n \"\"\"load bowtie output to DataFrame.\n\n Parameters\n ----------\n filename : str\n bowtie output file dir\n\n\n\n\n Returns\n -------\n DataFrame\n Pandas dataframe with ['queryId', 'strand', 'referenceId',\n 'off', 'Seq', 'otheInstances',\n 'quality', 'mismatchDescriptor' ]\n Notes\n -----\n .: Bowite for 0 mismathces output must be generated (bowtie 2 output) as\n bowtie --best -v X [library/path] -f [fasta/path] > [output/path]\n\n .: Bowtie library:\n bowtie-build -f [fasta/library/path] [name library]\n\n .: Historical\n bowtie -n 0 [library/path] -f [fasta/path] > [output/path]\n\n \"\"\"\n df = pd.read_csv(filename, names=[\n 'queryId',\n 'strand',\n 'referenceId',\n 'offset',\n 'Seq',\n 'Phred',\n 'otherInstances',\n 'mismatchDescriptor',\n ], sep='\\t')\n\n\n return df\n\n\n\n\n#\n# CUSTOM\n# Calculations\n#\ndef dropOutScore(row, sampling_points=[0,3,7,14], dbl_times = [0,2.4,4.5,10], normed=True, itemization=False, field='nReads_T{}'):\n \"\"\"This fucntion calcs the drop off score for each peptide_id\n\n Parameters\n ----------\n :param Serie row: Row from a dataframe, or dict\n :param list sampling_points: Time points, [0,3,7,14]\n :param list dbl_times: Double time of the cell line. [0,2.4,4.5,10]\n :param bool normed: Divison all the time points by the biggest value in the time serie\n :param bool itemization: return slope for each time point and the dropscore\n :param int scalar: scalar to multiply dropscore [increse the signal]\n :param str field: reads, of Cell viability base\n\n Returns\n -------\n :type float: dropout score\n if itemization is True:\n :type list: Slopes for each time point\n :type float: dropout score\n\n \"\"\"\n\n # Init variables\n sampling_points.sort()\n data = []\n # Get initial point\n T0 = row[field.format(0)]\n\n # sync time points and reads\n data_points = [row[field.format(t)] for t in sampling_points]\n\n # Divison all the time points by the biggest value in the time serie\n # Avoid bias by highread peptides, relative comparision\n\n if normed:\n Norm_vector = max(data_points)\n else:\n Norm_vector =T0\n # get number of points\n\n n = len(sampling_points)\n\n for i, t in enumerate(sampling_points):\n # Skip T = 0\n if i == 0:\n data.append(0)\n else:\n s = slope_i(y0= T0/Norm_vector,\n y1 = row[field.format(t)]/Norm_vector,\n deltaX = dbl_times[i])\n data.append(s)\n\n # Sum Slopes * 1 / N-1\n dropout = (sum(data)*(1/(float(n-1))))\n\n # return slope for each time point and the dropscore\n if itemization:\n return data,dropout*100\n else:\n return dropout*100\n\ndef dropOutScoreLog2(row, sampling_points=[0,3,7,14], dbl_times = [0,2.4,4.5,10], normed=True, itemization=False, field='nReads_T{}'):\n \"\"\"This fucntion calcs the drop off score for each peptide_id\n\n Parameters\n ----------\n :param Serie row: Row from a dataframe, or dict\n :param list sampling_points: Time points, [0,3,7,14]\n :param list dbl_times: Double time of the cell line. [0,2.4,4.5,10]\n :param bool normed: Divison all the time points by the biggest value in the time serie\n :param bool itemization: return slope for each time point and the dropscore\n :param int scalar: scalar to multiply dropscore [increse the signal]\n :param str field: reads, of Cell viability base\n\n Returns\n -------\n :type float: dropout score\n if itemization is True:\n :type list: Slopes for each time point\n :type float: dropout score\n\n \"\"\"\n\n # Init variables\n sampling_points.sort()\n data = []\n # Get initial point\n T0 = row[field.format(0)]\n\n # sync time points and reads\n data_points = [row[field.format(t)] for t in sampling_points]\n\n # Divison all the time points by the biggest value in the time serie\n # Avoid bias by highread peptides, relative comparision\n\n if normed:\n Norm_vector = max(data_points)\n else:\n Norm_vector =T0\n # get number of points\n\n n = len(sampling_points)\n\n for i, t in enumerate(sampling_points):\n # Skip T = 0\n if i == 0:\n data.append(0)\n else:\n s = slope_i(y0= np.log2(T0+.5),\n y1 = np.log2(row[field.format(t)]+.5),\n deltaX = dbl_times[i])\n data.append(s)\n\n # Sum Slopes * 1 / N-1\n dropout = (sum(data)*(1/(float(n-1))))\n\n # return slope for each time point and the dropscore\n if itemization:\n return data,dropout*100\n else:\n return dropout*100\n\n\ndef DP_linreg(row, sampling_points=[0,3,7,14], dbl_times = [0,2.4,4.5,10],field='nReads_T{}'):\n xis = list()\n yis = list()\n #m = row[['nReads_T0_RWP1','nReads_T4_RWP1','nReads_T7_RWP1','nReads_T14_RWP1']].max()\n for idx,t in enumerate(sampling_points):\n #for r in ['A', 'B', 'C']:\n xis.append(dbl_times[idx])\n yis.append(np.log2(row[field.format(t)]+.5))\n slope, i, r, p, e = sp.stats.linregress(xis,yis)\n\n return slope*100\n\n\ndef relative_increment(row, ref_value, target_value):\n \"\"\"Relative increment.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n increment = slope_i(y0 = row[ref_value],\n y1 = row[target_value],\n deltaX= row[target_value] + row[ref_value])\n\n\n return increment\n\ndef slope(y0, y1, x0, x1 ):\n \"\"\"Resturn slope.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n deltaX = float(x1) - float(x0)\n deltaY = float(y1) - float(y0)\n\n return deltaY/deltaX\n\n\ndef slope_i(y0, y1, deltaX):\n \"\"\"Resturn slope.\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n deltaY = float(y1) - float(y0)\n\n return deltaY/float(deltaX)\n","sub_path":"ngskit/pipelines/common_norm.py","file_name":"common_norm.py","file_ext":"py","file_size_in_byte":13967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312946130","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif', size=20)\nplt.rc('lines', lw=2.5)\nplt.rc('xtick', direction='in', top=True, bottom=True)\nplt.rc('ytick', direction='in', left=True, right=True)\n\ndef eigs_infLL(alpha=2, N=20):\n \"\"\"\n get eigenvalue spectrum for a large matrix satisfying Laplace-Lagrange\n\n Conclusion: indeed, the eigs's follow the expected power law, and indeed the\n \"forced\" mode amplitudes (inner planet's oscillation driven by mutual\n precession of (k)-(k+1) planet) should be well-described.\n\n tl;dr - forced mode amplitude falls off as we move outwards\n \"\"\"\n mat = np.zeros((N, N))\n for j in range(N):\n for k in range(N):\n if k == j:\n continue\n elif j > k:\n mat[j, k] = alpha**(-2 * (j - k) - 3 * j / 2)\n else:\n mat[j, k] = alpha**(-3 * (k - j) - 3 * j / 2)\n for j in range(N):\n rowsum = 0\n for k in range(N):\n if k == j:\n continue\n rowsum += mat[j, k]\n mat[j, j] = -rowsum\n eigs, eigvs = np.linalg.eig(mat)\n eigsortidx = np.argsort(eigs)\n eigs = eigs[eigsortidx][ :-1] # drop the smallest one (zero)\n eigvs = eigvs.T[eigsortidx][ :-1]\n idx = np.arange(N - 1)\n eigs_th = alpha**(-3 * (idx + 2) / 2) + alpha**(-3 * (idx + 2) / 2 + 1)\n\n fig, (ax1, ax2, ax3) = plt.subplots(\n 3, 1,\n figsize=(8, 8))\n ax1.semilogy(idx, eigs_th, 'k--')\n\n for idx, (eig, eigv) in enumerate(zip(eigs, eigvs)):\n eigv = np.abs(eigv)\n eigv = eigv / max(eigv)\n ax1.semilogy(idx, -eig, marker='o')\n ax2.semilogy(eigv)\n plt_idx = np.arange(N) - idx - 1\n ax3.semilogy(plt_idx, eigv, lw=0.5)\n ax2.set_ylim(bottom=1e-2, top=1)\n ax3.set_ylim(bottom=1e-2, top=1)\n ax3.set_xlim(-5, 2)\n\n ax1.set_ylabel('Eigs (vs index)')\n ax2.set_ylabel('Eigv (vs planet)')\n ax3.set_ylabel('Eigv (horiz offset)')\n plt.savefig('/tmp/foo')\n plt.close()\n\nif __name__ == '__main__':\n eigs_infLL()\n","sub_path":"initial/4nplanet/99tidbits.py","file_name":"99tidbits.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132420396","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Section, Article, Subsection, ArticleStatistic, Comment\nfrom django.contrib.auth.models import User\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.utils import timezone\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\nfrom .forms import CommentForm\nfrom django.contrib import auth\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\n\n# Create your views here.\n\ndef post_list(request, subsec_slug=None, sec_slug=None, author=None):\n all_posts = Article.objects.all().filter(status='опубликован').order_by('-date')\n if sec_slug and subsec_slug:\n sec = get_object_or_404(Section, sec_slug=sec_slug)\n subsec = get_object_or_404(Subsection, subsec_slug=subsec_slug)\n all_posts = all_posts.filter(section__in=[sec]).filter(subsection__in=[subsec]).filter(status='опубликован').order_by('-date')\n else:\n if subsec_slug:\n subsec = get_object_or_404(Subsection, subsec_slug=subsec_slug)\n all_posts = all_posts.filter(subsection__in=[subsec]).filter(status='опубликован').order_by('-date')\n if sec_slug:\n sec = get_object_or_404(Section, sec_slug=sec_slug)\n all_posts = all_posts.filter(section__in=[sec]).filter(status='опубликован').order_by('-date')\n if author:\n auth_post = get_object_or_404(User, username=author)\n all_posts = all_posts.filter(author__in=[auth_post]).filter(status='опубликован').order_by('-date')\n paginator = Paginator(all_posts, 3)\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n return render(request, 'blog/post_list.html', {'page': page, 'posts': posts})\n\ndef post_detail(request, slug):\n post = get_object_or_404(Article, slug=slug)\n\n obj, created = ArticleStatistic.objects.get_or_create(\n defaults={\n \"article\": post,\n \"date\": timezone.now()\n },\n # При этом определяем, забор объекта статистики или его создание\n # по двум полям: дата и внешний ключ на статью\n date=timezone.now(), article=post\n )\n obj.views += 1 # инкрементируем счётчик просмотров и обновляем поле в базе данных\n obj.save(update_fields=['views'])\n\n comments = post.comment_set.all().order_by('path')\n next = post.get_absolute_url()\n\n user = auth.get_user(request)\n if user.is_authenticated:\n form = CommentForm\n return render(request, 'blog/post_detail.html', {'post': post, 'comments': comments, 'next': next, 'form': form})\n else:\n return render(request, 'blog/post_detail.html',\n {'post': post, 'comments': comments, 'next': next})\n\n\n@login_required\n@require_http_methods([\"POST\"])\ndef add_comment(request, article_id):\n form = CommentForm(request.POST)\n article = get_object_or_404(Article, id=article_id)\n\n if form.is_valid():\n comment = Comment()\n comment.path = []\n comment.article_id = article\n comment.author_id = auth.get_user(request)\n comment.content = form.cleaned_data['comment_area']\n comment.save()\n\n # Django не позволяет увидеть ID комментария по мы не сохраним его,\n # хотя PostgreSQL имеет такие средства в своём арсенале, но пока не будем\n # работать с сырыми SQL запросами, поэтому сформируем path после первого сохранения\n # и пересохраним комментарий\n try:\n comment.path.extend(Comment.objects.get(id=form.cleaned_data['parent_comment']).path)\n comment.path.append(comment.id)\n except ObjectDoesNotExist:\n comment.path.append(comment.id)\n\n comment.save()\n\n return redirect(article.get_absolute_url())\n\ndef handler404(request, exception, template_name='404.html'):\n response = render_to_response('404.html', {},\n context_instance=RequestContext(request))\n response.status_code = 404\n return response","sub_path":"MemoryBlog/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634537295","text":"file = open(r\"C:\\Users\\lenovo\\Documents\\Objects\\1.hex\", \"r\")\nrows = file.read().split('\\n')\nrowlen = len(rows)\noutput = []\noutput0 = []\nbyte = 0\na, b, c = rows[0]+'\\n', rows[rowlen-3]+'\\n', rows[rowlen-2]+'\\n'\nrows = rows[1:-3]\nwhile byte < len(rows):\n output0 += [rows[byte]+'\\n']\n if (byte > 1 and byte % 32 == 31) or byte == len(rows) - 1:\n output0 = [a] + output0 + [b, c]\n output += [output0]\n output0 = []\n byte += 1\nfile.close()\nbyte = 1\nfor file in output:\n txt = open(fr\"C:\\Users\\lenovo\\Documents\\Objects\\1-{byte}.hex\", \"w\")\n txt.writelines(file)\n byte += 1\n txt.close()\n","sub_path":"屑/hex文件分割.py","file_name":"hex文件分割.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"32701617","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\nfrom django.db import models, migrations\n\n\ndef install(apps, schema_editor):\n Group = apps.get_model('core.Group')\n Permission = apps.get_model('core.Permission')\n\n users_group, is_new = Group.objects.get_or_create(name=\"users\")\n view_notification, is_new = Permission.objects.get_or_create_by_natural_key(\"view_notification\", \"notifications\", \"notification\")\n \n # Permissions.\n users_group.permissions.add(view_notification)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('notifications', '0001_initial'),\n ('core', '0002_initial_fixture'),\n ]\n\n operations = [\n migrations.RunPython(install),\n ]\n","sub_path":"djangoerp/notifications/migrations/0002_initial_fixture.py","file_name":"0002_initial_fixture.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"307756709","text":"\n\n#calss header\nclass _REEL():\n\tdef __init__(self,): \n\t\tself.name = \"REEL\"\n\t\tself.definitions = [u'a round, wheel-shaped object on which sewing thread, fishing wire, film, etc. can be rolled, or the amount of thread, etc. stored on one of these', u'a fast Scottish or Irish dance, or the music for this']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_reel.py","file_name":"_reel.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"589872538","text":"# -*-coding:utf-8 -*-\n \n\"\"\"\n The ``SMS`` module\n ========================\n \n This package contains functions for sinusoidal modeling\n \n Subpackages available\n ----------------------\n \n Comments and issues\n ------------------------\n \n None for the moment\n \n Contributors\n ------------------------\n \n * Adrien Bitton (bitton@ircam.fr)\n * Philippe Esling (esling@ircam.fr)\n \n\"\"\"\n \n# info\n__version__ = \"1.0\"\n__author__ = \"esling@ircam.fr\"\n__date__ = \"\"\n__all__ = [\"spsModel\", \"utilFunctions\", \"dftModel\", \"sineModel\", \"stochasticModel\"]\n# -*- coding: utf-8 -*-\n\n","sub_path":"data/signal/sms_models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"221602352","text":"from django.test import TestCase\r\n\r\n# Create your tests here.\r\n\r\n\r\nclass ff(object):\r\n def __init__(self,name,age):\r\n self.name = name\r\n self.age = age\r\n\r\n def dd(self,name,age):\r\n return name,age\r\n\r\ncc = ff('yin',19)\r\n\r\nif hasattr(cc,'dd'):\r\n str = getattr(cc,'dd')\r\n ss = str('yin',19)\r\n print(ss)\r\n\r\n\r\n","sub_path":"9/salt-test/Slpd/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299092795","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 29 10:51:47 2016\n\n@author: Stranger\n\"\"\"\n\nimport urllib2\nimport json\nimport random\n\n\ndef joke():\n try:\n for i in random.sample(range(335),1):\n page='page='+str(i)\n full_url='http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?'+page\n req = urllib2.Request(full_url)\n req.add_header(\"apikey\", \"badfbfd251581f2d4320fcac8c7538f4\")\n resp = urllib2.urlopen(req,timeout=5)\n data= json.loads(resp.read())\n for i in random.sample(range(len(data['showapi_res_body']['contentlist'])),1):\n return data['showapi_res_body']['contentlist'][i]['title']+'\\\\n'+data['showapi_res_body']['contentlist'][i]['text']+'\\\\n'\n except Exception:\n return u'抱歉,你运气不好,没有人愿意给你讲笑话,请重试。'","sub_path":"SAE/app/plugins/jok.py","file_name":"jok.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"21722012","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 14 00:09:22 2016\n\n@author: Aleksey\n\"\"\"\n\nimport numpy as np\nX = np.array([[0/3,1/3,2/3],\n [1/3,2/3,0],\n [0/3,2/3,1/3],\n [2/3,0,1/3] ])\n\ny = np.array([[0,1,2,3]]).T\n#syn0 = 2*np.random.random((3,4)) - 1\n#syn1 = 2*np.random.random((4,1)) - 1\n\n\ndef nonlin(x,deriv=False):\n if deriv==True:\n return x *(1-x)\n return 1/(1+np.exp(-x))\n\"\"\"\nfor j in range(60000):\n l1 = 1/(1+np.exp(-(np.dot(X,syn0))))\n l2 = 1/(1+np.exp(-(np.dot(l1,syn1))))\n l2_delta = (y - l2)*(l2*(1-l2))\n l1_delta = l2_delta.dot(syn1.T) * (l1 * (1-l1))\n syn1 += l1.T.dot(l2_delta)\n syn0 += X.T.dot(l1_delta)\n\"\"\"\nnp.random.seed(1)\nsyn0 = 2*np.random.random((3,1)) - 1\nl0 = X\nfor __ in range(10000):\n \n l1 = nonlin(np.dot(l0,syn0))\n l1_error = y - l1\n l1_delta = l1_error * nonlin(l1,True)\n syn0 += np.dot(l0.T,l1_delta)\n \nprint(l1)\nprint(X)","sub_path":"neural/neuron1.py","file_name":"neuron1.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"411228993","text":"#!/usr/bin/env python3\n\n# This script shows differences of groups of packets like the `multilinediff.py` script, but\n# will also only consider differences between all groups of packets where the bit differs between the groups\n# but does not differ in a group itself.\n# It expects at least a single file (then is similar to the `multilinediff.py`) as an argument.\n# Each file represents a group of packets and should contain packets in a hexstream string e.g.: \"dec07eab205e3b00\" per line.\n#\n# NOTE: Also make sure that the first packet has the most / the same amount of bytes than all others, otherwise this script wont work!\n\nfrom colorama import Fore, Back, Style\nimport sys\n\nif len(sys.argv) < 2:\n print('%s This needs at least 1 filename arguments to run! %s' % (Fore.RED, Style.RESET_ALL))\n exit(1)\n\nfiles = sys.argv[1:]\n\noverallfirstPacket = ''\noverallSimilarity = []\n\nfor filename in files:\n curfile = open(filename, 'r')\n input = []\n\n for line in curfile.readlines():\n input.append(bin(int(line[:-1], 16))[2:])\n\n if len(input) < 1:\n print('%s Not enough input lines to analyze a diff (< 1) %s' % (Fore.RED, Style.RESET_ALL))\n exit(1)\n\n if len(overallfirstPacket) == 0:\n overallfirstPacket = input[0]\n overallSimilarity = [False] * len(overallfirstPacket)\n\n referenceLine = input[0]\n outputStr = ''\n\n for pos in range(len(overallfirstPacket)):\n eq = True\n\n for line in input:\n if pos >= len(line) or line[pos] != referenceLine[pos]:\n eq = False\n break\n\n if eq:\n outputStr += Back.GREEN + Fore.WHITE\n else:\n outputStr += Back.RED + Fore.WHITE\n \n if not eq or overallfirstPacket != referenceLine and overallfirstPacket[pos] == referenceLine[pos]:\n overallSimilarity[pos] = True\n\n outputStr += referenceLine[pos]\n outputStr += Style.RESET_ALL\n \n if pos % 8 == 7:\n outputStr += ' '\n\n print(outputStr)\n\n\noutputStrEnd = ''\n\nfor pos in range(len(overallfirstPacket)):\n\n if overallSimilarity[pos]:\n outputStrEnd += Back.GREEN + Fore.WHITE\n else:\n outputStrEnd += Back.RED + Fore.WHITE\n\n outputStrEnd += overallfirstPacket[pos]\n outputStrEnd += Style.RESET_ALL\n \n if pos % 8 == 7:\n outputStrEnd += ' '\n\nprint(outputStrEnd)","sub_path":"tools/multilinediffbetweengroups.py","file_name":"multilinediffbetweengroups.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"411977419","text":"class LogisticRegression():\n def __init__(self, tol, C, l_rate, max_iter):\n self.tol=tol if tol!=None else 0.0001\n self.C=C if C!=None else 1.0\n self.l_rate=l_rate if l_rate!=None else 1.0\n self.max_iter=max_iter if max_iter!=None else 100\n \n def fit(self, x, y):\n x=add_x0(x)\n n=x.shape[1]\n self.theta=np.zeros((n,1))\n for i in range(self.max_iter):\n fxs=fxValue(x, self.theta)\n dJ=(1.0/m)*(np.dot((fxs-y).T, x)+self.C*self.theta.T)\n self.theta-=self.l_rate*dJ.T\n if(np.linalg.norm(dJ) I (0,1,0,2) -> ... ->\n (0,1,0,NSO-1) -> (0,1,1,2) -> ...\n \"\"\"\n NSO = np.size(T2, axis=0)\n\n # Check symmetries first\n chk_fail = 0\n if np.max(np.abs(T2 + np.einsum('qprs->pqrs', T2))) > t2_symm_tol:\n chk_fail = 1\n elif np.max(np.abs(T2 + np.einsum('pqsr->pqrs', T2))) > t2_symm_tol:\n chk_fail = 1\n else:\n pass\n\n if chk_fail:\n raise ValueError('Incorrect Symmetry for the input Tensor')\n\n T2_compressed = _compress_t2(T2, NSO)\n\n return T2_compressed\n\n\n#\n# Evolution Driver Functions\n#\n\ndef ci_beta_evolve(Beta, Amps, Alpha, Fug, eigs, OneH, ERI):\n \"\"\"\n Driver function for the Beta evolution of Thermal CISD\n Inputs:\n Beta :: Current Beta Value\n Amps :: Collection of CISD-amplitudes\n Alpha :: Current Alpha\n Fug :: (fugacity?) indicating initial exp(Alpha*Beta)\n eigs :: 1D array of one-body energy eigenvalues\n OneH :: 1-electron integral\n ERI :: 2-electron integral\n Returns:\n Concatenated array of unique R0,R1(pq) and R2(pqrs)\n \"\"\"\n\n # Number of Spin Orbitals\n NSO = np.size(eigs, axis=0)\n\n # Thermal HFB parameters\n U = np.ones(NSO) / np.sqrt(1 + Fug)\n V = np.sqrt(1 - U**2)\n\n # Extract the amplitudes\n T1 = np.reshape(Amps[1:1+len_t1], (NSO, NSO))\n T2 = DecompressT2(Amps[1+len_t1:], NSO)\n\n # Get the residuals\n r0, r1, r2 = betaci(eigs, OneH, ERI, T1, T2, U, V)\n\n # Antisymmetrize r2\n s2 = (\n r2\n - np.einsum('baij->abij', r2)\n - np.einsum('abji->abij', r2)\n + np.einsum('baji->abij', r2)\n ) / 4.0\n\n # Compress and concatenate\n dt0_dbeta = r0\n dt1_dbeta = np.reshape(r1, int(NSO**2))\n dt2_dbeta = CompressT2(s2)\n\n # return concatenated\n return np.concatenate(([dt0_dbeta], dt1_dbeta, dt2_dbeta))\n\n\ndef ci_alpha_evolve(Alpha, Amps, Beta, Fug, eigs):\n \"\"\"\n Driver function for the Alpha evolution of Thermal CISD\n Inputs:\n Alpha :: Current Alpha\n Amps :: Collection of CISD-amplitudes\n Beta :: Current Temperature\n Fug :: (fugacity?) indicating initial exp(Alpha*Beta)\n eigs :: 1D array of one-body energy eigenvalues\n Returns:\n Concatenated array of unique R0,R1(pq) and R2(pqrs)\n \"\"\"\n\n # Number of Spin Orbitals\n NSO = len(eigs)\n\n # Thermal HFB parameters\n U = np.ones(NSO) / np.sqrt(1 + Fug)\n V = np.sqrt(1 - U**2)\n\n # Extract the amplitudes\n T1 = np.reshape(Amps[1:1+len_t1], (NSO, NSO))\n T2 = DecompressT2(Amps[1+len_t1:], NSO)\n\n # Get the residuals\n r0, r1, r2 = numberci(T1, T2, U, V)\n\n # Compress and concatenate\n dt0_dbeta = r0\n dt1_dbeta = np.reshape(r1, int(NSO**2))\n dt2_dbeta = CompressT2(r2)\n\n # return concatenated\n return np.concatenate(([dt0_dbeta], dt1_dbeta, dt2_dbeta))\n\n\n#\n# Energy and Number Eval Functions\n#\n\ndef eval_number(CI_amps, X, Y):\n \"\"\"\n Function to evaluate the number expectation value\n \"\"\"\n\n Nso = len(X)\n\n T1 = np.reshape(CI_amps[1:Nso*Nso+1], (Nso, Nso))\n T2 = DecompressT2(CI_amps[Nso*Nso+1:], Nso)\n\n # Number Exp value\n num = evalenergy(np.eye(Nso), np.zeros((Nso, Nso, Nso, Nso)), T1, T2, X, Y)\n\n return num\n\n\ndef eval_energy(OneH, ERI, CI_amps, X, Y):\n \"\"\"\n Function to evaluate the number expectation value\n \"\"\"\n\n Nso = len(X)\n\n T1 = np.reshape(CI_amps[1:Nso*Nso+1], (Nso, Nso))\n T2 = DecompressT2(CI_amps[Nso*Nso+1:], Nso)\n\n # en1 /= ov1\n en = evalenergy(OneH, ERI, T1, T2, X, Y)\n\n return en\n\n\n#\n# ODE integration functions\n#\n\ndef DoIntegration(integrator, x_final):\n \"\"\"\n Intermediate function to perform integration from x_initial to x_final.\n The x_initial and all other information is inherently included\n in the integrator.\n \"\"\"\n yout = integrator.integrate(x_final)\n\n return yout\n\n\ndef _do_beta_integration(\n integrator, amps, betalpha, beta_step, fug, eigs, h1, eri\n):\n \"\"\"\n Perform the Beta integration - use parallel pool of processes\n \"\"\"\n\n # Extract info\n ci_integrator = integrator\n ci_amps = amps\n beta_in = betalpha[0]\n alpha_in = betalpha[1]\n\n # Set the initial condition\n ci_integrator.set_initial_value(ci_amps, beta_in)\n ci_integrator.set_f_params(alpha_in, fug, eigs, h1, eri)\n\n ci_amps = DoIntegration(ci_integrator, beta_in + beta_step)\n\n return ci_amps\n\n\ndef _do_alpha_integration(integrator, amps, betalpha, fug, eigs, n_elec, ntol):\n \"\"\"\n Bisection to find Chemical Pot / Alpha value\n and then do integration\n \"\"\"\n\n # Extract info\n ci_integrator = integrator\n ci_amps = amps\n\n beta_in = betalpha[0]\n alpha_in = betalpha[1]\n\n # Alpha step\n global alpha_step_0g\n\n alpha_step = alpha_step_0g\n\n global len_t1\n global len_t2\n\n # HFB coefficients\n nso = len(eigs)\n x = np.ones(nso) / np.sqrt(1 + fug)\n y = np.sqrt(1 - x**2)\n\n num = eval_number(ci_amps, x, y)\n\n # Record the differenc and sign\n ndiff_sgn = np.sign(num - n_elec)\n ndiff_mag = np.abs(num - n_elec)\n\n print('Number difference: ', ndiff_sgn, ndiff_mag)\n\n # if the number is already converged, then there is no need to do any of\n # the following and hence we keep an 'if' statement; if the condition\n # evaluates to FALSE, then the outputs will be yf, mu_f\n\n if ndiff_mag > ntol:\n\n # Reset the alpha step\n alpha_step = alpha_step_0g\n\n # Obtain the bracket to perform the bisection\n mu1 = alpha_in\n mu2 = alpha_in\n\n ci1 = ci_amps*1\n ci2 = ci_amps*1\n\n count = 0\n sp_count = 0\n\n while np.sign(num - n_elec) == ndiff_sgn:\n\n count += 1\n if count > 300:\n print('Could not find the bracket after ', count, ' steps')\n count = 0\n exit()\n break\n\n # Set up for next iteration\n mu1 = mu2\n mu2 += alpha_step\n\n # update solver initial conditions\n ci1 = ci2*1.0\n\n # Set initial condition for the ODE solvers\n ci_integrator.set_initial_value(ci1, mu1)\n ci_integrator.set_f_params(beta_in, fug, eigs)\n\n # Do Evolution\n ci2 = DoIntegration(ci_integrator, mu2)\n num = eval_number(ci2, x, y)\n\n # Exit if converged\n if np.abs(num - n_elec) <= ntol:\n break\n\n # Check if we are evolving in the right direction or do we need\n # to switch sign of step\n val = np.abs(num - n_elec) - ndiff_mag\n if (val > 0):\n if val < 1e-1:\n sp_count += 1\n else:\n alpha_step_0g *= -1\n alpha_step *= -1\n\n if sp_count >= 10:\n alpha_step_0g *= -1\n alpha_step *= -1\n sp_count = 0\n\n ndiff_mag = np.abs(num - n_elec)\n\n # # Do some printing\n print('\\t\\t\\tStart value of Mu = {}'.format(mu1-alpha_step))\n print('\\t\\t\\tEnd value of Mu = {}'.format(mu1))\n print('\\t\\t\\tNumber of particles after evolution = {}'.format(num))\n print('\\t\\t\\t----------------------------------------------\\n')\n\n # Printing disabled\n print(\n 'Bracket found betwee mu = {} and mu = {}'.format(\n mu1 - alpha_step, mu1\n )\n )\n\n # Now do the Bisection\n mu_bisect = [mu1, mu2]\n mu_mid = mu_bisect[1]\n\n ndiff_sgn_right = np.sign(num - n_elec)\n ndiff_sgn_left = -ndiff_sgn_right\n\n count = 0\n while np.abs(num - n_elec) > ntol:\n\n # Set the initial condition for solver\n ci_integrator.set_initial_value(ci1, mu_bisect[0])\n ci_integrator.set_f_params(beta_in, fug, eigs)\n\n # get mu_mid\n mu_mid = np.mean(mu_bisect)\n\n # Do Evolution\n ci2 = DoIntegration(ci_integrator, mu_mid)\n\n # Check the current number of particles\n num = eval_number(ci2, x, y)\n\n # Adjust bisection bracket\n if np.sign(num - n_elec) == ndiff_sgn_left:\n mu_bisect[0] = mu_mid\n ci1 = ci2\n else:\n mu_bisect[1] = mu_mid\n\n # Printing disabled\n # print('\\t\\tBisection Converged to mu = ',mu_mid)\n\n # Final one-shot evolution\n ci_integrator.set_initial_value(ci_amps, alpha_in)\n ci_integrator.set_f_params(beta_in, fug, eigs)\n\n # Do Evolution\n ci_amps_out = DoIntegration(ci_integrator, mu_mid)\n\n else:\n\n ci_amps_out = ci_amps\n mu_mid = alpha_in\n\n print(num)\n return ci_amps_out, mu_mid\n\n\n#\n# ODE SOLVER FUNCTIONS FOR CI - BETA AND MU EVOLUTIONS\n#\n\nclass EvolutionFixRef(IOps):\n \"\"\"\n class to handle all the imaginary-time evolution equations.\n \"\"\"\n\n # Length of T1 and T2 - unique values\n global len_t1\n global len_t2\n\n # Class attributes\n # Integration step size\n alpha_step_0 = 1e-1\n alpha_step = 1e-1\n # alpha, beta initial / current values\n alpha_in = 0.0\n beta_in = 0.0\n\n # Fugacity -- Initial number is fixed\n fug = 0.0\n\n def __init__(self, inp_file='Input', alpha_step=None):\n\n # Initialize super to read Input file and data\n super().__init__(inp_file=inp_file)\n\n # Set Up the Integrals\n self.setUpInts()\n\n # Step Sizes\n if alpha_step is not None:\n self.alpha_step = alpha_step\n global alpha_step_0g\n alpha_step_0g = self.alpha_step\n\n # Set the global parameters of length of t1 and t2 arrays\n global len_t1\n global len_t2\n len_t1 = self.nso**2\n len_t2 = int(comb(self.nso, 2)**2)\n\n # Initialize the amplitudes\n self.ci_amps = np.zeros(1+len_t1+len_t2)\n\n # ODE integrators\n # self.ci_beta_integrator = ode(ci_beta_evolve)\n # self.ci_beta_integrator.set_integrator('dopri5',rtol=self.deqtol)\n # self.ci_alpha_integrator = ode(ci_alpha_evolve)\n # self.ci_alpha_integrator.set_integrator('dopri5',rtol=self.deqtol)\n self.ci_beta_integrator = ode(ci_beta_evolve)\n self.ci_beta_integrator.set_integrator(\n 'vode', method='bdf', rtol=self.deqtol\n )\n self.ci_alpha_integrator = ode(ci_alpha_evolve)\n self.ci_alpha_integrator.set_integrator(\n 'vode', method='bdf', rtol=self.deqtol\n )\n\n return\n\n def setUpInts(self):\n\n # Read in the integrals\n eigs, oneh, eri, attrs = self.loadHDF()\n self.attrs = attrs\n\n # set up the class attributes\n self.eigs = eigs\n self.h1 = oneh\n self.eri = eri\n\n # Define fugacity\n self.fug = self.n_elec / (self.nso - self.n_elec)\n\n # set beta_step\n self.beta_step = self.beta_f/(self.beta_pts - 1)\n\n def setAmps(self, ci_amps):\n\n # Check the length of the incoming amplitudes\n len_req = int(1 + self.nso**2 + comb(self.nso, 2)**2)\n if len(ci_amps) != len_req:\n raise ValueError('Invalid length of {} amplitudes'.format(ci_amps))\n\n # Initial ci amplitudes for the current step\n self.ci_amps = ci_amps\n\n return\n\n def DoBetaIntegration(self):\n \"\"\"class level Beta integration function.\n \"\"\"\n\n intgrs = self.ci_beta_integrator\n amps = self.ci_amps\n\n ci_amps = _do_beta_integration(\n intgrs, amps, [self.beta_in, self.alpha_in],\n self.beta_step, self.fug, self.eigs, self.h1, self.eri\n )\n\n self.beta_in += self.beta_step\n self.ci_amps = ci_amps\n\n return\n\n def BisectionAndAlphaIntegrate(self):\n \"\"\"class level Beta integration function.\n \"\"\"\n\n intgrs = self.ci_alpha_integrator\n amps = self.ci_amps\n be_al = [self.beta_in, self.alpha_in]\n\n ci_amps, al_mid = _do_alpha_integration(\n intgrs, amps, be_al, self.fug, self.eigs, self.n_elec, self.ntol\n )\n\n self.alpha_in = al_mid\n self.ci_amps = ci_amps\n\n return\n","sub_path":"tfdcisd/fixrefodefuncs.py","file_name":"fixrefodefuncs.py","file_ext":"py","file_size_in_byte":15163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392159979","text":"from torch import nn\nfrom graph_encoder import MultiHeadAttentionLayer\nimport torch\nfrom problems import TSP, CVRP, SDVRP\nimport numpy as np\n\ndef position_encoding_init(n_position, emb_dim):\n ''' Init the sinusoid position encoding table '''\n\n # keep dim 0 for padding token position encoding zero vector\n position_enc = np.array([\n [pos / np.power(10000, 2 * (j // 2) / emb_dim) for j in range(emb_dim)]\n if pos != 0 else np.zeros(emb_dim) for pos in range(n_position)])\n \n\n position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2]) # dim 2i\n position_enc[1:, 1::2] = np.cos(position_enc[1:, 1::2]) # dim 2i+1\n return torch.from_numpy(position_enc).type(torch.FloatTensor)\n\nclass CriticNetwork(nn.Module):\n\n def __init__(\n self,\n input_dim, \n embedding_dim,\n hidden_dim,\n n_layers,\n encoder_normalization\n ):\n super(CriticNetwork, self).__init__()\n \n self.init_embed = nn.Linear(input_dim, embedding_dim)\n \n self.encoder = nn.Sequential(*(\n MultiHeadAttentionLayer(n_heads=1, embed_dim=embedding_dim)\n for _ in range(n_layers)\n ))\n \n self.project_graph = nn.Linear(embedding_dim, embedding_dim, bias=False)\n \n self.project_node = nn.Linear(embedding_dim, embedding_dim, bias=False)\n \n self.value_head = nn.Sequential(\n nn.Linear(embedding_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, 1)\n )\n\n def forward(self, inputs, rec):\n \"\"\"\n :param inputs: (batch_size, graph_size, input_dim)\n :return:\n \"\"\" \n \n input_info, pos_enc = self._emdedding(inputs, rec)\n \n h = self.encoder(self.init_embed(input_info)+pos_enc)\n\n graph_embed = h.mean(1)\n\n fixed_context = self.project_graph(graph_embed)[:, None, :] ######## batchsize, 1, embed_dim\n \n node_feature = self.project_node(h) ######## batchsize, gs, embed_dim\n \n fusion = node_feature + fixed_context.expand_as(node_feature)\n\n return self.value_head(fusion.mean(dim=1)), input_info, pos_enc\n \n def _emdedding(self, input, rec):\n \n ########## input: batch_size, graph, 2\n bs, gs = rec.size()\n \n enc = position_encoding_init(gs, 128) \n \n enc = enc.cuda()\n \n enc_b = enc.expand(bs,gs,128)\n\n seq_tensor_index = rec.long()\n \n node_2_cor = []\n \n pos_enc = []\n \n for i in range(gs):\n \n cor = torch.nonzero(rec.long() == i)\n \n pre = seq_tensor_index[cor[:,0], cor[:,1]]\n \n cor_indice = pre[:,None] \n\n cor_single = input.gather(1, cor_indice[..., None].expand(*cor_indice.size(), 2)) \n \n cor_single_fla = cor_single.view(cor_single.size(0),-1)\n \n node_2_cor.append(cor_single_fla)\n \n single_pos = enc_b.gather(1, cor[:,1][:,None][..., None].expand(bs, 1, 128)) \n\n pos_enc.append(single_pos.squeeze())\n\n return torch.stack(node_2_cor, 1), torch.stack(pos_enc, 1)\n \n \n\n","sub_path":"TSP/tsp50/critic_network.py","file_name":"critic_network.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288989036","text":"# 222870\n# https://adventofcode.com/2015/day/15\n\nimport sys\nimport pprint\nimport re\nimport itertools\nimport collections\n\nIngredient = collections.namedtuple('Ingredient', 'name capacity durability flavor texture calories')\n\nfilename = sys.argv[1]\n\nwith open(filename, 'r') as inputFile:\n lines = [line.strip().replace(':', '').replace(',', '').split(' ') for line in inputFile.readlines()]\n\n#Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8\n# name 0, capacity 2, durability 4, flavor 6, texture 8, calories 10\n\ningredients = {line[0]: Ingredient(line[0], int(line[2]), int(line[4]), int(line[6]), int(line[8]), int(line[10])) for line in lines}\n\nsugar = ingredients['Sugar']\nsprinkles = ingredients['Sprinkles']\ncandy = ingredients['Candy']\nchocolate = ingredients['Chocolate']\n\ndef evaluateRecipe(tSugar, tSprinkles, tCandy, tChocolate):\n capacity = tSugar * sugar.capacity + tSprinkles * sprinkles.capacity + tCandy * candy.capacity + tChocolate * chocolate.capacity\n durability = tSugar * sugar.durability + tSprinkles * sprinkles.durability + tCandy * candy.durability + tChocolate * chocolate.durability\n flavor = tSugar * sugar.flavor + tSprinkles * sprinkles.flavor + tCandy * candy.flavor + tChocolate * chocolate.flavor\n texture = tSugar * sugar.texture + tSprinkles * sprinkles.texture + tCandy * candy.texture + tChocolate * chocolate.texture\n\n if capacity < 0: capacity = 0\n if durability < 0: durability = 0\n if flavor < 0: flavor = 0\n if texture < 0: texture = 0\n score = capacity * durability * flavor * texture\n return score\n\ndef countCalories(tSugar, tSprinkles, tCandy, tChocolate):\n calories = tSugar * sugar.calories + tSprinkles * sprinkles.calories + tCandy * candy.calories + tChocolate * chocolate.calories\n return calories\n\n\nlimit = 100\nrecipes = [(su, sp, ca, limit - (su + sp + ca)) for su in range(0, limit + 1) for sp in range(0, limit - su + 1) for ca in range(0, limit - (su+sp) + 1)]\nscores = [evaluateRecipe(su, sp, ca, ch) for su, sp, ca, ch in recipes]\ncalories = [countCalories(su, sp, ca, ch) for su, sp, ca, ch in recipes]\nscoreCalorie = list(zip(scores, calories))\nscore500 = [score for score, calories in scoreCalorie if calories == 500]\nprint('part 1: ', max(scores))\nprint('part 2: ', max(score500))\n","sub_path":"day15/day15-1.py","file_name":"day15-1.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201558338","text":"'''\n3\n10\n1 3 7 2 5 1 4 2 1 5\n5\n1 1 1 1 1\n6\n1 1 2 2 2 3\n'''\nfrom collections import Counter\nfor _ in range(int(input())):\n noe = int(input())\n arr = [int(x) for x in input().split()]\n arrc = Counter(arr)\n \n stack = []\n idx = []\n ans = [-1] * noe\n \n for i in range(noe):\n if not stack:\n stack.append(arr[i])\n idx.append(i)\n else:\n while(arrc[arr[i]]>arrc[stack[-1]]):\n stack.pop()\n ans[idx.pop()]=arr[i]\n if not stack : break\n stack.append(arr[i])\n idx.append(i) \n print(\" \".join(map(str, ans))) \n \n \n \n \n \n''' \n \n t=int(input())\nfor i in range (t):\n n=int(input())\n a=[]\n a.extend(map(int,input().split()))\n f={}\n for j in a:\n try:\n f[j]+=1\n except:\n f[j]=1\n s=[]\n ind=[]\n ans=[]\n for j in range (n):\n ans.append(-1)\n for j in range (n):\n if(len(s)==0):\n s.append(a[j])\n ind.append(j)\n else:\n while(f[a[j]]>f[s[-1]]):\n s.pop()\n ans[ind.pop()]=a[j]\n if(len(s)==0):\n break\n s.append(a[j])\n ind.append(j)\n for i in ans:\n print(i,end=\" \")\n print()\n''' \n","sub_path":"HackerEarth/fight_for_laddus.py","file_name":"fight_for_laddus.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"540066617","text":"#!/usr/bin/env python\n\nPACKAGE = 'amr_braitenberg'\nNODE = 'braitenberg_vehicle'\n\nimport rospy\n\nfrom amr_srvs.srv import SwitchRanger, SwitchRangerRequest\nfrom amr_msgs.msg import WheelSpeeds, Ranges\nfrom amr_braitenberg.braitenberg_vehicle import BraitenbergVehicle\nimport amr_braitenberg.cfg.BraitenbergVehicleConfig as BraitenbergVehicleConfig\n\nimport dynamic_reconfigure.server\n\n\nclass BraitenbergVehicleNode:\n \"\"\"\n BraitenbergVehicle node ported and refactored.\n \"\"\"\n \n \n def __init__(self):\n \n rospy.init_node(NODE, log_level=rospy.DEBUG)\n \n # Wait until SwitchRanger service (and hence stage node) becomes available:\n rospy.loginfo('Waiting for the /switch_ranger service to be advertised...')\n switch_ranger_client = rospy.ServiceProxy('/switch_ranger', SwitchRanger)\n \n switch_ranger_client.wait_for_service()\n # Make sure that the braitenberg sonars are available and enable them.\n srr = SwitchRangerRequest()\n srr.name = 'sonar_braitenberg'\n srr.state = True\n \n if switch_ranger_client.call(srr):\n rospy.loginfo('Enabled braitenberg sonars.')\n else:\n rospy.logerr('Braitenberg sonars are not available, shutting down.')\n exit()\n self._vehicle = BraitenbergVehicle()\n \n \"\"\"\n Subscribers and publishers\n \"\"\"\n \n self._sonar_subscriber = rospy.Subscriber('/sonar_braitenberg',\n Ranges,\n self._sonar_callback,\n queue_size=100)\n self._wheel_speeds_publisher = rospy.Publisher('/cmd_vel_diff',\n WheelSpeeds,\n queue_size=100)\n self._dynamic_reconfigure = dynamic_reconfigure.server.Server(\n BraitenbergVehicleConfig,\n self._reconfigure_callback)\n rospy.loginfo('Started [braitenberg_vehicle] node.')\n \n \n def _sonar_callback(self, ranges_msg):\n \"\"\"\n ========================= YOUR CODE HERE =========================\n This node subscribes to the Braitenberg vehicle sonars.\n This function is called every time the Ranges message arrives.\n See the declaration of the ranges message in amr_msgs/msg/Ranges.msg\n for the message contents.\n\n Instructions: based on the ranges reported by the two\n sonars compute the wheel speds and fill\n in the WheelSpeeds message.\n \n Publish the message using\n self._wheel_speeds_publisher\n\n\n Hint: use self._vehicle.compute_wheel_speeds(...) function\n ==================================================================\n \"\"\"\n x = self._vehicle.compute_wheel_speeds(ranges_msg.ranges[0].range,ranges_msg.ranges[1].range)\n ws = WheelSpeeds()\n ws.speeds.append(x[0])\n ws.speeds.append(x[1])\n #ws.speeds[1] = y\n\n # Output the debug info:\n rospy.logdebug('[{:.2f}, {:.2f}] --> [{:.2f}, {:.2f}]'.format(\n ranges_msg.ranges[0].range,\n ranges_msg.ranges[1].range,\n ws.speeds[0],\n ws.speeds[1]))\n self._wheel_speeds_publisher.publish(ws)\n \n \n def _reconfigure_callback(self, config, params):\n \"\"\"\n ========================= YOUR CODE HERE =========================\n This function is called on the reconfiguration request via dynamic reconfigure.\n The dynamic reconfigurable parameters are declared in\n amr_braitenberg/cfg/BraitenbergVehicle.cfg\n\n Instructions: pass the new parameters to your BraitenbergVehicle instance\n self._vehicle.set_params(....)\n\n Hint: see the logdebug message below for an example how to access config parameters.\n ==================================================================\n \"\"\"\n self._vehicle.set_params(config.type,config.factor1,config.factor2)\n\n rospy.logdebug('Vehicle reconfigured: type {}, '\n 'factors {:.2f}] and {:.2f}]'.format(\n ['A','B','C'][config.type],\n config.factor1,\n config.factor2))\n return config\n\n\nif __name__ == '__main__':\n n = BraitenbergVehicleNode()\n rospy.spin()\n","sub_path":"amr_braitenberg/nodes/braitenberg_vehicle.py","file_name":"braitenberg_vehicle.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"571261871","text":"# -*- coding: utf-8 -*-\n\"\"\" 01 Higher-orer MC.py\nThis script assumes a higher order Markov chain model for a given taxi trip.\nGiven a partial trip, we loop through the complete training set and find all \ntrajectories that that contain the sequence of last k transitions of the \npartial trip.\n\nA quick destination density estimate can then be obtained by using the\nempirical distribution of the destinations of the matched trips.\n\nAlternatively, we can employ a random walk model where the transitional \nprobabilities are only estimated from the matched trips.\n\"\"\"\n\nfrom __future__ import division\nfrom DestinationGrid import *\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\n\ndef match(segment, trip, k):\n for idx in range(k, len(trip) + 1):\n partial = trip[(idx - k):idx]\n if partial == segment:\n return True\n \n return False\n \nif __name__ == \"__main__\":\n # Location of the data\n filepath = \"E:/MSc thesis/Processed data/train_binarized_trips_train.csv\"\n filepath_val = \"E:/MSc thesis/Processed data/train_binarized_trips_validation.csv\"\n \n # From visual inspection of porto map. We are only focusing on the city centre\n lon_vals = (-8.73, -8.5)\n lat_vals = (41.1, 41.25) \n \n # Number of points used for the discretization\n N = 100\n M = 75\n \n # Markov chain order\n k = 3\n \n # Import the training data in chunks\n trips = pd.read_csv(filepath_or_buffer = filepath,\n sep = \",\",\n nrows = 1000,\n #chunksize = 10000,\n usecols = [\"POLYLINE\", \"GRID_POLYLINE\"],\n converters = {\"POLYLINE\": lambda x: json.loads(x),\n \"GRID_POLYLINE\": lambda x: eval(x)})\n \n # Import the validation data\n test = pd.read_csv(filepath_or_buffer = filepath_val,\n sep = \",\",\n nrows = 10,\n converters = {#\"TIMESTAMP\" : lambda x: datetime.datetime.fromtimestamp(x),\n \"POLYLINE\": lambda x: json.loads(x),\n \"START_POINT\": lambda x: eval(x),\n \"GRID_POLYLINE\": lambda x: eval(x),\n \"TRUNC_POLYLINE\": lambda x: eval(x),\n \"TRUNC_GRID_POLYLINE\": lambda x: eval(x)})\n \n # Select a partial trip \n partial_trip = test.loc[0]\n \n trips[\"DEST_CELL\"] = trips.GRID_POLYLINE.map(lambda x: x[-1])\n \n # Select the last segment of the partial trip\n end = partial_trip.TRUNC_GRID_POLYLINE[-k:]\n \n # Create a dummy flag to indicate if a trip matches or not\n trips[\"MATCH\"] = False\n \n # Match this segment with trips in the training set\n for idx, row in trips.iterrows():\n if match(end, row.GRID_POLYLINE, k):\n trips.set_value(idx, 'MATCH', True)\n \n # We are only really interested in the matched trips now\n trips = trips[trips.MATCH]\n \n # Compute the destination distribution\n trips_agg = trips.groupby([\"DEST_CELL\"], as_index = False).aggregate({\"MATCH\": \"sum\"})\n trips_agg.MATCH = trips_agg.MATCH / np.sum(trips_agg.MATCH)\n \n # Store it in a DestinationGrid object\n grid = DestinationGrid(N, M)\n grid.setProbs(trips_agg.DEST_CELL.values, trips_agg.MATCH.values)\n \n # Plot the new distribution\n plt.subplot(1,2,1)\n plt.imshow(np.log(grid.as_array() + trip_to_array(partial_trip.GRID_POLYLINE, N, M)), interpolation = \"nearest\")\n plt.title(\"Complete trip superimposed\")\n \n plt.subplot(1,2,2)\n plt.imshow(np.log(grid.as_array() + trip_to_array(partial_trip.TRUNC_GRID_POLYLINE, N, M)), interpolation = \"nearest\")\n plt.title(\"Partial trip superimposed\")","sub_path":"Destination prediction/Trip-matching/01 Higher-order MC.py","file_name":"01 Higher-order MC.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"315371195","text":"#!/usr/bin/env python3\n\n\"\"\"\nScript:\trandom_documents.py\nDate:\t2018-09-30\n\nPlatform: MacOS\n\nDescription:\nCreates a radom text (English language like) document.\nWith no parameters, it outputs to screen\nWith a file specified, it will output to file\n\n\"\"\"\n__author__ = \"thedzy\"\n__copyright__ = \"Copyright 2018, thedzy\"\n__license__ = \"GPL\"\n__version__ = \"1.0\"\n__maintainer__ = \"thedzy\"\n__email__ = \"thedzy@hotmail.com\"\n__status__ = \"Developer\"\n\nimport os\nimport sys\nfrom random import *\n\n\ndef main():\n if len(sys.argv) == 1:\n print(document())\n\n # For file arguments\n for arg in range(1, len(sys.argv)):\n try:\n # Get filename\n filename = str(sys.argv[arg])\n\n # Check for txt extension\n extension = os.path.splitext(filename)[1][1:]\n if extension != \"txt\":\n filename += \".txt\"\n\n print(\"Writeing out to: \" + filename)\n file = open(filename, \"w\")\n except OSError as error:\n print(\"OS error: {0}\".format(error))\n sys.exit()\n\n file.write(document())\n file.close()\n\n\ndef word(capital=False):\n \"\"\"\n Create a pseudo english word\n :param capital: (Bool) Use captial letter\n :return: (String) word\n \"\"\"\n fletters = [\"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"qu\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"y\", \"z\", \"bl\", \"br\", \"ch\", \"cl\", \"cr\", \"dr\", \"fl\", \"fr\", \"gl\", \"gr\", \"gw\", \"ph\", \"pl\", \"pr\", \"sc\", \"sh\", \"sk\", \"sl\", \"sm\", \"sn\", \"sp\", \"st\", \"sw\", \"th\", \"tr\", \"tw\", \"wh\", \"wr\", \"sch\", \"scr\", \"shr\", \"sph\", \"spl\", \"spr\", \"squ\", \"str\", \"thr\"]\n cletters = [\"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"qu\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"z\", \"bl\", \"br\", \"ch\", \"cl\", \"cr\", \"dr\", \"fl\", \"fr\", \"gl\", \"gr\", \"gh\", \"gn\", \"ph\", \"pl\", \"pr\", \"sc\", \"sh\", \"sk\", \"sl\", \"sm\", \"sn\", \"sp\", \"st\", \"sw\", \"th\", \"tr\", \"tw\", \"wh\", \"wr\", \"sch\", \"scr\", \"shr\", \"sph\", \"spl\", \"spr\", \"squ\", \"str\", \"thr\"]\n vletters = [\"a\", \"e\", \"i\", \"o\", \"u\", \"ai\", \"au\", \"ay\", \"ea\", \"ee\", \"ei\", \"eu\", \"ey\", \"ie\", \"oi\", \"oo\", \"ou\", \"oy\", \"eau\", \"y\"]\n yletters = [\"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"qu\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"y\", \"z\", \"ch\", \"ph\", \"sh\", \"sk\", \"sp\", \"st\", \"th\"]\n zletters = [\"a\", \"e\", \"i\", \"o\", \"u\", \"ai\", \"au\", \"ay\", \"ea\", \"ee\", \"eu\", \"ey\", \"ie\", \"oi\", \"oo\", \"ou\", \"oy\", \"eau\", \"y\"]\n\n wordlen = randint(0, 5)\n\n if wordlen == 0:\n word = sample(vletters, 1)[0]\n else:\n word = sample(fletters, 1)[0]\n\n for i in range(wordlen):\n if i % 2 == 0:\n word += sample(vletters, 1)[0]\n else:\n word += sample(cletters, 1)[0]\n\n if i % 2 == 0:\n word += sample(yletters, 1)[0]\n else:\n word += sample(zletters, 1)[0]\n\n if capital:\n word = word.title()\n\n return word\n\n\ndef sentance(words=0):\n \"\"\"\n Create a pseudo english sentance\n :param words: (int) Number of words\n :return: (string) Sentance\n \"\"\"\n punctuation = [\".\", \".\", \".\", \".\", \".\", \".\", \"!\", \"?\"]\n quoted = False\n\n if words == 0:\n words = randint(2, 20)\n\n sentance = \"\"\n for i in range(words):\n if i == 0:\n sentance += word(True)\n else:\n # Chance of punctuation\n if i != words and randint(0, 100) == 0:\n sentance += \"\\'s\"\n\n if randint(0, 10) == 0:\n sentance += \",\"\n elif randint(0, 100) == 0:\n sentance += \";\"\n elif randint(0, 200) == 0:\n sentance += \":\"\n\n # Space words or Hyphenate\n if randint(0, 200) == 0:\n sentance += \"-\"\n else:\n sentance += \" \"\n\n # Chance of quote\n if randint(0, 100) == 0:\n quoted = True\n sentance += '\"'\n sentance += word()\n\n # Close quotes out within x words\n if quoted and randint(0, 8) == 0:\n quoted = False\n sentance += '\"'\n\n # Make sure quotes end\n if quoted:\n sentance += '\"'\n\n return sentance + sample(punctuation, 1)[0] + \" \"\n\n\ndef paragraph(sentances=0):\n \"\"\"\n Create a pseudo english paragraph\n :param sentances: (Int) Number of sentances\n :return: (String) Paragraph\n \"\"\"\n if sentances == 0:\n sentances = randint(5, 20)\n\n paragraph = \"\"\n for i in range(sentances):\n if i == 0:\n paragraph += sentance()\n else:\n paragraph += sentance()\n\n return paragraph + \"\\n\\n\"\n\n\ndef document(paragraphs=0):\n \"\"\"\n Create a pseudo english document\n :param paragraphs: (Int) Number of paragraphs\n :return: (String) Document\n \"\"\"\n if paragraphs == 0:\n paragraphs = randint(5, 20)\n\n document = \"\"\n for i in range(paragraphs):\n if i == 0:\n document += paragraph()\n else:\n document += paragraph()\n\n return document\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Scripts/random_documents/random_documents.py","file_name":"random_documents.py","file_ext":"py","file_size_in_byte":5096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326248128","text":"import torch\r\nfrom chapter08.knock71 import X_train\r\nfrom chapter08.knock72 import y_train\r\nfrom chapter08.knock74 import y_valid, X_valid\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n\r\nwriter = SummaryWriter()\r\n\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\n\r\nclass LogisticRegression(torch.nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n self.net = torch.nn.Sequential(\r\n torch.nn.Linear(300, 4),\r\n )\r\n def forward(self, X):\r\n return self.net(X)\r\n\r\nmodel = LogisticRegression()\r\n\r\nds = TensorDataset(X_train, y_train)\r\n\r\n# DataLoaderを作成\r\nloader = DataLoader(ds, batch_size=1, shuffle=True)\r\n\r\nloss_fn = torch.nn.CrossEntropyLoss()\r\noptimizer = torch.optim.SGD(model.net.parameters(), lr=1e-1)\r\n\r\nfor epoch in range(10):\r\n for xx, yy in loader:\r\n y_pred = model(xx)\r\n loss = loss_fn(y_pred, yy)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n with torch.no_grad():\r\n y_pred = model(X_train)\r\n loss = loss_fn(y_pred, y_train)\r\n writer.add_scalar('Loss/train', loss, epoch)\r\n writer.add_scalar('Accuracy/train', accuracy(y_pred,y_train), epoch)\r\n\r\n y_pred = model(X_valid)\r\n loss = loss_fn(y_pred, y_valid)\r\n writer.add_scalar('Loss/valid', loss, epoch)\r\n writer.add_scalar('Accuracy/valid', accuracy(y_pred,y_valid), epoch)\r\n","sub_path":"yamaguchi/chapter08/knock75.py","file_name":"knock75.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463080837","text":"import threading\n\n'''\nSome sort of \"job\" to be done\n'''\ndef thread_job(msg):\n print(\"{}:{}\".format(threading.current_thread().name, msg))\n\ndef main():\n\n msgs = [\n \"A message executing in parallel???\",\n \"yet another???\",\n \"DU YOR FAHVZ!!!!!!\",\n \"how much wood did the wood-chuck chuck???\"\n ]\n\n threads = []\n for msg in msgs:\n '''\n * Target: the function that the thread will execute\n * args: the tuple of arguments that the function will parse to\n the function - must end with an \",\" at the end!\n * daemon: if True, the threaddies when the master process stops\n running\n '''\n thread = threading.Thread(\n target = thread_job,\n args = (msg,),\n daemon = True\n )\n thread.start()\n threads.append(thread)\n\n '''\n If we want to wait for a thread to complete its task - prior to the exec\n of the next thread; calling thread.join() will acomplish this.\n '''\n for thread in threads:\n thread.join()\n\n print(\"All Done!\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Basic_Threading.py","file_name":"Basic_Threading.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"182726436","text":"#A program to calculate the largest prime factor of 600851475143\nimport time\n\n#Declare Variables\nstart = time.time()\n\nnumber = 600851475143\ni = 2\n\nwhile i * i < number:\n while number % i == 0:\n number = number / i\n i += 1\n\nprint (number)\nprint (\"Time =\", time.time()-start, \"s\")\n","sub_path":"Problem03/largestPrimeFactor.py","file_name":"largestPrimeFactor.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"523866755","text":"def solution(progresses, speeds):\n Q = []\n for p,s in zip(progresses, speeds):\n if ((100 - p) % s) != 0:\n day = (100 - p)//s + 1\n else:\n day = (100 - p)//s\n if len(Q) == 0 or Q[-1][0] < day:\n Q.append([day, 1])\n else:\n Q[-1][1] += 1\n return [q[1] for q in Q]\n","sub_path":"programmers/고득점_kit_python/stack-queue/기능개발.py","file_name":"기능개발.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"135145103","text":"import re\nimport urllib.request\n\nregex = re.compile((\"([a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`\"\n \"{|}~-]+)*(@|\\sat\\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\\.|\"\n \"\\sdot\\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\"))\ndef get_emails(s):\n return (email[0] for email in re.findall(regex, s) if not email[0].startswith('//'))\n\nif __name__ == '__main__':\n response = urllib.request.urlopen('https://www.cs.wisc.edu/people/undergraduate-students')\n page_source = response.read()\n emaillist = \"\"\n for email in get_emails(str(page_source, 'utf-8')):\n emaillist += email + \", \"\n print(emaillist)","sub_path":"EmailCrawler/csguysemail.py","file_name":"csguysemail.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455533017","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2018/10/15\n@Author : AnNing\n\"\"\"\nimport os\n\n\nCURRENT_FILE = os.path.realpath(__file__)\nCURRENT_DIR = os.path.dirname(CURRENT_FILE)\nGSICS_DIR = os.path.dirname(CURRENT_DIR)\n\n\ndef get_cross_cfg_path():\n \"\"\"\n 获取gsics cfg目录的路径\n :return:\n \"\"\"\n return os.path.join(GSICS_DIR, 'mod_cross', 'cfg')\n","sub_path":"lib_gsics/lib_cross_path.py","file_name":"lib_cross_path.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598832388","text":"\n\n#calss header\nclass _HIDING():\n\tdef __init__(self,): \n\t\tself.name = \"HIDING\"\n\t\tself.definitions = [u'a punishment that consists of being beaten repeatedly', u'a total defeat: ', u'to be/go somewhere where you cannot be found']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_hiding.py","file_name":"_hiding.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54663147","text":"import urllib.request\nimport urllib.parse\nfrom .TwitterAPIResponse import TwitterAPIResponse\n\n\nclass TwitterAPIRequest:\n\n _allowedRequestMethods = ['GET', 'POST', 'PUT', 'DELETE'] # Define allowed request methods\n\n _url = None\n _data = {}\n _method = 'GET'\n _header = {}\n\n def __init__(self, url, data=None, method='GET', header=None):\n \"\"\"Python\n\n :param url:\n :param data:\n :param method:\n :return:\n \"\"\"\n\n self.set_url(url)\n self.set_data(data)\n self.set_method(method)\n self.set_header(header)\n\n def set_url(self, url):\n\n self._url = url\n\n def set_data(self, data):\n\n if isinstance(data, dict) is True:\n self._data = data\n\n def set_method(self, method):\n\n if method in self._allowedRequestMethods:\n self._method = method\n\n def set_header(self, header):\n\n self._header = header\n\n def prepare_request(self):\n \"\"\"Python 3\n Prepare Request object\n\n :return: Request\n \"\"\"\n\n # Treat header codification\n has_encoding = False\n for key, value in self._header.items():\n if key.lower() == 'accept-encoding' and value == 'gzip':\n has_encoding = True\n\n if not has_encoding:\n self._header['Accept-Encoding'] = 'gzip'\n\n # Treat DATA that will be sent to server\n data_to_be_sent = urllib.parse.urlencode(self._data).encode('ascii')\n\n # Treat URL that will be requested\n url_requested = \"https://api.twitter.com%s\" % self._url\n\n if data_to_be_sent != b'':\n return urllib.request.Request(url_requested, data_to_be_sent, self._header)\n else:\n return urllib.request.Request(url_requested, headers=self._header)\n\n def request(self):\n \"\"\" Python 3\n Makes request to the server\n\n :return: TwitterAPIResponse\n \"\"\"\n\n try:\n response_from_request = urllib.request.urlopen(self.prepare_request())\n\n return TwitterAPIResponse(response_from_request)\n except Exception as ex:\n print(ex)\n return False\n","sub_path":"src/TwitterAPIRequest.py","file_name":"TwitterAPIRequest.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"417694062","text":"import sqlite3\nfrom typing import List, Optional\n\n\nclass WikiMapper:\n \"\"\" Uses a precomputed database created by `create_wikipedia_wikidata_mapping_db`. \"\"\"\n\n def __init__(self, path_to_db: str):\n self._path_to_db = path_to_db\n\n def title_to_id(self, page_title: str) -> Optional[str]:\n \"\"\" Given a Wikipedia page title, returns the corresponding Wikidata ID.\n\n The page title is the last part of a Wikipedia url **unescaped** and spaces\n replaced by underscores , e.g. for `https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem`,\n the title would be `Fermat's_Last_Theorem`.\n\n Args:\n page_title: The page title of the Wikipedia entry, e.g. `Manatee`.\n\n Returns:\n Optional[str]: If a mapping could be found for `wiki_page_title`, then return\n it, else return `None`.\n\n \"\"\"\n\n with sqlite3.connect(self._path_to_db) as conn:\n c = conn.cursor()\n c.execute(\"SELECT wikidata_id FROM mapping WHERE wikipedia_title=?\", (page_title,))\n result = c.fetchone()\n\n if result is not None and result[0] is not None:\n return result[0]\n else:\n return None\n\n def url_to_id(self, wiki_url: str) -> Optional[str]:\n \"\"\" Given an URL to a Wikipedia page, returns the corresponding Wikidata ID.\n\n This is just a convenience function. It is not checked whether the index and\n URL are from the same dump.\n\n Args:\n wiki_url: The URL to a Wikipedia entry.\n\n Returns:\n Optional[str]: If a mapping could be found for `wiki_url`, then return\n it, else return `None`.\n\n \"\"\"\n\n title = wiki_url.rsplit(\"/\", 1)[-1]\n return self.title_to_id(title)\n\n def id_to_titles(self, wikidata_id: str) -> List[str]:\n \"\"\" Given a Wikidata ID, return a list of corresponding pages that are linked to it.\n\n Due to redirects, the mapping from Wikidata ID to Wikipedia title is not unique.\n\n Args:\n wikidata_id (str): The Wikidata ID to map, e.g. `Q42797`.\n\n Returns:\n List[str]: A list of Wikipedia pages that are linked to this Wikidata ID.\n\n \"\"\"\n\n with sqlite3.connect(self._path_to_db) as conn:\n c = conn.cursor()\n c.execute(\n \"SELECT DISTINCT wikipedia_title FROM mapping WHERE wikidata_id =?\", (wikidata_id,)\n )\n results = c.fetchall()\n\n return [e[0] for e in results]\n","sub_path":"wikimapper/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"167514579","text":"# def is_palindrome(num):\n# # Skip single-digit inputs\n# if num // 10 == 0:\n# return False\n# temp = num\n# reversed_num = 0\n#\n# while temp != 0:\n# reversed_num = (reversed_num * 10) + (temp % 10)\n# temp = temp // 10\n#\n# if num == reversed_num:\n# return True\n# else:\n# return False\n#\n# def infinite_palindromes():\n# num = 0\n# while True:\n# if is_palindrome(num):\n# i = (yield num)\n# print(i)\n# if i is not None:\n# num = i\n# num += 1\n#\n# pal_gen = infinite_palindromes()\n# for i in pal_gen:\n# digits = len(str(i))\n# pal_gen.send(10 ** (digits))\n\n\ndef loops():\n x = 0\n print(x)\n while x < 10:\n print(x)\n yield x\n x = x + 1\n\n\ng = 1\nfor n in loops():\n print(n)\n # string = string + s\n g += 1\n\n","sub_path":"Generators/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"477378254","text":"import torch\nimport torch.nn.functional as F\nimport numbers\nimport collections\n\nfrom . import creation\nimport nestedtensor\n\nTensorMask = collections.namedtuple('TensorMask', 'tensor mask')\n\ndef nested_tensor_from_padded_tensor(tensor, nested_dim=1, padding=-1):\n mask = (tensor != padding)\n return nested_tensor_from_tensor_mask(tensor, mask, nested_dim)\n\n\n# Constructs nested tensor from passed tensor and mask.\ndef nested_tensor_from_tensor_mask(tensor, mask, nested_dim=1):\n if tensor is None:\n raise RuntimeError(\"Tensor can't be undefined (None).\")\n\n if mask is None:\n raise RuntimeError(\"Mask can't be undefined (None).\")\n\n # Scalar was passed\n if tensor.dim() == 0:\n raise RuntimeError(\"Can't construct nested tensor from a scalar.\")\n\n if nested_dim == 0:\n raise RuntimeError(\"Nested dimension can't be 0.\")\n\n if nested_dim is not None and nested_dim > tensor.dim():\n raise RuntimeError(\"Nested dimension ({0}) can't be bigger than data tensor dimension ({1}).\".format(nested_dim, tensor.dim()))\n\n if tensor.numel() == 0 and mask.numel() != 0:\n raise RuntimeError(\"Data tensor can't be emtpy if a mask has values.\")\n\n if tensor.numel() != 0 and mask.numel() == 0:\n raise RuntimeError(\"Mask tensor can't be emtpy if a data tensor has values.\")\n\n return nt_from_tensor_mask(tensor, mask, nested_dim)\n\n\ndef nt_from_tensor_mask(tensor, mask, nested_dim):\n def _merge(tensors, nested_dim):\n if len(tensors) == 0:\n return torch.tensor([]).to(tensor)\n return torch.stack(tensors)\n\n if nested_dim == 0:\n if (mask.numel() == 0) or (mask.numel() == 1 and mask.item() == True):\n return tensor\n\n if mask.dim() == 1:\n tensors = [tensor[i] if mask[i] else None for i in range(len(mask))]\n tensors = list(filter(lambda x: x is not None, tensors))\n return _merge(tensors, nested_dim)\n\n if mask.dim() > 1:\n tensors = [nt_from_tensor_mask(t, m, nested_dim) for (t, m) in zip(tensor, mask)]\n if not all(t.numel() == 0 for t in tensors):\n tensors = list(filter(lambda x: x.numel() > 0, tensors))\n return _merge(tensors, nested_dim)\n\n return None\n\n inner_tensors = []\n if (mask.numel() == 0) or (mask.numel() == 1 and mask == True):\n for i in range(len(tensor)):\n inner_tensors.append(nt_from_tensor_mask(tensor[i], mask, nested_dim - 1))\n elif (mask.numel() == 1 and mask == False):\n inner_tensors.append(None)\n else:\n inner_tensors = [nt_from_tensor_mask(t, m, nested_dim - 1) for (t, m) in zip(tensor, mask)]\n\n # Filtering out None values which were ignored by mask\n inner_tensors = list(filter(lambda x: x is not None, inner_tensors))\n return creation.nested_tensor(inner_tensors, requires_grad=tensor.requires_grad)\n\n# Get max size per each dimension from all the passed tensors.\ndef get_max_size(obj, res=None):\n if res is None:\n res = [1]\n if isinstance(obj, list) or isinstance(obj, tuple):\n for o in obj:\n res = get_max_size(o, res)\n\n if isinstance(obj, nestedtensor.nested.nested.NestedTensor):\n tres = get_max_size(obj.unbind())\n while len(tres) > len(res):\n res.append(0)\n\n res = [max(i, j) for (i, j) in zip(res, tres)]\n\n if isinstance(obj, torch.Tensor):\n # scalar\n if obj.dim() == 0 and obj.numel() == 1:\n res = [1]\n else:\n while len(obj.size()) > len(res):\n res.append(0)\n\n res = [max(i, j) for (i, j) in zip(res, obj.size())]\n\n return res\n\ndef get_tensor_mask(nt, shape):\n def pad_nt(nt, shape):\n\n if isinstance(nt, torch.Tensor):\n if nt.numel() == 0:\n raise RuntimeError(\"Empty tensors are not yet supported.\")\n\n # Dont pad in case of a scalar\n if nt.dim() == 0:\n return nt, torch.tensor(True)\n\n tensor = pad_tensor_to_shape(nt, shape)\n mask = pad_tensor_to_shape(nt.new_full(nt.size(), True, dtype=torch.bool), shape)\n return tensor, mask\n\n res_tensor = []\n res_mask = []\n if len(nt) == 0:\n return torch.tensor([0]), torch.tensor([False], dtype=torch.bool)\n else:\n for entry in nt:\n tensor, mask = pad_nt(entry, shape)\n res_tensor.append(tensor)\n res_mask.append(mask)\n\n return torch.stack(res_tensor), torch.stack(res_mask)\n\n t, m = pad_nt(nt, shape)\n return t, m\n\n\n# Return a tuple of a tensor and a mask that represent the given tensor list\n# Returned tensor is always the same no matter what mask_dim was passed.\n# If mask_dim was not passed, a mask with the smallest dimensionality would be returned.\n# if passed mask_dim is lower than the minimal dimensionality of the mask that can represent\n# the data tensor, an error is thrown.\ndef to_tensor_mask(nt, mask_dim):\n if mask_dim is not None and mask_dim > nt.dim():\n raise RuntimeError(\"Mask dimension is bigger than nested dimension of a nested tensor.\")\n\n # Check if scalar was passed\n if not isinstance(nt, list) and nt.size() == (1,):\n res_scalar = torch.tensor([nt[0].item()], dtype=nt.dtype, device=nt.device, requires_grad=nt.requires_grad)\n mask = torch.tensor(True) if mask_dim == 0 or mask_dim == None else torch.tensor([True])\n return res_scalar, mask\n\n max_size = get_max_size(nt)\n res_tensor, res_mask = get_tensor_mask(nt, max_size)\n tensor_mask_tuple = merge_tensor_mask(TensorMask(res_tensor, res_mask), mask_dim)\n\n return tensor_mask_tuple.tensor, tensor_mask_tuple.mask\n\n\n# Merge mask to a given dimension if possible.\ndef merge_tensor_mask(tensor_mask, mask_dim):\n tensor = tensor_mask.tensor\n mask = tensor_mask.mask\n if mask_dim is not None and mask.dim() == mask_dim:\n return tensor_mask\n\n if mask.dim() == 0:\n return tensor_mask\n\n last_size = mask.size(-1)\n collapsed_mask = mask.sum(-1)\n is_last_size = (collapsed_mask == last_size)\n is_zero = (collapsed_mask == 0)\n if (is_last_size.sum() + is_zero.sum()) == collapsed_mask.numel():\n collapsed_mask = collapsed_mask.to(torch.bool)\n return merge_tensor_mask(TensorMask(tensor=tensor, mask=collapsed_mask), mask_dim)\n\n if mask_dim is not None and mask_dim != mask.dim():\n raise RuntimeError(\"Mask dimension is too small to represent data tensor.\")\n # This is expected to be a no-op, except in rare cases.\n tensor = tensor.contiguous()\n mask = mask.contiguous()\n return TensorMask(tensor=tensor, mask=mask)\n\n\ndef pad_tensor_to_shape(t, goal_shape):\n padd = ()\n tup = tuple(t.size())\n assert(t.dim() == len(goal_shape))\n for i in range(len(tup)):\n padd = (0, goal_shape[i] - tup[i]) + padd\n new_tensor = F.pad(t, padd)\n new_tensor = new_tensor.reshape(goal_shape)\n return new_tensor\n","sub_path":"nestedtensor/nested/masking.py","file_name":"masking.py","file_ext":"py","file_size_in_byte":7014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"576416459","text":"\"\"\"wat URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views.generic import RedirectView\nfrom .views import (\n IndexView,\n SuccessView,\n FailedView,\n WatView,\n)\nfrom correction.views import (\n CorrectView,\n ValidateView,\n)\n \nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', IndexView.as_view(), name=\"index\"),\n url(r'^home/',RedirectView.as_view(url='/')),\n url(r'^success/', SuccessView.as_view(), name='success'),\n url(r'^failed/', FailedView.as_view(), name='failed'),\n url(r'^correct/', CorrectView.as_view(), name=\"correct\"),\n url(r'^validate/', ValidateView.as_view(), name=\"validate\"),\n url(r'^wat/', WatView.as_view(), name='wat'),\n url(r'^demo/', include('demo.urls')),\n]\n","sub_path":"demo/wat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"145828336","text":"import json\nimport boto3\nimport base64\n\ns3 = boto3.client('s3')\n\n\ndef lambda_handler(event, context):\n print(event)\n if event['httpMethod'] == 'POST':\n print\n event['body']\n data = json.loads(event['body'])\n name = data['name']\n image = data['file']\n image = image[image.find(\",\") + 1:]\n dec = base64.b64decode(image + \"===\")\n s3.put_object(Bucket='image-storing-bucket-ahrar', Key=name, Body=dec)\n return {'statusCode': 200, 'body': json.dumps({'message': 'successful lambda function call'}),\n 'headers': {'Access-Control-Allow-Origin': '*'}}","sub_path":"image_upload_api.py","file_name":"image_upload_api.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546852442","text":"from .base import ModelType, AbstractModel\n\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.externals import joblib\nimport os\nimport numpy as np\n\nclass NaiveBeyes(AbstractModel):\n def __init__(self,\n X_train = None,\n Y_train = None,\n X_test = None,\n Y_test = None,\n fpath = None):\n '''\n The NaiveBeyes model class\n\n :param X_train: training data\n :param Y_train: training target\n :param X_test: testing data\n :param Y_test: testing target\n :param fpath: the dictionart path of loading-model\n '''\n if fpath is None and (\n (X_train is None) or\n (Y_train is None) or\n (X_test is None) or\n (Y_test is None)\n ):\n raise ValueError(\"Should input 'X_train, Y_train, X_test, Y_test' or 'fpath'\")\n\n self.type = ModelType.NB\n\n if fpath is None:\n self.X_train = X_train\n self.Y_train = Y_train\n self.X_test = X_test\n self.Y_test = Y_test\n self.model = self._generate_model()\n else:\n self.model = self._load_model(fpath)\n\n def _generate_model(self):\n '''\n Generate model with empty class\n '''\n model = BernoulliNB(alpha=0.6)\n return model\n\n def evalution(self, is_GA = False):\n '''\n Evalution model with data 'self.X_test' and 'self.Y_test'\n\n :param is_GA: True or False. Whether using by Genetic Algorithm\n :return:\n if is_GA is True: AUC\n if is_GA is False: Accuracy, Precision, Recall, F1, TPR, FPR, AUC\n '''\n self.model.fit(self.X_train, self.Y_train)\n Y_pred = self.model.predict_proba(self.X_test)\n Y_pred = Y_pred[:,1]\n Y_test = self.Y_test\n return self.calculate(Y_test, Y_pred, is_GA=is_GA)\n\n def _load_model(self, fpath):\n '''\n Loading model from the dictionary 'fpath'.\n The model will be loaded from the 'fpath' in format:\n if keras: '_model_architecture.json' and '_model_weights.h5'\n if sklearn: '_model.pkl'\n\n :param fpath: the dictionary of saving-model\n :return:\n '''\n if os.path.exists(fpath):\n try:\n model = joblib.load(os.path.join(fpath, 'NB_model.pkl'))\n except:\n raise FileExistsError(\"The dictionary {} doesn't exist model pkl file\".format(fpath))\n return model\n else:\n raise FileExistsError(\"The dictionary {} doesn't exist model files\".format(fpath))\n\n def save_model(self, fpath):\n '''\n Save model into the dictionary 'fpath'.\n The model will be saved into the 'fpath' in format:\n if keras: '_model_architecture.json' and '_model_weights.h5'\n if sklearn: '_model.pkl'\n\n :param fpath: the dictionary of saving-model\n :return:\n '''\n if not os.path.exists(fpath):\n os.makedirs(fpath)\n joblib.dump(self.model, os.path.join(fpath, 'NB_model.pkl'))\n print(\"The NaiveBeyes Model save in \\n {}\".format(os.path.join(fpath, 'NB_model.pkl')))\n\n def evalution_with_data(self, X_test, Y_test):\n '''\n Evalution model with data 'X_test' and 'Y_test'\n\n :param X_test: the data using into model.predict\n :param Y_test: the true target data\n :return: Accuracy, Precision, Recall, F1, TPR, FPR, AUC\n '''\n Y_pred = self.model.predict(X_test)\n return self.calculate(Y_test, Y_pred)\n\n def predict(self, X_test):\n '''\n Predict data 'X_test' and return the classified output\n\n :param X_test: the data using into model.predict\n :return: np.array of classifed data(0 or 1)\n '''\n Y_pred = self.model.predict(X_test)\n return np.round(Y_pred).reshape(-1)\n\n def predict_proba(self, X_test):\n '''\n Predict data 'X_test' and return the probability output\n\n :param X_test: the data using into model.predict_proba\n :return: np.array of probability data([0, 1])\n '''\n Y_pred = self.model.predict_proba(X_test)[:,1]\n return Y_pred.reshape(-1)","sub_path":"code/model/naivebayes.py","file_name":"naivebayes.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"58041629","text":"from channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\n\nfrom prospects.channel_routing import urlpatterns as websocket_url_patterns\n\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n websocket_url_patterns\n )\n )\n\n})\n","sub_path":"realtime_resume/channel_routing.py","file_name":"channel_routing.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"78742415","text":"# Import images using the custom image pipeline for BW images.\n# Train a very basic conv net\n# The conv net and training code is based on the Udacity FMNIST tutorial\n\n\n# Import all needed libraries\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom torch.optim import Adam\nfrom torch.autograd import Variable\n\n# Import custom image handling functions\nfrom image_import_BW import get_mean_std, process_image_BW, wormDataset_BW, wormDatasetSampler, count_loader_samples\n\n# These last two are used to save info about how the training progressed\nimport pickle\nimport datetime\n\n# Set the full path to the main image directory\n# Paths on minimac\n#train_dir = '/Users/zplab/Desktop/VeraPythonScripts/vera_autofocus/microscope_images_5cat/train'\n#test_dir = '/Users/zplab/Desktop/VeraPythonScripts/vera_autofocus/microscope_images_5cat/test'\n\n# Paths on Squidward\n#train_dir = '/home/vera/VeraPythonScripts/vera_autofocus/microscope_images/train'\n#test_dir = '/home/vera/VeraPythonScripts/vera_autofocus/microscope_images/test'\n\n# Practice paths\ntrain_dir = '/Users/zplab/Desktop/VeraPythonScripts/vera_autofocus/microscope_images_3cat/practice'\ntest_dir = '/Users/zplab/Desktop/VeraPythonScripts/vera_autofocus/microscope_images_3cat/practice'\n\nnum_train = 32\nnum_test = 32\n\n# Get mean and std of images in the dataset\nmean, std = get_mean_std(train_dir, 30)\n\n# Load the images into the dataset\ntestdata = wormDataset_BW(test_dir, mean, std)\n\n# Augment the training set with vertical and horizontal flip\ntraindata = wormDataset_BW(train_dir, mean, std)\ntraindata_hflip = wormDataset_BW(train_dir, mean, std, 'hflip')\ntraindata_vflip = wormDataset_BW(train_dir, mean, std, 'vflip')\naugmented_traindata = torch.utils.data.ConcatDataset([traindata, traindata_hflip, traindata_vflip])\n\n# Get the classes\nclass_names = augmented_traindata.datasets[0].classes\nprint('Detected ' + str(len(class_names)) + ' classes in training data')\nprint(class_names)\n\n# Print out how many images are in the trainloader and testloader\nprint('Traindata length = ' + str(len(traindata)) + ', testdata length = ' + str(len(testdata)))\n\ntrainloader = torch.utils.data.DataLoader(augmented_traindata, batch_size=num_train, shuffle=False)\ntestloader = torch.utils.data.DataLoader(testdata, batch_size=num_test, shuffle=False)\n# Shuffle has to be set to False when using a sampler. If you want shuffling it needs to happen in the sampler\n# Removed sampler for now because it slows things down. Replace once the model is working\n# sampler = wormDatasetSampler(augmented_traindata)\n# sampler = wormDatasetSampler(testdata)\n\n# Check number of samples and distribution into classes for both the test and trainloaders\n#train_dict = count_loader_samples(trainloader)\n#test_dict = count_loader_samples(testloader)\n#print('Classes and sample counts in train loader:')\n#print(train_dict)\n#print('Classes and sample counts in test loader:')\n#print(test_dict)\n\n\n# Check if cuda is available, and set pytorch to run on GPU or CPU as appropriate\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\n print('Cuda available, running on GPU')\nelse:\n device = torch.device(\"cpu\")\n print('Cuda is not available, running on CPU')\n # Give the user a message so they know what is going on\n\nclass SimpleNet(nn.Module):\n def __init__(self, num_classes=10):\n super(SimpleNet, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=12, kernel_size=3, stride=1, padding=1)\n self.relu1 = nn.ReLU()\n\n self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=3, stride=1, padding=1)\n self.relu2 = nn.ReLU()\n\n self.pool = nn.MaxPool2d(kernel_size=2)\n\n self.conv3 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=3, stride=1, padding=1)\n self.relu3 = nn.ReLU()\n\n self.conv4 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=3, stride=1, padding=1)\n self.relu4 = nn.ReLU()\n\n self.fc = nn.Linear(in_features=16 * 16 * 24, out_features=num_classes)\n\n def forward(self, input):\n\n print(np.shape(input))\n output = self.conv1(input)\n output = self.relu1(output)\n print('Conv layer 1')\n print(np.shape(output))\n\n output = self.conv2(output)\n output = self.relu2(output)\n print('Conv layer 2')\n print(np.shape(output))\n\n output = self.pool(output)\n print('Pool layer 1')\n print(np.shape(output))\n\n output = self.conv3(output)\n output = self.relu3(output)\n print('Conv layer 3')\n print(np.shape(output))\n\n output = self.conv4(output)\n output = self.relu4(output)\n print('Conv layer 4')\n print(np.shape(output))\n\n output = self.pool(output)\n print('Pool layer 2')\n print(np.shape(output))\n\n output = output.view(-1, 16 * 16 * 24)\n print('Reshape')\n print(np.shape(output))\n\n output = self.fc(output)\n print('Fully connected')\n print(np.shape(output))\n\n return output\n\nprint('model defined')\n# Create an instance of the model\nmodel = SimpleNet()\noptimizer = Adam(model.parameters(), lr=0.001, weight_decay=0.0001)\n\n# Select a loss function\nloss_fn = nn.CrossEntropyLoss()\nprint('model created')\n\n#Create a learning rate adjustment function that divides the learning rate by 10 every 30 epochs\ndef adjust_learning_rate(epoch):\n\n lr = 0.001\n\n if epoch > 180:\n lr = lr / 1000000\n elif epoch > 150:\n lr = lr / 100000\n elif epoch > 120:\n lr = lr / 10000\n elif epoch > 90:\n lr = lr / 1000\n elif epoch > 60:\n lr = lr / 100\n elif epoch > 30:\n lr = lr / 10\n\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n\ndef save_models(epoch):\n torch.save(model.state_dict(), \"cifar10model_{}.model\".format(epoch))\n print(\"Checkpoint saved\")\n\ndef test():\n model.eval()\n test_acc = 0.0\n for i, (images, labels) in enumerate(testloader):\n \n test_acc = []\n\n #Predict classes using images from the test set\n images.unsqueeze_(0) # Color is 1D, make the tensor have a 4D shape anyway (color x batch x height x width)\n images.transpose_(0, 1) # Transpose to get expected order (batch x color x height x width)\n\n outputs = model(images)\n _,prediction = torch.max(outputs.data, 1)\n test_acc.append(torch.sum(prediction == labels.data))\n print('Test accuracy: ' + str(test_acc))\n \n return accuracy\n \n\n\n #Compute the average acc and loss over all 10000 test images\n test_acc = test_acc / 10000\n\n return test_acc\n\ndef train(num_epochs, losses):\n\n for epoch in range(num_epochs):\n\n # Put the model in training mode\n model.train()\n\n for i, (images, labels) in enumerate(trainloader):\n \n #Clear all accumulated gradients\n optimizer.zero_grad()\n \n # Pass the batch of images to the model, get outputs\n images.unsqueeze_(0) # Color is 1D, make the tensor have a 4D shape anyway (color x batch x height x width)\n images.transpose_(0, 1) # Transpose to get expected order (batch x color x height x width)\n outputs = model(images)\n\n # Pass the outputs and labels to the loss function, calculate loss\n loss = loss_fn(outputs,labels)\n #Backpropagate the loss\n loss.backward()\n\n #Adjust parameters according to the computed gradients\n optimizer.step()\n print('Loss: ' + str(loss.item()))\n losses.append(loss.item())\n\n #Call the learning rate adjustment function\n adjust_learning_rate(epoch)\n\n return losses\n\nlosses = []\nlosses = train(3, losses)\naccuracy = test()\n\n","sub_path":"train_simple_scratch.py","file_name":"train_simple_scratch.py","file_ext":"py","file_size_in_byte":7940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"258442995","text":"from room import Room\nfrom player import Player, Queue\nfrom world import World\n\nimport random\nfrom ast import literal_eval\nimport time\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\nmap_file = \"maps/test_line.txt\"\nmap_file = \"maps/test_cross.txt\"\nmap_file = \"maps/test_loop.txt\"\nmap_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph=literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n# traversal_path = ['n', 'n']\ntraversal_path = []\n\ndef traverse(player, moves_cue):\n # init queue\n q = Queue()\n # init set for visited rooms\n visited = set()\n # add current room to queue\n q.enqueue([player.current_room.id])\n # if queue is bigger than 0 there are things to explore\n while q.size() > 0:\n # as path is explored removefrom queue\n path = q.dequeue()\n # keep track of last room visited\n last_room = path[-1]\n # if the last room was not in previously visited\n if last_room not in visited:\n # add to list of visited\n visited.add(last_room)\n # Find all the exits for the room\n for exit in graph[last_room]:\n # if we find an exit in the room that is unexplored\n if graph[last_room][exit] == \"?\":\n # add path to list to explore\n return path\n # otherwise remove path as already explored\n else:\n # print('PAAAATH', path)\n lost = list(path)\n lost.append(graph[last_room][exit])\n q.enqueue(lost)\n return []\n\n\ndef move(player, moves_q):\n current_exits = graph[player.current_room.id]\n # print(current_exits)\n untried_exits = []\n for direction in current_exits:\n if current_exits[direction] == \"?\":\n untried_exits.append(direction)\n if len(untried_exits) == 0:\n unexplored = traverse(player, moves_q)\n room_num = player.current_room.id\n temp ={}\n for next in unexplored:\n temp[next] = next\n for direction in graph[room_num]:\n if graph[room_num][direction] in temp:\n moves_q.enqueue(direction)\n room_num = temp[next]\n break\n else:\n moves_q.enqueue(untried_exits[random.randint(0, len(untried_exits) - 1)])\n\n\nwill_not_give_up = True\nmax_moves = 960\nstart = time.time()\n\nwhile will_not_give_up:\n \n player = Player(world.starting_room)\n graph = {}\n # print(player.current_room.name)\n\n new_room = {}\n for direction in player.current_room.get_exits():\n new_room[direction] = \"?\"\n # print(new_room)\n graph[world.starting_room.id] = new_room\n # print(graph[world.starting_room.id])\n\n queue = Queue()\n total_moves = []\n move(player, queue)\n\n reverse_compass = {\"n\": \"s\", \"s\": \"n\", \"e\": \"w\", \"w\": \"e\"}\n\n while queue.size() > 0:\n init_prev_room = player.current_room.id\n dir = queue.dequeue()\n # print(dir. curr)\n player.travel(dir)\n total_moves.append(dir)\n next_room = player.current_room.id\n # print(next_room, init_prev_room)\n graph[init_prev_room][dir] = next_room\n # print(graph[init_prev_room], dir)\n if next_room not in graph:\n graph[next_room] = {}\n for exit in player.current_room.get_exits():\n graph[next_room][exit] = \"?\"\n # print(init_prev_room)\n graph[next_room][reverse_compass[dir]] = init_prev_room\n # print(graph[next_room])\n if queue.size() == 0:\n move(player, queue)\n if len(total_moves) < max_moves:\n traversal_path = total_moves\n max_moves = len(total_moves)\n will_not_give_up = False\n \nend = time.time()\nprint(end - start)\n\n\n# TRAVERSAL TEST\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\nplayer.current_room.print_room_description(player)\nwhile True:\n cmds = input(\"-> \").lower().split(\" \")\n if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n player.travel(cmds[0], True)\n elif cmds[0] == \"q\":\n break\n else:\n print(\"I did not understand that command.\")\n","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"460411992","text":"# -*- coding = utf-8 -*-\r\n# @Time:2021-02-01 17:16\r\n# @Author:来瓶安慕嘻\r\n# @File:力扣56_合并区间.py\r\n# @开始美好的一天吧 @Q_Q@\r\n\r\n\r\n\"\"\"\r\n以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。\r\n请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。\r\n\r\n示例 1:\r\n\r\n输入:intervals = [[1,3],[2,6],[8,10],[15,18]]\r\n输出:[[1,6],[8,10],[15,18]]\r\n解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].\r\n\r\n\"\"\"\r\n\r\n\r\ndef merge(intervals):\r\n result = []\r\n intervals.sort(key=lambda x: x[0])\r\n print(intervals)\r\n for interval in intervals:\r\n if len(result)==0 or interval[0]>result[-1][1]:\r\n result.append(interval)\r\n else:\r\n result[-1][1] = max(result[-1][1],interval[1])\r\n return result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n intervals = [[2, 6], [8, 10],[1, 3], [15, 18]]\r\n print(merge(intervals))\r\n li = [[1,4],[2,3]]\r\n print(merge(li))","sub_path":"力扣题/力扣56_合并区间.py","file_name":"力扣56_合并区间.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140356643","text":"import pygame\nimport os\nimport random\n\n\npygame.init()\n\nwidth, height = 600, 600\n\nwindow = pygame.display.set_mode((width, height))\npygame.display.set_caption(\"No Internet\")\n\nfps = 40\ncolor = (56, 240, 255)\nclock = pygame.time.Clock()\ncactus_speed = 2\ncactus_pos = [0, 500]\nx = [750, 900, 1050]\ncoordinate_x = random.choice(x)\n\nSPACE = pygame.transform.scale(pygame.image.load(os.path.join('Assets', '193.jpg')), (width, height))\nCACTUS_1 = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Cactus.png')), (64, 64))\nCACTUS_2 = pygame.transform.scale(pygame.image.load(os.path.join('Assets', '2cactus.png')), (75, 64))\nCACTUS_3 = pygame.transform.scale(pygame.image.load(os.path.join('Assets', '3cactus.png')), (80, 90))\n\ndef choose_cactus():\n cactus = [CACTUS_1, CACTUS_2, CACTUS_3] \n i = random.choice(cactus)\n return i\n \n\nrun = True\nwhile run == True:\n window.blit(SPACE, (0, 0))\n window.blit(choose_cactus(), (coordinate_x, cactus_pos[1]))\n if coordinate_x < -80:\n choose_cactus()\n coordinate_x = coordinate_x - cactus_speed \n clock.tick(fps)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n run = False\n \n pygame.display.update()\n \npygame.quit()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510421911","text":"import numpy as np\nimport discretisedfield as df\nimport matplotlib.pyplot as plt\nimport os\n\ndef getTime(file):\n with open(file, \"rb\") as ovffile:\n f = ovffile.read()\n lines = f.split(b\"\\n\")\n\n mdatalines = filter(lambda s: s.startswith(bytes(\"#\", \"utf-8\")), lines)\n for line in mdatalines:\n if b\"Total simulation time\" in line:\n return float(line.split()[5])\n\ndef getSpatialDimensions(file):\n with open(file, \"rb\") as ovffile:\n f = ovffile.read()\n lines = f.split(b\"\\n\")\n\n xNodes = 0\n yNodes = 0\n zNodes = 0\n\n mdatalines = filter(lambda s: s.startswith(bytes(\"#\", \"utf-8\")), lines)\n for line in mdatalines:\n if b\"xnodes\" in line:\n xNodes = int(line.split()[2])\n elif b\"ynodes\" in line:\n yNodes = int(line.split()[2])\n elif b\"znodes\" in line:\n zNodes = int(line.split()[2])\n\n if xNodes != 0 and yNodes != 0 and zNodes != 0:\n return xNodes, yNodes, zNodes\n\ndef getDiffArray(directory, relaxedStateFile):\n\n \"\"\" Gets the spatially-resolved power spectral density as a function of frequency f \"\"\"\n\n relaxedStateArray = df.read(relaxedStateFile).array\n\n xNodes, yNodes, zNodes = getSpatialDimensions(relaxedStateFile)\n N = xNodes * yNodes * zNodes\n\n # filesToScan = []\n # for file in os.listdir(directory):\n # if file.endswith(\".ovf\") and file.startswith(\"m\"):\n # print(file)\n # filesToScan.append(directory + file)\n #\n # filesToScan = sorted(filesToScan)\n # # filesToScan = filesToScan[:2]\n #\n # allFiles = np.zeros((len(filesToScan), len(relaxedStateArray), len(relaxedStateArray[0]), len(relaxedStateArray[0][0]), len(relaxedStateArray[0][0][0])))\n # timesArray = np.zeros(len(filesToScan))\n #\n # for i, file in enumerate(filesToScan):\n # print(\"Loading file\", i+1, \"of\", len(filesToScan))\n # allFiles[i] = df.read(file).array\n # timesArray[i] = getTime(file)\n #\n # diffArray = allFiles - relaxedStateArray\n #\n # diffArray = diffArray.reshape((len(allFiles), xNodes * yNodes * zNodes, 3))\n\n # return diffArray, timesArray\n return N\n\ndirectory = '../SquareIn.out/'\ninitial = '../InitialSquare.out/Initial.ovf'\n\ndiffArray, timesArray, N = getDiffArray(directory, initial)\nnp.save('SquareIn', diffArray)\nnp.save('SquareInTimes', timesArray)\nnp.save('N', N)\n","sub_path":"AskLattice/ManyCells/ForHamilton/GetDiffArrays.py","file_name":"GetDiffArrays.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"58736445","text":"from taskTypes import Task\nfrom time import time\nimport time\nimport math\nimport logging\nclass Scheduler:\n def __init__(self, rootlogger):\n self.rootLogger = rootlogger\n self.rootLogger.info(\"[SCHEDULER] Initialising scheduler\")\n\n self.criticalQ = []\n self.downtimeQ = []\n\n self.addTask(Task.RELOAD, {})\n\n self.rootLogger.info(\"[SCHEDULER] Finished Initialisation\")\n\n def addTask(self, taskType, params):\n self.rootLogger.info(f\"[SCHEDULER] Adding a {taskType}\")\n self.rootLogger.debug(f\"[SCHEDULER] With params: {params}\")\n if \"timestamp\" not in params:\n params[\"timestamp\"] = 0\n if taskType == Task.LOGIN or taskType == Task.ENROLL or taskType == Task.REMOVE or taskType == Task.LOGOUT:\n options = {\n \"taskType\": taskType,\n \"params\": params\n }\n self.criticalQ.append(options)\n\n if taskType == Task.RELOAD or taskType == Task.SAVE or taskType == Task.CHECKID:\n options = {\n \"taskType\": taskType,\n \"params\": params\n }\n self.downtimeQ.append(options)\n\n def getTask(self):\n self.criticalQ.sort(key=lambda x: x[\"params\"][\"timestamp\"])\n self.downtimeQ.sort(key=lambda x: x[\"params\"][\"timestamp\"])\n\n self.printQueue()\n\n if len(self.criticalQ) > 0:\n for t in self.criticalQ:\n if \"timestamp\" not in t[\"params\"]:\n t[\"params\"][\"timestamp\"] = 0\n if t[\"params\"][\"timestamp\"] <= math.floor(time.time()):\n task = t\n self.criticalQ.remove(task)\n self.rootLogger.info(f\"[SCHEDULER] Returning a {task['taskType']}\")\n self.rootLogger.debug(f\"[SCHEDULER] With the following params: {task['params']}\")\n\n return task\n\n if len(self.downtimeQ) > 0:\n for t in self.downtimeQ:\n if \"timestamp\" not in t[\"params\"]:\n t[\"params\"][\"timestamp\"] = 0\n if t[\"params\"][\"timestamp\"] <= math.floor(time.time()):\n task = t\n self.downtimeQ.remove(task)\n self.rootLogger.info(f\"[SCHEDULER] Returning a {task['taskType']}\")\n self.rootLogger.debug(f\"[SCHEDULER] With the following params: {task['params']}\")\n return task\n\n return False\n\n def printQueue(self):\n\n self.rootLogger.debug(\"[SCHEDULER] Printing current queue!\")\n self.rootLogger.debug(\"###################################\")\n\n for entry in self.criticalQ:\n self.rootLogger.debug(f\"{time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(entry['params']['timestamp']))} CRITICALQ \"\n f\"{entry['taskType']} \")\n for entry in self.downtimeQ:\n self.rootLogger.debug(f\"{time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(entry['params']['timestamp']))} DOWNTIMEQ \"\n f\"{entry['taskType']}\")\n\n self.rootLogger.debug(\"###################################\")\n\n def removeEntriesByUser(self, user):\n for entry in self.criticalQ:\n if \"params\" in entry and \"user\" in entry[\"params\"] and entry[\"params\"][\"user\"] is user:\n self.criticalQ.remove(entry)\n for entry in self.downtimeQ:\n if \"params\" in entry and \"user\" in entry[\"params\"] and entry[\"params\"][\"user\"] is user:\n self.downtimeQ.remove(entry)\n","sub_path":"src/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624783148","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"Measure minimum edit distance of 2 datasets.\nThe minimum edit distance of a log template in a dataset is defined as \nthe minimum value of edit distances between the template and\nall templates in another dataset..\nThis metric shows the similarity of log templates in 2 datasets.\n\nIn this script, the dataset is defined as a part of 1 DB.\nThe part definition is described in amulog.config.parse_condition format.\n\"\"\"\n\n\nimport sys\nfrom collections import defaultdict\n\nfrom amulog import config\nfrom amulog import log_db\nfrom amulog.lt_shiso import edit_distance\nfrom amulog.__main__ import parse_condition\n\nRELATIVE = True\nACCEPT_SYM = False\n\nif len(sys.argv) < 4:\n sys.exit(\"usage: {0} CONFIG RULE1 RULE2\".format(sys.argv[0]))\n\nconf = config.open_config(sys.argv[1])\nif ACCEPT_SYM:\n sym = conf.get(\"log_template\", \"variable_symbol\")\nelse:\n sym = None\nd_rule1 = parse_condition(sys.argv[2].split(\",\"))\nd_rule2 = parse_condition(sys.argv[3].split(\",\"))\ns_ltid1 = set()\ns_ltid2 = set()\n\nld = log_db.LogData(conf)\nfor lm in ld.iter_lines(**d_rule1):\n s_ltid1.add(lm.lt.ltid)\n\nfor lm in ld.iter_lines(**d_rule2):\n s_ltid2.add(lm.lt.ltid)\n\ncommon = s_ltid1 & s_ltid2\nprint(\"{0} common log template found... \".format(len(common)))\n\nd_ed1 = {}\nd_ed2 = {}\nfor key in common:\n d_ed1[key] = 0\n d_ed2[key] = 0\n s_ltid1.remove(key)\n s_ltid2.remove(key)\n\nfor ltid1 in s_ltid1:\n for ltid2 in s_ltid2:\n lt1 = ld.lt(ltid1)\n lt2 = ld.lt(ltid2)\n ed = edit_distance(lt1.ltw, lt2.ltw, sym)\n if RELATIVE:\n ed = 1.0 * ed / max(len(lt1.ltw), len(lt2.ltw))\n\n if d_ed1.get(ltid1, sys.maxsize) > ed:\n d_ed1[ltid1] = ed\n if d_ed2.get(ltid2, sys.maxsize) > ed:\n d_ed2[ltid2] = ed\n\navg1 = 1.0 * sum(d_ed1.values()) / len(d_ed1)\navg2 = 1.0 * sum(d_ed2.values()) / len(d_ed2)\nprint(\"Average distance 1 : {0}\".format(avg1))\nprint(\"Average distance 2 : {0}\".format(avg2))\nprint()\n\nprint(\"group 1 ({0}):\".format(sys.argv[2]))\nfor ltid, ed in sorted(d_ed1.items(), key = lambda x: x[1], reverse = True):\n print(\"ltid {0} : {1}\".format(ltid, ed))\n\nprint(\"group 2 ({0}):\".format(sys.argv[3]))\nfor ltid, ed in sorted(d_ed2.items(), key = lambda x: x[1], reverse = True):\n print(\"ltid {0} : {1}\".format(ltid, ed))\n\nfn = \"tpl_ed_pickle\"\nimport pickle\nwith open(fn, \"w\") as f:\n pickle.dump((d_ed1, d_ed2), f)\nprint(\"> {0}\".format(fn))\n\n\n\n","sub_path":"scripts/tpl_ed.py","file_name":"tpl_ed.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"253594846","text":"from typing import List\n\nVector = List[float]\n\ndef dot( v:Vector, w:Vector) -> Vector:\n ''''Computes v_1 * w_1 + ... v_n * w_n'''\n assert len(v) == len(w)##Vectors must be same length\n\n return sum(v_i * w_i for v_i,w_i in zip(v,w))\n\n\nassert dot([1,2,3],[4,5,6]) == 32 #1* 4+2*5+3*6","sub_path":"DataScienceFromScratch/LinearAlgebra/Vectors/DotProductVector.py","file_name":"DotProductVector.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"489615691","text":"import torch\nimport argparse\nimport pdb\nimport os\nimport time\nimport copy\nimport torch\nimport torch_geometric.transforms as T\nfrom model.GraphSAGE import GraphSAGE_PPI\nfrom sklearn import metrics\nfrom torch.optim import Adam\nfrom torch.nn import functional as F\nfrom torch_geometric.datasets import PPI\nfrom torch_geometric.data import DataLoader\n\n\ndef train():\n # get the parameters\n args = get_args()\n\n # decide the device\n device = torch.device('cuda:1' if torch.cuda.is_available() and args.cuda else 'cpu')\n\n # load dataset\n train_dataset = PPI(root='/home/amax/xsx/data/gnn_datas/PPI', split='train')\n val_dataset = PPI(root='/home/amax/xsx/data/gnn_datas/PPI', split='val')\n test_dataset = PPI(root='/home/amax/xsx/data/gnn_datas/PPI', split='test')\n train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True)\n val_loader = DataLoader(val_dataset, batch_size=2, shuffle=False)\n test_loader = DataLoader(test_dataset, batch_size=2, shuffle=False)\n # data = dataset[0].to(device)\n\n # create the model and optimizer\n model = GraphSAGE_PPI(train_dataset.num_features, args.hidden_dim, train_dataset.num_classes, args.normalize).to(device)\n optimizer = Adam(model.parameters(), lr=args.lr)\n criterion = torch.nn.BCEWithLogitsLoss()\n\n # the information which need to be recorded\n start_time = time.time()\n bad_counter = 0\n best_valid_f1 = 0.0\n best_epoch = 0\n least_loss = float(\"inf\")\n best_model = None\n\n # beging training\n for epoch in range(args.epochs):\n # the steps of training\n model.train()\n total_loss = 0.0\n for data in train_loader:\n data.batch = None\n data = data.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, data.y)\n total_loss += loss.item()\n loss.backward()\n optimizer.step()\n avg_loss = total_loss / len(train_loader.dataset)\n f1 = validate(model, val_loader, device)\n # print('Epoch: {:04d}'.format(epoch + 1), 'f1: {:.4f}'.format(f1), 'loss: {:.4f}'.format(avg_loss))\n\n if avg_loss < least_loss:\n least_loss = avg_loss\n best_epoch = epoch + 1\n best_valid_f1 = f1\n best_model = copy.deepcopy(model)\n bad_counter = 0\n else:\n bad_counter += 1\n\n if bad_counter >= args.patience:\n break\n\n print(\"Optimization Finished!\")\n used_time = time.time() - start_time\n print(\"Total epochs: {:2d}\".format(best_epoch + 100))\n print(\"Best epochs: {:2d}\".format(best_epoch))\n # print(\"Time for each epoch: {:.2f}s\".format(used_time / (best_epoch + args.patience)))\n print(\"Best epoch's validate f1: {:.2f}\".format(best_valid_f1 * 100))\n # test the best trained model\n test(best_model, test_loader, device)\n print(\"Total time elapsed: {:.2f}s\".format(used_time))\n\ndef validate(model, data_loader, device):\n model.eval()\n\n ys, preds = [], []\n for data in data_loader:\n ys.append(data.y) # data.y shape: (num_nodes, num_classes)\n data = data.to(device)\n with torch.no_grad():\n output = model(data)\n preds.append((output > 0).float().cpu())\n gold, pred = torch.cat(ys, dim=0).numpy(), torch.cat(preds, dim=0).numpy() # shape: (num_nodes, num_class)\n return metrics.f1_score(gold, pred, average='macro')\n\n\ndef test(model, data_loader, device):\n model.eval()\n\n ys, preds = [], []\n for data in data_loader:\n ys.append(data.y)\n data = data.to(device)\n with torch.no_grad():\n output = model(data)\n preds.append((output > 0).float().cpu())\n gold, pred = torch.cat(ys, dim=0).numpy(), torch.cat(preds, dim=0).numpy()\n\n print(\"Test set results:\",\n \"accu= {:.2f}\".format(metrics.accuracy_score(gold, pred) * 100),\n \"macro_p= {:.2f}\".format(metrics.precision_score(gold, pred, average='macro') * 100),\n \"macro_r= {:.2f}\".format(metrics.recall_score(gold, pred, average='macro') * 100),\n \"macro_f1= {:.2f}\".format(metrics.f1_score(gold, pred, average='macro') * 100),\n \"micro_f1= {:.2f}\".format(metrics.f1_score(gold, pred, average='micro') * 100))\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--cuda', action='store_true', default=True, help='Disables CUDA training.')\n parser.add_argument('--epochs', type=int, default=2000, help='Number of epochs to train.')\n parser.add_argument('--lr', type=float, default=0.005, help='Initial learning rate.')\n parser.add_argument('--hidden_dim', type=int, default=256, help='Number of hidden units.')\n parser.add_argument('--patience', type=int, default=100, help='Patience')\n parser.add_argument('--normalize', default=True, help='Number of hidden units.')\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n for i in range(5):\n print(\"################ \", i, \" ################\")\n train()\n","sub_path":"GraphSAGE-pyg/train_ppi.py","file_name":"train_ppi.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"379364728","text":"#!/usr/bin/python\nimport time\nimport sys\nfrom daemon import runner\nimport requests\n\nsys.path.append(\"../\")\nfrom etc.config import *\n\n\nclass App():\n\n def __init__(self):\n self.stdin_path = '/dev/null'\n self.stdout_path = '/dev/tty'\n self.stderr_path = '/dev/tty'\n self.pidfile_path = '/tmp/foo.pid'\n self.pidfile_timeout = 5\n\n def get_request_info(self):\n headers = {'Content-Type': 'application/json', }\n data = '{\"server\": \"%s\"}' % (server_name)\n url = base_url + '/api/request'\n r = requests.put(url, headers=headers, data=data)\n return r.json()\n\n def send_update_to_master(self, request_id, job_status):\n headers = {'Content-Type': 'application/json', }\n\n data = '{\"status\": \"%s\"}' % (job_status)\n url = base_url + '/api/requests/{0}'.format(request_id)\n r = requests.put(url, headers=headers, data=data)\n\n def run(self):\n while True:\n request = self.get_request_info()\n print(request)\n if request != {'Pending requests': 'Not found'}:\n request_id = request['id']\n cmd = '/usr/bin/python {1} \"{0}\"'.format(\n str(request), script_to_execute)\n from subprocess import call\n job_start_time = time.time()\n status = call(cmd, shell=True)\n running_time = time.time() - job_start_time\n if status == 0:\n job_status = \"Finished\"\n else:\n job_status = \"Failed\"\n self.send_update_to_master(request_id, job_status)\n else:\n time.sleep(5)\n\napp = App()\ndaemon_runner = runner.DaemonRunner(app)\ndaemon_runner.do_action()\n","sub_path":"client/bin/run_daemon.py","file_name":"run_daemon.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328517617","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"System tool functions.\"\"\"\n\nimport os\nimport datetime as dt\nimport calendar as cal\nimport argparse\nimport tarfile as tf\nimport shutil\n\n#import smtplib\n#import imaplib\n#import email\n#import pysftp\n\nfrom dateutil.relativedelta import relativedelta\n\nimport const\n\ndef input_parser(user_input):\n \"\"\"User input parser.\n\n Parameters:\n user_input (object):\n\n Return:\n (tuple): containing:\n - **control** (*int*): 0 for success, 1 otherwise.\n - **flag** (*str*): A string (1 or 2 characters at most) describing which kind of period is to analyze. Chosen among those available in the help of the script.\n - **date_parsed** (*list*): Composed by 2 elements: starting and ending date of the period chosen by the user through the script arguments or automatically (i.e. period for weather forecast is fixed to 3 days before the current date).\n \"\"\"\n try:\n if user_input.period == 'Y':\n datetime0 = dt.datetime.strptime(user_input.time, const.Y)\n datetime1 = datetime0 + relativedelta(years=1, minutes=-1)\n if user_input.period == 'M':\n datetime0 = dt.datetime.strptime(user_input.time, const.Ym)\n datetime1 = (datetime0 + dt.timedelta(\n cal.monthrange(datetime0.year, datetime0.month)[1])) + relativedelta(minutes=-1)\n if user_input.period == 'D':\n datetime0 = dt.datetime.strptime(user_input.time, const.Ymd)\n datetime1 = datetime0 + relativedelta(days=1, minutes=-1)\n if user_input.period == 'W':\n # The input is one random day\n # The script calculates the week nr of the week antecedent\n # to the input.\n # The function get_week_days returns the beginning and ending day\n # of the week selected\n datetime = dt.datetime.strptime(user_input.time + '0000',\n const.YmdHM)\n week_nr = dt.datetime.isocalendar(datetime)[1] - 1\n datetime0, datetime1 = get_week_days(dt.datetime.strptime(\n user_input.time, const.Ymd).year, week_nr)\n if user_input.period == 'U':\n try:\n datetime0 = dt.datetime.strptime(user_input.time[0:12],\n const.YmdHM)\n datetime1 = dt.datetime.strptime(user_input.time[13:27],\n const.YmdHM)\n except:\n try:\n #for archive purposes\n datetime0 = dt.datetime.strptime(user_input.time[0:9],\n const.Ym)\n datetime1 = datetime0 + relativedelta(months=1)\n except:\n logger('Error in date parsing', 'error')\n if user_input.period == 'UD':\n if user_input.time == const.AVAIL_DYNAMICAL_INPUT[0]: # lastday\n datetime0 = const.NOW - dt.timedelta(days=1)\n datetime1 = const.NOW\n if user_input.time == const.AVAIL_DYNAMICAL_INPUT[1]: # lastmonth\n datetime0 = const.NOW - relativedelta(months=1)\n datetime1 = const.NOW\n if user_input.time == const.AVAIL_DYNAMICAL_INPUT[2]: # lastyear\n datetime0 = const.NOW - relativedelta(years=1)\n datetime1 = const.NOW\n\n logger('Period chosen: from ' +\n datetime0.strftime('%d-%m-%y at %H:%M') + ' ' +\n const.TIME_TYPE + ' to ' +\n datetime1.strftime('%d-%m-%y at %H:%M') + ' ' +\n const.TIME_TYPE, 'bold')\n control = 0\n except:\n logger('##No user input \"-p\"', 'error')\n control = 1\n return control, user_input.period, [None, None]\n flag = user_input.period\n date_parsed = [datetime0, datetime1]\n return control, flag, date_parsed\n\ndef get_week_days(year, week):\n \"\"\"Calculate the beginning end ending day of a specific week.\n\n Parameters:\n year (int): Year.\n week (int): Nr. of the week of which calculated starting and ending dates.\n\n Return:\n (tuple): containing:\n - **starting_date** (*dt.datetime*): Start date of th eselected week.\n - **ending_date** (*dt.datetime*): End date of the selected week.\n \"\"\"\n try:\n temp = dt.datetime(int(year), 1, 1)\n if temp.weekday() > 3:\n temp = temp + dt.timedelta(7-temp.weekday())\n dlt = dt.timedelta(days=(int(week)-1)*7)\n else:\n temp = temp - dt.timedelta(temp.weekday())\n dlt = dt.timedelta(days=(int(week)-1)*7)\n except:\n logger('###Impossibile to calculate the extremes of the week', 'error')\n starting_date = temp + dlt\n ending_date = temp + dlt + dt.timedelta(days=6, hours=23, minutes=59)\n return starting_date, ending_date\n\ndef logger(string, log_type):\n \"\"\"Log of the outputs of the script for debugging.\n\n Parameters:\n string (int): String containing the message to be displayed.\n log type (str): Type of message displayed. Can be chosen among: *error*, *warning*, *header*, *ok*, *underline*, *bold*.\n\n Return:\n None\n \"\"\"\n color_reset = const.LOG_COLORS['RESET']['lbl']\n if log_type == 'error':\n color = const.LOG_COLORS['FAIL']['lbl']\n if log_type == 'warning':\n color = const.LOG_COLORS['WARNING']['lbl']\n if log_type == 'header':\n color = const.LOG_COLORS['RESET']['lbl']\n if log_type == 'ok':\n color = const.LOG_COLORS['OKGREEN']['lbl']\n if log_type == 'underline':\n color = const.LOG_COLORS['UNDERLINE']['lbl']\n if log_type == 'bold':\n color = const.LOG_COLORS['BOLD']['lbl']\n with open(const.FOLDER_LOG, mode='a') as log:\n log.writelines(string)\n log.writelines('\\n')\n if const.DEBUG_SWITCH:\n print(color + string + color_reset)\n print(' ')\n return\n\ndef rm_tmp(folder, exclude=[]):\n \"\"\"Remove files in a specific directory.\n\n Parameters:\n folder (str): Path the folder you want to empty.\n exclude (list): List of filenames to be excluded from the erasing process\n\n Return:\n None\n \"\"\"\n for i in os.listdir(folder):\n try:\n if i not in exclude:\n os.remove(folder + i)\n logger('folder '+ str(folder)+ ' cleared', 'ok')\n except:\n try:\n shutil.rmtree(folder + i)\n logger('folder '+ str(folder)+ ' cleared', 'ok')\n except:\n logger('Unable to erase content of folder ' + str(folder), 'error')\n\ndef compress_data(user_input, date_parsed):\n \"\"\"Compress previous month data into archive .tbz2.\n\n Parameters:\n user_input (object):\n date_parsed (list): Composed by 2 elements: starting and ending date of the period chosen by the user through the script arguments or automatically (i.e. period for weather forecast is fixed to 3 days before the current date).\n\n Return:\n int: 0 for success, 1 otherwise.\n\n Todo:\n - Implement archiving option for period UD.\n - Reduce and optimize the function.\n \"\"\"\n if user_input.period == 'Y':\n date_format = const.Y\n date_format_file = const.Y\n date_format_out = const.y\n if user_input.period == 'M':\n date_format = const.Ym\n date_format_file = const.Y_m\n date_format_out = const.ym\n if user_input.period == 'D':\n date_format = const.Ymd\n date_format_file = const.Y_m_d\n date_format_out = const.ymd\n if user_input.period == 'U':\n date_format = const.Ymd_HM\n date_format_file = const.Y_m_d\n date_format_out = const.ymd\n if user_input.period == 'W':\n date_format = const.Ymd\n date_format_file = const.Y_m_d\n date_format_out = const.Y\n if user_input.period == 'UD':\n logger('Impossible to archive data for lastday, lastmonth and lastyear.'\n ' Use instead argument -p U.', 'warning')\n control = 0\n return control\n\n # Creating list of raw data\n date = date_parsed[0]\n folder_compress = const.FOLDER_DATA_COMPRESSED + str(date.strftime(date_format)) + '/'\n file_list = []\n if user_input.period == 'Y':\n for i in os.listdir(const.FOLDER_TMP):\n if i.startswith(date.strftime(date.strftime(date_format_file))):\n file_list.append(i)\n if user_input.period == 'M':\n for i in os.listdir(const.FOLDER_TMP):\n if i.startswith(date.strftime(date.strftime(date_format_file))):\n file_list.append(i)\n if user_input.period == 'D':\n for i in os.listdir(const.FOLDER_TMP):\n if i.startswith(date.strftime(date.strftime(date_format_file))):\n file_list.append(i)\n if user_input.period == 'U' or user_input.period == 'W':\n for i in os.listdir(const.FOLDER_TMP):\n if dt.datetime.strptime(i[0:10], '%Y-%m-%d') >= date_parsed[0] and \\\n dt.datetime.strptime(i[0:10], '%Y-%m-%d') <= date_parsed[1]:\n file_list.append(i)\n\n try:\n os.mkdir(folder_compress)\n except:\n rm_tmp(folder_compress)\n os.rmdir(folder_compress)\n os.mkdir(folder_compress)\n if user_input.period == 'W':\n date_out = (str(date.strftime(date_format_out)) + '_W_' +\n str(dt.datetime.isocalendar(date_parsed[0])[1]))\n else:\n date_out = str(date.strftime(date_format_out))\n if const.TIME_TYPE == 'LT':\n filename = (date_out + const.FILE_SUFFIX_ZIP_LT)\n arcname = (date_out + const.FILE_SUFFIX_ZIP_LT[:-5])\n if const.TIME_TYPE == 'UTC':\n filename = (date_out + const.FILE_SUFFIX_ZIP_UTC)\n arcname = (date_out + const.FILE_SUFFIX_ZIP_UTC[:-5])\n\n # Copying raw data in the folder to be compressed\n try:\n for j in file_list:\n shutil.copy(const.FOLDER_TMP + j, folder_compress)\n # Copying stats and images\n try:\n for i in os.listdir(const.FOLDER_STATS):\n if i.startswith('stats_' + date.strftime('%Y%m%d')):\n shutil.copy(const.FOLDER_STATS + i, folder_compress)\n for i in os.listdir(const.FOLDER_IMAGES_HTML):\n if user_input.period == 'W':\n if i.startswith(date_out):\n shutil.copy(const.FOLDER_IMAGES_HTML + i, folder_compress)\n else:\n if i.startswith(date.strftime(date.strftime(date_format))):\n shutil.copy(const.FOLDER_IMAGES_HTML + i, folder_compress)\n except:\n logger('Impossible to copy statistics and images inside'\n ' the archive folder', 'warning')\n os.chdir(const.FOLDER_DATA_COMPRESSED)\n with tf.open(filename, \"w:gz\") as tar:\n tar.add(folder_compress, arcname=arcname)\n logger('Compression completed. New file created: ' + str(filename), 'ok')\n control = 0\n except:\n logger('Impossible to archive data', 'error')\n control = 1\n return control, None\n\n try:\n rm_tmp(folder_compress)\n os.removedirs(folder_compress)\n #for i in os.listdir(const.FOLDER_DATA):\n #if i.startswith(date.strftime(const.Y_m)):\n #os.remove(const.FOLDER_DATA + i)\n logger('Deleting of files and folder completed', 'ok')\n control = 0\n except:\n logger('Impossible to delete files and folders: ' +\n str(folder_compress), 'error')\n control = 1\n return control\n\ndef connect_to_ftp(host, user, passwd):\n \"\"\"Connect to an FTP server for files uploading.\n\n Parameters:\n host (str): Hostname of the FTP service.\n user (str): Username of the FTP service.\n passwd (str): Password of the FTP service.\n\n Return:\n object: FTP object after connection with FTP server.\n \"\"\"\n logger('Connecting to FTP server ' + host, 'header')\n ftp = pysftp.Connection(host=host, username=user, password=passwd)\n return ftp\n\ndef connect_to_email(smtp_server, org_domain, user, pwd):\n \"\"\"Connect to an email postbox.\n\n Parameters:\n smtp_server (str): Server SMTP of the email service.\n org_domain (str): Domain of the email service.\n user (str): Username of the email service.\n pwd (str): Password of the email service.\n\n Return:\n\n Warning:\n - This function has to be developed.\n\n Todo:\n Develop this function.\n \"\"\"\n logger('Connecting to IMAP email ' + user + org_domain, 'header')\n logger('NOT IMPLEMENTED CORRECTLY YET', 'warning')\n #try:\n #mail_imap = imaplib.IMAP4(smtp_server)\n #ans1 = mail_imap.login(user, pwd)\n #logger('Successfully connected to IMAP email ' +\n #user +\n #org_domain +\n #'\\n The server answered ' + ans1[0], 'ok')\n #except:\n #logger('Impossible to connect to IMAP email ' + user + org_domain, 'error')\n\n #try:\n #for folder in ('forecast_Genthon', 'inbox'):\n #mail_imap.select(folder)\n #answer, data = mail_imap.search(None, 'ALL')\n #mail_ids = data[0]\n\n #id_list = mail_ids.split()\n #first_email_id = int(id_list[0])\n #latest_email_id = int(id_list[-1])\n\n #for i in range(latest_email_id, first_email_id, -1):\n #typ0, data0 = mail_imap.fetch(i, \"(RFC822)\")\n #typ1, data1 = mail_imap.fetch(i, \"(UID BODY[TEXT])\")\n\n #for response_part in data0:\n #if isinstance(response_part, tuple):\n #msg = email.message_from_string(response_part[1])\n #if msg['subject'] == email_subject:\n #msg_sub = msg['subject']\n #msg_from = msg['from']\n ##print 'From : ' + msg_from + '\\n'\n ##print 'Subject : ' + msg_sub + '\\n'\n #forecast = data1[0][1]\n #ans2 = mail_imap.logout()\n #return forecast.split('\\r\\n')\n #ans2 = mail_imap.logout()\n #except:\n #print('Impossible to retrieve forecast from email', 'warning')\n\n #logger('Trying to connect to SMTP email ' + user + org_domain, 'header')\n #try:\n #mail_smtp = smtplib.SMTP(smtp_server)\n #ans1 = mail_smtp.login(user, pwd)\n #ans2 = mail_smtp.close()\n #logger('Successfully connected to SMTP email ' + user +\n #org_domain + '\\n The server answered ' + str(ans1), 'ok')\n #except:\n #logger('Impossible to connect to SMTP email ' + user + org_domain, 'error')\n\ndef argparse_func():\n \"\"\"Parsing of the input, help and other command line commands.\n\n Return:\n object:\n \"\"\"\n parser = argparse.ArgumentParser(prog='meteo_main.py',\n description=const.PARSER_DESCR,\n epilog=const.PARSER_EPI,\n )\n parser.add_argument(\n '-d',\n '--debug',\n action='store_true',\n required=False,\n help=str('Show on the terminal the print output in order to '\n 'better and easier debug'))\n parser.add_argument(\n '-u',\n '--utc',\n action='store_true',\n required=False,\n help=str('Specify this argument if you want to use UTC data.'\n ' The default is local tima data (UTC+8)'))\n parser.add_argument(\n '-p',\n '--period',\n type=str,\n required=False,\n help=str('Period type choosen among D=day, M=month, Y=year, W=weeky, '\n 'U=user defined period, UD=user dynamic (lastday, lastmonth, '\n 'lastyear). Arg -t is required.'))\n parser.add_argument(\n '-t',\n '--time',\n type=str,\n required=False,\n help=str('Time: -p Y --> YYYY, -p M --> YYYYmm, -p D --> YYYYmmdd, '\n '-p W --> YYYYmmdd (the script will calculates statistics of '\n 'the week before the inserted date), -p U -->'\n 'YYYYmmddHHMM:YYYYmmddHHMM'\n '(i.e. start_date:end:date), -p UD --> choose between: '\n 'lastday, lastmonth, lastyear'))\n parser.add_argument(\n '-s',\n '--synop',\n action='store_true',\n required=False,\n help=str('Create and send SYNOP message for a specific synoptic hour.'\n ' Arg -d is required.'))\n parser.add_argument(\n '-ms',\n '--metar-str-decode',\n type=str,\n required=False,\n help=str(\"Decode METAR message in plain english. Specify the METAR as a string, i.e. 'DOMC 170700Z AUTO 17005KT CAVOK M25/M29 Q0957'.\"))\n parser.add_argument(\n '-md',\n '--metar-date-decode',\n type=str,\n required=False,\n help=str('Decode METAR message in plain english. Specify the date (YYYYmmddHHMM, HHMM in UTC time) or ''last'' in orde to decodes the last METAR available.'))\n parser.add_argument(\n '-f',\n '--forecast',\n action='store_true',\n required=False,\n help=str('Create plot with realtime data and forecast.'))\n parser.add_argument(\n '-a',\n '--archive-utility',\n action='store_true',\n required=False,\n help=str('Archive old datafiles. Args -d and -p are required.'\n ' You can specify a specific month, otherwise the last month'\n ' will be selected.'))\n parser.add_argument(\n '--shortvarrep',\n required=False,\n help=str('i.e. -shortvarrep TEMPE.'\n ' Args -p and -t are required. Arg -u can be used.'\n ' Calculate avg, max and min over a specific time and for a'\n ' specific variable.'\n ' Choose among: TEMPE (temperature), WINDC (windchill),'\n ' WINDS (wind speed), WINDD (wind direction),'\n ' RELHU (relative humidity), PRESS (atm pressure).'\n ))\n parser.add_argument(\n '--DEST_images',\n required=False,\n help=str('Destination of reports and plots. By default it is set to ' +\n const.FOLDER_IMAGES_HTML))\n parser.add_argument(\n '--DEST_tmp',\n required=False,\n help=str('Destination of temporary files. By default it is set to ' +\n const.FOLDER_TMP))\n parser.add_argument(\n '--DEST_stats',\n required=False,\n help=str('Destination of statistics. By default it is set to ' +\n const.FOLDER_STATS))\n parser.add_argument(\n '--DEST_messages',\n required=False,\n help=str('Destination of .short reports and messages By default it'\n ' is set to ' + const.FOLDER_MESSAGES))\n parser.add_argument(\n '--DEST_log',\n required=False,\n help=str('Destination of log files. By default it is set to ' +\n const.FOLDER_LOG))\n parser.add_argument(\n '--DEST_datacompressed',\n required=False,\n help=str('Destination of compressed files (result of -a argument).'\n ' By default it is set to ' + const.FOLDER_DATA_COMPRESSED))\n\n args = parser.parse_args()\n\n return args\n\ndef switches_settings(user_input):\n \"\"\"Setting switches (verbose, utc/lt, destinations, etc).\n\n Parameters:\n user_input (object):\n\n Return:\n None\n \"\"\"\n const.DEBUG_SWITCH = user_input.debug\n const.UTC_LT_SWITCH = user_input.utc\n if const.UTC_LT_SWITCH:\n const.TIME_TYPE = 'UTC'\n const.FOLDER_DATA = const.FOLDER_DATA_UTC\n const.FILE_SUFFIX_ZIP = const.FILE_SUFFIX_ZIP_UTC\n const.FILE_SUFFIX = const.FILE_SUFFIX_UTC\n const.NOW = const.NOW_UTC\n else:\n const.TIME_TYPE = 'LT'\n const.FOLDER_DATA = const.FOLDER_DATA_LT\n const.FILE_SUFFIX_ZIP = const.FILE_SUFFIX_ZIP_LT\n const.FILE_SUFFIX = const.FILE_SUFFIX_LT\n const.NOW = const.NOW_LT\n if user_input.DEST_images != None:\n const.FOLDER_IMAGES_HTML = user_input.DEST_images\n if user_input.DEST_tmp != None:\n const.FOLDER_TMP = user_input.DEST_tmp\n if user_input.DEST_stats != None:\n const.FOLDER_STATS = user_input.DEST_stats\n if user_input.DEST_messages != None:\n const.FOLDER_MESSAGES = user_input.DEST_messages\n if user_input.DEST_log != None:\n const.FOLDER_LOG = user_input.DEST_log\n if user_input.DEST_datacompressed != None:\n const.FOLDER_DATA_COMPRESSED = user_input.DEST_datacompressed\n\ndef folder_clearing():\n \"\"\"Remove files from different folders.\n\n Return:\n None\n \"\"\"\n try:\n rm_tmp(const.FOLDER_TMP)\n except:\n logger('Impossible to remove tmp files', 'error')\n try:\n exclude = []\n for i in os.listdir(const.FOLDER_IMAGES_HTML):\n if (i.startswith('last') or i.startswith('Meteo') or i.startswith('RS')):\n exclude.append(i)\n rm_tmp(const.FOLDER_IMAGES_HTML, exclude=exclude)\n except:\n logger('Impossible to remove old images', 'error')\n try:\n rm_tmp(const.FOLDER_MESSAGES)\n except:\n logger('Impossible to remove old short reports', 'error')\n try:\n exclude = []\n for i in os.listdir(const.FOLDER_STATS):\n if i.startswith('stats_last'):\n exclude.append(i)\n rm_tmp(const.FOLDER_STATS, exclude=exclude)\n except:\n logger('Impossible to remove old statistics', 'error')\n try:\n rm_tmp(const.FOLDER_DATA_COMPRESSED)\n except:\n logger('Impossible to remove old compressed data', 'error')\n","sub_path":"system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":21931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35488651","text":"##Faça um programa que receba de um produto:\n##o preço\n##o tipo (A — alimentação; L — limpeza; e V — vestuário)\n##a refrigeração (S — produto que necessita de refrigeração; e N — produto que não necessita de refrigeração).\n\n##Suponha que haverá apenas a digitação de dados válidos e, quando houver digitação de letras, utilize maiúsculas. Calcule e mostre:\n##O valor adicional\n##O valor do imposto\n##O preço de custo, ou seja, preço mais imposto. O desconto.\n##O produto que não preencher nenhum dos requisitos a seguir terá desconto de 3%, caso contrário, 0 (zero).\n##VALORES FIXOS PRÉ-ESTABELECIDOS\n\npreco = float(input('Qual o preço do produto? '))\ntipo = input('Qual o tipo do produto?''\\n' 'A - Alimentação' '\\n' 'L - Limpeza' '\\n' 'V - Vestuário')\nrefrig = input('Selecione a opção que indica o tipo de refrigeração' '\\n' 'S - Refrigeração necessária' '\\n' 'N - Não precisa de refrigração')\nif refrig == 'N':\n if tipo == 'A':\n if preco < 15:\n valor_adic = 2\n else: \n valor_adic = 5\n if tipo == 'L':\n if preco < 10:\n valor_adic = 1.5\n else:\n valor_adic = 2.5\n if tipo == 'V':\n if preco < 30:\n valor_adic = 3\n else:\n valor_adic = 2.5\nelif tipo == 'A':\n valor_adic = 8\n if tipo == 'L':\n valor_adic = 0\n if tipo == 'V':\n valor_adic = 0\nprint('O valor adicional do produto é de R$',valor_adic)\nif preco < 25:\n imposto = 5/100 * preco\nelse: \n imposto = 8/100 * preco\n\nprint('O valor do imposto é de R$',imposto)\npre_custo = preco + imposto\nprint('O pre��o de custo é de R$',pre_custo)\n\nif tipo != 'A' and refrig != 'S':\n desconto = 3/100 * pre_custo\nelse: \n desconto = 0\nprint('O desconto é de R$',desconto)\n\nnovo_preco = pre_custo + valor_adic - desconto\nprint('O novo preço é de R$',novo_preco)\n\nif novo_preco <= 50:\n print('Barato.')\nelif novo_preco < 100:\n print('Normal.')\nelse:\n print('Caro.')\n","sub_path":"Estrutura_de_decisão_Ex30.py","file_name":"Estrutura_de_decisão_Ex30.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323142179","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport streamlit as st\nimport pickle\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\ndef predict(message):\n \n model=load_model('news_in.h5')\n with open('tokenizer.pickle', 'rb') as handle:\n \n tokenizer2 = pickle.load(handle)\n x_1 = tokenizer2.texts_to_sequences([message])\n x_1 = pad_sequences(x_1, maxlen=500)\n predictions = model.predict(x_1)[0][0]\n return predictions\n\n\ntitle_ = '''\n\n\n\n

Testing

\n\n'''\nst.markdown(title_, unsafe_allow_html=True)\nst.title('News/Not News Sentiment Analyzer')\nmessage = st.text_area('Enter sentence','Type Here ..')\n\nif st.button('Analyze'):\n with st.spinner('Analyzing the text …'):\n prediction = predict(message)\n \n if prediction > 0.6:\n st.success('Tagged as News with {:.2f}% confidence'.format(prediction*100))\n st.balloons()\n elif prediction < 0.4:\n st.error('Tagged as Not News with {:.2f}% confidence'.format((1-prediction)*100))\n else:\n st.warning('Not sure! Try to add some more words')\n#https://www.intellectualtakeout.org/assets/3/28/star_wars_vs_star_trek_by_hapo57.jpg\npage_bg_img = '''\n\n'''\n\n\n\nst.markdown(page_bg_img, unsafe_allow_html=True)","sub_path":"Mobile_Laptop/wk7_start/my_app.py","file_name":"my_app.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"592105791","text":"import os\nimport json\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\n# from threading import Thread\n\n\nprint (\"Process started\")\n\nfile_path = os.path.join(os.getcwd(), 'mf') + '.json'\n\nwith open(file_path) as data_file:\n data = json.load(data_file)\n\ncount = 0\ncompany_data = list()\n\nes_settings = {\n \"settings\": {\n \"analysis\": {\n \"filter\": {\n \"edge_nGram_filter\": {\n \"type\": \"edge_ngram\",\n \"min_gram\": 2,\n \"max_gram\": 20,\n \"token_chars\": [\n \"letter\",\n \"digit\"\n ]\n }\n },\n \"analyzer\": {\n \"edge_nGram_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"whitespace\",\n \"filter\": [\n \"lowercase\",\n \"asciifolding\",\n \"edge_nGram_filter\"\n ]\n },\n \"whitespace_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"whitespace\",\n \"filter\": [\n \"lowercase\",\n \"asciifolding\"\n ]\n }\n }\n }\n },\n \"mappings\": {\n \"company_data\": {\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"analyzer\": \"edge_nGram_analyzer\",\n \"search_analyzer\": \"whitespace_analyzer\"\n },\n }\n }\n }\n}\n\nes = Elasticsearch([{'host': 'elasticsearch', 'port': 9200}])\n\ntry:\n es.indices.delete(index='bmo_capital_markets')\n es.indices.create(index='bmo_capital_markets', body=es_settings)\n # XMLData.objects.all().delete()\nexcept Exception as err:\n print (err)\n # es.indices.create(index='bmo_capital_markets', body=es_settings)\n\ntotal = len(data)\n\nfor company in data:\n row = {}\n row['_index'] = 'bmo_capital_markets'\n row['_type'] = 'company_data'\n row['_source'] = company\n company_data.append(row)\n\n if count == 500:\n count = 0\n bulk(es, company_data, index='bmo_capital_markets', raise_on_error=True)\n company_data = list()\n total = total - 500\n\n count += 1\n\n if count == total:\n bulk(es, company_data, index='bmo_capital_markets', raise_on_error=True)\nprint (\"Process ended\")\n","sub_path":"xmlParser/import_company_data.py","file_name":"import_company_data.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"579385143","text":"import exceptions\r\n\r\nclass StreamClosedError(exceptions.IOError):\r\n def __init__(self, stream):\r\n self.stream = stream\r\n\r\n def __str__(self):\r\n try:\r\n return \"Stream {} is closed.\".format(self.stream.fileno())\r\n except Exception as e:\r\n return \"Stream {} is closed.\".format(self.stream)\r\n\r\nclass SocketError(exceptions.Exception):\r\n def __str__(self):\r\n return \"A socket error occurred.\"\r\n\r\nclass HostCommunicationError(object):\r\n def __init__(self, *args, **kwargs):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n def addr_str(self):\r\n if self.host is not None and self.port is not None:\r\n return \"({}:{})\".format(self.host, self.port)\r\n elif host is not None:\r\n return \"({})\".format(self.host)\r\n else:\r\n return \"\"\r\n\r\nclass ConnectionError(exceptions.IOError, SocketError, HostCommunicationError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(ConnectionError, self).__init__(*args)\r\n\r\nclass ConnectionRefused(ConnectionError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(ConnectionRefused, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return \"The connection was refused by the remote host {}.\".format(self.addr_str())\r\n\r\nclass HostUnreachable(ConnectionError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(HostUnreachable, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return \"Destination host {} unreachable.\".format(self.addr_str())\r\n\r\nclass ConnectionTimeout(ConnectionError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(ConnectionTimeout, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return \"The connection timed out {}.\".format(self.addr_str())\r\n\r\nclass InvalidDestination(ConnectionError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(InvalidDestination, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return \"The destination is invalid: {}.\".format(self.addr_str())\r\n \r\nclass BindError(exceptions.ValueError, ConnectionError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(BindError, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return \"The address is already in use or is unavailable: {}.\".format(self.addr_str())\r\n\r\nclass AddressInUseError(ConnectionError):\r\n def __init__(self, *args):\r\n try:\r\n self.host = args[0]\r\n except Exception:\r\n self.host = None\r\n try:\r\n self.port = args[1]\r\n except Exception:\r\n self.port = None\r\n\r\n return super(AddressInUseError, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return \"The address is already in use or is unavailable: {}.\".format(self.addr_str())\r\n \r\nclass UnsupportedProtocolError(exceptions.ValueError, SocketError):\r\n def __init__(self, proto = None):\r\n self.proto = proto\r\n return super(UnsupportedProtocolError, self).__init__()\r\n\r\n def __str__(self):\r\n return \"The protocol {} is not supported.\".format(self.proto)\r\n \r\nclass ConnectionProxyError(ConnectionError):\r\n def __init__(self, *args):\r\n self.host = args[0]\r\n self.port = args[1]\r\n self.ptype = args[2]\r\n self.reason = args[3]\r\n return super(ConnectionProxyError, self).__init__(*args)\r\n\r\n def __str__(self):\r\n return self.ptype + \": \" + self.reason\r\n","sub_path":"amncore/xcepts.py","file_name":"xcepts.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300391492","text":"from __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.core.cache import cache\n\nfrom djblets.integrations.manager import shutdown_integration_managers\nfrom djblets.testing.testcases import TestCase, TestModelsLoaderMixin\n\n\nclass IntegrationsTestCase(TestModelsLoaderMixin, TestCase):\n \"\"\"Base class for unit tests that work with integrations.\"\"\"\n\n tests_app = 'djblets.integrations.tests'\n\n def setUp(self):\n super(IntegrationsTestCase, self).setUp()\n\n self.old_middleware_classes = list(settings.MIDDLEWARE_CLASSES)\n settings.MIDDLEWARE_CLASSES = self.old_middleware_classes + [\n 'djblets.integrations.middleware.IntegrationsMiddleware',\n ]\n\n cache.clear()\n\n def tearDown(self):\n super(IntegrationsTestCase, self).tearDown()\n\n settings.MIDDLEWARE_CLASSES = self.old_middleware_classes\n\n shutdown_integration_managers()\n","sub_path":"djblets/integrations/tests/testcases.py","file_name":"testcases.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138292051","text":"import aiohttp\r\n\r\n\r\nasync def get_json(url):\r\n try:\r\n async with aiohttp.ClientSession() as client:\r\n async with client.get(url) as responce:\r\n res = await responce.json()\r\n except TypeError:\r\n return\r\n\r\n return res","sub_path":"cogs/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"542525866","text":"class OrderingFood:\n ordering_food_name = ['酸菜鱼','红烧排骨','红烧茄子','香肠套餐'] #套餐的清单\n ordering_food_price = [64,18,15,14]\n order_list = [] #清单列表(打印)\n #初始化方法\n def __init__(self):\n self.do_order_food()\n #欢迎界面\n def welcome(self):\n print(\"================================\")\n print(\" 欢迎来到编程狮点餐系统\")\n print(\" 1、套餐类\")\n print(\" 2、结账\")\n print(\" 3、退出\")\n print(\"================================\")\n #打印清单的方法\n def order_list_(self,b=2):\n total_price = 0.0 # 总价\n if b==1:\n #如果结账完成,直接把清单放在order.txt文件;\n f = open('./order.txt','a',encoding='UTF-8')\n import time\n f.write(\"===========================================\\n\")\n f.write(\"订单打印时间:\" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())+\"\\n\")\n for v in self.order_list:\n value = v.split(\"@@\")\n f.write(value[0] + \"\\t\" + value[1] + \"份\\t\" + value[2] + '元\\n')\n total_price = float(total_price) + float(value[2])\n f.write(\"\\t\\t\\t\\t总价:\" + str(total_price)+\"\\n\")\n f.write(\"===========================================\\n\")\n f.close()\n return total_price\n else:\n import time\n print(\"订单打印时间:\" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n for v in self.order_list:\n value = v.split(\"@@\")\n print(value[0] + \"\\t\" + value[1] + \"份\\t\" + value[2] + '元')\n total_price = float(total_price) + float(value[2])\n print(\"\\t\\t\\t\\t总价:\" + str(total_price))\n return total_price\n #执行点餐的方法\n def do_order_food(self):\n while True:\n self.welcome()\n num = input(\"请选择:\")\n index = 0 #为了列表的序号从1开始;\n if num==\"1\":\n print(\"-----------套餐清单-----------------\")\n ordering_food_len = self.ordering_food_name.__len__() #获取列表的长度;\n for k in range(ordering_food_len):\n index = index + 1\n print(str(index)+\"、\"+str(self.ordering_food_name[k])+\"\\t\\t\"+str(self.ordering_food_price[k])+\"元\")\n print(\"-----------------------------------\")\n food_index = int(input(\"请选择套餐:\"))\n food_index = food_index - 1 #列表的下标���从0开始;\n\n if food_index >= 0 and food_index < ordering_food_len:\n order_list_index = -1 # 获取订单可能有相同下标的值\n b = True #去重(修改),如没有相同商品时,重新添加,如果有,则修改;\n for each in self.order_list:\n order_list_index = order_list_index + 1\n food_name = self.ordering_food_name[food_index] #获取到商品名称\n food_name_len = food_name.__len__() #商品的长度;\n if food_name == each[0:food_name_len]:\n b = False\n break\n f = input(\"请输入购买份数:\") #请输入购买份数\n if b:\n price = float(self.ordering_food_price[food_index] * int(f))\n print(\"您选择了:\" + self.ordering_food_name[food_index] + \"\\t\" + f + \"份\\t总价:\" + str(price) + \"元\")\n self.order_list.append(self.ordering_food_name[food_index] + \"@@\" + str(f) + \"@@\" + str(price))\n print(self.order_list)\n else:\n list = self.order_list[order_list_index].split('@@')\n sum = int(list[1]) + int(f) #已有列表的份数+新购买的份数=new\n price = float(self.ordering_food_price[food_index] * sum)\n self.order_list[order_list_index] = self.ordering_food_name[food_index] + \"@@\" + str(sum) + \"@@\" + str(price)\n print(\"您选择了:\" + self.ordering_food_name[food_index] + \"\\t\" + f + \"份\\t总价:\" + str(price) + \"元\")\n\n else:\n print('没有该商品')\n elif num==\"2\":\n print(\"-----------------清单列表--------------------\")\n total_price = self.order_list_()\n print(\"--------------------------------------------\")\n while True:\n if self.order_list:\n money = input(\"请输入金额支付:\")\n import re\n res = re.match(r'\\d+', money)\n if res:\n if int(money)>=total_price:\n print('支付成功,找您' + str(float(money) - float(total_price)) + '元,欢迎再次光临!')\n self.order_list_(1)\n self.order_list = [] #清空列表\n break\n else:\n print(\"金额不够,请重新支付!\")\n else:\n print(\"您这不是RMB,看不懂!-^-\")\n else:\n print(\"没有购买清单,无法结账!\")\n break\n\n elif num=='3':\n exit()\n else:\n print('请重新输入!')\n\nof = OrderingFood()","sub_path":"19 Python3开发点餐系统-实战/ordering_food.py","file_name":"ordering_food.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455770439","text":"from Node import Node\n\n\nclass Tree(object):\n def __init__(self):\n self.__name = None\n self.__node = None\n\n @property\n def name(self):\n return self.__name\n\n @property\n def node(self):\n return self.__node\n\n @name.setter\n def name(self, name):\n self.__name = name\n\n @node.setter\n def node(self, node):\n self.__node = node\n\n def create_tree(self, str_tree):\n self.__name = str_tree[0]\n\n node = Node()\n node.data = str_tree[1]\n self.__node = node\n\n str_tree = str_tree[2:]\n\n level = 0\n node_stack = [node]\n\n for line in str_tree:\n new_level = self.__count_level(line)\n if new_level > level:\n parent = self.__create_node(node_stack[len(node_stack) - 1], line)\n node_stack.append(parent)\n level = new_level\n elif new_level == level:\n node_stack.pop()\n parent = self.__create_node(node_stack[len(node_stack) - 1], line)\n node_stack.append(parent)\n else:\n while new_level <= level:\n node_stack.pop()\n level -= 1\n parent = self.__create_node(node_stack[len(node_stack) - 1], line)\n node_stack.append(parent)\n\n def __count_level(self, line):\n counter = 0\n for char in line:\n if char == '|' or char == ' ' or char == '-':\n counter += 1\n return counter / 3\n\n def __create_node(self, parent, line):\n node = Node()\n line = line.replace('|', '').replace('-', '').replace(' ', '')\n node.data = line\n node.parent = parent\n if parent.left is None:\n parent.left = node\n else:\n parent.right = parent.left\n parent.left = node\n return node\n\n def find(self, value):\n black = []\n gray = []\n current = self.__node\n path = ''\n nodes = []\n paths = []\n while self.__node not in black:\n if current.data == value and current not in gray:\n nodes.append(current)\n paths.append(path)\n gray.append(current)\n if current.left is not None and current.left not in black:\n current = current.left\n path = path + '1'\n elif current.right is not None and current.right not in black:\n current = current.right\n path = path + '2'\n else:\n black.append(current)\n current = current.parent\n path = path[:-1]\n\n return nodes, paths\n\n def find_part(self, value):\n black = []\n current = self.__node\n path = ''\n\n while self.__node not in black:\n if value in current.data:\n return current, path\n else:\n if current.left is not None and current.left not in black:\n current = current.left\n path = path + '1'\n elif current.right is not None and current.right not in black:\n current = current.right\n path = path + '2'\n else:\n black.append(current)\n current = current.parent\n path = path[:-1]\n return '', ''\n\n def find_node(self, path):\n node = self.__node\n while path != '':\n if path[0] == '1':\n if node.left is not None:\n node = node.left\n else:\n return 'error'\n else:\n if node.right is not None:\n node = node.right\n else:\n return 'error'\n path = path[1:]\n return node\n\n def print(self):\n black = []\n grey = []\n current = self.__node\n path = ''\n print(self.__name)\n right = True\n while self.__node not in black:\n if current not in grey:\n print(path + current.data)\n grey.append(current)\n if current.right is not None and current.right not in black:\n if path == '':\n path = '|--'\n else:\n if right:\n path = path[:-2] + ' |--'\n else:\n path = path[:-3] + ' |--'\n right = True\n current = current.right\n\n elif current.left is not None and current.left not in black:\n if path == '':\n path = '|--'\n else:\n if right:\n path = path[:-2] + ' |--'\n else:\n path = path[:-3] + ' |--'\n\n current = current.left\n right = False\n else:\n black.append(current)\n current = current.parent\n path = path[:-3]\n right = True\n\n def check(self, sentence):\n sentence = sentence.split()\n word = sentence[0]\n black = []\n current = self.__node\n while self.__node not in black:\n if current.left is None and current.right is None:\n if current.data == word:\n sentence = sentence[1:]\n if len(sentence) > 0:\n word = sentence[0]\n elif current.data != 'e':\n return False\n if current.left is not None and current.left not in black:\n current = current.left\n elif current.right is not None and current.right not in black:\n current = current.right\n else:\n black.append(current)\n current = current.parent\n if len(sentence) != 0:\n return False\n return True\n\n","sub_path":"Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292784629","text":"# coding = utf-8\nimport xlrd\nimport xlwt\n\n# 读取excel文件\n# 打开excel文件,打开工作表\nxlsx = xlrd.open_workbook('路径')\n\n# 读取工作簿(数字从0开始,打开第几个sheet)\ntable = xlsx.sheet_by_index(0)\n\n# 读取某个单元格的数据\n# 第一种方式\na = table.cell_value #参数填写坐标,也是从0开始\n# 第二种方式\nb = table.cell().cell\nprint(a, b)\n\n#写入excel文件\n#创建文件\nnew_workbook = xlwt.Workbook()\nworksheet = new_workbook.add_sheet('name')\nworksheet.write(1, 1, '内容')\nnew_workbook.save('路径')","sub_path":"读写excel文件.py","file_name":"读写excel文件.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18371533","text":"#!/usr/local/bin/python3\n\n### Script to compare sRNA abundances in two databases using summary two table\n\n###### IMPORTS ######################\nimport sys\nimport mysql.connector as sql\n#####################################\n\n\n##### INPUT #########################\nmode = 1 ## 0: Fetch from tag position summary table \n ## 1: Fetch from sRNA DB - Required when sRNA libraries are mapped to other genome and has no hits\ntagfile = 'Streptochaeta.txt' ## Text file with tags\nDB = 'STREPTOCHAETA_priv_sRNA' ## Used with mode:1 - If abundance to be fetched directly from sRNA DB, required if no genome is vaialble, and hit = 0\n\ntestTable = 'STREPTOCHAETA_priv_sRNA_TagPosSummNorm' ## Used with mode:0\n\nCompareDBs = 'N' ## Used with mode:0 AND ComapareDBs:Y - Fetch abundance from two tables each for one DB for comparision\nconTable = 'STREPTOCHAETA_priv_sRNA_TagPosSummNorm'\n\ndb = 'kakrana' ## Used with mode:0\nserver = 'raichu.dbi.udel.edu'\n\n#####################################\n\ndef ConnectToDB(server):\n \n ##infile values are '0' when you dont want to pulaod data from local file and '1' when you wish to upload data by local file\n ##EX:con=sql.connect(host= server, user='kakrana', passwd='livetheday', local_infile = infile)\n ##Now later in script you can\n ##cur.execute(\"LOAD DATA LOCAL INFILE './scoring_input_extend2' INTO TABLE kakrana_data.mir_page_results FIELDS TERMINATED BY ','\")\n \n print ('\\nTrying to connect to mySQL server on %s' % (server))\n # Try to connect to the database\n try:\n con=sql.connect(host= server, user='kakrana', passwd='livetheday')###local_infile = 1 not supported yet so a table has to be updated on row basis\n print ('Connection Established\\n')\n\n # If we cannot connect to the database, send an error to the user and exit the program.\n except sql.Error:\n print (\"Error %d: %s\" % (sql.Error.args[0],sql.Error.args[1]))\n sys.exit(1)\n return con\n\ndef tags2Abun(con,tagfile,testTable,conTable):\n \n cur = con.cursor()\n \n outfile = tagfile.split('.')[0]+'Abun_FC.csv'\n fh_out = open(outfile,'w')\n\n ### Get column anmes\n columns = []## empty list\n cur.execute(\"describe kakrana.%s\" % (testTable))\n testTablefield = cur.fetchall()\n cur.execute(\"describe kakrana.%s\" % (conTable))\n conTablefield = cur.fetchall()\n \n #print (testTablefield)\n columns = []## empty list\n for i in testTablefield:\n col = i[0]\n columns.append(col)\n \n testTablecol =\",\".join(str(x) for x in columns[5:])### Manually mentioned starting lib column - should work on all tag summary2 tables\n print(testTablecol)\n \n #print(conTablefield)\n columns = []## empty list - emptied again\n for i in conTablefield:\n col = i[0]\n columns.append(col)\n conTablecol = \",\".join(str(x) for x in columns[5:])### Manually mentioned starting lib column - should work on all tag summary2 tables\n print(conTablecol)\n \n ##Write file header\n fh_out.write('tag,NormSumRatio,%s,%s\\n' % (testTablecol,conTablecol))\n \n ### Open and read tag file\n fh_in = open(tagfile, 'r')\n \n for i in fh_in:\n tag = i.strip('\\n').replace('-','').translate(str.maketrans(\"U\",\"T\"))## Manipulation if tag is from PARE valid results - reversed and U -> T\n print(\"'%s' being queried:\" % (tag))\n ### Query test table\n cur.execute(\"select * from %s.%s where tag = '%s'\" % (db,testTable,tag))####\n temp = cur.fetchall()\n print (\"\\nTemp:\",temp)\n \n if temp: ## Tag exists in normalized table\n testNormSum = temp[0][-2] ## There could be multiple entries for different hits\n print(\"NormSum:\",testNormSum)\n testAbundances = \",\".join(str(x) for x in temp[0][5:]) ## in comma separated format, from fifth column onwars i.e abundance columns\n print(\"Test Abundances:\",testAbundances)\n else:\n testNormSum = 'NA' \n testAbundances = 'NA'\n \n if CompareDBs == 'Y':\n ### Query control table\n cur.execute(\"select * from %s.%s where tag = '%s'\" % (db,conTable,tag))####\n temp = cur.fetchall() ### What if tag is not found\n if temp: ## Tag is found \n conAbundances = \",\".join(str(x) for x in temp[0][5:]) ## in comma separated format, from fifth column onwars i.e abundance columns\n conNormSum = temp[0][4]\n fh_out.write('%s,%s,%s,%s\\n' % (tag,round((testNormSum/conNormSum),2),testAbundances,conAbundances))\n else: ## Tag is not found in control - cheers\n conLib = len(conTablecol.split(',')) ## The number of control column i.e number of libraries\n emptyList = [0]*int(conLib) ## Create abundance list with zeros\n conAbundances = \",\".join(str(x) for x in emptyList)\n conNormSum = temp[0][4]\n fh_out.write('%s,%s,%s,%s\\n' % (tag,round((testNormSum-conNormSum),2),testAbundances,conAbundances)) ## NormAbundance is substracted to avoid division to zero error\n \n else:\n if temp:\n NormSumRatio = 0 ## There is no comparision between two tables so no two NormSum to calculate ratios - just fetching abundance for single table - calculate ratio for required libraries manually\n fh_out.write('%s,%s,%s\\n' % (tag,NormSumRatio,testAbundances)) ## NormAbundance is substracted to avoid division to zero error\n else:\n NormSumRatio = 0 ## There is no comparision between two tables so no two NormSum to calculate ratios - just fetching abundance for single table - calculate ratio for required libraries manually\n fh_out.write('%s,%s,%s\\n' % (tag,NormSumRatio,testAbundances)) ## NormAbundance is substracted to avoid division to zero error\n \n\n fh_in.close()\n fh_out.close()\n \n return outfile\n\ndef tag2Abun2(con,tagfile):\n '''This fetches tag abundance from sRNA DB'''\n\n cur = con.cursor()\n outfile = tagfile.split('.')[0]+'Abun_runmaster.csv'\n\n ## Get libs\n cur.execute(\"select lib_id from %s.library\" % (DB))\n temp = cur.fetchall()\n print(temp)\n\n libs = []\n for x in temp:\n libs.append(x[0])\n print(libs)\n \n fh_out = open(outfile,'w')\n fh_out.write(\"tag\\thits\\t%s\\t%s\\n\" % ('\\t'.join(str(x)+\"_raw\" for x in libs),'\\t'.join(str(x)+\"_norm\" for x in libs))) ## For raw and norm abundances\n\n fh_in = open(tagfile, 'r')\n\n for i in fh_in:\n rawAbun = [] ## For every tag\n normAbun = [] ## FOr every tag\n tag = i.strip('\\n').replace('-','').translate(str.maketrans(\"U\",\"T\"))## Manipulation if tag is from PARE valid results - reversed and U -> T\n print(\"'%s' being queried:\" % (tag))\n cur.execute(\"select hits from %s.run_master where tag = '%s'\" % (DB,tag))\n temp = cur.fetchall()\n hits = temp[0][0]\n ### Query test table\n for lib in libs:\n cur.execute(\"select raw_value,norm from %s.run_master where tag = '%s' and lib_id ='%s'\" % (DB,tag,lib))####\n temp = cur.fetchall()\n # print (\"\\nTemp:\",temp)\n if temp:\n rawAbun.append(temp[0][0])\n normAbun.append(temp[0][1])\n else:\n rawAbun.append(0)\n normAbun.append(0)\n\n print(\"\\nTag:%s | Hits:%s\" % (tag,hits))\n print(\"raw abundances\",rawAbun)\n print(\"norm abundances\",normAbun)\n # print(\"%s\\t%s\\t%s\\t%s\\n\" % (tag,str(hits),'\\t'.join(str(x) for x in rawAbun),'\\t'.join(str(x) for x in normAbun)))\n fh_out.write(\"%s\\t%s\\t%s\\t%s\\n\" % (tag,str(hits),'\\t'.join(str(x) for x in rawAbun),'\\t'.join(str(x) for x in normAbun)))\n\n fh_out.close()\n\n return None\n \ndef main(db,tagfile,testTable,conTable):\n con = ConnectToDB(server)\n if mode == 0:\n tags2Abun(con,tagfile,testTable,conTable)\n elif mode == 1:\n tag2Abun2(con,tagfile)\n\nif __name__ == '__main__':\n main(db,tagfile,testTable,conTable)\n print('script finished sucessfully')\n sys.exit()\n\n## v01 -> v02\n## Added fetching tag abundace from run_master tabel of database - This is imporatant because tag_pos_summary might not have tags for which there are no hits.\n## These are kind of important for species with no genome","sub_path":"helper/old/getTagAbun.v02.py","file_name":"getTagAbun.v02.py","file_ext":"py","file_size_in_byte":8705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"46686060","text":"# Problem Set 4C\n# Name: \n# Collaborators:\n# Time Spent: x:xx\n\nimport string\nfrom ps4a import get_permutations\n\n### HELPER CODE ###\ndef load_words(file_name):\n '''\n file_name (string): the name of the file containing \n the list of words to load \n \n Returns: a list of valid words. Words are strings of lowercase letters.\n \n Depending on the size of the word list, this function may\n take a while to finish.\n '''\n \n #print(\"Loading word list from file...\")\n # inFile: file\n inFile = open(file_name, 'r')\n # wordlist: list of strings\n wordlist = []\n for line in inFile:\n wordlist.extend([word.lower() for word in line.split(' ')])\n #print(\" \", len(wordlist), \"words loaded.\")\n return wordlist\n\ndef is_word(word_list, word):\n '''\n Determines if word is a valid word, ignoring\n capitalization and punctuation\n\n word_list (list): list of words in the dictionary.\n word_list,列表类型,单词的列表\n word (string): a possible word.\n \n Returns: True if word is in word_list, False otherwise\n\n Example:\n print(is_word(WORDLIST_FILENAME,\"bat\"))\n >>> is_word(word_list, 'bat') returns\n True\n >>> is_word(word_list, 'asdf') returns\n False\n '''\n word = word.lower()\n word = word.strip(\" !@#$%^&*()-_+={}[]|\\:;'<>?,./\\\"\")\n return word in word_list\n\n\n### END HELPER CODE ###\n\nWORDLIST_FILENAME = 'words.txt'\n\n# you may find these constants helpful\nVOWELS_LOWER = 'aeiou'\nVOWELS_UPPER = 'AEIOU'\nCONSONANTS_LOWER = 'bcdfghjklmnpqrstvwxyz'\nCONSONANTS_UPPER = 'BCDFGHJKLMNPQRSTVWXYZ'\n\nclass SubMessage(object):\n def __init__(self, text):\n '''\n Initializes a SubMessage object\n \n text (string): the message's text\n\n A SubMessage object has two attributes:\n self.message_text (string, determined by input text)\n self.valid_words (list, determined using helper function load_words)\n '''\n self.message_text=text #字符串类型\n self.valid_words=load_words(WORDLIST_FILENAME) #列表类型\n \n def get_message_text(self):\n '''\n Used to safely access self.message_text outside of the class\n \n Returns: self.message_text\n '''\n return self.message_text\n\n def get_valid_words(self):\n '''\n Used to safely access a copy of self.valid_words outside of the class.\n This helps you avoid accidentally mutating class attributes.\n \n Returns: a COPY of self.valid_words\n '''\n valid_words_copy=self.valid_words.copy()\n return valid_words_copy\n def build_transpose_dict(self, vowels_permutation):\n '''\n vowels_permutation (string): a string containing a permutation of vowels (a, e, i, o, u)\n \n Creates a dictionary that can be used to apply a cipher to a letter.\n The dictionary maps every uppercase and lowercase letter to an\n uppercase and lowercase letter, respectively. Vowels are shuffled \n according to vowels_permutation. The first letter in vowels_permutation \n corresponds to a, the second to e, and so on in the order a, e, i, o, u.\n The consonants remain the same. The dictionary should have 52 \n keys of all the uppercase letters and all the lowercase letters.\n\n Example: When input \"eaiuo\":\n Mapping is a->e, e->a, i->i, o->u, u->o\n and \"Hello World!\" maps to \"Hallu Wurld!\"\n\n Returns: a dictionary mapping a letter (string) to \n another letter (string). \n '''\n #vowels_permutation 字符串类型,元音对应的转换方式\n #返回一个字典,包含52个关键字,辅音对应不变,元音转换,大小写的转换一致\n #字典的关键字和取值都是string类型\n num_1=0\n num_2=0\n vowels_permutation_lower=vowels_permutation.lower()\n vowels_permutation_upper=vowels_permutation.upper()\n transpose_dict={}\n for i in CONSONANTS_LOWER:#小写辅音\n transpose_dict[i]=i\n for i in CONSONANTS_UPPER:#大写辅音\n transpose_dict[i]=i\n for i in VOWELS_LOWER:#小写元音\n transpose_dict[i]=vowels_permutation_lower[num_1]\n num_1=num_1+1\n for i in VOWELS_UPPER:#大写元音\n transpose_dict[i]=vowels_permutation_upper[num_2]\n num_2=num_2+1\n return transpose_dict\n \n def apply_transpose(self, transpose_dict):\n '''\n transpose_dict (dict): a transpose dictionary\n \n Returns: an encrypted version of the message text, based \n on the dictionary\n '''\n #返回一个编码后的版本\n\n encrypted_list=\"\"\n for i in self.message_text:\n if i in transpose_dict.keys():\n encrypted_list=encrypted_list+transpose_dict[i]\n else:\n encrypted_list=encrypted_list+i\n return encrypted_list\n\nclass EncryptedSubMessage(SubMessage):\n def __init__(self, text):\n '''\n Initializes an EncryptedSubMessage object\n\n text (string): the encrypted message text\n\n An EncryptedSubMessage object inherits from SubMessage and has two attributes:\n self.message_text (string, determined by input text)\n self.valid_words (list, determined using helper function load_words)\n '''\n SubMessage.__init__(self, text)\n\n def decrypt_message(self):\n #对加密的字符进行解密\n #测试每一种可能的加密方式,找到一种加密方式,其对应的valid_word个数最多\n #返回最有可能的解密文档,若所有解密方式都没有valid_word,返回原字符串,存在多种best解密方式时,返回任意一个\n '''\n Attempt to decrypt the encrypted message \n \n Idea is to go through each permutation of the vowels and test it\n on the encrypted message. For each permutation, check how many\n words in the decrypted text are valid English words, and return\n the decrypted message with the most English words.\n \n If no good permutations are found (i.e. no permutations result in \n at least 1 valid word), return the original string. If there are\n multiple permutations that yield the maximum number of words, return any\n one of them.\n\n Returns: the best decrypted message \n \n Hint: use your function from Part 4A\n '''\n #print(is_word(load_words(WORDLIST_FILENAME),\"bat\"))\n final_dict={}#建立一个字典,存储每一种变换方式所对应的valid_word的个数\n all_kinds_lower_list=get_permutations(\"aeiou\")\n for i in all_kinds_lower_list:\n num=0\n transpose_dict=self.build_transpose_dict(i)\n message_transposed=self.apply_transpose(transpose_dict)#转换后的文本\n #print(i)\n #print(self.build_transpose_dict(i))\n #print(message_transposed)#输出转换后的文本\n words_transposed_list=message_transposed.split()\n #print(words_transposed_list)\n for j in words_transposed_list:\n #print(j)\n if is_word(load_words(WORDLIST_FILENAME), j)==True: #单词没有识别出来\n #print(\"yes\")\n num=num+1\n final_dict[i]=num\n max_valid_word_num=max(final_dict.values())\n #print(final_dict) 字典正确\n #print(len(final_dict.keys())) #字典关键字正确\n if max_valid_word_num<1:\n print(\"no\")\n return self.message_text\n\n else:\n for key,values in final_dict.items():\n if values==max_valid_word_num:\n best_permutation=key\n break\n return self.apply_transpose(self.build_transpose_dict(best_permutation))\n\n\n\n\n\n \n\n \n\n\n\n \n \n\nif __name__ == '__main__':\n\n # Example test case\n message = SubMessage(\"Hello World!\")\n permutation = \"eaiuo\"\n enc_dict = message.build_transpose_dict(permutation)\n print(\"Original message:\", message.get_message_text(), \"Permutation:\", permutation)\n print(\"Expected encryption:\", \"Hallu Wurld!\")\n print(\"Actual encryption:\", message.apply_transpose(enc_dict))\n enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict)) \n print(\"Decrypted message:\", enc_message.decrypt_message())\n message = SubMessage(\"Too fast!\")\n permutation = \"eaiuo\"\n enc_dict = message.build_transpose_dict(permutation)\n print(\"Original message:\", message.get_message_text(), \"Permutation:\", permutation)\n print(\"Expected encryption:\", \"Tuu fest!\")\n print(\"Actual encryption:\", message.apply_transpose(enc_dict))\n enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict)) #加密的字符串,正确\n print(\"Decrypted message:\", enc_message.decrypt_message())\n\n","sub_path":"my_pset_code/ps4/ps4c.py","file_name":"ps4c.py","file_ext":"py","file_size_in_byte":9029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"519267224","text":"#!/usr/bin/python\n\n\nfrom Bio.SeqIO import parse\nfrom Bio.Seq import Seq\nimport sys\n\ninfileName = sys.argv[1]\ninfile = parse(infileName, \"fasta\")\nLmin = 100\n\noutfile = open(\"cleaned_consensus.fas\", \"w\")\nfor i in infile:\n\tname = i.id\n\tseq = str(i.seq)\n\t# multiple of 3\n\twhile(len(seq)%3 != 0):\n\t\tseq = seq[:1]\n\tnewSeq = \"\"\n\tfor j in range(0, len(seq), 3):\n\t\tcodon = seq[j] + seq[j+1] + seq[j+2]\n\t\tif \"N\" not in codon:\n\t\t\tnewSeq += codon\n\tif len(newSeq) >= Lmin:\n\t\toutfile.write(\">{0}\\n{1}\\n\".format(name, newSeq))\noutfile.close()\n\n","sub_path":"scripts/3_clean_consensus.py","file_name":"3_clean_consensus.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35682979","text":"import findspark\r\nfindspark.init()\r\n\r\nfrom pyspark import SparkConf,SparkContext\r\nfrom pyspark.streaming import StreamingContext\r\nfrom pyspark.sql import Row,SQLContext\r\nimport sys\r\nimport requests\r\n\r\ndef hastags(line):\r\n k = line.split(\";\")[7]\r\n if(',' in k):\r\n return k.split(\",\")\r\n return [k]\r\ndef sortandprint(rdd):\r\n sorted_rdd = rdd.sortBy(lambda a: (-a[1],a[0])).filter(lambda x : x[0] != '')\r\n sorted_list = sorted_rdd.collect()\r\n if(sorted_list != []):\r\n print(sorted_list[0][0],sorted_list[1][0],sorted_list[2][0],sorted_list[3][0],sorted_list[4][0],sep=\",\")\r\n\r\nconf=SparkConf()\r\nconf.setAppName(\"BigData\")\r\nsc=SparkContext(conf=conf)\r\n\r\nssc=StreamingContext(sc,int(sys.argv[2]))\r\nssc.checkpoint(\"~/checkpoint_BIGDATA\")\r\n\r\ndataStream=ssc.socketTextStream(\"localhost\",9009)\r\n\"\"\"\r\nhashtags_count=dataStream.flatMap(hastags)\\\r\n .map(lambda hashtag : (hashtag, 1))\\\r\n .reduceByKeyAndWindow(lambda x,y:int(x)+int(y),int(sys.argv[1]),1)\r\n\"\"\"\r\nhashtags_count=dataStream.window(int(sys.argv[1]),1)\\\r\n .flatMap(hastags)\\\r\n .map(lambda hashtag : (hashtag, 1))\\\r\n .reduceByKey(lambda x,y:int(x)+int(y))\r\n\r\nhashtags_count.foreachRDD(sortandprint)\r\n\r\nssc.start()\r\nssc.awaitTermination(60)\r\nssc.stop()\r\n","sub_path":"adminmgr/media/code/A3/task3/BD_151_987_1496_1503_4FLb7Ka.py","file_name":"BD_151_987_1496_1503_4FLb7Ka.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"382788045","text":"'''\n$ python3 -m install pyfinance\n$ pip install yfinance --upgrade --no-cache-dir\n$ pip install tensorflow\nhttps://pypi.org/project/pyfinance/\nhttps://pandas-datareader.readthedocs.io/en/latest/#\n'''\n# Stock data from yahoo\nimport pandas as pd \npd.set_option('display.width', 400)\npd.set_option('display.max_columns', 10) \nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom pandas_datareader.data import DataReader\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.linear_model import LinearRegression\nimport pprint\n\nbeginDate ='2011-03-04'\nendDate ='2021-03-04' \nstock='AAPL'\ndf = DataReader(stock, 'yahoo', beginDate, endDate)\n#df = pd.read_csv('MSFT.csv',index_col=0)\ndf['Close'] = df['Adj Close']\ndf = df.drop('Adj Close',axis=1)\n\n# Moving averages with periods 5,10,20,50,100,200 days\nfor ma_period in [5,10,20,50,100,200]:\n indicator_name = 'ma_%d' % (ma_period)\n df[indicator_name] = df['Close'].rolling(ma_period).mean()\n\n# Bollinger bands (the moving average plus and minus 1 and 2 standard deviations)\ndf['Boll_Up_20_2'] = df['Close'].rolling(20).mean() + 2*df['Close'].rolling(20).std()\ndf['Boll_Down_20_2'] = df['Close'].rolling(20).mean() - 2*df['Close'].rolling(20).std()\ndf['Boll_Up_20_1'] = df['Close'].rolling(20).mean() + df['Close'].rolling(20).std()\ndf['Boll_Down_20_1'] = df['Close'].rolling(20).mean() - df['Close'].rolling(20).std()\ndf['Boll_Up_10_1'] = df['Close'].rolling(10).mean() + df['Close'].rolling(10).std()\ndf['Boll_Down_10_1'] = df['Close'].rolling(10).mean() - df['Close'].rolling(10).std()\ndf['Boll_Up_10_2'] = df['Close'].rolling(10).mean() + 2*df['Close'].rolling(10).std()\ndf['Boll_Down_10_2'] = df['Close'].rolling(10).mean() - 2*df['Close'].rolling(10).std()\n\n# Donchian channels - rolling maximum and minimum prices during the same periods as moving avg\nfor channel_period in [5,10,20,50,100,200]:\n up_name = 'Don_Ch_Up_%d' % (channel_period)\n down_name = 'Don_Ch_Down_%d' % (channel_period)\n df[up_name] = df['High'].rolling(channel_period).max()\n df[down_name] = df['Low'].rolling(channel_period).min()\n \n# Shifted into time lags, 1-10 days prior\nnewdata = df['Close'].to_frame()\nfor lag in [1,2,3,4,5,6,7,8,9,10]:\n shift = lag\n shifted = df.shift(shift)\n shifted.columns = [str.format('%s_shift_by_%d' % (column,shift)) for column in shifted.columns]\n newdata = pd.concat((newdata,shifted),axis=1) \n\n# Future Days - target days to predict\nforward_lag = 5\nnewdata['target'] = newdata['Close'].shift(-forward_lag)\nnewdata = newdata.drop('Close',axis=1)\nnewdata = newdata.dropna()\npprint.pprint(newdata, width=80)\n\nX = newdata.drop('target',axis=1)\nY = newdata['target']\ntrain_size = int(X.shape[0]*0.7)\nX_train = X[0:train_size]\ny_train = Y[0:train_size]\nX_test = X[train_size:]\ny_test = Y[train_size:]\n\ncorrelations = np.abs(X_train.corrwith(y_train))\nfeatures = list(correlations.sort_values(ascending=False)[0:50].index)\nX_train = X_train[features]\nX_test = X_test[features]\npprint.pprint(features)\n#\n# Linear Regression model\n#\n# Train model\nlr = LinearRegression()\nlr.fit(X_train,y_train)\n# Calc prediction of the model\ny_pred = lr.predict(X_test)\n# Compare to real test set\nprint('\\nMean Absolute Error:', mean_absolute_error(y_test,y_pred),'\\n')\n\n# Plot real values of test set and the predicted value\nplt.scatter(y_test,y_pred)\nplt.xlabel('Actual')\nplt.ylabel('Predicted')\nplt.title(f'{stock} - Linear Regression')\nplt.show()\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":"carl/Testing/FinalProject_Stock-ML1.py","file_name":"FinalProject_Stock-ML1.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304296764","text":"\"\"\" Modul Action\n\nModul ini mengendalikan seluruh aksi yang terekam;\n- Menyimpan sejarah aksi\n- Membatalkan/undo aksi\n- Meniadakan pembatalan/redo aksi\n\"\"\"\n\n\n__author__ = [('Naufan Rusyda Faikar', 'idmuslimdev@gmail.com')]\n__version__ = '0.1'\n\n\nfrom .. import config\nfrom ..model.action import Action, ActionType, ActionTransition\nfrom ..model.message import MessageTemplate\n\nfrom PyQt5.QtCore import QObject, pyqtSignal\n\nfrom typing import List\n\n\nclass ActionHandler(QObject):\n \"\"\" Kelas Aksi\n\n Kelas ini menyediakan fitur untuk manajemeni aksi.\n \"\"\"\n\n info_requested = pyqtSignal(MessageTemplate)\n\n _stack: List[Action] = []\n _pointer: int = -1\n _opt: List[ActionType] = [\n ActionType.ADD,\n ActionType.DELETE,\n ActionType.MODIFY\n ]\n _stack_size = 32\n\n def __init__(self) -> None:\n super().__init__()\n\n def reset(self) -> None:\n at = ActionTransition()\n at.old = reversed(config.objects)\n self.commit(Action(ActionType.DELETE, objects=at))\n self._stack = []\n self._pointer = -1\n\n def commit(self, action: Action) -> bool:\n \"\"\" Merekam aksi terakhir. \"\"\"\n\n # Menghapus rentetan rekaman aksi yang memiliki indeks melebihi\n # nilai pointer\n # -------------------------------------------------------------\n remove_it = self._stack[self._pointer + 1:]\n # FIXME: hapus objek yang tidak digunakan pada stack terakhir\n for rm in remove_it:\n self._stack.remove(rm)\n\n # Merekam aksi terakhir\n # ---------------------\n if action.type_ not in self.opt:\n self._stack.append(action)\n\n # Trigger aksi terakhir\n # ---------------------\n # Trigger untuk aksi SELECT\n if action.type_ is ActionType.SELECT:\n config.selects = action.objects.new\n\n # Trigger untuk aksi ADD\n elif action.type_ is ActionType.ADD:\n config.selects = action.objects.new\n config.objects.extend(action.objects.new)\n config.file.save_state = False\n self.info_requested.emit(MessageTemplate.ADD_OBJECT)\n\n # Trigger untuk aksi DELETE\n elif action.type_ is ActionType.DELETE:\n for obj in action.objects.old:\n obj.setParent(None)\n config.objects.remove(obj)\n config.selects = []\n config.file.save_state = False\n\n # Trigger untuk aksi MODIFY\n elif action.type_ is ActionType.MODIFY:\n config.file.save_state = False\n\n self._pointer += 1\n\n # FIXME: hapus objek yang tidak digunakan pada stack terakhir\n if self._pointer == self.stack_size:\n self._stack = self._stack[:-1]\n\n config.win.objectsInfo.setText(\n f'Objects: {len(config.selects)}/{len(config.objects)}')\n return True\n\n # def undo(self) -> bool:\n # \"\"\" Membatalkan aksi terakhir. \"\"\"\n # # Mendapatkan informasi aksi terakhir\n # # -----------------------------------\n # if self._pointer < 0:\n # return False\n # s = self._stack[self._pointer]\n # type_ = s[0]\n # diff = s[1]\n # parent = s[2]\n # value = s[3]\n\n # # Mengeksekusi pembatalan aksi terakhir\n # # -------------------------------------\n # # Membatalkan aksi SELECT\n # if type_ is ActionType.SELECT:\n # config.selects = diff[0]\n\n # # Membatalkan aksi ADD\n # elif type_ is ActionType.ADD:\n # diff[1][0].setParent(None)\n # config.objects.remove(diff[1][0])\n # s = self._stack[self._pointer - 1]\n # config.selects = diff[0]\n # config.file.save_state = False\n\n # # Membatalkan aksi DELETE\n # elif type_ is ActionType.DELETE:\n # for obj in diff[1]:\n # obj.setParent(parent)\n # obj.setVisible(True)\n # config.objects.append(obj)\n # config.selects = diff[1]\n # config.file.save_state = False\n\n # # Membatalkan aksi MODIFY\n # elif type_ is ActionType.MODIFY:\n # for i, obj in enumerate(diff[1]):\n # obj.setGeometry(value[2][i])\n # obj.rotation = value[0][i]\n # config.file.save_state = False\n\n # self._pointer -= 1\n # self.action_requested.emit()\n # return True\n\n # def redo(self) -> bool:\n # \"\"\" Meniadakan pembatalan aksi terakhir. \"\"\"\n # # Mendapatkan informasi aksi terakhir\n # # -----------------------------------\n # s = self._stack[self._pointer + 1]\n # type_ = s[0]\n # diff = s[1]\n # parent = s[2]\n # value = s[3]\n\n # # Mengeksekusi peniadaan pembatalan aksi terakhir\n # # -----------------------------------------------\n # try:\n # # Meniadakan pemmbatalan aksi SELECT\n # if type_ is ActionType.SELECT:\n # config.selects = diff[1]\n\n # # Meniadakan pemmbatalan aksi ADD\n # elif type_ is ActionType.ADD:\n # diff[1][0].setParent(parent)\n # diff[1][0].setVisible(True)\n # config.objects.append(diff[1][0])\n # config.selects = diff[1]\n # config.file.save_state = False\n\n # # Meniadakan pemmbatalan aksi DELETE\n # elif type_ is ActionType.DELETE:\n # for obj in diff[1]:\n # obj.setParent(None)\n # config.objects.remove(obj)\n # config.selects = []\n # config.file.save_state = False\n\n # # Meniadakan pemmbatalan aksi MODIFY\n # elif type_ is ActionType.MODIFY:\n # for i, obj in enumerate(diff[1]):\n # obj.setGeometry(value[3][i])\n # obj.rotation = value[1][i]\n # config.file.save_state = False\n\n # self._pointer += 1\n # except Exception:\n # return False\n\n # self.action_requested.emit()\n # return True\n\n @property\n def opt(self) -> List[ActionType]:\n return self._opt\n\n @opt.setter\n def opt(self, list_: List[ActionType]) -> None:\n self._opt = list_\n\n @property\n def stack_size(self) -> int:\n return self._stack_size\n\n @stack_size.setter\n def stack_size(self, size: int) -> None:\n self._stack_size = size\n","sub_path":"src/controller/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":6472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"547192805","text":"import uuid\n\nfrom unicore.ask.service.tests import DBTestCase\nfrom unicore.ask.service.models import QuestionOption, Question\n\n\nclass QuestionApiTestCase(DBTestCase):\n def create_question_option(self, session=None, **attrs):\n return self.create_model_object(QuestionOption, session, **attrs)\n\n def create_question(self, session=None, **attrs):\n return self.create_model_object(Question, session, **attrs)\n\n def setUp(self):\n super(QuestionApiTestCase, self).setUp()\n self.question_1 = self.create_question(\n self.db, title='What is your name', short_name='name',\n question_type='free_text',\n options=[])\n self.db.flush()\n self.question_1_option = self.create_question_option(\n self.db, question_id=self.question_1.uuid)\n\n self.question_2 = self.create_question(\n self.db, title='What is your age', short_name='age',\n question_type='multiple_choice',\n options=[])\n self.db.flush()\n\n self.create_question_option(\n self.db, title='<18', question_id=self.question_2.uuid)\n self.create_question_option(\n self.db, title='18-29', question_id=self.question_2.uuid)\n self.create_question_option(\n self.db, title='30-49', question_id=self.question_2.uuid)\n self.create_question_option(\n self.db, title='50+', question_id=self.question_2.uuid)\n\n self.question_3 = self.create_question(\n self.db, title='Which sports do you watch', short_name='sports',\n multiple=True, question_type='multiple_choice',\n options=[])\n self.db.flush()\n\n self.create_question_option(\n self.db, title='cricket', question_id=self.question_3.uuid)\n self.create_question_option(\n self.db, title='rugby', question_id=self.question_3.uuid)\n self.create_question_option(\n self.db, title='soccer', question_id=self.question_3.uuid)\n self.create_question_option(\n self.db, title='tennis', question_id=self.question_3.uuid)\n self.create_question_option(\n self.db, title='other', question_id=self.question_3.uuid)\n\n self.db.commit()\n\n def test_uuid(self):\n the_uuid = self.question_1._uuid\n self.assertEqual(the_uuid, uuid.UUID(self.question_1.uuid))\n self.question_1.uuid = self.question_1.uuid\n self.assertEqual(the_uuid, self.question_1._uuid)\n self.question_1.uuid = uuid.UUID(self.question_1.uuid)\n self.assertEqual(the_uuid, self.question_1._uuid)\n\n def test_question_not_found(self):\n self.app.get('/questions/%s' % uuid.uuid4(), status=404)\n\n def test_free_text_question(self):\n resp = self.app.get(\n '/questions/%s' % self.question_1.uuid)\n self.assertEqual(resp.status_int, 200)\n self.assertEqual(resp.json_body, self.question_1.to_dict())\n\n def test_multiple_choice_question(self):\n resp = self.app.get(\n '/questions/%s' % self.question_2.uuid)\n self.assertEqual(resp.status_int, 200)\n self.assertEqual(resp.json_body, self.question_2.to_dict())\n\n def test_multiple_choice_question_with_multiple_response(self):\n resp = self.app.get(\n '/questions/%s' % self.question_3.uuid)\n self.assertEqual(resp.status_int, 200)\n self.assertEqual(resp.json_body, self.question_3.to_dict())\n\n def test_edit(self):\n # change non-privileged fields\n resp = self.app.put_json(\n '/questions/%s' % uuid.uuid4().hex,\n params={'title': 'foo2'})\n self.assertEqual(resp.status_int, 200)\n self.assertEqual(resp.json_body, {})\n\n def test_create(self):\n data = {'title': 'foobar'}\n resp = self.app.post_json(\n '/questions', params=data)\n self.assertEqual(resp.json_body, {})\n","sub_path":"unicore/ask/service/tests/test_question_api.py","file_name":"test_question_api.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"600632359","text":"##################################\n#encoding=utf8 #\n#version =py27, py33 #\n#author =sanhe #\n#date =2014-11-24 #\n# #\n# (\\ (\\ #\n# ( -.-)o I am a Rabbit! #\n# o_(\")(\") #\n# #\n##################################\n\n\"\"\"\na library that allow human just draw a waveform on a canvas, and the program can convert\nthe image to X, Y data as you wish.\n\nApplications:\n 1. Easily create any probability density function you want.\n 2. Create a customized waveform simply just draw it.\n 3. Extract the data from any image you see on any publication.\n\nPre-requisite:\n scipy-stack\n download = http://www.lfd.uci.edu/~gohlke/pythonlibs/\n\"\"\"\n\nfrom __future__ import print_function\nfrom PIL import Image\nfrom scipy.interpolate import interp1d\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nclass WaveformMaster(object):\n def img_to_wav(self, path, min_x, max_x, min_y, max_y, tick_x, window_size = 3):\n x, y = self._img_to_wav(path, min_x, max_x, min_y, max_y, window_size)\n return self._resample(x, y, min_x, max_x, tick_x)\n \n def _expand_window(self, center, window_size, array_size):\n \"\"\"\n center, window_size, max = 10, 3, 100\n returns [7, 8, 9, 10, 11, 12, 13]\n center, window_size, max = 2, 3, 100\n returns [99, 0, 1, 2, 3, 4, 5]\n center, window_size, max = 98, 3, 100\n returns [95, 96, 97, 98, 99, 0, 1]\n \"\"\"\n if center - window_size < 0:\n lower = 0\n else:\n lower = center - window_size\n if center + window_size + 1 > array_size:\n upper = array_size\n else:\n upper = center + window_size + 1\n return np.array(range(lower, upper))\n \n def _img_to_wav(self, path, min_x, max_x, min_y, max_y, window_size = 3):\n \"\"\"\n Generate a waveform X, Y data from a scribble image.\n For example:\n Having a 1920 pixel width, 1080 pixel height image, we want to have\n (x1, y1), (x2, y2), ... to ..., (x1920, y1920) scatter data set that can represent\n the image waveform very well.\n \n if we set min_x = 0.0, max_x = 365.0, min_y = 0.0, max_y = 100.0, then finally we get 1920\n points where x is evenly from 0.0 to 365.0 and its corresponding y value\n \n [Args]\n ------\n path: the image file path, absolute path\n \n min_x, max_x, min_y, max_y:\n the x axis is from min_x - max_x, float type\n the y axis is from min_y - max_y, float type\n \n window_size: margin smooth sampling window size, int type\n \n [Return]\n --------\n x, y value\n \"\"\"\n \n im = Image.open(path).convert(\"L\")\n # in python, a numpy array that represent a image is from left to the right, top to the bottom\n # but in coordinate, it's from bottom to the top. So we use ::-1 for a reverse output\n data = np.array(im)[::-1] \n \n tick_x, tick_y = (max_x - min_x)/data.shape[1], (max_y - min_y)/data.shape[0] \n \n x, y = list(), list()\n \n for i in range(data.shape[1]):\n window = self._expand_window(i, window_size, data.shape[1]) # sliding margin window\n margin_dots_y_indices = np.where(data[:, window] == 0)[0]\n \n if len(margin_dots_y_indices) > 0: # if found at least one dots in margin\n x.append((i+1) * tick_x)\n y.append(margin_dots_y_indices.mean() * tick_y)\n \n return np.array(x), np.array(y)\n \n def _resample(self, x_data, y_data, start, end, tick):\n \"\"\"resampling the x, y data using cubic interpolation. Usually, for a good fit, start and end\n has to be within the range(min_x, min_y). But the tail can be little outbound.\n \n [Args]\n ------\n x_data, y_data: origin waveform data\n start, end, tick: from #start to #end, take sample at every #tick\n \"\"\"\n min_x, max_x = x_data.min(), x_data.max()\n xnew = np.arange(start, end * 1.001, tick) # \n xnew = xnew[np.where(np.logical_and(xnew >= min_x, \n xnew <= max_x ) )]\n interpolator = interp1d(x_data, y_data, kind=\"cubic\") ## cubic interpolation algorithm\n return xnew, interpolator(xnew)\n\nif __name__ == \"__main__\":\n \n def unittest1():\n wfm = WaveformMaster()\n x, y = wfm.img_to_wav(r\"test_data\\3.png\", 0.0, 24.0 * 60, 0.0, 100.0, 15)\n print(\"new axis is from %s to %s\" % (x.min(), x.max()))\n plt.plot(x, y)\n plt.show()\n \n unittest1()","sub_path":"wavmaster.py","file_name":"wavmaster.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628939907","text":"# -*- coding: utf-8 -*-\n\nfrom .base import *\n\n# Parse database configuration from $DATABASE_URL\nDATABASES['default'] = dj_database_url.config()\n\n# Enable Connection Pooling (if desired)\nDATABASES['default']['ENGINE'] = 'django_postgrespool'\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n","sub_path":"scire/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514566253","text":"import argparse\nimport socket\nimport json\nimport logging\nimport inspect\nfrom functools import wraps\n\nADDRESS = 'localhost'\nPORT = 7777\nCONNECTIONS = 10\nTIMEOUT = 0.5\n\nserver_logger = logging.getLogger('chat.server')\nclient_logger = logging.getLogger('chat.client')\n\n\ndef log(func):\n @wraps(func)\n def call(*args, **kwargs):\n outer_func = inspect.stack()[1][3]\n server_logger.debug(f'Function \"{func.__name__}\" is called into \"{outer_func}\"')\n client_logger.debug(f'Function \"{func.__name__}\" is called into \"{outer_func}\"')\n return func(*args, **kwargs)\n return call\n\n\n@log\ndef get_server_socket(addr, port):\n s = socket.socket()\n s.bind((addr, port))\n s.listen(CONNECTIONS)\n s.settimeout(TIMEOUT)\n return s\n\n\n@log\ndef get_client_socket(addr, port):\n s = socket.socket()\n s.connect((addr, port))\n return s\n\n\n@log\ndef send_data(recipient, data):\n recipient.send(json.dumps(data).encode('utf-8'))\n\n\n@log\ndef get_data(sender):\n return json.loads(sender.recv(1048576).decode(\"utf-8\"))\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n description='JSON instant messaging'\n )\n\n parser_group = parser.add_argument_group(title='Parameters')\n parser_group.add_argument('-a', '--addr', default=ADDRESS, help='IP address')\n parser_group.add_argument('-p', '--port', type=int, default=PORT, help='TCP port')\n\n return parser\n","sub_path":"lesson_7/chat/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"584929080","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Time : 2019/6/13 下午10:35\n# @Author : Aries\n# @Site : \n# @File : LTU.py\n# @Software: PyCharm\n'''\n人工神经网络: ANN\n'''\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.linear_model import Perceptron\n\n'''\n输入:输入神经网络\n每一个输出:代表一个神经网络 eg:入鸢尾花有3个输出神经网络\n\n感知器是最简单的ANN架构之一,它基于一个稍微不同的被称为线性阈值单元(LTU)的人工神经元:\n1.输入输出都是数字,每个输入的连接都有一个对应的权重\n\n2.LTU会加权求和(z = wT * X)\n\n3.对求值结果应用一个阶跃函数.最后求得最后的输出: step(z)\n\n\n基于鸢尾花,看下面的代码:\nscikit代码 提供了一个实现单一LTU网络的Perceptron类,他基本可以再鸢尾花的数据集上如期工作:\n'''\n\niris = load_iris()\nX = iris.data[:, (2, 3)]\ny = (iris.target == 0).astype(np.int) # is Setosa?\nper_clf = Perceptron(random_state=42)\nper_clf.fit(X, y)\n\ny_pred = per_clf.predict([[2, 0.5]])\nprint(y_pred)\n\n\n'''\n注意和逻辑回归分类器相反,感知器不成熟出某个概率,它只是更具一个固定的阈值来做预测(也就是说智慧输出0 或者 1这样)\n所以可以直接看出单个感知器是不如逻辑分类的\n所以我们要将多个感知器堆叠起来进行弥补这个弊端.这种形式的ANN叫做多层感知器[MLP]\nMLP同样可以解决异或者同的问题xxxx\n'''\n","sub_path":"artificial_neural_network/core/LTU.py","file_name":"LTU.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351123208","text":"import sys\r\n\r\n#joins consecutive parts together and outputs simplified string\r\ndef simplify(str):\r\n new_str=[]\r\n curr=None\r\n for c in str:\r\n if c != curr:\r\n curr = c\r\n new_str.append(c)\r\n return ''.join(new_str)\r\n\r\n\r\ndef calc_flips(case):\r\n if len(case) == 1:\r\n if case=='+':\r\n return 0\r\n else:\r\n return 1\r\n else:\r\n if case[0] == '-':\r\n if case[-1] == '-':\r\n return len(case)\r\n return len(case) -1\r\n else:\r\n if case[-1] == '-':\r\n return len(case)\r\n return len(case)-1\r\n return 0\r\n\r\n\r\ndef main(argv):\r\n f = open(argv, 'r')\r\n N = int(f.readline())\r\n\r\n for i in range(N):\r\n case = simplify(f.readline().strip())\r\n print( \"Case #%d: %d\" % (i+1, calc_flips(case)))\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1])","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_DatBDude_coinJam.py","file_name":"16_0_2_DatBDude_coinJam.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80358144","text":"\"\"\"BulletinChainSystem URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom webui import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('root_chain', views.root_chain, name=\"root_chain\"),\n path('get_block', views.get_block, name=\"get_block\"),\n path('get_root_block', views.get_root_block, name=\"get_root_block\"),\n path('msg_of_send', views.msg_of_send, name=\"msg_of_send\"),\n path('comment_hash_request', views.comment_hash_request, name=\"comment_hash_request\"),\n path('key_set_request', views.key_set_request, name=\"key_set_request\"),\n\n]\n\n","sub_path":"BulletinChainSystem/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"121450852","text":"import logging\nimport botocore.vendored.requests\nimport boto3\nimport cfnresponse\nfrom dateutil import parser\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nsession = boto3.session.Session()\nclient = session.client(service_name='ec2')\n\n\ndef handler(event, context):\n response_data = {}\n ami_name = event['ResourceProperties']['AmiName']\n filters = [{'Name': 'name', 'Values': [ami_name]}]\n response = None\n\n if event['RequestType'] == 'Create' or event['RequestType'] == 'Update':\n response = client.describe_images(Owners=['self'], Filters=filters)\n if response != None:\n return_image = newest_image(response['Images'])\n if return_image != None:\n response_data['AmiId'] = return_image['ImageId']\n logger.info(response_data['AmiId'])\n if response_data['AmiId'] != None:\n cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data=response_data)\n else:\n cfnresponse.send(event, context, cfnresponse.FAILED, reason=\"AmiId for AmiName {AmiName} not found\".format(AmiName=ami_name))\n\n else:\n cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data={})\n\n\ndef newest_image(list_of_images):\n latest = None\n\n for image in list_of_images:\n if not latest:\n latest = image\n continue\n\n if parser.parse(image['CreationDate']) > parser.parse(latest['CreationDate']):\n latest = image\n\n return latest\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445205921","text":"import pandas as pd\nfrom math import pi\nfrom bokeh.plotting import figure, output_file, show\n\nAAPL = pd.read_csv(\n 'http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010',\n parse_dates=['Date']\n)\n\noutput_file('datetime.html')\n\n# create plot with a 'datetime' axis type\np = figure(width=1000, height=600, title='AAPL', x_axis_type='datetime')\n\n# style the axes (not really necessary, the defaults are good enough)\n# http://bokeh.pydata.org/en/latest/docs/user_guide/styling.html#axes\np.xaxis.axis_label = 'Date'\np.xaxis.axis_label_text_color = '#ff0000'\np.xaxis.major_label_orientation = pi/6\np.xgrid.grid_line_color = None\n\np.yaxis.axis_label = 'Price ($)'\np.yaxis.axis_label_text_font_style = 'italic'\np.yaxis.major_label_orientation = 'horizontal'\np.ygrid.grid_line_alpha = 0.7\np.ygrid.grid_line_dash = [6, 4]\n\n# add renderers\np.line(AAPL['Date'], AAPL['Open'], color='orange', alpha=1, legend='Open')\np.line(AAPL['Date'], AAPL['Close'], color='steelblue', alpha=1, legend='Close')\n\n# style the legend\n# http://bokeh.pydata.org/en/latest/docs/user_guide/styling.html#legends\np.legend.label_text_font = 'times'\np.legend.location = 'bottom_right'\np.legend.border_line_width = 3\np.legend.border_line_color = 'red'\np.legend.background_fill_color = 'gray'\np.legend.background_fill_alpha = 0.2\n\nshow(p)\n","sub_path":"bokeh_timeseries.py","file_name":"bokeh_timeseries.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37437332","text":"import os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nsys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\n\nimport random\nfrom math import ceil\nimport time\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom util.nifti_io import ni_save, ni_load\nfrom util.constant import *\n\n\ndef init_parameter(module):\n if hasattr(module, 'weight'):\n nn.init.constant_(module.weight, 1e-2)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, 1e-2)\n\n\n# 将origin_dict中的值换成map中的值。\ndef transform_dict_data(origin_dict, map):\n map_keys = map.keys()\n for key, value in origin_dict.items():\n if value in list(map_keys):\n origin_dict[key] = map[value]\n\n\ndef save_images(pred_dir, f_name, ni_aff, score=None, ori=None, rec=None):\n ni_aff = ni_aff.astype(np.float64)\n if score is not None:\n score_dir = os.path.join(pred_dir, 'score')\n if not os.path.exists(score_dir): os.mkdir(score_dir)\n score = score.astype(np.float64)\n ni_save(os.path.join(score_dir, f_name), score, ni_aff)\n\n if ori is not None:\n ori_dir = os.path.join(pred_dir, 'ori')\n if not os.path.exists(ori_dir): os.mkdir(ori_dir)\n ori = ori.astype(np.float64)\n ni_save(os.path.join(ori_dir, f_name), ori, ni_aff)\n\n if rec is not None:\n rec_dir = os.path.join(pred_dir, 'rec')\n if not os.path.exists(rec_dir): os.mkdir(rec_dir)\n rec = rec.astype(np.float64)\n ni_save(os.path.join(rec_dir, f_name), rec, ni_aff)\n\n\ndef clip_image(input_folder, output_folder):\n for folder_name in os.listdir(input_folder):\n folder_path = os.path.join(input_folder, folder_name)\n if os.path.isdir(folder_path):\n if not os.path.exists(os.path.join(output_folder, folder_name)):\n os.mkdir(os.path.join(output_folder, folder_name))\n for f_name in os.listdir(folder_path):\n ni_file = os.path.join(folder_path, f_name)\n ni_data, ni_affine = ni_load(ni_file)\n ni_data = np.clip(ni_data, a_max=1.0, a_min=0.0)\n ni_save(os.path.join(output_folder, folder_name, f_name), ni_data, ni_affine)\n\n\ndef template_statistics(test_dir):\n import matplotlib.pyplot as plt\n\n predict_dir = os.path.join(test_dir, 'eval', 'temmat', 'predict')\n assert os.path.exists(predict_dir), '先预测,再统计'\n statistics_dir = os.path.join(predict_dir, 'statistics')\n if not os.path.exists(statistics_dir):\n os.mkdir(statistics_dir)\n\n handle = tqdm(enumerate(os.listdir(os.path.join(predict_dir, 'pixel', 'rec'))))\n for i, file_name in handle:\n prefix = file_name.split('.')[0]\n each_statistics_dir = os.path.join(statistics_dir, prefix)\n if not os.path.exists(each_statistics_dir): os.mkdir(each_statistics_dir)\n\n score, ni_aff = ni_load(os.path.join(predict_dir, 'pixel', 'score', file_name))\n flatten_score = score.flatten()\n\n # 整体打分直方图\n plt.hist(flatten_score, bins=50, log=False)\n plt.savefig(os.path.join(each_statistics_dir, 'whole_score_histogram'))\n plt.cla()\n\n with open(os.path.join(test_dir, 'label', 'sample', file_name + '.txt'), \"r\") as f:\n sample_label = f.readline()\n sample_label = int(sample_label)\n\n if sample_label == 1:\n # 异常区域打分直方图\n label, _ = ni_load(os.path.join(test_dir, 'label', 'pixel', file_name))\n abnormal_area_score = score[label == 1]\n plt.hist(abnormal_area_score, bins=50, log=False)\n plt.savefig(os.path.join(each_statistics_dir, 'abnormal_area_score_histogram'))\n plt.cla()\n\n abnormal_number = len(abnormal_area_score)\n # print(f'abnormal_number: {abnormal_number}')\n elif sample_label == 0:\n abnormal_number = 10000\n else: raise Exception(f'sample_label有问题: {sample_label}')\n\n # 高分区域打分直方图\n ordered_flatten_score = np.sort(flatten_score)[::-1]\n large_score = ordered_flatten_score[0: abnormal_number]\n plt.hist(large_score, bins=50, log=False)\n plt.savefig(os.path.join(each_statistics_dir, 'max_score_area_score_histogram'))\n plt.cla()\n\n max_score = large_score[0]\n img = score / max_score\n ni_save(os.path.join(each_statistics_dir, 'normalized'), img, ni_aff)\n\n\ndef template_match_ex(test_dir): # 读进来的是nii.gz\n from util.configure import TRAIN_DATASET_DIR\n from scripts.evalresults import eval_dir\n\n score_dir, pred_pixel_dir, pred_sample_dir = init_validation_dir('temmat', test_dir)\n templates = load_array(os.path.join(TRAIN_DATASET_DIR, 'preprocessed'))\n\n print('predict')\n for f_name in os.listdir(os.path.join(test_dir, 'data')):\n print(f'f_name: {f_name}')\n np_array, ni_aff = ni_load(os.path.join(test_dir, 'data', f_name))\n\n score, rec = template_match(templates, np_array)\n save_images(pred_pixel_dir, f_name, ni_aff, score=score, rec=rec)\n\n sample_score = get_sample_score(score)\n with open(os.path.join(pred_sample_dir, f_name + \".txt\"), \"w\") as target_file:\n target_file.write(str(sample_score))\n \n eval_dir(pred_dir=os.path.join(pred_pixel_dir, 'score'), label_dir=os.path.join(test_dir, 'label', 'pixel'), mode='pixel', save_file=os.path.join(score_dir, 'pixel'))\n eval_dir(pred_dir=pred_sample_dir, label_dir=os.path.join(test_dir, 'label', 'sample'), mode='sample', save_file=os.path.join(score_dir, 'sample'))\n\n\ndef template_match(imgs, np_array): # imgs 四维\n min_score_num = np.inf\n min_score_index = -1\n\n length = len(imgs)\n handle = tqdm(enumerate(imgs))\n for i, img in handle:\n score = (img - np_array) ** 2\n score_num = np.sum(score)\n if score_num < min_score_num:\n min_score_num = score_num\n min_score_index = i\n\n handle.set_description_str(f'{i+1}/{length}')\n\n rec = imgs[min_score_index]\n score = (rec - np_array) ** 2\n return score, rec\n\n\ndef get_sample_score(score):\n slice_scores = []\n for sli in score:\n slice_score = np.mean(sli)\n slice_scores.append(slice_score)\n return np.max(slice_scores)\n\n\ndef load_array(path):\n print(f'load_array')\n imgs = []\n handle = tqdm(os.listdir(path))\n for fname in handle:\n if fname.endswith('data.npy'):\n np_array = np.load(os.path.join(path, fname))\n imgs.append(np_array)\n return imgs\n\n\ndef init_validation_dir(algo_name, dataset_dir):\n eval_dir = os.path.join(dataset_dir, 'eval')\n if not os.path.exists(eval_dir): os.mkdir(eval_dir)\n algo_dir = os.path.join(eval_dir, algo_name)\n if not os.path.exists(algo_dir): os.mkdir(algo_dir)\n pred_dir = os.path.join(algo_dir, 'predict')\n if not os.path.exists(pred_dir): os.mkdir(pred_dir)\n score_dir = os.path.join(algo_dir, 'score')\n if not os.path.exists(score_dir): os.mkdir(score_dir)\n\n pred_pixel_dir = os.path.join(pred_dir, 'pixel')\n if not os.path.exists(pred_pixel_dir): os.mkdir(pred_pixel_dir)\n pred_sample_dir = os.path.join(pred_dir, 'sample')\n if not os.path.exists(pred_sample_dir): os.mkdir(pred_sample_dir)\n\n return score_dir, pred_pixel_dir, pred_sample_dir\n\n\nif __name__ == '__main__':\n from util.configure import TEST_DATASET_DIR\n # template_match_ex(test_dir=TEST_DATASET_DIR)\n template_statistics(test_dir=TEST_DATASET_DIR)","sub_path":"example_algos/util/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":7618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37296307","text":"# -*- coding: utf-8 -*-\n# Part of BrowseInfo. See LICENSE file for full copyright and licensing details.\n\nfrom datetime import datetime, timedelta\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError, ValidationError\nfrom odoo.tools import float_is_zero, float_compare, \\\n DEFAULT_SERVER_DATETIME_FORMAT\nfrom odoo.http import request\nfrom collections import defaultdict\n\n\nclass PosPayment(models.Model):\n _inherit = 'pos.payment'\n\n actual_session_id = fields.Many2one('pos.session', string='Session',\n compute='get_session_id', store=True)\n\n @api.depends('pos_order_id')\n def get_session_id(self):\n for rec in self:\n if rec.session_id and rec.pos_order_id.is_reserved and rec.actual_session_id:\n rec.actual_session_id = rec.actual_session_id.id\n else:\n rec.actual_session_id = rec.pos_order_id.session_id and \\\n rec.pos_order_id.session_id.id or False\n\n\nclass PosSessionInherit(models.Model):\n _inherit = 'pos.session'\n\n total_payments_amount_display = fields.Float(\n compute='_compute_total_payments_amount_display',\n string='Total Payments Amount')\n\n @api.depends('order_ids.payment_ids.amount')\n def _compute_total_payments_amount_display(self):\n for session in self:\n session.total_payments_amount_display = sum(\n session.order_ids.mapped('payment_ids').filtered(\n lambda x: x.actual_session_id.id == session.id).mapped(\n 'amount'))\n\n def action_show_payments_list(self):\n return {\n 'name': _('Payments'),\n 'type': 'ir.actions.act_window',\n 'res_model': 'pos.payment',\n 'view_mode': 'tree,form',\n 'domain': [('actual_session_id', '=', self.id)],\n 'context': {'search_default_group_by_payment_method': 1}\n }\n\n @api.model\n def create(self, vals):\n res = super(PosSessionInherit, self).create(vals)\n orders = self.env['pos.order'].search([\n ('state', '=', 'reserved'), ('user_id', '=', request.env.uid)])\n orders.write({'session_id': res.id})\n orders.mapped('payment_ids').get_session_id()\n return res\n\n def _accumulate_amounts(self, data):\n # Accumulate the amounts for each accounting lines group\n # Each dict maps `key` -> `amounts`, where `key` is the group key.\n # E.g. `combine_receivables` is derived from pos.payment records\n # in the self.order_ids with group key of the `payment_method_id`\n # field of the pos.payment record.\n amounts = lambda: {'amount': 0.0, 'amount_converted': 0.0}\n tax_amounts = lambda: {'amount': 0.0, 'amount_converted': 0.0,\n 'base_amount': 0.0, 'base_amount_converted': 0.0}\n split_receivables = defaultdict(amounts)\n split_receivables_cash = defaultdict(amounts)\n combine_receivables = defaultdict(amounts)\n combine_receivables_cash = defaultdict(amounts)\n invoice_receivables = defaultdict(amounts)\n sales = defaultdict(amounts)\n taxes = defaultdict(tax_amounts)\n stock_expense = defaultdict(amounts)\n stock_output = defaultdict(amounts)\n # Track the receivable lines of the invoiced orders' account moves for reconciliation\n # These receivable lines are reconciled to the corresponding invoice receivable lines\n # of this session's move_id.\n order_account_move_receivable_lines = defaultdict(\n lambda: self.env['account.move.line'])\n rounded_globally = self.company_id.tax_calculation_rounding_method == 'round_globally'\n for order in self.order_ids:\n # if order.state != 'reserved':\n # Combine pos receivable lines\n # Separate cash payments for cash reconciliation later.\n for payment in order.payment_ids.filtered(lambda x:\n x.actual_session_id.id == self.id):\n amount, date = payment.amount, payment.payment_date\n if payment.payment_method_id.split_transactions:\n if payment.payment_method_id.is_cash_count:\n split_receivables_cash[payment] = self._update_amounts(\n split_receivables_cash[payment], {'amount': amount},\n date)\n else:\n split_receivables[payment] = self._update_amounts(\n split_receivables[payment], {'amount': amount},\n date)\n else:\n key = payment.payment_method_id\n if payment.payment_method_id.is_cash_count:\n combine_receivables_cash[key] = self._update_amounts(\n combine_receivables_cash[key], {'amount': amount},\n date)\n else:\n combine_receivables[key] = self._update_amounts(\n combine_receivables[key], {'amount': amount}, date)\n if order.is_invoiced:\n # Combine invoice receivable lines\n key = order.partner_id.property_account_receivable_id.id\n invoice_receivables[key] = self._update_amounts(\n invoice_receivables[key],\n {'amount': order._get_amount_receivable()},\n order.date_order)\n # side loop to gather receivable lines by account for reconciliation\n for move_line in order.account_move.line_ids.filtered(lambda\n aml: aml.account_id.internal_type == 'receivable' and not aml.reconciled):\n order_account_move_receivable_lines[\n move_line.account_id.id] |= move_line\n else:\n order_taxes = defaultdict(tax_amounts)\n for order_line in order.lines:\n line = self._prepare_line(order_line)\n # Combine sales/refund lines\n sale_key = (\n # account\n line['income_account_id'],\n # sign\n -1 if line['amount'] < 0 else 1,\n # for taxes\n tuple((tax['id'], tax['account_id'],\n tax['tax_repartition_line_id']) for tax in\n line['taxes']),\n )\n sales[sale_key] = self._update_amounts(\n sales[sale_key], {\n 'amount': sum(\n p.amount for p in\n order.payment_ids.filtered(\n lambda x: x.actual_session_id.id ==\n self.id))},\n order.date_order)\n # Combine tax lines\n for tax in line['taxes']:\n tax_key = (\n tax['account_id'], tax['tax_repartition_line_id'],\n tax['id'], tuple(tax['tag_ids']))\n order_taxes[tax_key] = self._update_amounts(\n order_taxes[tax_key],\n {'amount': tax['amount'],\n 'base_amount': tax['base']},\n tax['date_order'],\n round=not rounded_globally\n )\n for tax_key, amounts in order_taxes.items():\n if rounded_globally:\n amounts = self._round_amounts(amounts)\n for amount_key, amount in amounts.items():\n taxes[tax_key][amount_key] += amount\n\n if self.company_id.anglo_saxon_accounting and order.picking_id.id:\n # Combine stock lines\n stock_moves = self.env['stock.move'].search([\n ('picking_id', '=', order.picking_id.id),\n ('company_id.anglo_saxon_accounting', '=', True),\n ('product_id.categ_id.property_valuation', '=',\n 'real_time')\n ])\n for move in stock_moves:\n exp_key = move.product_id.property_account_expense_id or move.product_id.categ_id.property_account_expense_categ_id\n out_key = move.product_id.categ_id.property_stock_account_output_categ_id\n amount = -sum(\n move.stock_valuation_layer_ids.mapped('value'))\n stock_expense[exp_key] = self._update_amounts(\n stock_expense[exp_key], {'amount': amount},\n move.picking_id.date, force_company_currency=True)\n stock_output[out_key] = self._update_amounts(\n stock_output[out_key], {'amount': amount},\n move.picking_id.date, force_company_currency=True)\n\n # Increasing current partner's customer_rank\n order.partner_id._increase_rank('customer_rank')\n\n MoveLine = self.env['account.move.line'].with_context(\n check_move_validity=False)\n\n data.update({\n 'taxes': taxes,\n 'sales': sales,\n 'stock_expense': stock_expense,\n 'split_receivables': split_receivables,\n 'combine_receivables': combine_receivables,\n 'split_receivables_cash': split_receivables_cash,\n 'combine_receivables_cash': combine_receivables_cash,\n 'invoice_receivables': invoice_receivables,\n 'stock_output': stock_output,\n 'order_account_move_receivable_lines': order_account_move_receivable_lines,\n 'MoveLine': MoveLine\n })\n return data\n\n def _confirm_orders(self):\n for session in self:\n company_id = session.config_id.journal_id.company_id.id\n orders = session.order_ids.filtered(\n lambda order: order.state == 'paid')\n journal_id = self.env['ir.config_parameter'].sudo().get_param(\n 'pos.closing.journal_id_%s' % company_id,\n default=session.config_id.journal_id.id)\n if not journal_id:\n raise UserError(\n _(\"You have to set a Sale Journal for the POS:%s\") % (\n session.config_id.name,))\n\n move = self.env['pos.order'].with_context(\n force_company=company_id)._create_account_move(session.start_at,\n session.name,\n int(journal_id),\n company_id)\n orders.with_context(\n force_company=company_id)._create_account_move_line(session,\n move)\n\n for order in session.order_ids.filtered(\n lambda o: o.state not in ['done', 'invoiced']):\n if order.state in ('paid'):\n order.action_pos_order_done()\n\n orders_to_reconcile = session.order_ids._filtered_for_reconciliation()\n orders_to_reconcile.sudo()._reconcile_payments()\n\n def _reconcile_account_move_lines(self, data):\n # reconcile cash receivable lines\n split_cash_statement_lines = data.get('split_cash_statement_lines')\n combine_cash_statement_lines = data.get('combine_cash_statement_lines')\n split_cash_receivable_lines = data.get('split_cash_receivable_lines')\n combine_cash_receivable_lines = data.get(\n 'combine_cash_receivable_lines')\n order_account_move_receivable_lines = data.get(\n 'order_account_move_receivable_lines')\n invoice_receivable_lines = data.get('invoice_receivable_lines')\n stock_output_lines = data.get('stock_output_lines')\n\n for statement in self.statement_ids:\n if not self.config_id.cash_control:\n statement.write({'balance_end_real': statement.balance_end})\n statement.button_confirm_bank()\n all_lines = (split_cash_statement_lines[statement].mapped(\n 'journal_entry_ids').filtered(\n lambda aml: aml.account_id.internal_type == 'receivable')\n | combine_cash_statement_lines[statement].mapped(\n 'journal_entry_ids').filtered(\n lambda\n aml: aml.account_id.internal_type == 'receivable')\n | split_cash_receivable_lines[statement]\n | combine_cash_receivable_lines[statement]\n )\n accounts = all_lines.mapped('account_id')\n lines_by_account = [\n all_lines.filtered(lambda l: l.account_id == account) for\n account in accounts]\n for lines in lines_by_account:\n lines.reconcile()\n # reconcile invoice receivable lines\n for account_id in order_account_move_receivable_lines:\n (order_account_move_receivable_lines[account_id]\n | invoice_receivable_lines.get(account_id,\n self.env['account.move.line'])\n ).reconcile()\n\n # reconcile stock output lines\n stock_moves = self.env['stock.move'].search([\n ('picking_id', 'in', self.order_ids.filtered(\n lambda order: not order.is_invoiced).mapped('picking_id').ids)\n ])\n stock_account_move_lines = self.env['account.move'].search(\n [('stock_move_id', 'in', stock_moves.ids)]).mapped('line_ids')\n for account_id in stock_output_lines:\n (stock_output_lines[account_id].filtered(\n lambda aml: not aml.reconciled)\n | stock_account_move_lines.filtered(\n lambda\n aml: not aml.reconciled and aml.account_id == account_id)).reconcile()\n return data\n","sub_path":"pos_reserve_order_app/models/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":14507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"651378777","text":"'''\nurls.py is the the first file that bssWeb server side runs.\n\nIt act as the table of content for all applications in the project, \nby mapping the global urls to the application's api module.\n\nIt can also map the static files as well. This is used for development purpose only, \nsince in production static files should be serve by more capable server like nginx.\n\nThere are two type of content that need to register to table of content, \n1) the dynamic: app/api.py and the app/views/*.html\n2) the static: app/static/*\n'''\n\nimport traceback, os, sys, time\nfrom pprint import pformat\n\nfrom django.conf.urls import include, url, patterns\nfrom django.conf import settings\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.views.decorators.csrf import csrf_exempt\nimport django\n\nfrom . import list_webapp_pypackages, PROJ_NAME, get_logger, PROJ_DIR\nfrom . import base_app\nfrom . import load_app_module, get_app_root, failed_handler, generate_env_info_html\n\nLOG = get_logger()\n\n# get the debug settings from the environment. \nsettings.DEBUG = (os.environ.get(PROJ_NAME.upper() + '_DEBUG', 'true')=='true')\nDEBUG_SERVE_STATIC = (os.environ.get(PROJ_NAME.upper() + '_SERVE_STATIC', 'true')=='true')\n \n# this is sourced by dJango to handle 404 request (for missing url) \nhandler404 = lambda request_not_used: HttpResponse( content = '

Can not find page.

' + generate_env_info_html(), \n content_type = 'text/html; charset=utf-8', \n status = 404) \n# this is sourced by django, the table of content \nurlpatterns = []\n\ndef register_dynamic_content():\n global urlpatterns\n \n # register the app modules to be callable by client side ajax calls. \n for app in list_webapp_pypackages():\n app_name = app['basename']\n # first check if there is view.py, if there is then skip this.\n app_root = get_app_root(app_name)\n \n # html views are protected and serve \n view_root = app_root + '/views'\n \n if os.path.isdir(view_root):\n for viewfile in os.listdir( view_root ):\n if viewfile.split('.')[-1] in ('htm','html'): \n LOG.debug(\"Adding view '%s'...\" % viewfile)\n protected_handler = lambda req, viewpath=view_root + '/'+ viewfile: base_app.protected_view_handler( req, viewpath )\n \n if viewfile=='index.html':\n urlpatterns.append( url(r'^%s/$' % app_name, csrf_exempt( protected_handler ) ) )\n \n urlpatterns.append( url(r'^%s/%s' % (app_name, viewfile), csrf_exempt( protected_handler ) ) )\n urlpatterns.append( url(r'^%s/%s' % (app_name, viewfile[:viewfile.rfind('.')] ), csrf_exempt( protected_handler ) ) )\n\n \n for app_root_pyfile in [ f for f in os.listdir(app_root) if f.endswith('.py') and f!='__init__.py' ]:\n # expect module like api.py \n module_name = app_root_pyfile[:app_root_pyfile.rfind('.')]\n pkg, err_msg = load_app_module(app_name, module_name)\n module_handler = lambda req, pkg=pkg, module_name=module_name: base_app.handle_request( req, app_name, getattr(pkg, module_name) )\n urlpatterns.append( url(r'^%s/%s$' % (app_name, module_name), csrf_exempt(module_handler) ) )\n \n\n\ndef register_static_content(): \n '''\n Register the static content for each app, as well as the shared web js/css library.\n Register all the \n '''\n global urlpatterns\n \n ###############################################\n # serve global appkit static content\n ############################################### \n #static_path = os.path.split(os.path.split( os.path.split( __file__ )[0])[0])[0] + '/webkit'\n appkit_path = PROJ_DIR + '/resource/appkit'\n \n assert os.path.isdir(appkit_path), \"Failed to find the appkit path '%s'.\" % appkit_path\n \n LOG.info(\"Registering the static appkit '%s'...\" % appkit_path ) \n \n urlpatterns += patterns( '',\n url( r'^appkit/(?P.*)$', # regex \n 'django.views.static.serve', # view\n { # kwargs\n 'document_root': appkit_path, \n 'show_indexes': True\n } \n ) \n )\n \n ###############################################\n # serve app's static content\n ############################################### \n for app in list_webapp_pypackages():\n app_name = app['basename'] \n pkg, err_msg = load_app_module(app_name)\n if pkg:\n app_path = os.path.split( os.path.abspath( pkg.__file__ ) )[0]\n \n LOG.info( \"Registering local static files of app '%s' in dir '%s'...\" % (app_name, app_path) )\n \n if os.path.isdir(app_path): \n urlpatterns += patterns( '', # prefix\n url(r'^%s/static/(?P.*)$' % app_name, # regex \n 'django.views.static.serve', # view\n { # kwargs\n 'document_root': app_path + '/static', \n 'show_indexes': True\n }\n ) \n )\n else:\n LOG.warning( \"No static directory found for app '%s' at dir '%s'...\" % (app_name, static_path) )\n \n\ndef register_admin_app():\n '''\n The admin app is comes with DJango and it useful to create permission groups. \n Potentially very useful gui/api to facilitate App permissions. \n '''\n global urlpatterns\n from django.contrib import admin\n \n urlpatterns += patterns ( '',\n url(r'^admin/', include(admin.site.urls)),\n )\n \n if True: #if DEBUG_SERVE_STATIC: \n static_path = PROJ_DIR + '/resource/admin' \n urlpatterns += patterns ( '',\n url(r'^resource/admin/(?P.*)$', # regex \n 'django.views.static.serve', # view\n { # kwargs\n 'document_root': static_path, \n 'show_indexes': True\n }\n ) \n )\n \ndef register_root_link():\n '''\n Decide where to link http://apps/\n '''\n global urlpatterns\n \n if 'wapDashboard' in list_webapp_pypackages(as_hash=True):\n response = HttpResponseRedirect( '/wapDashboard' )\n \n else:\n response = HttpResponse( content = generate_env_info_html(), \n content_type = 'text/html; charset=utf-8', \n status = 404) \n\n urlpatterns.append( url(r'^$', lambda not_used: response ) )\n \n \n\ndef register_main():\n '''\n Map the top level table of content.\n ''' \n global urlpatterns\n \n # The default url root of app just prints information about environment\n #urlpatterns.append( url(r'^/debug$', handler404 ) )\n #urlpatterns.append( url(r'^$', handle_root_link ) )\n \n register_root_link() \n \n register_admin_app()\n register_dynamic_content()\n \n if DEBUG_SERVE_STATIC: \n register_static_content()\n \n \n\nregister_main()\n","sub_path":"bssWeb/bssWeb/python/bssWeb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":8024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635435544","text":"import datetime\nfrom django.forms.extras.widgets import SelectDateWidget \nfrom django.forms.widgets import CheckboxSelectMultiple, Select\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.contrib.auth.hashers import make_password\nfrom django.core.exceptions import ValidationError\nfrom properties.models import (RealProperty, PropertyBedrooms, PropertyBathrooms, PropertyFeatures, \n\tPropertyType, PropertySurroundingAreas,)\n\nyears_to_display = range(datetime.date.today().year, datetime.date.today().year + 20)\n\nclass RealPropertyForm(ModelForm):\n\t\n\tclass Meta:\n\t\tmodel = RealProperty\n\t\tfields = ('owner','address','address2','city','state','zip_code','country','year_built','square_footage','description', 'is_for_sale',\n\t\t\t'is_for_sale','for_sale_amount','is_vacant', 'available_date','is_rented', 'lease_begins',\n\t\t\t'lease_ends', 'description','property_type','bedrooms','bathrooms',\n\t\t\t'features','surrounding_areas',)\n\t\twidgets = {\n\t\t\t'owner': forms.Select(attrs={'type':'input', 'class': 'form-control'}),\n\t\t\t'state': forms.Select(attrs={'type':'input', 'class': 'form-control'}),\n\t\t\t'address': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': '123 Main Street'}),\n\t\t\t'address2': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'Apt 2'}),\n\t\t\t'available_date': SelectDateWidget(empty_label=(\"Year\", \"Month\", \"Day\"), years= years_to_display),\n\t\t\t'city': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'New York'}),\n\t\t\t'zip_code': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'e.g. 1111'}),\n\t\t\t'country': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'e.g. United States'}),\n\t\t\t'year_built': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'e.g. 1956'}),\n\t\t\t'square_footage': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'e.g. 1200 sq. ft.'}),\n\t\t\t'for_sale_amount': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'e.g. $200000'}),\n\t\t\t'description': forms.Textarea(attrs={'cols' :50, 'rows': 5, 'class' :'form-control flat-contact', 'placeholder': 'Describe the property.' }),\n\t\t\t'lease_begins': SelectDateWidget(empty_label=(\"Year\", \"Month\", \"Day\"), years=years_to_display),\n\t\t\t'lease_ends': SelectDateWidget(empty_label=(\"Year\", \"Month\", \"Day\"), years=years_to_display),\n\t\t\t'features' : CheckboxSelectMultiple(),\n\t\t\t'surrounding_areas' : CheckboxSelectMultiple(),\n\t\t}\n\nclass BedroomPropertyForm(ModelForm):\n\tclass Meta:\n\t\tmodel = PropertyBedrooms\n\t\tfields = '__all__'\n\t\twidgets = {\n\t\t\t'bed_title': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'Enter Bedroom Amount'}),\n\t\t}\n\nclass BathroomPropertyForm(ModelForm):\n\tclass Meta:\n\t\tmodel = PropertyBathrooms\n\t\tfields = '__all__'\n\t\twidgets = {\n\t\t\t'bath_title': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'Enter Bathroom Amount'}),\n\t\t}\n\nclass PropertyFeaturesForm(ModelForm):\n\tclass Meta:\n\t\tmodel = PropertyFeatures\n\t\tfields = '__all__'\n\t\twidgets = {\n\t\t\t'property_feature': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'Enter Feature Amount'}),\n\t\t}\n\nclass PropertyTypeForm(ModelForm):\n\tclass Meta:\n\t\tmodel = PropertyType\n\t\tfields = '__all__'\n\t\twidgets = {\n\t\t\t'property_type': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'Enter Type Amount'}),\n\t\t}\n\nclass SurroundingAreasForm(ModelForm):\n\tclass Meta:\n\t\tmodel = PropertySurroundingAreas\n\t\tfields = '__all__'\n\t\twidgets = {\n\t\t\t'property_area': forms.TextInput(attrs={'type':'input', 'class': 'form-control flat-contact', 'placeholder': 'Enter Surrounding Area Options'}),\n\t\t}","sub_path":"globalSite/global/properties/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30031902","text":"import pandas as pd\ndata = pd.read_csv(\"iris.data\",header= None)\n#data.columns=[\"char_a\",\"char_b\",\"char_c\",\"char_d\",\"Result\"]\ndata_lst=[]\nfor i in range(150):\n temp_lst=[1]\n for j in range(4):\n temp_lst.append(data.iloc[i,j])\n\n data_lst.append(temp_lst)\n\ndesired = []\nfor i in range(150):\n if data.iloc[i,4] == 'Iris-setosa':\n desired.append([1,0,0])\n if data.iloc[i,4] == 'Iris-versicolor':\n desired.append([0,1,0])\n if data.iloc[i,4] == 'Iris-virginica':\n desired.append([0,0,1])\n\n#print(data_lst[149])\n","sub_path":"q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356512178","text":"#Kullanilan kutuphaneler\r\nfrom openpyxl import Workbook,load_workbook # Excel dosyasi okuma ve yazma islemleri icin\r\nimport zeep # WCF servis\r\nfrom scipy.spatial import distance #Oklid uzakligi hesaplama\r\n\r\n\"\"\"\r\n#Is ilani dosyasi okuma\r\npath='c:/Users/veyse/Desktop/pythonexcel/110K_IlanDatasi_23012020_Canli.xlsx' \r\nwb = load_workbook(path)\r\nws = wb.active\r\n\r\n\"\"\"\r\n\"\"\"\r\n#CV dosyasi okuma\r\npath4 = 'c:/Users/veyse/Desktop/pythonexcel/data_9EylulCvData_10000.xlsx' \r\nwb4 = load_workbook(path4)\r\nws4 = wb4.active\r\n\r\n#CV dosyasindan istenilen satirlari okuma ve yeni excel dosyasina yazma\r\nwb5 = Workbook() \r\nws5 = wb5.active\r\n\r\n#Is dosyasi ilanindan istenilen satirlari okuma ve yeni excel dosyasina yazma\r\nwb6 = Workbook() \r\nwb6 = wb6.active\r\n\r\n\"\"\"\r\n#Yeni olusturulan CV dosyasini okuma\r\npath2='c:/Users/veyse/Desktop/pythonexcel/Bilgisayar_Yazilim_CV_Ilanlari.xlsx'\r\nwb2 = load_workbook(path2)\r\nws2 = wb2.active\r\n\r\n#Yeni olusturulan is ilani dosyasini okuma\r\npath3 = 'c:/Users/veyse/Desktop/pythonexcel/Bilgisayar_Muhendisi_Is_Ilanlari.xlsx'\r\nwb3 = load_workbook(path3)\r\nws3 = wb3.active\r\n\r\n\"\"\"\r\n\r\n#Is ilanlari\r\n#dosyasindan istenilen satirlarin ayiklanmasi ve yeni excel tablosuna yazilmasi\r\ncount = 1\r\nflag = False\r\nfor i in range(1,ws.max_row+1):\r\n if str(ws.cell(i,7).value) == 'Bilgisayar Mühendisi':\r\n for j in range(1,ws.max_column+1):\r\n c = ws.cell(i,j)\r\n ws6.cell(count,j).value = c.value\r\n flag = True\r\n if flag == True:\r\n count += 1 \r\n flag = False\r\n\r\n#Yeni olusturulan is ilanlari dosyasini kaydetme\r\nwb6.save('c:/Users/veyse/Desktop/pythonexcel/Bilgisayar_Muhendisi_110K_CV_Ilanlari.xlsx')\r\n\r\n\r\n\"\"\"\r\n\"\"\"\r\n#CV dosyasindan istenilen satirlarin ayiklanmasi ve yeni excel tablosuna yazilmasi\r\n\r\ncount = 1\r\nflag = False\r\nfor i in range(1,ws4.max_row+1):\r\n if str(ws4.cell(i,11).value) == 'Bilgisayar Mühendisliği' or str(ws4.cell(i,11).value) == 'Yazılım Mühendisliği' :\r\n for j in range(1,ws4.max_column+1):\r\n c = ws4.cell(i,j)\r\n ws5.cell(count,j).value = c.value\r\n flag = True\r\n if flag == True:\r\n count += 1 \r\n flag = False\r\n#Yeni olusturulan CV dosyasini kaydetme\r\nwb5.save('c:/Users/veyse/Desktop/pythonexcel/Bilgisayar_Yazilim_CV_Ilanlari.xlsx')\r\nwb4.close()\r\nwb5.close()\r\n\"\"\"\r\n#WCF servisi kullanmak icin link ve client atamasi\r\nprint(\"Connecting to service\")\r\nwsdl = \"http://193.140.150.95/KariyerServisleri/Service1.svc?singleWsdl\"\r\nclient = zeep.Client(wsdl=wsdl)\r\n\r\n#Olusturulmus CV dosyasindan secilen satirin okunarak attributelerine parcalanmasi\r\nCV_rowNum = 6\r\ncvAttributes = \"\"\r\nCV = []\r\n# 6 7 8 9 29 32 33 38 39 42 43 49 52 53 58 62 66 70 71 72 73 74 75 76 77 78 79\r\ncells = [6,7,8,9,11,29,32,33,38,39,42,43,49,52,53,58,62,66,70,71,72,73,74,75,76,77,78,79]\r\n\r\nfor j in range(1,ws2.max_column+1):\r\n if j in cells: \r\n if str(ws2.cell(CV_rowNum,j).value) == 'İstanbul(Asya)' or str(ws2.cell(CV_rowNum,j).value) =='İstanbul(Avr.)':\r\n sehir = \"İstanbul\" \r\n cvAttributes = cvAttributes + \" \" + str(sehir) \r\n else: \r\n cvAttributes = cvAttributes + \" \" + str(ws2.cell(CV_rowNum,j).value) \r\n \r\nCV.append(client.service.getRoots(cvAttributes)) \r\nwb2.close()\r\n\r\n#Olusturulmus is ilani dosyasindan satirlarin okunarak attributelerine parcalanmasi\r\nilanlar = []\r\nilan_cells = [5,6,8,9]\r\nfor i in range(1,ws3.max_row+1):\r\n ilan_explanation =\"\"\r\n for j in range(3,ws3.max_column+1):\r\n if j in ilan_cells:\r\n if str(ws3.cell(i,j).value) == 'İstanbul(Asya)' or str(ws3.cell(i,j).value) =='İstanbul(Avr.)':\r\n sehir = \"İstanbul\"\r\n ilan_explanation += \" \" + \"İstanbul\"\r\n else:\r\n ilan_explanation += \" \"+ str(ws3.cell(i,j).value)\r\n \r\n ilanlar.append(client.service.getRoots(ilan_explanation))\r\n \r\nwb3.close()\r\n\r\n#Olusturulmus is ilani ozelliklerinin CV ilanindaki karsiliklarinin bulunmasi\r\ndataset = [[] for _ in range(len(ilanlar))]\r\nfor x in range(len(ilanlar)):\r\n for y in range(len(CV[0])):\r\n if CV[0][y] in ilanlar[x]:\r\n dataset[x].insert(y,1)\r\n else:\r\n dataset[x].insert(y,0)\r\n#CV ilanini da matrix haline getirme\r\nX = []\r\nfor x in range(len(CV[0])):\r\n X.append(1)\r\n\r\n#Oklid uzakligi hesaplama\r\nsiralanmisİlanlar = [[] for _ in range(len(dataset))]\r\nfor i in range(len(dataset)):\r\n dst = distance.euclidean(X,dataset[i])\r\n siralanmisİlanlar[i].insert(0,i)\r\n siralanmisİlanlar[i].insert(1,dst)\r\n\r\n#Uzunluga gore siralama\r\nsiralanmisİlanlar = sorted(siralanmisİlanlar , key = lambda x: x[1])\r\n\r\n#CV dosyasina en yakin ilk 5 is ilaninin ekrana yazdirilmasi\r\nfor i in range(5):\r\n row = siralanmisİlanlar[i][0]\r\n print(ilanlar[row])\r\n\r\n","sub_path":"En uygun is ilani bulma.py","file_name":"En uygun is ilani bulma.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"256288551","text":"# Inventory Tracker.\n# Inventory tracker, database will be a text file, security\n# concerns for text file, public inventory list instead of private.\n# Can also create an ini file for dictionary saving but I don't know how to do that yet so using text files for now.\n\n# import pickle\n\n\n# Load the dictionary back from the pickle file.\n# favorite_color = pickle.load( open( \"save.p\", \"rb\" ) )\n\n\n# The inventory stored as a dictionary.\ninventory_dict = {}\n\n\ndef user_choice():\n print(\"1: Find Location Of Item In Inventory\")\n print(\"2: Change Item Location In Inventory\")\n print(\"3: Delete Item From Inventory\")\n print(\"4: Add Item To Inventory\")\n\n # Get user input.\n user_input = int(input(\"Type Choice: \"))\n\n # User input determines what happens.\n if user_input == 1:\n return find_location()\n if user_input == 2:\n return location_update()\n if user_input == 3:\n return delete_item()\n if user_input == 4:\n return add_item()\n else:\n return print(\"Not a choice, please try again.\")\n\n\ndef find_location():\n return print(\"Find Location\")\n\n\ndef location_update():\n return print(\"Update Location\")\n\n\ndef delete_item():\n return print(\"Delete Item\")\n\n\n# FIX ME\ndef add_item():\n add_item_num = input(print(\"Enter Item Number To Add To Inventory: \"))\n add_item_location = input(print(\"Enter Item Location Of Item Added To Inventory: \"))\n verify_input = input(print(\"Are You Sure You Want To Add Item:\", add_item_num, \"To Location:\", add_item_location))\n if verify_input == \"Y\" or \"y\":\n inventory_dict.update({add_item_num: add_item_location})\n else:\n add_item()\n\n\nuser_choice()\n\n# Save a dictionary into a pickle file.\n# favorite_color = { \"lion\": \"yellow\", \"kitty\": \"red\" }\n# pickle.dump( favorite_color, open( \"save.p\", \"wb\" ) )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569771864","text":"import matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nimport numpy as np\nimport pandas as pd\n\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\ndata = pd.read_csv(r\"csv/totalTime_9.csv\", index_col=0)\ndata = data['totalTime']\ndata = np.array(data).reshape(-1, 1)\n\nscore = []\nscore2 = []\nfig, ax1 = plt.subplots(1)\nfor i in [2, 3, 4, 5]:\n cluster = KMeans(n_clusters=i, random_state=1).fit(data)\n y_pred = cluster.labels_\n score2.append(cluster.inertia_)\nax1.plot([2, 3, 4, 5], score2, 'r--', label='K 与 SSE的关系')\nplt.xlabel('K')\nplt.ylabel('SSE')\nplt.legend()\n# plt.savefig(\"/\")\nplt.show()\n\n","sub_path":"sk/c++/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462944482","text":"# -*- coding: utf-8 -*-\n#\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.\nimport os\nimport re\nimport uuid\nimport copy\n\nfrom airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook\nfrom airflow.contrib.hooks.gcp_dataflow_hook import DataFlowHook\nfrom airflow.models import BaseOperator\nfrom airflow.version import version\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass DataFlowJavaXcomKeysOperator(BaseOperator):\n \"\"\"\n Start a Java Cloud DataFlow batch job. The parameters of the operation\n will be passed to the job. Supports pulling xcom keys as parameters\n\n **Example**: ::\n\n default_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date':\n (2016, 8, 1),\n 'email': ['alex@vanboxel.be'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=30),\n 'dataflow_default_options': {\n 'project': 'my-gcp-project',\n 'zone': 'us-central1-f',\n 'stagingLocation': 'gs://bucket/tmp/dataflow/staging/',\n }\n }\n\n dag = DAG('test-dag', default_args=default_args)\n\n task = DataFlowJavaOperator(\n gcp_conn_id='gcp_default',\n task_id='normalize-cal',\n jar='{{var.value.gcp_dataflow_base}}pipeline-ingress-cal-normalize-1.0.jar',\n options={\n 'autoscalingAlgorithm': 'BASIC',\n 'maxNumWorkers': '50',\n 'start': '{{ds}}',\n 'partitionType': 'DAY'\n\n },\n dag=dag)\n\n .. seealso::\n For more detail on job submission have a look at the reference:\n https://cloud.google.com/dataflow/pipelines/specifying-exec-params\n\n :param jar: The reference to a self executing DataFlow jar (templated).\n :type jar: str\n :param job_name: The 'jobName' to use when executing the DataFlow job\n (templated). This ends up being set in the pipeline options, so any entry\n with key ``'jobName'`` in ``options`` will be overwritten.\n :type job_name: str\n :param dataflow_default_options: Map of default job options.\n :type dataflow_default_options: dict\n :param options: Map of job specific options.\n :type options: dict\n :param gcp_conn_id: The connection ID to use connecting to Google Cloud\n Platform.\n :type gcp_conn_id: str\n :param delegate_to: The account to impersonate, if any.\n For this to work, the service account making the request must have\n domain-wide delegation enabled.\n :type delegate_to: str\n :param poll_sleep: The time in seconds to sleep between polling Google\n Cloud Platform for the dataflow job status while the job is in the\n JOB_STATE_RUNNING state.\n :type poll_sleep: int\n :param job_class: The name of the dataflow job class to be executed, it\n is often not the main class configured in the dataflow jar file.\n :type job_class: str\n :param xcom_keys: The xcom elements list of dictionaries containing the xcom data you want to pull data\n from in order to pass as parameters to dataflow. e.g.\n [{'xcom_key': xcom_key_value, 'task_id': task_id_value, 'dataflow_par_name': schema},...]\n If you specify this value, the operator will pull a value from xcom with\n key=xcom_key_value, task_id=task_id_value\n It will then pass --schema xcom_key_value as pipeline parameter value to the dataflow job.\n :type xcom_keys: dict\n\n ``jar``, ``options``, and ``job_name`` are templated so you can use variables in them.\n\n Note that both\n ``dataflow_default_options`` and ``options`` will be merged to specify pipeline\n execution parameter, and ``dataflow_default_options`` is expected to save\n high-level options, for instances, project and zone information, which\n apply to all dataflow operators in the DAG.\n\n It's a good practice to define dataflow_* parameters in the default_args of the dag\n like the project, zone and staging location.\n\n .. code-block:: python\n\n default_args = {\n 'dataflow_default_options': {\n 'project': 'my-gcp-project',\n 'zone': 'europe-west1-d',\n 'stagingLocation': 'gs://my-staging-bucket/staging/'\n }\n }\n\n You need to pass the path to your dataflow as a file reference with the ``jar``\n parameter, the jar needs to be a self executing jar (see documentation here:\n https://beam.apache.org/documentation/runners/dataflow/#self-executing-jar).\n Use ``options`` to pass on options to your job.\n\n .. code-block:: python\n\n t1 = DataFlowJavaOperator(\n task_id='datapflow_example',\n jar='{{var.value.gcp_dataflow_base}}pipeline/build/libs/pipeline-example-1.0.jar',\n options={\n 'autoscalingAlgorithm': 'BASIC',\n 'maxNumWorkers': '50',\n 'start': '{{ds}}',\n 'partitionType': 'DAY',\n 'labels': {'foo' : 'bar'}\n },\n gcp_conn_id='gcp-airflow-service-account',\n dag=my-dag)\n\n \"\"\"\n template_fields = ['options', 'jar', 'job_name']\n ui_color = '#0273d4'\n\n @apply_defaults\n def __init__(\n self,\n jar,\n job_name='{{task.task_id}}',\n dataflow_default_options=None,\n options=None,\n gcp_conn_id='google_cloud_default',\n delegate_to=None,\n poll_sleep=10,\n job_class=None,\n xcom_element_list=None,\n *args,\n **kwargs):\n super(DataFlowJavaXcomKeysOperator, self).__init__(*args, **kwargs)\n\n dataflow_default_options = dataflow_default_options or {}\n options = options or {}\n options.setdefault('labels', {}).update(\n {'airflow-version': 'v' + version.replace('.', '-').replace('+', '-')})\n self.gcp_conn_id = gcp_conn_id\n self.delegate_to = delegate_to\n self.jar = jar\n self.job_name = job_name\n self.dataflow_default_options = dataflow_default_options\n self.options = options\n self.poll_sleep = poll_sleep\n self.job_class = job_class\n self.xcom_element_list = xcom_element_list\n\n def execute(self, context):\n bucket_helper = GoogleCloudBucketHelper(\n self.gcp_conn_id, self.delegate_to)\n self.jar = bucket_helper.google_cloud_to_local(self.jar)\n hook = DataFlowHook(gcp_conn_id=self.gcp_conn_id,\n delegate_to=self.delegate_to,\n poll_sleep=self.poll_sleep)\n\n dataflow_options = copy.copy(self.dataflow_default_options)\n dataflow_options.update(self.options)\n # Legacy code for xcom key\n if 'xcom_key' in dataflow_options:\n value = context['task_instance'].xcom_pull(key=dataflow_options['xcom_key'])\n dataflow_options['queryParameters'] = value\n del dataflow_options['xcom_key']\n\n # Code for xcom_keys (to be implemented sanity check)\n if self.xcom_element_list is not None:\n for xcom_element in self.xcom_element_list:\n # Sanity check:'\n if any(key in xcom_element for key in ['xcom_key', 'task_id', 'dataflow_par_name']):\n\n pulled_xcom_value = \\\n context['task_instance'].xcom_pull(key=xcom_element['xcom_key'],\n task_ids=xcom_element['task_id'])\n dataflow_options[xcom_element['dataflow_par_name']] = pulled_xcom_value\n else:\n raise Exception(\"ERROR: one of the fields ['xcom_key', 'task_id', 'dataflow_par_name']\"\n \" is not non-existent\")\n\n print(\"dataflow_options: \", dataflow_options)\n hook.start_java_dataflow(self.job_name, dataflow_options,\n self.jar, self.job_class)\n\n\nclass GoogleCloudBucketHelper(object):\n \"\"\"GoogleCloudStorageHook helper class to download GCS object.\"\"\"\n GCS_PREFIX_LENGTH = 5\n\n def __init__(self,\n gcp_conn_id='google_cloud_default',\n delegate_to=None):\n self._gcs_hook = GoogleCloudStorageHook(gcp_conn_id, delegate_to)\n\n def google_cloud_to_local(self, file_name):\n \"\"\"\n Checks whether the file specified by file_name is stored in Google Cloud\n Storage (GCS), if so, downloads the file and saves it locally. The full\n path of the saved file will be returned. Otherwise the local file_name\n will be returned immediately.\n\n :param file_name: The full path of input file.\n :type file_name: str\n :return: The full path of local file.\n :rtype: str\n \"\"\"\n if not file_name.startswith('gs://'):\n return file_name\n\n # Extracts bucket_id and object_id by first removing 'gs://' prefix and\n # then split the remaining by path delimiter '/'.\n path_components = file_name[self.GCS_PREFIX_LENGTH:].split('/')\n if len(path_components) < 2:\n raise Exception(\n 'Invalid Google Cloud Storage (GCS) object path: {}'\n .format(file_name))\n\n bucket_id = path_components[0]\n object_id = '/'.join(path_components[1:])\n local_file = '/tmp/dataflow{}-{}'.format(str(uuid.uuid4())[:8],\n path_components[-1])\n self._gcs_hook.download(bucket_id, object_id, local_file)\n\n if os.stat(local_file).st_size > 0:\n return local_file\n raise Exception(\n 'Failed to download Google Cloud Storage (GCS) object: {}'\n .format(file_name))\n","sub_path":"plugins/operators/dataflow_xcom_operator.py","file_name":"dataflow_xcom_operator.py","file_ext":"py","file_size_in_byte":10591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316762617","text":"\n# http://www.fileformat.info/info/unicode/block/arabic/list.htm\n\nimport re\n# -*- coding: utf-8 -*-\n# ==============================================================================\nimport json\nimport os\n# ==============================================================================\n# %% functions\n# ==============================================================================\nclass Persian_Normalizer:\n def persian_normalizer(self,doc_name):\n normalized_text = []\n if doc_name is None:\n return \"\"\n if not os.path.exists(\"logs\"):\n os.mkdir(\"logs\")\n doc = open(doc_name, 'r', encoding='utf8')\n self.name = doc_name + 'NormAlpha.txt'\n text = open(self.name, 'w', encoding='utf8')\n\n #================ White Char\n ENTER=\"\\n\"\n TAB=\"\\t\"\n RETURN=\"\\r\"\n\n # ================ Numbers ======================\n # Persian Numbers\n FA_D0 = '\\u06F0'\n FA_D1 = '\\u06F1'\n FA_D2 = '\\u06F2'\n FA_D3 = '\\u06F3'\n FA_D4 = '\\u06F4'\n FA_D5 = '\\u06F5'\n FA_D6 = '\\u06F6'\n FA_D7 = '\\u06F7'\n FA_D8 = '\\u06F8'\n FA_D9 = '\\u06F9'\n # Arabic Numbers\n Ar_D0 = '\\u0660'\n Ar_D1 = '\\u0661'\n Ar_D2 = '\\u0662'\n Ar_D3 = '\\u0663'\n Ar_D4 = '\\u0664'\n Ar_D5 = '\\u0665'\n Ar_D6 = '\\u0666'\n Ar_D7 = '\\u0667'\n Ar_D8 = '\\u0668'\n Ar_D9 = '\\u0669'\n # English Numbers\n EN_D0 = '\\u0030'\n EN_D1 = '\\u0031'\n EN_D2 = '\\u0032'\n EN_D3 = '\\u0033'\n EN_D4 = '\\u0034'\n EN_D5 = '\\u0035'\n EN_D6 = '\\u0036'\n EN_D7 = '\\u0037'\n EN_D8 = '\\u0038'\n EN_D9 = '\\u0039'\n # Mosavet Charecters\n # --------------------- DAL -----------------------------------\n ARABIC_LETTER_DAL = u'\\u062F' # د\n ARABIC_LETTER_DDAL = u'\\u0688' # ڈ\n ARABIC_LETTER_DAL_WITH_RING = u'\\u0689' # ډ\n ARABIC_LETTER_DAL_WITH_DOT_BELOW = u'\\u068A' # ڊ\n ARABIC_LETTER_DAL_WITH_DOT_BELOW_AND_SMALL_TAH = u'\\u068B' # ڋ\n ARABIC_LETTER_DAHAL = u'\\u068C' # ڌ\n ARABIC_LETTER_DDAHAL = u'\\u068D' # ڍ\n ARABIC_LETTER_DUL = u'\\u068E' # ڎ\n ARABIC_LETTER_DAL_WITH_THREE_DOTS_ABOVE_DOWNWARDS = u'\\u068F' # ڏ\n ARABIC_LETTER_DAL_WITH_FOUR_DOTS_ABOVE = u'\\u0690' # ڐ\n # ----------------------- REH ------------------------------------\n ARABIC_LETTER_REH = u'\\u0631' # ر\n ARABIC_LETTER_RREH = u'\\u0691' # ڑ\n ARABIC_LETTER_REH_WITH_SMALL_V = 'u\\u0692' # ڒ\n ARABIC_LETTER_REH_WITH_RING = u'\\u0693' # ړ\n ARABIC_LETTER_REH_WITH_DOT_BELOW = u'\\u0694' # ڔ\n ARABIC_LETTER_REH_WITH_SMALL_V_BELOW = u'\\u0695' # ڕ\n ARABIC_LETTER_REH_WITH_DOT_BELOW_AND_DOT_ABOVE = u'\\u0696' # ږ\n ARABIC_LETTER_REH_WITH_TWO_DOTS_ABOVE = u'\\u0697' # ڗ\n # ---------------------- SEEN -----------------------------------\n ARABIC_LETTER_SEEN = u'\\u0633' # س\n ARABIC_LETTER_SEEN_WITH_THREE_DOTS_BELOW = u'\\u069B' # ڛ\n ARABIC_LETTER_SEEN_WITH_DOT_BELOW_AND_DOT_ABOVE = u'\\u069A' # ښ\n # --------------------- YEH -----------------------------\n DOTLESS_YEH2 = u'\\u06cc' # ی == persian\n DottedYEH = u'\\u064A' # ي\n DOTLESS_YEH1 = u'\\u0649' # ى\n ARABIC_LETTER_YEH_WITH_HAMZA_ABOVE = u'\\u0626' # ئ\n ARABIC_LETTER_KASHMIRI_YEH=u'\\u0620' # ؠ\n ARABIC_LETTER_FARSI_YEH_WITH_INVERTED_V = u'\\u063D' # ؽ\n ARABIC_LETTER_FARSI_YEH_WITH_TWO_DOTS_ABOVE = u'\\u063E' # ؾ\n ARABIC_LETTER_FARSI_YEH_WITH_THREE_DOTS_ABOVE = u'\\u063F' # ؿ\n ARABIC_LETTER_HIGH_HAMZA_YEH = u'\\u0678' # ٸ\n # ---------------------- KAF ----------------------------\n ARABIC_KAF = u'\\u0643' # ك\n ARABIC_KEHEH = u'\\u06A9' # ک persian\n ARABIC_LETTER_KEHEH_WITH_TWO_DOTS_ABOVE =u'\\u063B' # ػ\n ARABIC_LETTER_KEHEH_WITH_THREE_DOTS_BELOW = u'\\u063C' # ؼ\n ARABIC_LETTER_SWASH_KAF = u'\\u06AA' # ڪ\n ARABIC_LETTER_KAF_WITH_RING = u'\\u06AB' # ګ\n ARABIC_LETTER_KAF_WITH_DOT_ABOVE = 'u\\u06AC' # ڬ\n ARABIC_LETTER_NG = u'\\u06AD' # ڭ\n ARABIC_LETTER_KAF_WITH_THREE_DOTS_BELOW = 'u\\u06AE' # ڮ\n # --------------------- GAF -------------------------------\n ARABIC_LETTER_GAF = u'\\u06AF' # گ persian\n ARABIC_LETTER_GAF_WITH_RING = u'\\u06B0' # ڰ\n ARABIC_LETTER_NGOEH = u'\\u06B1' # ڱ\n ARABIC_LETTER_GAF_WITH_TWO_DOTS_BELOW = 'u\\u06B2' # ڲ\n ARABIC_LETTER_GUEH = 'u\\u06B3' # ڳ\n ARABIC_LETTER_GAF_WITH_THREE_DOTS_ABOVE = u'\\u06B4' # ڴ\n # --------------------- LAM ------------------------------\n ARABIC_LETTER_LAM = u'\\u0644' # ل\n ARABIC_LETTER_LAM_WITH_SMALL_V = u'\\u06B5' # ڵ\n ARABIC_LETTER_LAM_WITH_DOT_ABOVE = u'\\u06B6' # ڶ\n ARABIC_LETTER_LAM_WITH_THREE_DOTS_ABOVE = u'\\u06B7' # ڷ\n ARABIC_LETTER_LAM_WITH_THREE_DOTS_BELOW = u'\\u06B8' # ڸ\n # -------------------- BEH ---------------------\n ARABIC_LETTER_DOTLESS_BEH = u'\\u066E' # ٮ\n ARABIC_LETTER_BEH = u'\\u0628' # ب\n # -------------------- ALEF ---------------------------------\n ARABIC_LETTER_ALEF = u'\\u0627' # ا\n ARABIC_LETTER_ALEF_WITH_HAMZA_ABOVE =u'\\u0623' # أ\n ARABIC_LETTER_ALEF_WITH_MADDA_ABOVE = u'\\u0622' # آ\n ARABIC_LETTER_ALEF_WITH_HAMZA_ABOVE = u'\\u0623' # أ\n RABIC_LETTER_ALEF_WITH_HAMZA_BELOW = u'\\u0625' # إ\n ARABICـLETTERـALEFـWASLA =u'\\u0671' # ٱ\n ARABIC_LETTER_ALEF_WITH_WAVY_HAMZA_ABOVE = u'\\u0672' # ٲ\n ARABIC_LETTER_ALEF_WITH_WAVY_HAMZA_BELOW = u'\\u0673' # ٳ\n # --------------------- NOON --------------------------------------------\n ARABIC_LETTER_NOON = u'\\u0646' # ن\n ARABIC_LETTER_NOON_WITH_DOT_BELOW = u'\\u06B9' # ڹ\n ARABIC_LETTER_NOON_GHUNNA = u'\\u06BA' # ں\n ARABIC_LETTER_RNOON = u'\\u06BB' # ڻ\n ARABIC_LETTER_NOON_WITH_RING = u'\\u06BC' # ڼ\n ARABIC_LETTER_NOON_WITH_THREE_DOTS_ABOVE = u'\\u06BD' # ڽ\n # ---------------------- ح HAH --------------------\n ARABIC_LETTER_HAH = u'\\u062D' # ح\n ARABIC_LETTER_HAH_WITH_HAMZA_ABOVE = u'\\u0681' # ځ\n ARABIC_LETTER_HAH_WITH_TWO_DOTS_VERTICAL_ABOVE = u'\\u0682' # ڂ\n # -------------------- WAW ---------------------------------\n ARABIC_LETTER_WAW = u'\\u0648' # و\n ARABIC_LETTER_WAW_WITH_HAMZA_ABOVE = u'\\u0624' # ؤ\n ARABIC_LETTER_HIGH_HAMZA_WAW = u'\\u0676' # ٶ\n ARABIC_LETTER_WAW_WITH_RING = u'\\u06C4' # ۄ\n ARABIC_LETTER_WAW_WITH_TWO_DOTS_ABOVE = u'\\u06CA' # ۊ\n ARABIC_LETTER_WAW_WITH_DOT_ABOVE = u'\\u06CF' # ۏ\n ARABIC_LETTER_WAW_WITH_SAKEN_ABOVE = u'\\u06C6' # ۆ\n # =============================================\n ARABIC_LETTER_HAMZA =u'\\u0621' # ء\n # --------------------- HEH - TEH_MARBUTU ------------------------------\n TEH_MARBUTA = u'\\u0629' #TEH_MARBUTA: ة\n TEH_CHASBAN= u'\\u06C0'\n HEH = u'\\u0647' #HEH=> ه\n # -------------------- ERAB -----------------------------------------\n TATWEEL = u'\\u0640' # ـ\n FATHATAN = u'\\u064B' # ً\n DAMMATAN = u'\\u064C' # ٌ\n KASRATAN = u'\\u064D' # ٍ\n FATHA = u'\\u064E' # َ\n DAMMA = u'\\u064F' # ُ\n ARABIC_KASRA = u'\\u0650' # ِ\n arial_unic = u'\\u0650' # ِ\n SHADDA = u'\\u0651' # ّ\n SUKUN = u'\\u0652' # ْ\n ARABIC_SMALL_HIGH_ZAIN = u'\\u0617' # ؗ\n ARABIC_SMALL_HIGH_LIGATURE_ALEF_WITH_LAM_WITH_YEH = u'\\u0616' # ؖ\n ARABIC_SMALL_HIGH_TAH = u'\\u0615' # ؕ\n ARABIC_SIGN_TAKHALLUS = u'\\u0614' # ؔ\n ARABIC_SIGN_RADI_ALLAHOU_ANHU = u'\\u0613' # ؓ\n ARABIC_SIGN_RAHMATULLAH_ALAYHE = u'\\u0612' # ؒ\n ARABIC_SIGN_ALAYHE_SSALLAM = u'\\u0611' # ؑ\n ARABIC_SIGN_SALLALLAHOU_ALAYHE_WASSALLAM = u'\\u0610' # ؐ\n ARABIC_SIGN_MISRA =u'\\u060F' # ؏\n ARABIC_POETIC_VERSE_SIGN = u'\\u060E' # ؎\n ARABIC_DATE_SEPARATOR = u'\\u060D' # ؍\n AFGHANI_SIGN = u'\\u060B' # ؋\n ARABIC_RAY = u'\\u0608' # ؈\n ARABIC_NUMBER_MARK_ABOVE = 'u\\u0605' # ؅\n ARABIC_SIGN_SAMVAT = 'u\\0604' # ؄\n ARABIC_SIGN_SAFHA = u'\\0603' # ؃\n ARABIC_FOOTNOTE_MARKER = u'\\u0602' # ؂\n ARABIC_SIGN_SANAH = u'\\u0601' # ؁\n ARABIC_NUMBER_SIGN = u'\\u0600' # ؀\n ARABIC_SMALL_FATHA = u'\\u0618' # ؘ\n ARABIC_HAMZA_ABOVE = u'\\u0654' # ٔ\n ARABIC_HAMZA_BELOW = u'\\u0655' # ٖ ٕ\n ARABIC_SUBSCRIPT_ALEF = u'\\u0656' #\n ARABIC_INVERTED_DAMMA = u'\\u0657' # ٗ\n ARABIC_MARK_NOON_GHUNNA = u'\\u0658' # ٘\n ARABIC_VOWEL_SIGN_SMALL_V_ABOVE = u'\\u065A' # ٚ\n ARABIC_VOWEL_SIGN_INVERTED_SMALL_V_ABOVE = u'\\u065B' #\tٛ\n ARABIC_VOWEL_SIGN_DOT_BELOW = u'\\u065C' # ٜ\n ARABIC_REVERSED_DAMMA = u'\\u065D' # ٝ\n ARABIC_FATHA_WITH_TWO_DOTS = u'\\u065E' # ٞ\n ARABIC_WAVY_HAMZA_BELOW = u'\\u065F' # ٟ\n ARABIC_LETTER_SUPERSCRIPT_ALEF = u'\\u0670' # ٰ\n ARABIC_LETTER_HIGH_HAMZA_ALEF = u'\\u0674' # ٴ\n ARABIC_FULL_STOP = 'u\\u06D4' # ۔\n ARABIC_SMALL_LOW_MEEM = u'\\u06ED' # ۭ\n ARABIC_EMPTY_CENTRE_HIGH_STOP = u'\\u06EB' # ۫\n ARABIC_SMALL_HIGH_NOON = u'\\u06E8' # ۨ\n ARABIC_SMALL_HIGH_YEH = u'\\u06E7' # ۧ\n ARABIC_SMALL_WAW = u'\\u06E5' # ۥ\n ARABIC_SMALL_HIGH_MADDA = u'\\u06E4' # ۤ\n ARABIC_SMALL_LOW_SEEN = u'\\u06E3' # ۣ\n ARABIC_SMALL_HIGH_MEEM_ISOLATED_FORM = u'\\u06E2' # ۢ\n ARABIC_SMALL_HIGH_DOTLESS_HEAD_OF_KHAH = u'\\u06E1' # ۡ\n ARABIC_SMALL_HIGH_UPRIGHT_RECTANGULAR_ZERO = u'\\u06E0' # ۠\n ARABIC_SMALL_HIGH_THREE_DOTS = u'\\u06DB' # ۛ\n ARABIC_SMALL_HIGH_MEEM_INITIAL_FORM = u'\\u06D8' # ۘ\n ARABIC_SMALL_HIGH_LIGATURE_QAF_WITH_LAM_WITH_ALEF_MAKSURA = u'\\u06D7' # ۗ\n ARABIC_SMALL_HIGH_LIGATURE_SAD_WITH_LAM_WITH_ALEF_MAKSURA = u'\\u06D6' # ۖ\n ARABIC_SHADDA = u'\\u0651' # ّ\n\n ARABIC_SMALL_HIGH_JEEM = u'\\u06DA' # ۚ\n\n ARABIC_EMPTY_CENTRE_LOW_STOP = u'\\u06EA' # ۪\n\n ARABIC_SMALL_HIGH_LAM_ALEF = u'\\u06D9'\n # ۙ\n# ------------------- SPACE -----------------------------------------------\n EN_QUAD = u'\\u2000' #SPACE\n EM_QUAD = u'\\u2001' #SPACE\n EN_SPACE = u'\\u2002' #   #SPACE\n EM_SPACE = u'\\u2003' # #SPACE\n THREE_PER_EM_SPACE = u'\\u2004' #SPACE\n FOUR_PER_EM_SPACE = u'\\u2005' #SPACE\n SIX_PER_EM_SPACE = u'\\u2006' #SPACE\n FIGURE_SPACE = u'\\u2007' #SPACE\n THIN_SPACE = u'\\u2009' #SPACE\n NARROW_NO_BREAK_SPACE = u'\\u202F' #SPACE\n MEDIUM_MATHEMATICAL_SPACE = u'\\u205F' #SPACE\n\n PUNCTUATION_SPACE = u'\\u2008' # نیم فاصله\n HAIR_SPACE = u'\\u200A' # نیم فاصله\n ZERO_WIDTH_NON_JOINER = u'\\u200C' # نیم فاصله\n\n# ============== REMOVE ===========================\n ZERO_WIDTH_SPACE = u'\\u200B' # چسبان\n ZERO_WIDTH_JOINER = u'\\u200D' # حذف میکنم چسبان\n# ============================================\n LEFT_TO_RIGHT_MARK = u'\\u200E'\n RIGHT_TO_LEFT_MARK = u'\\u200F'\n LEFT_TO_RIGHT_OVERRIDE = u'\\u202D'\n RIGHT_TO_LEFT_OVERRIDE = u'\\u202E'\n POP_DIRECTIONAL_FORMATTING = u'\\u202C'\n # ------------------- HYPHEN - ----------------------------------------------\n HYPHEN =u'\\u2010'\n NON_BREAKING_HYPHEN = u'\\u2011'\n# ------------------- DASH – ----------------------------------------------\n FIGURE_DASH = u'\\u2012'\n EN_DASH = u'\\u2013'\n EM_DASH = u'\\u2014'\n\n# ------------------- advanced char – ----------------------------------------------\n FIGURE_DASH = u'\\u2012'\n EN_DASH = u'\\u2013'\n EM_DASH = u'\\u2014'\n# -======================================== replace char in all text ===========================================\n# self.text = self.text.replace('“', '\"') #جایگزین کردن تمام “ با \"\n# self.text = self.text.replace('”', '\"') #جایگزین کردن تمام ” با \"\n # text = self.text.replace('ىء', 'ء')#جایگزین کردن تمام ىء با ء\n for c in text:\n # print(c)\n # if c ==\"٬\" or c =='،' or c == ',': # change , and ٬ and ، in numbers and date\n # # print(\"----\",c)\n # c_index=self.text.index(c)\n # # print(\"c=>\",c_index)\n # # print(type(self.text[c_index + 1]))\n # if self.text[c_index-1].isdigit() :\n # try: # add for edit date with space: 17, 2018\n # # print(type(self.text[c_index+1]))\n # if self.text[c_index+1].isdigit():\n # # print(\"dig =>\",self.text[c_index+1])\n # continue\n # except:\n # print(\"except Normalizer Digit\")\n # continue\n\n\n#=================== evaluate end char of each word for TEH_MARBUTA and replace with HEH ======================\n if c==ENTER or c==TAB or c==RETURN:\n normalized_text.append(\"\")\n elif c == TEH_MARBUTA or c==TEH_CHASBAN: #if c == item[-1] and c == HEH:\n normalized_text.append(HEH)\n # ----------------------------- DAL -----------------------------------------------------\n elif c == ARABIC_LETTER_DDAL or c == ARABIC_LETTER_DAL_WITH_RING \\\n or c == ARABIC_LETTER_DAL_WITH_DOT_BELOW \\\n or c == ARABIC_LETTER_DAL_WITH_DOT_BELOW_AND_SMALL_TAH \\\n or c == ARABIC_LETTER_DAHAL or c == ARABIC_LETTER_DDAHAL \\\n or c == ARABIC_LETTER_DUL or c == ARABIC_LETTER_DAL_WITH_THREE_DOTS_ABOVE_DOWNWARDS \\\n or c == ARABIC_LETTER_DAL_WITH_THREE_DOTS_ABOVE_DOWNWARDS \\\n or c == ARABIC_LETTER_DAL_WITH_FOUR_DOTS_ABOVE:\n normalized_text.append(ARABIC_LETTER_DAL)\n # ----------------------------- REH -------------------------------------------------------\n elif c == ARABIC_LETTER_RREH or c == ARABIC_LETTER_REH_WITH_SMALL_V \\\n or c == ARABIC_LETTER_REH_WITH_RING or c == ARABIC_LETTER_REH_WITH_DOT_BELOW \\\n or c == ARABIC_LETTER_REH_WITH_SMALL_V_BELOW or c == ARABIC_LETTER_REH_WITH_DOT_BELOW_AND_DOT_ABOVE \\\n or c == ARABIC_LETTER_REH_WITH_TWO_DOTS_ABOVE:\n normalized_text.append(ARABIC_LETTER_REH)\n # ------------------------------ SEEN --------------------------------------------------\n elif c == ARABIC_LETTER_SEEN_WITH_THREE_DOTS_BELOW \\\n or c == ARABIC_LETTER_SEEN_WITH_DOT_BELOW_AND_DOT_ABOVE:\n normalized_text.append(ARABIC_LETTER_SEEN)\n # ---------------------------- YEH-------------------------------------------------------\n elif c == ARABIC_LETTER_YEH_WITH_HAMZA_ABOVE or c== DottedYEH or c == DOTLESS_YEH1 \\\n or c == ARABIC_LETTER_KASHMIRI_YEH \\\n or c == ARABIC_LETTER_FARSI_YEH_WITH_INVERTED_V \\\n or c == ARABIC_LETTER_FARSI_YEH_WITH_TWO_DOTS_ABOVE \\\n or c == ARABIC_LETTER_FARSI_YEH_WITH_THREE_DOTS_ABOVE \\\n or c == ARABIC_LETTER_HIGH_HAMZA_YEH:\n normalized_text.append(DOTLESS_YEH2)\n # ----------------------------_KAF--------------------------------------------------------\n elif c == ARABIC_KAF \\\n or c == ARABIC_LETTER_KEHEH_WITH_TWO_DOTS_ABOVE \\\n or c == ARABIC_LETTER_KEHEH_WITH_THREE_DOTS_BELOW \\\n or c == ARABIC_LETTER_SWASH_KAF \\\n or c == ARABIC_LETTER_KAF_WITH_RING \\\n or c == ARABIC_LETTER_KAF_WITH_DOT_ABOVE \\\n or c == ARABIC_LETTER_NG \\\n or c == ARABIC_LETTER_KAF_WITH_THREE_DOTS_BELOW:\n normalized_text.append(ARABIC_KEHEH)\n # ----------------------------- GAF ------------------------------------------------------\n elif c == ARABIC_LETTER_GAF_WITH_RING \\\n or c == ARABIC_LETTER_NGOEH \\\n or c == ARABIC_LETTER_GAF_WITH_TWO_DOTS_BELOW \\\n or c == ARABIC_LETTER_GUEH \\\n or c == ARABIC_LETTER_GAF_WITH_THREE_DOTS_ABOVE: # print(\"c=\", \"ARABIC_GAF Replace with ARABIC_KAF: \",ARABIC_KAF)\n normalized_text.append(ARABIC_LETTER_GAF)\n # ----------------------------- LAM ------------------------------------------------------\n elif c == ARABIC_LETTER_LAM_WITH_SMALL_V \\\n or c == ARABIC_LETTER_LAM_WITH_DOT_ABOVE \\\n or c == ARABIC_LETTER_LAM_WITH_THREE_DOTS_ABOVE \\\n or c == ARABIC_LETTER_LAM_WITH_THREE_DOTS_BELOW:\n normalized_text.append(ARABIC_LETTER_LAM)\n # ------------------------------- BEH ----------------------------------------------------\n elif c == ARABIC_LETTER_DOTLESS_BEH:\n normalized_text.append(ARABIC_LETTER_BEH)\n # ----------------------------- ALEF -----------------------------------------------------\n elif c == ARABIC_LETTER_ALEF_WITH_HAMZA_ABOVE or c == ARABIC_LETTER_ALEF_WITH_MADDA_ABOVE \\\n or c == ARABIC_LETTER_ALEF_WITH_HAMZA_ABOVE \\\n or c == RABIC_LETTER_ALEF_WITH_HAMZA_BELOW \\\n or c == ARABICـLETTERـALEFـWASLA \\\n or c == ARABIC_LETTER_ALEF_WITH_WAVY_HAMZA_ABOVE \\\n or c == ARABIC_LETTER_ALEF_WITH_WAVY_HAMZA_BELOW:\n normalized_text.append(ARABIC_LETTER_ALEF)\n # ----------------------------- NOON -----------------------------------------------------\n elif c == ARABIC_LETTER_NOON_WITH_DOT_BELOW \\\n or c == ARABIC_LETTER_NOON_GHUNNA \\\n or c == ARABIC_LETTER_RNOON or c == ARABIC_LETTER_NOON_WITH_RING \\\n or c == ARABIC_LETTER_NOON_WITH_THREE_DOTS_ABOVE:\n normalized_text.append(ARABIC_LETTER_NOON)\n # ---------------------------- HAH -------------------------------------------------------\n elif c == ARABIC_LETTER_HAH_WITH_HAMZA_ABOVE or c == ARABIC_LETTER_HAH_WITH_TWO_DOTS_VERTICAL_ABOVE:\n normalized_text.append(ARABIC_LETTER_HAH)\n\n # ===================================================================\n elif c == EM_QUAD or c == EN_SPACE or c == EM_SPACE \\\n or c== THREE_PER_EM_SPACE or c == FOUR_PER_EM_SPACE \\\n or c == SIX_PER_EM_SPACE or c== FIGURE_SPACE \\\n or c==THIN_SPACE or c== NARROW_NO_BREAK_SPACE or c == MEDIUM_MATHEMATICAL_SPACE :\n normalized_text.append(EN_QUAD)\n # --------------------------- Half-space -------------------------------------------------\n elif c == PUNCTUATION_SPACE:\n normalized_text.append(\" \")\n elif c == HAIR_SPACE or c == ZERO_WIDTH_NON_JOINER:\n normalized_text.append(\" \")\n # ---------------------------- DASH -----------------------------------------------------\n elif c == FIGURE_DASH or c == EM_DASH:\n normalized_text.append(EN_DASH)\n # ---------------------------- HYPHEN ----------------------------------------------------\n elif c == NON_BREAKING_HYPHEN:\n normalized_text.append(HYPHEN)\n # ---------------------------- WAW -------------------------------------------------------\n elif c == ARABIC_LETTER_WAW_WITH_HAMZA_ABOVE or c== ARABIC_LETTER_HIGH_HAMZA_WAW \\\n or c == ARABIC_LETTER_WAW_WITH_RING \\\n or c == ARABIC_LETTER_WAW_WITH_TWO_DOTS_ABOVE \\\n or c == ARABIC_LETTER_WAW_WITH_DOT_ABOVE \\\n or c==ARABIC_LETTER_WAW_WITH_SAKEN_ABOVE:\n normalized_text.append(ARABIC_LETTER_WAW)\n # ---------------------------- Evaluate Ereb AND Skip -----------------------------------\n elif c == TATWEEL or c == FATHATAN or c == DAMMATAN or c == KASRATAN \\\n or c == FATHA or c == DAMMA or c == ARABIC_KASRA or c == arial_unic \\\n or c == SHADDA or c == SUKUN or c == ARABIC_HAMZA_ABOVE or c == ARABIC_HAMZA_BELOW \\\n or c == ARABIC_SUBSCRIPT_ALEF or c == ARABIC_INVERTED_DAMMA or c == ARABIC_MARK_NOON_GHUNNA \\\n or c == ARABIC_VOWEL_SIGN_SMALL_V_ABOVE or c == ARABIC_VOWEL_SIGN_INVERTED_SMALL_V_ABOVE \\\n or c == ARABIC_VOWEL_SIGN_DOT_BELOW or c == ARABIC_REVERSED_DAMMA or c == ARABIC_FATHA_WITH_TWO_DOTS \\\n or c == ARABIC_WAVY_HAMZA_BELOW or c == ARABIC_LETTER_SUPERSCRIPT_ALEF or c == ARABIC_LETTER_HIGH_HAMZA_ALEF \\\n or c == ARABIC_FULL_STOP or c == ARABIC_SMALL_LOW_MEEM or c == ARABIC_EMPTY_CENTRE_HIGH_STOP \\\n or c == ARABIC_SMALL_HIGH_NOON or c == ARABIC_SMALL_HIGH_YEH or c == ARABIC_SMALL_WAW or c == ARABIC_SMALL_HIGH_MADDA \\\n or c == ARABIC_SMALL_LOW_SEEN or c == ARABIC_SMALL_HIGH_MEEM_ISOLATED_FORM or c == ARABIC_SMALL_HIGH_DOTLESS_HEAD_OF_KHAH \\\n or c == ARABIC_SMALL_HIGH_UPRIGHT_RECTANGULAR_ZERO or c == ARABIC_SMALL_HIGH_THREE_DOTS or c == ARABIC_SMALL_HIGH_MEEM_INITIAL_FORM \\\n or c == ARABIC_SMALL_HIGH_LIGATURE_QAF_WITH_LAM_WITH_ALEF_MAKSURA or c == ARABIC_SMALL_HIGH_LIGATURE_SAD_WITH_LAM_WITH_ALEF_MAKSURA \\\n or c == ARABIC_SHADDA or c == ARABIC_SMALL_HIGH_JEEM or c== ARABIC_EMPTY_CENTRE_LOW_STOP or c == ARABIC_SMALL_HIGH_LAM_ALEF\\\n or c == ARABIC_SMALL_FATHA or c == ARABIC_SMALL_HIGH_ZAIN or c== ARABIC_SMALL_HIGH_LIGATURE_ALEF_WITH_LAM_WITH_YEH \\\n or c == ARABIC_SMALL_HIGH_TAH or c == ARABIC_SIGN_TAKHALLUS or c == ARABIC_SIGN_RADI_ALLAHOU_ANHU or c == ARABIC_SIGN_RAHMATULLAH_ALAYHE \\\n or c == ARABIC_SIGN_ALAYHE_SSALLAM or c == ARABIC_SIGN_SALLALLAHOU_ALAYHE_WASSALLAM or c == ARABIC_SIGN_MISRA \\\n or c == ARABIC_POETIC_VERSE_SIGN or c== ARABIC_DATE_SEPARATOR or c == AFGHANI_SIGN or c == ARABIC_RAY or c == ARABIC_NUMBER_MARK_ABOVE \\\n or c == ARABIC_SIGN_SAMVAT or c == ARABIC_SIGN_SAFHA or c == ARABIC_FOOTNOTE_MARKER or c == ARABIC_SIGN_SANAH or c == ARABIC_NUMBER_SIGN \\\n or c == ZERO_WIDTH_SPACE or c == ZERO_WIDTH_JOINER or c == LEFT_TO_RIGHT_OVERRIDE or c == RIGHT_TO_LEFT_OVERRIDE \\\n or c == POP_DIRECTIONAL_FORMATTING \\\n or c == LEFT_TO_RIGHT_MARK or c == RIGHT_TO_LEFT_MARK :\n continue\n\n # -----------------------convert English_Arabic_numbers to Persian_numbers ----------\n elif c == Ar_D0 or c == EN_D0:\n #print(c)\n normalized_text.append(c.replace(c,FA_D0))\n elif c == Ar_D1 or c == EN_D1:\n normalized_text.append(c.replace(c,FA_D1))\n #print(c)\n elif c == Ar_D2 or c == EN_D2:\n normalized_text.append(c.replace(c,FA_D2))\n elif c == Ar_D3 or c == EN_D3:\n normalized_text.append(c.replace(c,FA_D3))\n elif c == Ar_D4 or c == EN_D4:\n normalized_text.append(c.replace(c,FA_D4))\n elif c == Ar_D5 or c == EN_D5:\n normalized_text.append(c.replace(c,FA_D5))\n elif c == Ar_D6 or c == EN_D6 :\n normalized_text.append(c.replace(c,FA_D6))\n elif c == Ar_D7 or c == EN_D7:\n normalized_text.append(c.replace(c,FA_D7))\n elif c == Ar_D8 or c ==EN_D8 :\n normalized_text.append(c.replace(c,FA_D8))\n elif c == Ar_D9 or c == EN_D9:\n normalized_text.append(c.replace(c,FA_D9))\n # =================================================================\n elif c == \"?\":\n c = \"؟\"\n normalized_text.append(c)\n else:\n normalized_text.append(c)\n\n\n self.result = ''.join(normalized_text)\n #print(self.result)\n return self.result\n\n","sub_path":"Lemm/Persian_Normalization.py","file_name":"Persian_Normalization.py","file_ext":"py","file_size_in_byte":28704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"101812329","text":"import pandas as pd\nimport numpy as np\nfrom itertools import chain\nimport datetime\n\ndf = pd.read_csv('C:/Users/EUGENE/PycharmProjects/dogpre_final/2021_08_11_12-41-14dogpre.csv') #파일 불러오기(경로 지정하셔야되요)\n\ndef chainer(s):\n return list(chain.from_iterable(s.str.split(',')))\n\n# calculate lengths of splits\nlens = df['review_date'].str.split(',').map(len)\n\n# 'item_name', 'review_title', 'review_content','review_date', 'review_star', 'dog_breed', 'dog_age'\n\n# print(chainer(df['review_title']))\nprint(\"review_title 개수\")\nprint(len(chainer(df['review_title'])))\n\n# print(chainer(df['review_content']))\nprint(\"review_content 개수\")\nprint(len(chainer(df['review_content'])))\n\n\nres = pd.DataFrame({'item_name': np.repeat(df['item_name'],lens),\n 'review_title': chainer(df['review_title']),\n 'review_content': chainer(df['review_content']),\n 'review_date': chainer(df['review_date']),\n 'review_star': chainer(df['review_star']),\n 'dog_breed': chainer(df['dog_breed']),\n 'dog_age': chainer(df['dog_age'])})\n\n# res[\"review_total\"] = res[\"review_title\"].map(str) + \" \" + res[\"review_content\"]\n# res = res.drop(columns = ['review_title', 'review_content'])\n\nprint(res)\n\nnow = datetime.datetime.now()\nnowDate = now.strftime(\"%Y_%m_%d_%H-%M-%S\")\n\nres.to_csv( str(nowDate) + 'dogPre' + '.csv', encoding='utf-8-sig')\nprint(\"Finish!\")","sub_path":"convertFile.py","file_name":"convertFile.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457155743","text":"from __future__ import absolute_import, division, print_function\n\n\"\"\"Tests for dials.split_experiments when experiment ids are set\"\"\"\n\nimport procrunner\nfrom dials.array_family import flex\nfrom dxtbx.model import Beam, Experiment, ExperimentList\nfrom dxtbx.model.experiment_list import ExperimentListFactory\n\n\ndef generate_exp(wavelength=1):\n \"\"\"Generate an experiment containing a beam with a given wavelength.\"\"\"\n beam = Beam(direction=(0.0, 0.0, 1.0), wavelength=wavelength)\n exp = Experiment(beam=beam)\n return exp\n\n\ndef test_split_by_wavelength(tmpdir):\n \"\"\"Test the split_by_wavelength option of dials.split_experiments\"\"\"\n experiments = ExperimentList()\n exp = generate_exp(wavelength=1.0)\n exp.identifier = \"0\"\n experiments.append(exp)\n exp = generate_exp(wavelength=0.5)\n exp.identifier = \"1\"\n experiments.append(exp)\n\n reflections = flex.reflection_table()\n reflections[\"id\"] = flex.int([0, 1])\n reflections[\"intensity\"] = flex.double([100.0, 200.0])\n reflections.experiment_identifiers()[0] = \"0\"\n reflections.experiment_identifiers()[1] = \"1\"\n\n experiments.as_json(tmpdir.join(\"tmp.expt\").strpath)\n reflections.as_file(tmpdir.join(\"tmp.refl\").strpath)\n\n result = procrunner.run(\n [\"dials.split_experiments\", \"tmp.expt\", \"tmp.refl\", \"by_wavelength=True\"],\n working_directory=tmpdir,\n )\n assert not result.returncode and not result.stderr\n\n for i, (wl, ids, intensity) in enumerate(\n zip([0.5, 1.0], [\"1\", \"0\"], [200.0, 100.0])\n ):\n assert tmpdir.join(\"split_%d.expt\" % i).check()\n assert tmpdir.join(\"split_%d.refl\" % i).check()\n exp_single = ExperimentListFactory.from_json_file(\n tmpdir.join(\"split_%d.expt\" % i).strpath, check_format=False\n )\n ref_single = flex.reflection_table.from_file(\n tmpdir.join(\"split_%d.refl\" % i).strpath\n )\n assert exp_single[0].beam.get_wavelength() == wl\n assert exp_single[0].identifier == ids\n id_ = ref_single[\"id\"][0]\n assert ref_single.experiment_identifiers()[id_] == ids\n assert list(ref_single[\"intensity\"]) == [intensity]\n\n # Now test for successful error handling if no identifiers set.\n experiments[0].identifier = \"\"\n experiments[1].identifier = \"\"\n experiments.as_json(tmpdir.join(\"tmp.expt\").strpath)\n result = procrunner.run(\n [\"dials.split_experiments\", \"tmp.expt\", \"tmp.refl\", \"by_wavelength=True\"],\n working_directory=tmpdir,\n )\n assert result.returncode == 1\n assert result.stderr.startswith(b\"Sorry\")\n\n experiments[0].identifier = \"0\"\n experiments[1].identifier = \"1\"\n del reflections.experiment_identifiers()[0]\n del reflections.experiment_identifiers()[1]\n experiments.as_json(tmpdir.join(\"tmp.expt\").strpath)\n reflections.as_file(tmpdir.join(\"tmp.refl\").strpath)\n result = procrunner.run(\n [\"dials.split_experiments\", \"tmp.expt\", \"tmp.refl\", \"by_wavelength=True\"],\n working_directory=tmpdir,\n )\n assert result.returncode == 1\n assert result.stderr.startswith(b\"Sorry\")\n","sub_path":"modules/dials/test/command_line/test_split_experiments.py","file_name":"test_split_experiments.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"262775612","text":"\"\"\"\nOptions for building Stripping21r0p1. \n\"\"\"\n\nstripping='stripping21r0p1'\n\n#use CommonParticlesArchive\nfrom CommonParticlesArchive import CommonParticlesArchiveConf\nCommonParticlesArchiveConf().redirect(stripping)\n\n\nfrom Gaudi.Configuration import *\nMessageSvc().Format = \"% F%30W%S%7W%R%T %0W%M\"\n\n# Tighten Trk Chi2 to <3\nfrom CommonParticles.Utils import DefaultTrackingCuts\nDefaultTrackingCuts().Cuts = { \"Chi2Cut\" : [ 0, 3 ],\n \"CloneDistCut\" : [5000, 9e+99 ] }\n\n#\n# Disable the cache in Tr/TrackExtrapolators \n#\nfrom Configurables import TrackStateProvider\nTrackStateProvider().CacheStatesOnDemand = False\n\n#\n# Fix for TrackEff lines\n#\nfrom Configurables import DecodeRawEvent\nDecodeRawEvent().setProp(\"OverrideInputs\",4.2)\n\n#\n# Build the streams and stripping object\n#\nfrom StrippingConf.Configuration import StrippingConf, StrippingStream\nfrom StrippingSettings.Utils import strippingConfiguration\nfrom StrippingArchive.Utils import buildStreams\nfrom StrippingArchive import strippingArchive\n\n#get the configuration dictionary from the database\nconfig = strippingConfiguration(stripping)\n#get the line builders from the archive\narchive = strippingArchive(stripping)\n\nstreams = buildStreams(stripping = config, archive = archive)\n\t\nleptonicMicroDSTname = 'Leptonic'\ncharmMicroDSTname = 'Charm'\npidMicroDSTname = 'PID'\nbhadronMicroDSTname = 'Bhadron'\nmdstStreams = [ leptonicMicroDSTname,charmMicroDSTname,pidMicroDSTname,bhadronMicroDSTname ]\ndstStreams = [ \"BhadronCompleteEvent\", \"CharmCompleteEvent\", \"CharmToBeSwum\", \"Dimuon\",\n \"EW\", \"Semileptonic\", \"Calibration\", \"MiniBias\", \"Radiative\" ]\n\nstripTESPrefix = 'Strip'\n\nfrom Configurables import ProcStatusCheck\n\t\nfrom PhysConf.Filters import LoKi_Filters\nflts = LoKi_Filters(VOID_Code = \"( TrSource(TrSOURCE('/Event/Rec/Track/Best', TrLONG))\"\\\n \" >> ( sum( TrPT,TrP < 1 * TeV ) > 1 * TeV ) )\" ,\n VOID_Preambulo = [\"from LoKiTracks.decorators import *\" ,\n \"from LoKiCore.functions import * \",\n \"from GaudiKernel.SystemOfUnits import *\"])\nfilterBadEvents = GaudiSequencer(\"BadEventFilter\",\n ModeOR = True,\n Members = [ flts.sequencer(\"GECFilter\"),\n ProcStatusCheck() ] )\nstreamFilter = { 'default' : filterBadEvents,\n 'MiniBias' : ProcStatusCheck() }\n\nsc = StrippingConf( Streams = streams,\n MaxCandidates = 2000,\n AcceptBadEvents = False,\n BadEventSelection = ProcStatusCheck(),\n TESPrefix = stripTESPrefix,\n ActiveMDSTStream = True,\n Verbose = True,\n DSTStreams = dstStreams,\n MicroDSTStreams = mdstStreams )\n\nfrom Configurables import ApplicationMgr, AuditorSvc, SequencerTimerTool\n\t\n# Initial IOV time\n# http://www.onlineconversion.com/unix_time.htm\n# values in ns (so multiply values from above link by 1e9)\n#from Configurables import EventClockSvc\n#EventClockSvc().EventTimeDecoder = \"OdinTimeDecoder\"\n\nappMgr = ApplicationMgr()\nappMgr.OutputLevel = 6\nappMgr.ExtSvc += [ 'ToolSvc', 'AuditorSvc' ]\n\nappMgr.HistogramPersistency = \"ROOT\"\nntSvc = NTupleSvc()\nappMgr.ExtSvc += [ ntSvc ]\n\nfrom Configurables import ( LHCbApp, PhysConf, AnalysisConf,\n DstConf, LumiAlgsConf, DDDBConf )\n\n#LHCbApp().DDDBtag = \"dddb-20150724\"\n#LHCbApp().CondDBtag = \"cond-20150805\"\n\n# Can be enabled for next full stack release\nPhysConf().OutputLevel = appMgr.OutputLevel\n#AnalysisConf().OutputLevel = appMgr.OutputLevel\n\ndatatype = \"2012\"\nPhysConf().DataType = datatype\nAnalysisConf().DataType = datatype\nLumiAlgsConf().DataType = datatype\nDDDBConf().DataType = datatype\n\ninputType = \"DST\"\nLumiAlgsConf().InputType = inputType\nPhysConf().InputType = inputType\n\nunPack = [\"Reconstruction\"]\nPhysConf().EnableUnpack = unPack\nDstConf().EnableUnpack = unPack\n\nlumiSeq = GaudiSequencer(\"LumiSeq\")\nLumiAlgsConf().LumiSequencer = lumiSeq\n\nappMgr.TopAlg += [ PhysConf().initSequence(),\n AnalysisConf().initSequence(),\n sc.sequence(), lumiSeq ]\n\n#from Configurables import DaVinci\n#DaVinci().ProductionType = \"Stripping\"\n#DaVinci().DataType = datatype\n#DaVinci().DDDBtag = LHCbApp().DDDBtag\n#DaVinci().CondDBtag = LHCbApp().CondDBtag\n#DaVinci().appendToMainSequence( [ sc.sequence() ] )\n","sub_path":"DaVinci/Phys/StrippingCache/options/DV-Stripping21r0p1-Stripping.py","file_name":"DV-Stripping21r0p1-Stripping.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140433041","text":"from .BaseNodeListsBuilder import BaseNodeListsBuilder\nfrom ...Dtos.Enums.DataSetType import DataSetType\nfrom ...Dtos.NodeLists import NodeLists\nfrom ...Dtos.NodeIds import DrugId, SideEffectId, ProteinId\nfrom ...Dtos.TypeShortcuts import EdgeList, RelationIDToEdgeList, RelationIDToGraph, RelationIDToSparseMtx\nfrom ...Utils import Config\nfrom collections import defaultdict\nfrom typing import Iterator\nimport networkx as nx\nimport numpy as np\nimport scipy.sparse as sp\n\nclass DecagonPublicDataNodeListsBuilder(\n BaseNodeListsBuilder,\n functionalityType = DataSetType.DecagonPublicData\n):\n def __init__(self, config: Config) -> None:\n self.drugDrugRelationGraph: nx.MultiGraph = nx.read_edgelist(\n config.getSetting('DecagonDrugDrugRelationsFilename'),\n delimiter=',',\n create_using=nx.MultiGraph(),\n nodetype=DrugId,\n data=(('relationType', str),)\n )\n\n self.drugProteinRelationGraph: nx.Graph = nx.read_edgelist(\n config.getSetting('DecagonDrugProteinRelationsFilename'),\n delimiter=','\n )\n\n self.ppiGraph: nx.Graph = nx.read_edgelist(\n config.getSetting('DecagonProteinProteinRelationsFilename'),\n nodetype=ProteinId,\n delimiter=','\n )\n\n def build(self) -> NodeLists:\n proteinNodeList = self._getOrderedProteinNodeList()\n drugNodeList = self._getOrderedDrugNodeList()\n\n return NodeLists(proteinNodeList, drugNodeList)\n\n def _getOrderedDrugNodeList(self) -> EdgeList:\n allDrugs = set(\n self.drugDrugRelationGraph.nodes\n ).union(set(self._getDrugProteinGraphDrugs()))\n\n return sorted(list(allDrugs))\n\n def _getDrugProteinGraphDrugs(self) -> Iterator[tuple]:\n # In preprocessed dataset, all drug identifiers are prefixed with 'CID'\n # while protein identifiers are not\n drugNodes = filter(\n lambda x: x[:3] == 'CID',\n self.drugProteinRelationGraph.nodes\n )\n\n # Convert all drug id strs to DrugIds\n return map(DrugId, drugNodes)\n\n def _getOrderedProteinNodeList(self) -> EdgeList:\n allProteins = set(\n self.ppiGraph.nodes\n ).union(set(self._getDrugProteinGraphProteins()))\n\n return sorted(list(allProteins))\n\n def _getDrugProteinGraphProteins(self) -> Iterator[tuple]:\n # In preprocessed dataset, all drug identifiers are prefixed with 'CID'\n # while protein identifiers are not\n proteinNodes = filter(\n lambda x: x[:3] != 'CID',\n self.drugProteinRelationGraph.nodes\n )\n\n\n return map(ProteinId, proteinNodes)\n\n","sub_path":"main/DataSetParsers/NodeLists/DecagonPublicDataNodeListsBuilder.py","file_name":"DecagonPublicDataNodeListsBuilder.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377552692","text":"import os\nimport time\n\nimport cv2\nimport keras.backend as K\nimport numpy as np\nfrom console_progressbar import ProgressBar\n\n# from utils import load_model\nfrom resnet_152 import resnet152_model\n# from resnet_50 import resnet50_model\n\nimport common_util\n\nCLASSID_JSON = r\"D:\\DATA\\@car\\car_classification\\classid_to_folder.json\"\n# BASE_FOLDER_PATH = r\"D:\\DATA\\@car\\car_classification\\valid\"\n# BASE_FOLDER_PATH = r\"D:\\DATA\\@car\\car_classification_google\\@TEST\"\n# BASE_FOLDER_PATH = r\"D:\\DATA\\@car\\car_classification\\test_hyundai\\20190528\"\nBASE_FOLDER_PATH = r\"D:\\DATA\\@car\\car_photo\\carphoto_20190618\"\nIMG_WIDTH, IMG_HEIGHT = 224, 224\n\ndef load_model():\n model_weights_path = 'models/model.63-0.93.hdf5'\n # img_width, img_height = 224, 224\n num_channels = 3\n num_classes = 60\n # num_classes = 196\n model = resnet152_model(IMG_WIDTH, IMG_HEIGHT, num_channels, num_classes)\n # model = resnet50_model(IMG_WIDTH, IMG_HEIGHT, num_channels, num_classes)\n model.load_weights(model_weights_path, by_name=True)\n return model\n\n\n\n\n\nif __name__ == '__main__':\n \n classid_dict = common_util.load_json(CLASSID_JSON)\n\n model = load_model()\n num_samples = 81\n\n pb = ProgressBar(total=100, prefix='Predicting test data', suffix='', decimals=3, length=50, fill='=')\n start = time.time()\n out = open('result.txt', 'a')\n\n # for i in range(num_samples):\n\n i = 0\n for (path, dir, files) in os.walk(BASE_FOLDER_PATH):\n for filename in files:\n file_path = os.path.join(path, filename)\n if \"output\" in file_path:\n continue\n\n # filename = os.path.join('data/test', '%05d.jpg' % (i + 1))\n print(file_path)\n bgr_img = cv2.imread(file_path)\n rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)\n\n rgb_img = cv2.resize(rgb_img, dsize=(IMG_WIDTH, IMG_HEIGHT), interpolation=cv2.INTER_AREA)\n rgb_img = np.expand_dims(rgb_img, 0)\n\n preds = model.predict(rgb_img)\n prob = np.max(preds)\n class_id = np.argmax(preds)\n out.write(f'{class_id} {file_path} \\n')\n pb.print_progress_bar((i + 1) * 100 / num_samples)\n\n print(file_path, classid_dict[str(class_id)])\n\n i += 1\n\n end = time.time()\n seconds = end - start\n print('avg fps: {}'.format(str(num_samples / seconds)))\n\n out.close()\n K.clear_session()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"417916168","text":"import requests\nimport zipfile\nimport os.path\nimport os\nfrom user_info import PASSWORD\nfrom user_info import USER_NAME\n\n# doesnt list names of repos\n\n\ndef list_repos(user):\n r = requests.get('https://api.github.com/users/' + user,\n auth=(USER_NAME, PASSWORD))\n return r.json()\n\n\ndef get_repo_zip(user, repo):\n r = requests.get(\n 'https://github.com/' + user + '/' + repo + '/archive/master.zip')\n with open(repo + \".zip\", \"wb\") as code:\n code.write(r.content)\n\n\ndef unzip():\n zfile = zipfile.ZipFile(\"Zoo.zip\")\n for name in zfile.namelist():\n (dirname, filename) = os.path.split(name)\n zfile.extract(name)\n\n\ndef count_file_rows(file_name):\n file = open(\n r'/home/milen/Documents/Python/virtual/code/Zoo-master/' + file_name, 'r')\n content = file.read()\n file.close()\n content = content.split('\\n')\n return len(content)\n\n\ndef count_directory_rows():\n rows = 0\n for subdir, dirs, files in os.walk('/home/milen/Documents/Python/virtual/code/Zoo-master'):\n for item in files:\n if get_extension(item) != 'db':\n rows += count_file_rows(item)\n return rows\n\n\ndef count_directory_extensions():\n cnt = {}\n for subdir, dirs, files in os.walk('/home/milen/Documents/Python/virtual/code/Zoo-master'):\n for item in files:\n try:\n cnt[get_extension(item)] += 1\n except KeyError:\n cnt[get_extension(item)] = 1\n return cnt\n\n\ndef get_extension(file_name):\n result = file_name.split('.')\n return result[1]\n\n\ndef main():\n\n print(count_directory_rows())\n print(count_directory_extensions())\nif __name__ == '__main__':\n main()\n","sub_path":"code/scrypt.py","file_name":"scrypt.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90576897","text":"import warnings\nimport collections\nfrom pathlib import Path\nfrom typing import (\n Any,\n Dict,\n List,\n Tuple,\n Sequence,\n Optional,\n Callable,\n)\nimport torch\nfrom torch.utils.data import Dataset\nimport numpy as np\nfrom ..utils import get_stem\nfrom ..torchio import DATA, AFFINE, TYPE, PATH, STEM, TypePath\nfrom .io import read_image, write_image\n\n\nclass Image:\n r\"\"\"Class to store information about an image.\n\n Args:\n path: Path to a file that can be read by\n :mod:`SimpleITK` or :mod:`nibabel` or to a directory containing\n DICOM files.\n type_: Type of image, such as :attr:`torchio.INTENSITY` or\n :attr:`torchio.LABEL`. This will be used by the transforms to\n decide whether to apply an operation, or which interpolation to use\n when resampling.\n **kwargs: Items that will be added to image dictionary within the\n subject sample.\n \"\"\"\n\n def __init__(self, path: TypePath, type_: str, **kwargs):\n self.path = self._parse_path(path)\n self.type = type_\n self.__dict__.update(kwargs)\n\n @staticmethod\n def _parse_path(path: TypePath) -> Path:\n try:\n path = Path(path).expanduser()\n except TypeError:\n message = f'Conversion to path not possible for variable: {path}'\n raise TypeError(message)\n if not (path.is_file() or path.is_dir()): # might be a dir with DICOM\n raise FileNotFoundError(f'File not found: {path}')\n return path\n\n def load(self, check_nans: bool = True) -> Tuple[torch.Tensor, np.ndarray]:\n r\"\"\"Load the image from disk.\n\n The file is expected to be monomodal and 3D. A channels dimension is\n added to the tensor.\n\n Args:\n check_nans: If ``True``, issues a warning if NaNs are found\n in the image\n\n Returns:\n Tuple containing a 4D data tensor of size\n :math:`(1, D_{in}, H_{in}, W_{in})`\n and a 2D 4x4 affine matrix\n \"\"\"\n tensor, affine = read_image(self.path)\n tensor = tensor.unsqueeze(0) # add channels dimension\n if check_nans and torch.isnan(tensor).any():\n warnings.warn(f'NaNs found in file \"{self.path}\"')\n return tensor, affine\n\n\nclass Subject(dict):\n \"\"\"Class to store information about the images corresponding to a subject.\n\n Args:\n *args: If provided, a dictionary of items.\n **kwargs: Items that will be added to the subject sample.\n\n Example:\n\n >>> import torchio\n >>> from torchio import Image, Subject\n >>> # One way:\n >>> subject = Subject(\n ... one_image=Image('path_to_image.nii.gz, torchio.INTENSITY),\n ... a_segmentation=Image('path_to_seg.nii.gz, torchio.LABEL),\n ... age=45,\n ... name='John Doe',\n ... hospital='Hospital Juan Negrín',\n ... )\n >>> # If you want to create the mapping before, or have spaces in the keys:\n >>> subject_dict = {\n ... 'one image': Image('path_to_image.nii.gz, torchio.INTENSITY),\n ... 'a segmentation': Image('path_to_seg.nii.gz, torchio.LABEL),\n ... 'age': 45,\n ... 'name': 'John Doe',\n ... 'hospital': 'Hospital Juan Negrín',\n ... }\n >>> Subject(subject_dict)\n\n \"\"\"\n\n def __init__(self, *args, **kwargs: Dict[str, Any]):\n if args:\n if len(args) == 1 and isinstance(args[0], dict):\n kwargs.update(args[0])\n else:\n message = (\n 'Only one dictionary as positional argument is allowed')\n raise ValueError(message)\n super().__init__(**kwargs)\n self.images = [\n (k, v) for (k, v) in self.items()\n if isinstance(v, Image)\n ]\n self._parse_images(self.images)\n\n def __repr__(self):\n string = (\n f'{self.__class__.__name__}'\n f'(Keys: {tuple(self.keys())}; images: {len(self.images)})'\n )\n return string\n\n @staticmethod\n def _parse_images(images: List[Tuple[str, Image]]) -> None:\n # Check that it's not empty\n if not images:\n raise ValueError('A subject without images cannot be created')\n\n\nclass ImagesDataset(Dataset):\n \"\"\"Base TorchIO dataset.\n\n :class:`~torchio.data.images.ImagesDataset`\n is a reader of 3D medical images that directly\n inherits from :class:`torch.utils.data.Dataset`.\n It can be used with a :class:`torch.utils.data.DataLoader`\n for efficient loading and augmentation.\n It receives a list of subjects, where each subject is an instance of\n :class:`~torchio.data.images.Subject` containing instances of\n :class:`~torchio.data.images.Image`.\n The file format must be compatible with `NiBabel`_ or `SimpleITK`_ readers.\n It can also be a directory containing\n `DICOM`_ files.\n\n Indexing an :class:`~torchio.data.images.ImagesDataset` returns a\n Python dictionary with the data corresponding to the queried subject.\n The keys in the dictionary are the names of the images passed to that\n subject, for example ``('t1', 't2', 'segmentation')``.\n\n The value corresponding to each image name is another dictionary\n ``image_dict`` with information about the image.\n The data is stored in ``image_dict[torchio.IMAGE]``,\n and the corresponding `affine matrix`_\n is in ``image_dict[torchio.AFFINE]``:\n\n >>> sample = images_dataset[0]\n >>> sample.keys()\n dict_keys(['image', 'label'])\n >>> image_dict = sample['image']\n >>> image_dict[torchio.DATA].shape\n torch.Size([1, 176, 256, 256])\n >>> image_dict[torchio.AFFINE]\n array([[ 0.03, 1.13, -0.08, -88.54],\n [ 0.06, 0.08, 0.95, -129.66],\n [ 1.18, -0.06, -0.11, -67.15],\n [ 0. , 0. , 0. , 1. ]])\n\n Args:\n subjects: Sequence of instances of\n :class:`~torchio.data.images.Subject`.\n transform: An instance of\n :class:`torchio.transforms.Transform` that is applied to each\n image after loading it.\n check_nans: If ``True``, issues a warning if NaNs are found\n in the image.\n load_image_data: If ``False``, image data and affine will not be loaded.\n These fields will be set to ``None`` in the sample. This can be\n used to quickly iterate over the samples to retrieve e.g. the\n images paths. If ``True``, transform must be ``None``.\n\n .. _NiBabel: https://nipy.org/nibabel/#nibabel\n .. _SimpleITK: https://itk.org/Wiki/ITK/FAQ#What_3D_file_formats_can_ITK_import_and_export.3F\n .. _DICOM: https://www.dicomstandard.org/\n .. _affine matrix: https://nipy.org/nibabel/coordinate_systems.html\n\n \"\"\"\n\n def __init__(\n self,\n subjects: Sequence[Subject],\n transform: Optional[Callable] = None,\n check_nans: bool = True,\n load_image_data: bool = True,\n ):\n self._parse_subjects_list(subjects)\n self.subjects = subjects\n self._transform: Optional[Callable]\n self.set_transform(transform)\n self.check_nans = check_nans\n self._load_image_data: bool\n self.set_load_image_data(load_image_data)\n\n def __len__(self):\n return len(self.subjects)\n\n def __getitem__(self, index: int) -> dict:\n if not isinstance(index, int):\n raise ValueError(f'Index \"{index}\" must be int, not {type(index)}')\n subject = self.subjects[index]\n sample = self.get_sample_dict_from_subject(subject)\n\n # Apply transform (this is usually the bottleneck)\n if self._transform is not None:\n sample = self._transform(sample)\n return sample\n\n def get_sample_dict_from_subject(self, subject: Subject):\n \"\"\"Create a dictionary of dictionaries with subject information.\n\n Args:\n subject: Instance of :py:class:`~torchio.data.images.Subject`.\n \"\"\"\n subject_sample = {}\n for (key, value) in subject.items():\n if isinstance(value, Image):\n subject_sample[key] = self.get_image_dict_from_image(value)\n else:\n subject_sample[key] = value\n return subject_sample\n\n def get_image_dict_from_image(self, image: Image):\n \"\"\"Create a dictionary with image information.\n\n Args:\n image: Instance of :py:class:`~torchio.data.images.Image`.\n\n Return:\n Dictionary with keys\n :py:attr:`torchio.DATA`,\n :py:attr:`torchio.AFFINE`,\n :py:attr:`torchio.TYPE`,\n :py:attr:`torchio.PATH` and\n :py:attr:`torchio.STEM`.\n \"\"\"\n if self._load_image_data:\n tensor, affine = image.load(check_nans=self.check_nans)\n else:\n tensor = affine = None\n image_dict = {\n DATA: tensor,\n AFFINE: affine,\n TYPE: image.type,\n PATH: str(image.path),\n STEM: get_stem(image.path),\n }\n return image_dict\n\n def set_transform(self, transform: Optional[Callable]) -> None:\n \"\"\"Set the :attr:`transform` attribute.\n\n Args:\n transform: An instance of :py:class:`torchio.transforms.Transform`\n or :py:class:`torchvision.transforms.Compose`.\n \"\"\"\n if transform is not None and not callable(transform):\n raise ValueError(\n f'The transform must be a callable object, not {transform}')\n self._transform = transform\n\n @staticmethod\n def _parse_subjects_list(subjects_list: Sequence[Subject]) -> None:\n # Check that it's list or tuple\n if not isinstance(subjects_list, collections.abc.Sequence):\n raise TypeError(\n f'Subject list must be a sequence, not {type(subjects_list)}')\n\n # Check that it's not empty\n if not subjects_list:\n raise ValueError('Subjects list is empty')\n\n # Check each element\n for subject in subjects_list:\n if not isinstance(subject, Subject):\n message = (\n 'Subjects list must contain instances of torchio.Subject,'\n f' not \"{type(subject)}\"'\n )\n raise TypeError(message)\n\n @classmethod\n def save_sample(\n cls,\n sample: Dict[str, dict],\n output_paths_dict: Dict[str, TypePath],\n ) -> None:\n for key, output_path in output_paths_dict.items():\n tensor = sample[key][DATA][0] # remove channels dim\n affine = sample[key][AFFINE]\n write_image(tensor, affine, output_path)\n\n def set_load_image_data(self, load_image_data: bool):\n if not load_image_data and self._transform is not None:\n message = (\n 'Load data cannot be set to False if transform is not None.'\n f'Current transform is {self._transform}')\n raise ValueError(message)\n self._load_image_data = load_image_data\n","sub_path":"torchio/data/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":11255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612107867","text":"import logger as logger\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom argparse import ArgumentParser\nfrom pl_module.ViT_SEG import vit_seg\nfrom pl_module.SWIN import SwinUnet\nfrom pl_module.Edge_Connect import edge_connect\nfrom data.dataset import MyDataModule\nfrom pytorch_lightning import Trainer, seed_everything\nfrom pytorch_lightning.callbacks import *\nimport os\nimport torch\n\n\ndef parse_batch_1(batch):\n x = torch.cat([batch[\"mask_image\"], batch[\"mask\"]], dim=1)\n return (x, batch[\"image\"]), (batch[\"mask_image\"], batch[\"mask\"])\n\n\ndef parse_batch_2(batch):\n x = torch.cat([batch[\"mask_image\"], batch[\"gradient\"], batch[\"mask\"]], dim=1)\n return (x, batch[\"image\"]), (batch[\"mask_image\"], batch[\"mask\"])\n\n\ndef parse_batch_3(batch):\n x = torch.cat([batch[\"mask_image\"], batch[\"gray\"], batch[\"mask\"]], dim=1)\n return (x, batch[\"image\"]), (batch[\"mask_image\"], batch[\"mask\"])\n\n\ndef parse_batch_4(batch):\n x = torch.cat([batch[\"mask_image\"], batch[\"gradient\"], batch[\"gray\"], batch[\"mask\"]], dim=1)\n return (x, batch[\"image\"]), (batch[\"mask_image\"], batch[\"mask\"])\n\n\ndef main(args):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '2,3'\n seed_everything(100, workers=True)\n data_module = MyDataModule(opt=args)\n parser_batch_func = eval(\"parse_batch_{}\".format(args.stage))\n\n prefix = \"/data/wm_data/ablation\"\n if args.save_result:\n path = \"test/{}/{}/{}\".format(args.model, args.dataset_name, args.stage)\n if not os.path.exists(path):\n os.makedirs(path)\n\n ckpt_path = os.path.join(prefix, 'ckpt/{}/{}_{}'.format(args.model, args.dataset_name, args.stage))\n\n if train:\n data_module.setup(\"fit\")\n\n early_stop = EarlyStopping(monitor=\"val_loss\", mode=\"min\", patience=10)\n checkpoint = ModelCheckpoint(monitor=\"val_loss\",\n dirpath=ckpt_path,\n filename='{epoch:03d}-{val_loss:.8f}',\n save_top_k=10,\n save_last=True,\n save_weights_only=False,\n every_n_train_steps=args.every_n_train_steps # how many train_step save weights ckpt\n )\n callbacks = [checkpoint]\n logger_path = 'logs/{}/{}/{}'.format(args.model, args.dataset_name, args.stage)\n logger = TensorBoardLogger(os.path.join(prefix, logger_path))\n\n trainer = None\n model = None\n if not resume:\n if args.stage == 1:\n model = eval(args.model)(3+1, 3, args.lr, args)\n elif args.stage == 2 or args.stage == 3:\n model = eval(args.model)(3+1+1, 3, args.lr, args)\n else:\n model = eval(args.model)(3+1+1+1, 3, args.lr, args)\n\n trainer = Trainer(callbacks=callbacks, logger=logger, max_epochs=args.max_epoch, gpus=args.gpus,\n accelerator=\"ddp\", # if model is edge_connect set \"ddp2\" will distribute error\n val_check_interval=int(args.val_check_interval),\n limit_val_batches=args.limit_val_batches,\n log_every_n_steps=args.log_every_n_steps)\n\n else:\n resume_checkpoint_path = os.path.join(ckpt_path, \"last.ckpt\")\n model = eval(args.model).load_from_checkpoint(resume_checkpoint_path)\n\n trainer = Trainer(callbacks=callbacks, logger=logger, max_epochs=args.max_epoch, gpus=args.gpus,\n accelerator=\"ddp\",\n val_check_interval=int(args.val_check_interval),\n resume_from_checkpoint=resume_checkpoint_path,\n limit_val_batches=args.limit_val_batches,\n log_every_n_steps=args.log_every_n_steps)\n model.set_parse_batch(parser_batch_func)\n trainer.fit(model, datamodule=data_module)\n\n if test:\n data_module.setup(\"test\")\n ckpt_name = \"last.ckpt\"\n resume_checkpoint_path = os.path.join(ckpt_path, ckpt_name)\n model = eval(args.model).load_from_checkpoint(resume_checkpoint_path)\n model.set_parse_batch(parser_batch_func)\n model.hparams[\"args\"] = args\n trainer = Trainer(gpus=args.gpus, accelerator=\"ddp\")\n\n result = trainer.test(model, datamodule=data_module)\n\n\nif __name__ == '__main__':\n data_prefix = \"/data/wm_data\"\n\n flag = 1 # 1 for train, 2 for resume train, 3 for test\n\n if flag == 1:\n train = True\n resume = False\n test = False\n elif flag == 2:\n train = True\n resume = True\n test = False\n else:\n train = False\n resume = False\n test = True\n\n parser = ArgumentParser()\n parser.add_argument('--gpus', default=[0, 1], help=\"gpu use list or str\")\n parser.add_argument(\"--lr\", default=0.0001, type=float, help=\"learning rate\")\n parser.add_argument(\"--batch_size\", default=35, type=int)\n parser.add_argument(\"--size\", default=256, type=int, help=\"input image size\")\n parser.add_argument(\"--num_workers\", default=2, type=int, help=\"parallel load example num\")\n parser.add_argument(\"--shuffle\", default=True, type=bool, help=\"shuffle the dataloader\")\n parser.add_argument(\"--max_epoch\", default=500, type=int)\n parser.add_argument(\"--save_result\", default=True, type=bool, help=\"whether save test result\")\n parser.add_argument(\"--every_n_train_steps\", default=500, type=int, help=\"how many train_setp to save a model\")\n parser.add_argument(\"--val_check_interval\", default=100, type=int, help=\"how many train_step val_step\")\n parser.add_argument(\"--limit_val_batches\", default=1, type=int, help=\"how many val batch to validate\")\n parser.add_argument(\"--log_every_n_steps\", default=100, type=int, help=\"how many train_step to log once\")\n\n parser.add_argument(\"--model\", default=\"SwinUnet\", choices=[\"vit_seg\", \"SwinUnet\", \"edge_connect\"])\n parser.add_argument(\"--dataset_name\", default=\"celebA\", choices=[\"celebA\", \"places2\", \"paris\"], help=\"which dataset use save ckpt and logs\")\n parser.add_argument(\"--stage\", default=4, choices=[1, 2, 3, 4], type=int) # 消融实验:验证的是第几组消融实验\n parser.add_argument(\"--if_split\", default=False, type=bool, help=\"whether seperate test zero-1 - zero-6 mask\")\n\n # below the args not need to set\n parser.add_argument(\"--train_image_path\", default=None, type=str, help=\"train image path\")\n parser.add_argument(\"--train_mask_path\", default=None, type=str, help=\"train mask path\")\n parser.add_argument(\"--val_image_path\", default=None, type=str, help=\"validation image path\")\n parser.add_argument(\"--val_mask_path\", default=None, type=str, help=\"validation mask path\")\n parser.add_argument(\"--test_image_path\", default=None, type=str, help=\"test image path\")\n parser.add_argument(\"--test_mask_path\", default=None, type=str, help=\"test mask path\")\n args = parser.parse_args()\n\n # change your data and mask below\n train_image_path = None\n val_image_path = None\n test_image_path = None\n if args.dataset_name == \"celebA\":\n train_image_path = \"celebA/celeba_train\"\n val_image_path = \"celebA/celeba_val\"\n test_image_path = \"celebA/celeba_test\"\n elif args.dataset_name == \"places2\":\n train_image_path = \"places2/train\"\n val_image_path = \"places2/test\"\n test_image_path = val_image_path\n elif args.dataset_name == \"paris\":\n train_image_path = \"paris/train\"\n val_image_path = \"paris/eval/paris_eval_gt\"\n test_image_path = \"paris/test\"\n\n if args.if_split:\n test_mask_path = \"celebA/split_mask_yeah\"\n else:\n test_mask_path = \"celebA/500_test_mask\"\n\n train_mask_path = \"celebA/1000_train_mask\"\n val_mask_path = \"celebA/500_val_mask\"\n\n args.train_image_path = os.path.join(data_prefix, train_image_path)\n args.val_image_path = os.path.join(data_prefix, val_image_path)\n args.test_image_path = os.path.join(data_prefix, test_image_path)\n args.train_mask_path = os.path.join(data_prefix, train_mask_path)\n args.val_mask_path = os.path.join(data_prefix, val_mask_path)\n args.test_mask_path = os.path.join(data_prefix, test_mask_path)\n\n main(args)","sub_path":"stage3/train4.py","file_name":"train4.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"104433611","text":"import json\nimport os\nfrom Books.models import *\n\n\ndef book_from_json(json_obj):\n if not (\"deathdate\" in json_obj):\n json_obj['deathdate'] = None\n b = Books(id=int(json_obj[\"id\"]),\n title=json_obj[\"title\"],\n page_count=json_obj[\"pagecount\"],\n annotation=json_obj[\"annotation\"],\n release_date=json_obj[\"date\"],\n genre=json_obj[\"genre\"],\n author=json_obj[\"author\"],\n birthdate=json_obj[\"birthdate\"],\n deathdate=json_obj[\"deathdate\"],\n )\n b.save()\n\n\ndef load_model_from_json(path, func):\n if os.path.exists(path):\n json_objects = json.load(open(path))\n else:\n print(\"no json file!\")\n return\n\n for o in json_objects:\n func(o)\n\n\ndef load_all_models_from_json():\n Books.objects.all().delete()\n load_model_from_json(\"books.json\", book_from_json)\n","sub_path":"Books/json_load.py","file_name":"json_load.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380310373","text":"from django import forms\nfrom CTM_Requester.models import Folder, Job, Schedualing, OS_Job\nfrom django.core import validators\n\n# def check_for_z(value):\n# print(letter)\n# if value[0].lower() != 'z':\n# raise forms.ValidationError(\"Name needs to start with Z\")\n\n# class FormName(forms.Form):\n# name = forms.CharField()\n# email = forms.EmailField()\n# text = forms.CharField(widget=forms.Textarea)\n# # botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, \n# # validators=[validators.MaxLengthValidator(0)])\n \n# def clean(self):\n# jobsPrefixes = {\n# 'OS': 'OS', \n# 'DB': 'SQL', \n# 'FTP-MF-Open': 'FTP-MF-OP-', \n# 'FTP-Open-MF': 'FTP-OP-MF-',\n# 'FW-FTP-Open-MF': 'FW-FTP-OP-MF-',\n# 'Oracle Application': 'OEBS-'\n# }\n# all_clean = super().clean()\n# name = all_clean['name']\n# email = all_clean['email']\n# jobType = 'FTP-MF-Open'\n# predictedPrefix = jobsPrefixes[jobType]\n# print(predictedPrefix)\n \n# # Checks the prefix of the job name\n# if not name.startswith(predictedPrefix):\n# raise forms.ValidationError(\"Name needs to start with \" + predictedPrefix ) \n \n# class NewFolderForm(forms.ModelForm):\n \n \n# class Meta():\n# model = Folder\n# # fields = '__all__'\n# exclude = ('name',)\n \n# def clean(self):\n# all_clean = super().clean()\n# applName = all_clean['appl']\n# subApplName = all_clean['subAppl']\n \n# folderName = str(applName) + \"-\" + str(subApplName)\n \n# print(folderName)\n\nclass FolderCreateForm(forms.ModelForm):\n class Meta:\n model = Folder\n fields = ('author', 'appl', 'subAppl', 'name', 'description')\n widgets = {\n 'description':forms.Textarea(attrs={'class': 'editable medium-editor-textarea tempcontent'}),\n 'appl':forms.TextInput(attrs={'readonly':'readonly'}),\n 'author':forms.HiddenInput(attrs={'readonly':'readonly'}),\n 'name':forms.HiddenInput(attrs={'readonly':'readonly'})\n }\n\n\nclass JobCreateForm(forms.ModelForm):\n class Meta:\n model = Job\n fields = ('folder', 'jobType', 'name', 'description')\n widgets = {\n 'folder':forms.HiddenInput(attrs={'readonly':'readonly'})\n }\n\n\nclass DummyForm(forms.Form):\n pass\n \nclass JobCreateFormGeneral(forms.ModelForm):\n \n class Meta():\n model = Job\n fields = ('folder', 'jobType', 'name', 'description')\n widgets = {\n 'folder':forms.HiddenInput(attrs={'readonly':'readonly'})\n }\n \n # def clean(self):\n # pass\n\n\n\nclass JobCreateFormSchedualing(forms.ModelForm):\n \n class Meta():\n model = Schedualing\n fields = ('job', 'calenderName', 'fromTime', 'toTime', 'isCyclic', 'cyclicInterval', 'cyclivIntervalMinutesHours', 'retention')\n widgets = {\n 'job':forms.HiddenInput(attrs={'readonly':'readonly'})\n }\n \n \n \nclass JobCreateFormOS_Job(forms.ModelForm):\n \n class Meta():\n model = OS_Job\n fields = ('job', 'executionType', 'scriptName', 'scriptPath', 'scriptContent', 'hostName')\n widgets = {\n 'job':forms.HiddenInput(attrs={'readonly':'readonly'})\n }\n\n# class JobCreateFormOS_Job(forms.ModelForm):\n \n# class Meta():\n# model = OS_Job\n# fields = ('job', 'executionType', 'scriptName', 'scriptPath', 'scriptContent', 'hostName')\n# widgets = {\n# 'job':forms.HiddenInput(attrs={'readonly':'readonly'})\n# }\n \n\nclass JobCreateFormPreqs(forms.Form):\n koko2 = forms.CharField(max_length=50)\n\nclass JobCreateFormPosts(forms.Form):\n koko3 = forms.CharField(max_length=50)","sub_path":"CTM_Requester/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"603094295","text":"# 提示用户输入一个整数n,然后输出 [1,n) 之间所有的素数。\n# 提示:质数(prime number)又称素数,有无限个。\n# 质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数的数称为质数。\nimport math\n\nn = int(input(\"Please input an integer as range:\"))\nfor i in range(2, n):\n j = int(math.sqrt(i))\n flag = True\n for k in range(2, j + 1):\n if i % k == 0:\n flag = False\n break\n if flag:\n print(i, end=\"\\t\")\n","sub_path":"循环结构/24-1.py","file_name":"24-1.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"224232360","text":"import tensorflow as tf\n\n\nclass Network:\n\n def __init__(self, input_size, architecture, init_lr, name):\n self.layers = []\n self.name = name\n self.learning_rate = init_lr\n\n with tf.compat.v1.variable_scope(self.name):\n self.inputs = tf.compat.v1.placeholder(tf.float32, (None, input_size), name=self.name+\"_inputs\")\n self.layers.append(self.inputs)\n\n self.loss_weight = tf.compat.v1.placeholder(tf.float32, (None, 1), name=self.name+\"_loss_weights\")\n\n for i in range(len(architecture)):\n layer_size = architecture[i]\n self.add_fc_layer(inputs=self.layers[-1], size=layer_size, name=self.name+\"_layer_%i\" % i)\n\n self.add_fc_layer(inputs=self.layers[-1], size=1, activation=None, name=self.name+\"_output\")\n self.output = self.layers[-1]\n\n self.q_target = tf.compat.v1.placeholder(tf.float32, (None, 1), name=self.name+\"_Q_target\")\n diff = self.q_target - self.output\n\n self.absolute_error = tf.abs(diff)\n self.loss = tf.reduce_mean(self.loss_weight * tf.square(diff))\n self.optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n def add_fc_layer(self, inputs, size, name, activation=tf.nn.relu):\n self.layers.append(\n tf.layers.dense(inputs,\n units=size,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n activation=activation,\n name=name)\n )\n","sub_path":"Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535029043","text":"from datetime import datetime\nimport calendar\n\n\ndef months_to_today():\n month_list = list()\n today = datetime.now()\n month = today.month\n year = today.year\n\n for m in range(1, month + 1):\n last_day = calendar.monthrange(year, m)[1]\n month_list.append((year, m, last_day))\n\n # for i in month_list:\n # print(i)\n\n return month_list\n\n\ndef age(date):\n # Get the current date\n return int((datetime.today() - date).days/365)\n\n\ndef isValidDate(input_value):\n try:\t\t\n datetime.strptime(input_value, \"%Y-%m-%d\")\n except ValueError:\n return False\n else:\n return True\t\n\n\ndef date2str(input_value):\n # print(input_value)\n try:\t\t\n return datetime.strftime(input_value, \"%Y-%m-%d\")\n except:\n return None\t\n\n\ndef isValidDateSeg(input_value):\n\n try:\t\t\n input_string = ' '.join(input_value.split())\n input_string_list = input_string.split(\" \")\n if len(input_string_list) != 2:\n return False\n else:\n datetime.strptime(input_string_list[0], \"%Y-%m-%d\")\n input_string_list[1] = input_string_list[1].upper()\n if input_string_list[1] != \"AM\" and input_string_list[1] != \"PM\":\n return False\n except ValueError:\n return False\n else:\n return True\n\n","sub_path":"dateUtils.py","file_name":"dateUtils.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585598756","text":"from ai4u.core import RemoteEnv, EnvironmentManager\r\nimport numpy as np\r\nimport threading\r\nimport time\r\n\r\n\r\nclass SkipframesWrapper(RemoteEnv):\r\n def step(self, action, value=None):\r\n state = None\r\n for i in range(4):\r\n state = super().step(action, value)\r\n return state\r\n\r\nenvs = EnvironmentManager(4, wrapper=SkipframesWrapper)\r\n\r\nenvs.openAll()\r\n\r\ndef agent(env):\r\n for i in range(10000000):\r\n sum_energy = 0\r\n state = env.step(\"get_status\")\r\n prev_energy = state['energy']\r\n #print(state)\r\n done = state['done']\r\n while not done:\r\n frame = None\r\n action = np.random.normal(0.0, 1.0, 12)\r\n state = env.stepfv(\"act\", action)\r\n done = state[\"done\"]\r\n energy = state['energy']\r\n frame = state['frame']\r\n touched = state['touched']\r\n ID = state['id']\r\n sum_energy += (energy - prev_energy)\r\n prev_energy = energy\r\n time.sleep(0.05)\r\n print(sum_energy)\r\n\r\n env.close() \r\n\r\nif __name__ == \"__main__\":\r\n t1 = threading.Thread(target=agent, args=(envs[0], ))\r\n t2 = threading.Thread(target=agent, args=(envs[1], ))\r\n t3 = threading.Thread(target=agent, args=(envs[2], ))\r\n t4 = threading.Thread(target=agent, args=(envs[3], ))\r\n t1.start()\r\n t2.start()\r\n t3.start()\r\n t4.start()\r\n t1.join()\r\n t2.join()\r\n t3.join()\r\n t4.join()\r\n\r\n","sub_path":"PetsWorld/PetsWorldClient/a3cv2/agrnd_threads.py","file_name":"agrnd_threads.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"621296156","text":"import datetime\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import login as login_user\nfrom django.contrib.auth import logout as logout_user\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.views.decorators.cache import never_cache\nfrom django.conf import settings\nfrom utils.view_functions import render_to\nfrom utils.user_functions import get_user\nfrom utils import log as logging\nfrom utils import json_functions as json\nfrom utils.ratelimit import ratelimit\nfrom apps.social.views import load_social_page\nfrom apps.statistics.models import MStatistics\nfrom apps.social.models import MSocialProfile\nfrom apps.reader.forms import LoginForm,SignupForm\nfrom apps.reader.models import UserSubscription\nfrom apps.reader.models import UserSubscriptionFolders\nfrom apps.recommendations.models import RecommendedFeed\n\n\n@never_cache\n@render_to('reader/dashboard.xhtml')\ndef index(request, **kwargs):\n if request.method == 'GET' and request.subdomain and request.subdomain not in ['dev','www','debug']:\n username = request.subdomain\n if '.' in username:\n username = username.split('.')[0]\n user = User.objects.filter(username=username)\n if not user:\n user = User.objects.filter(username__iexact=username)\n if user:\n user = user[0]\n if not user:\n return HttpResponseRedirect('http://%s%s' % (\n Site.objects.get_current().domain,\n reverse('index')\n ))\n return load_social_page(request, user_id=user.pk, username = request.subdomain, **kwargs)\n\n if request.user.is_anonymous():\n return welcome(request, **kwargs)\n else:\n return dashboard(request, **kwargs)\n\n\ndef dashboard(request, **kwargs):\n user = request.user\n feed_count = UserSubscription.objects.filter(user=user).count()\n recommended_feeds = RecommendedFeed.objects.filter(is_public=True,\n approved_date__lte=datetime.datetime.now()\n ).select_related('feed')[:2]\n unmoderated_feeds = []\n if user.is_staff:\n unmoderated_feeds = RecommendedFeed.objects.filter(is_public=False,\n declined_date__isnull=True\n ).select_related('feed')[:2]\n statistics = MStatistics.all()\n social_profile = MSocialProfile.get_user(user.pk)\n\n start_import_from_google_reader = request.session.get('import_from_google_reader', False)\n if start_import_from_google_reader:\n del request.session['import_from_google_reader']\n\n if not user.is_active:\n url = \"https://%s%s\" % (Site.objects.get_current().domain,\n reverse('stripe-form'))\n return HttpResponseRedirect(url)\n\n logging.user(request, \"~FBLoading dashboard\")\n\n return {\n 'user_profile': user.profile,\n 'feed_count': feed_count,\n 'account_images': range(1,4),\n 'recommended_feeds': recommended_feeds,\n 'unmoderated_feeds': unmoderated_feeds,\n 'statistics': statistics,\n 'social_profile': social_profile,\n 'start_import_from_google_reader': start_import_from_google_reader,\n 'debug': settings.DEBUG\n }, \"reader/dashboard.xhtml\"\n\ndef welcome(request, **kwargs):\n user = get_user(request)\n statistics = MStatistics.all()\n social_profile = MSocialProfile.get_user(user.pk)\n\n if request.method == \"POST\":\n pass\n else:\n login_form = LoginForm(prefix='login')\n signup_form = SignupForm(prefix='signup')\n\n return {\n 'user_profile': hasattr(user, 'profile') and user.profile,\n 'login_form': login_form,\n 'signup_form': signup_form,\n 'statistics': statistics,\n 'social_profile': social_profile,\n 'post_request': request.method == 'POST'\n }, \"reader/welcome.xhtml\"\n\n\n@never_cache\ndef signup(request):\n if request.method == 'POST':\n form = SignupForm(prefix='signup', data = request.POST)\n if form.is_valid():\n new_user = form.save()\n login_user(request, new_user)\n logging.user(new_user, \"~FG~SB~BBNEW SIGNUP: ~FW%s\" % new_user.email)\n if not new_user.is_active:\n url = \"https://%s%s\" % (Site.objects.get_current().domain,\n reverse('stripe-form'))\n return HttpResponseRedirect(url)\n\n return index(request)\n\n@ratelimit(minutes=1, requests=24)\n@never_cache\n@json.json_view\ndef load_feeds(request):\n user = get_user(request)\n feeds = {}\n include_favicons = request.REQUEST.get('include_favicons', False)\n flat = request.REQUEST.get('flat', False)\n update_counts = request.REQUEST.get('update_counts', False)\n version = int(request.REQUEST.get('v', 1))\n\n if include_favicons == 'false': include_favicons = False\n if update_counts == 'false': update_counts = False\n if flat == 'false': flat = False\n\n if flat: return load_feeds_flat(request)\n\n try:\n folders = UserSubscriptionFolders.objects.get(user=user)\n except UserSubscriptionFolders.DoesNotExist:\n data = dict(feeds=[], folders=[])\n return data\n except UserSubscriptionFolders.MultipleObjectsReturned:\n UserSubscriptionFolders.objects.filter(user=user)[1:].delete()\n folders = UserSubscriptionFolders.objects.get(user=user)\n\n user_subs = UserSubscription.objects.select_related('feed').filter(user=user)\n day_ago = datetime.datetime.now() - datetime.timedelta(days=1)\n scheduled_feeds = []\n for sub in user_subs:\n pk = sub.feed_id\n if update_counts and sub.needs_unread_recalc:\n sub.calculate_feed_scores(silent=True)\n feeds[pk] = sub.canonical(include_favicon=include_favicons)\n\n if not sub.active:continue\n if not sub.feed.active and not sub.feed.has_feed_exception:\n scheduled_feeds.append(sub.feed.pk)\n elif sub.feed.active_subscribers <= 0:\n scheduled_feeds.append(sub.feed.pk)\n elif sub.feed.next_scheduled_update < day_ago:\n scheduled_feeds.append(sub.feed.pk)\n\n if len(scheduled_feeds) > 0 and request.user.is_authenticated():\n logging.user(request, \"~SN~FMTasking the scheduling immediate fetch of ~SB%s~SN feeds...\" %\n len(scheduled_feeds))\n\n\n\n\n\n@json.json_view\ndef load_feed_favicons(request):\n pass\n\ndef load_feeds_flat(request):\n pass\n\n\n\n\n","sub_path":"apps/reader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368014675","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\n\n\nclass TrainParams:\n \"\"\"\n :ivar optim_type: optimizer type: 0: SGD, 1: ADAM\n\n :ivar load_weights:\n 0: train from scratch\n 1: load and test\n 2: load if it exists and continue training\n\n :ivar save_criterion: when to save a new checkpoint\n 0: max validation accuracy\n 1: min validation loss\n 2: max training accuracy\n 3: min training loss\n\n :ivar lr: learning rate\n :ivar eps: term added to the denominator to improve numerical stability in ADAM optimizer\n\n :ivar valid_ratio: fraction of training data to use for validation\n :ivar valid_gap: no. of training epochs between validations\n\n :ivar vis: visualize the input and reconstructed images during validation and testing;\n only works for offline runs since colab doesn't support cv2.imshow\n \"\"\"\n\n def __init__(self):\n self.batch_size = 128\n self.optim_type = 1\n self.lr = 1e-3\n self.momentum = 0.9\n self.n_epochs = 1000\n self.eps = 1e-8\n self.weight_decay = 0\n self.save_criterion = 0\n self.load_weights = 0\n self.valid_gap = 1\n self.valid_ratio = 0.2\n self.weights_path = './checkpoints/model.pt'\n self.vis = 0\n\n\nclass Classifier(nn.Module):\n def __init__(self):\n super(Classifier, self).__init__()\n \"\"\"\n add your code here\n \"\"\"\n self.conv1 = nn.Conv2d(1, 5, kernel_size=4)\n self.conv2 = nn.Conv2d(5,25, kernel_size=4)\n self.fc1 = nn.Linear(400,128)\n self.fc2 = nn.Linear(128,41)\n self.fc3 = nn.Linear(41,13)\n\n def init_weights(self):\n \"\"\"\n add your code here\n \"\"\"\n pass \n\n def forward(self, x):\n \"\"\"\n add your code here\n \"\"\"\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n x = x.view(x.size(0), -1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return F.log_softmax(x)\n","sub_path":"Lab 10/A10_submission.py","file_name":"A10_submission.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"500711818","text":"import subprocess\nimport time\nimport logging\nimport os\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\ndef run_cmd(cmd: str):\n logger.info(cmd)\n subprocess.check_call(cmd, shell=True)\n\n\ndef wait_for_file(file: str):\n if not os.path.exists(file):\n logger.info(f'Could not find file {file}. Waiting...')\n minute_cnt = 0\n while not os.path.exists(file):\n print(f'The {minute_cnt}th minute...')\n time.sleep(60)\n minute_cnt += 1\n time.sleep(60)\n logger.info(f'Find file {file} after waiting for {minute_cnt} minutes')\n\n\n# model\nbert_base_model = \"../BERT/bert-base-uncased.tar.gz\"\nbert_base_vocab = \"../BERT/bert-base-uncased-vocab.txt\"\nbert_large_model = \"../BERT/bert-large-uncased.tar.gz\"\nbert_large_vocab = \"../BERT/bert-large-uncased-vocab.txt\"\n\ntrain_file = '/home/jiaofangkai/multi-rc/splitv2/train.json'\ndev_file = '/home/jiaofangkai/multi-rc/splitv2/dev.json'\n\ntask_name = 'topk-rc'\nreader_name = 'multi-rc-topk-search-ex'\nbert_name = 'hie-topk'\n\nk = 2000\nlabel_threshold = 0.8\nweight_threshold = 0.5\nrecurrent_times = 10\nnum_train_epochs = [8] * 10\nsentence_id_file = None\nnum_evidence = 3\n\nroot_dir = f'experiments/multi-rc/topk-evidence/self-training/v2.0_acc_top{k}'\nos.makedirs(root_dir, exist_ok=True)\n\nf_handler = logging.FileHandler(os.path.join(root_dir, f'output.log'))\nf_handler.setLevel(logging.INFO)\nf_handler.setFormatter(logging.Formatter(fmt=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt='%m/%d/%Y %H:%M:%S'))\nlogger.addHandler(f_handler)\n\nlogger.info('Self-training parameters:')\nlogger.info(f'k: {k}')\nlogger.info(f'label_threshold: {label_threshold}')\nlogger.info(f'weight_threshold: {weight_threshold}')\nlogger.info(f'recurrent_times: {recurrent_times}')\nlogger.info(f'num_evidence: {num_evidence}')\n\nlearning_rate = 2e-5\nfor i in range(recurrent_times):\n logger.info(f'Start running for the {i}th times.')\n output_dir = f'{root_dir}/recurrent{i}'\n predict_dir = f'{output_dir}/sent3_predict/ex'\n evidence_search_file = f'{output_dir}/sent2_predict/ex/evidence_id_ex.json'\n\n if i == 0:\n evidence_lambda = 0.0\n else:\n evidence_lambda = 0.8\n\n cmd = f'python main_0.6.2_topk.py --bert_model bert-base-uncased ' \\\n f'--vocab_file {bert_base_vocab} --model_file {bert_base_model} --output_dir {output_dir} --predict_dir {predict_dir} ' \\\n f'--train_file {train_file} --predict_file {dev_file} ' \\\n f'--max_seq_length 512 --train_batch_size 32 --predict_batch_size 8 ' \\\n f'--learning_rate {learning_rate} --num_train_epochs {num_train_epochs[i]} ' \\\n f'--fp16 --gradient_accumulation_steps 4 --per_eval_step 6000 ' \\\n f'--bert_name {bert_name} --task_name {task_name} --reader_name {reader_name} ' \\\n f'--evidence_lambda {evidence_lambda} ' \\\n f'--num_evidence {num_evidence} ' \\\n f'--evidence_search_file {evidence_search_file}'\n\n cmd += ' --do_predict '\n\n run_cmd(cmd)\n","sub_path":"scripts/multi_rc/topk_evidence_self_training/self_training2.0_sent_3_predict_ex.py","file_name":"self_training2.0_sent_3_predict_ex.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245762714","text":"# Fabryka prętów metalowych może sprzedać pręty o długości wyrażonej liczbą naturalną od 1 do 10 m. Przykładowe ceny za pręty odpowiednich długości podane są w liście 'p'. Napisz program, który wczyta od użytkownika liczbę naturalną n oznaczającą długość pręta i poda optymalny sposób pocięcia go, tak aby zmaksymalizować zysk fabryki.\n\np = [0,1,5,8,9,10,17,17,20,24,30];\n\nn = int(input(\"Enter the length of the rod:\"))\nr = [0] * (n+1) # Holds the max revenue of each length\nr[1] = p[1]\nnodes = [0] * (n+1)\nnodes[1] = 1\n\ndef cut_rod(n):\n if n == 0:\n q = 0;\n elif n == 1:\n q = p[1];\n else:\n for k in range (1, n+1):\n q = max(r[n], p[k] + cut_rod(n-k))\n if (q>r[n]):\n r[n] = q\n nodes[n] = k\n return q\n\nprint(\"Most profit:\",cut_rod(n))\nprint(\"How to cut: \", end='');\nwhile n>0:\n print(nodes[n],end=' ')\n n -= nodes[n]\n","sub_path":"Zajęcia_7/rod_cut.py","file_name":"rod_cut.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347212515","text":"# Mercenary feature\n# adapted into this file by Flunky\n\n### Imports\nfrom CvPythonExtensions import *\n# import CvEventInterface\nimport CvUtil\n\n### Defines\ngc = CyGlobalContext()\nlocalText = CyTranslator()\n\n### Globals\nPAEInstanceHiringModifier = {} # Soeldner werden teurer innerhalb einer Runde\nPAEMercComission = {} # Soelnder koennen nur 1x pro Runde beauftragt werden\n\n# Reminder: How to use ScriptData: CvUtil.getScriptData(pUnit, [\"b\"], -1), CvUtil.addScriptData(pUnit, \"b\", eBonus) (add uses string, get list of strings)\n# getScriptData returns string => cast might be necessary\n# Update (Ramk): No, CvUtil-Functions unpack an dict. You could directly use int, etc.\n\n# Used keys for UnitScriptData:\n# \"x\"/\"y\": coordinates of plots where bonus was picked up (merchants)\n# \"b\": index of bonus stored in merchant/cultivation unit (only one at a time)\n# \"originCiv\": original owner of the bonus stored in merchant (owner of the city where it was bought)\n\ndef onModNetMessage(argsList):\n # Hire or Commission Mercenary Menu\n iData0, iData1, iData2, iData3, iData4 = argsList\n if iData0 == 707:\n # iData1, iData2, ...\n # 707, iCityID, -1, -1, iPlayer\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n iCity = iData1\n pCity = pPlayer.getCity(iCity)\n iRandStr = str(1 + CvUtil.myRandom(5, \"POPUP_MERCENARIES_MAIN-String\"))\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_MAIN\" + iRandStr, (pCity.getName(),)))\n popupInfo.setData1(iCity) # CityID\n popupInfo.setData2(iPlayer)\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesMain\") # EntryPoints/CvScreenInterface und CvGameUtils -> 708, 709 usw\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_HIRE\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_mercenary_hire.dds\")\n\n # do this only once per turn\n PAEMercComission.setdefault(iPlayer, 0)\n if PAEMercComission[iPlayer] == 0:\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_mercenary_assign.dds\")\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n # Hire Mercenaries\n elif iData0 == 708:\n # iData1, iData2, ... iData5 = iPlayer\n # 708, iCityID, iButtonID (Typ), iButtonID (Unit), iButtonID (Cancel)\n\n iCity = iData1\n iTypeButton = iData2\n iUnitButton = iData3\n iPlayer = iData4\n doHireMercenariesPopup(iCity, iTypeButton, iUnitButton, iPlayer)\n\n # Commission Mercenaries (CIV)\n elif iData0 == 709:\n # iData1, iData2, ...\n # 709, (1) -1 (2) iButtonId (CIV) , -1, -1, iPlayer\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n\n # Check neighbours\n lNeighbors = []\n iRange = gc.getMAX_PLAYERS()\n for iLoopPlayer in range(iRange):\n pLoopPlayer = gc.getPlayer(iLoopPlayer)\n if iLoopPlayer != gc.getBARBARIAN_PLAYER() and iLoopPlayer != iPlayer:\n if pLoopPlayer.isAlive():\n if gc.getTeam(pLoopPlayer.getTeam()).isHasMet(pPlayer.getTeam()):\n lNeighbors.append(iLoopPlayer)\n\n\n if iData1 != -1 and iData1 < len(lNeighbors):\n iData0 = 710\n iData1 = lNeighbors[iData1]\n\n # First screen (Civilizations)\n else:\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN1\", (\"\",)))\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesAssign1\") # EntryPoints/CvScreenInterface -> 709\n popupInfo.setData3(iPlayer)\n\n # List neighbors ---------\n # Friendly >= +10\n # Pleased >= +3\n # Cautious: -\n # Annoyed: <= -3\n # Furious: <= -10\n # ATTITUDE_FRIENDLY\n # ATTITUDE_PLEASED\n # ATTITUDE_CAUTIOUS\n # ATTITUDE_ANNOYED\n # ATTITUDE_FURIOUS\n if not lNeighbors:\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN1_1\", (\"\",)))\n else:\n for iLoopPlayer in lNeighbors:\n # Flunky keldath fix\n if iLoopPlayer == iPlayer:\n continue\n szBuffer = {\n AttitudeTypes.ATTITUDE_FRIENDLY:\"\",\n AttitudeTypes.ATTITUDE_PLEASED:\"\",\n AttitudeTypes.ATTITUDE_CAUTIOUS:\"\",\n AttitudeTypes.ATTITUDE_ANNOYED:\"\",\n AttitudeTypes.ATTITUDE_FURIOUS:\"\"\n }[pLoopPlayer.AI_getAttitude(iPlayer)]\n \"\"\"\n pLoopPlayer = gc.getPlayer(iLoopPlayer)\n eAtt = pLoopPlayer.AI_getAttitude(iPlayer)\n if eAtt == AttitudeTypes.ATTITUDE_FRIENDLY:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_PLEASED:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_CAUTIOUS:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_ANNOYED:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_FURIOUS:\n szBuffer = \"\"\n \"\"\"\n\n szBuffer = szBuffer + \" (\" + localText.getText(\"TXT_KEY_\"+str(eAtt), ()) + \")\"\n popupInfo.addPythonButton(pLoopPlayer.getCivilizationShortDescription(0) + szBuffer, gc.getCivilizationInfo(pLoopPlayer.getCivilizationType()).getButton())\n #popupInfo.addPythonButton(gc.getCivilizationInfo(pLoopPlayer.getCivilizationType()).getText(), gc.getCivilizationInfo(pLoopPlayer.getCivilizationType()).getButton())\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n\n # Commission Mercenaries (Inter/national mercenaries)\n # on-site\n # local\n # international\n # elite\n if iData0 == 710:\n # Werte von 709 weitervererbt\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN2\", (\"\",)))\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesAssign2\") # EntryPoints/CvScreenInterface -> 711\n popupInfo.setData1(iData1) # iTargetPlayer\n popupInfo.setData3(iPlayer) # iPlayer\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN2_1\", (\"\", )), gc.getCivilizationInfo(gc.getPlayer(iData1).getCivilizationType()).getButton())\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN2_2\", (\"\", )), gc.getCivilizationInfo(pPlayer.getCivilizationType()).getButton())\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN2_3\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_merc_international.dds\")\n if gc.getTeam(pPlayer.getTeam()).isHasTech(gc.getInfoTypeForString(\"TECH_BANKWESEN\")):\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN2_4\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_merc_elite.dds\")\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n # Commission Mercenaries (mercenary size)\n # small\n # medium\n # large\n # army\n elif iData0 == 711:\n # iData1, iData2, iData3, ...\n # 710, iTargetPlayer, iFaktor, -1, iPlayer\n # iFaktor:\n # 1: Urban (iTargetCiv) +200 Kosten\n # 2: Own units +300\n # 3: international +400\n # 4: elite +500\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN3\", (\"\", )))\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesAssign3\") # EntryPoints/CvScreenInterface -> 712\n popupInfo.setData1(iData1) # iTargetPlayer\n popupInfo.setData2(iData2) # iFaktor\n popupInfo.setData3(iPlayer) # iPlayer\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN3_1\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_mercenaries1.dds\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN3_2\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_mercenaries2.dds\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN3_3\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_mercenaries3.dds\")\n if iData2 != 4:\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN3_4\", (\"\", )), \"Art/Interface/Buttons/Actions/button_action_mercenaries4.dds\")\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n # Commission Mercenaries (primary unit types)\n # defensice\n # ranged combat\n # offensive\n # city attack\n elif iData0 == 712:\n # iData1, iData2, iData3, ...\n # 710, iTargetPlayer, iFaktor, -1, iPlayer\n # iFaktor:\n # 10: small group +0\n # 20: medium group +150\n # 30: big group +300\n # 40: huge group +400\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN4\", (\"\", )))\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesAssign4\") # EntryPoints/CvScreenInterface -> 713\n popupInfo.setData1(iData1) # iTargetPlayer\n popupInfo.setData2(iData2) # iFaktor\n popupInfo.setData3(iPlayer) # iPlayer\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN4_1\", (\"\", )), \"Art/Interface/Buttons/Promotions/tarnung.dds\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN4_2\", (\"\", )), \",Art/Interface/Buttons/Promotions/Cover.dds,Art/Interface/Buttons/Promotions_Atlas.dds,2,5\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN4_3\", (\"\", )), \",Art/Interface/Buttons/Promotions/Shock.dds,Art/Interface/Buttons/Promotions_Atlas.dds,4,5\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN4_4\", (\"\", )), \",Art/Interface/Buttons/Promotions/CityRaider1.dds,Art/Interface/Buttons/Promotions_Atlas.dds,5,2\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_UNITCOMBAT_NAVAL\", (\"\", )), \",Art/Interface/Buttons/Promotions/Naval_Units.dds,Art/Interface/Buttons/Promotions_Atlas.dds,3,7\")\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n # Commission Mercenaries (siege units)\n elif iData0 == 713:\n # iData1, iData2, iData3, ...\n # 710, iTargetPlayer, iFaktor, -1, iPlayer\n # iFaktor:\n # 100: defensive\n # 200: ranged\n # 300: offensive\n # 400: city raiders\n # 500: naval units\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN5\", (\"\", )))\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesAssign5\") # EntryPoints/CvScreenInterface -> 714\n popupInfo.setData1(iData1) # iTargetPlayer\n popupInfo.setData2(iData2) # iFaktor\n popupInfo.setData3(iPlayer) # iPlayer\n\n if gc.getGame().countKnownTechNumTeams(gc.getInfoTypeForString(\"TECH_MECHANIK\")) > 0:\n iUnit = gc.getInfoTypeForString(\"UNIT_BATTERING_RAM2\")\n szName = localText.getText(\"TXT_KEY_UNIT_BATTERING_RAM2_PLURAL\", ())\n elif gc.getGame().countKnownTechNumTeams(gc.getInfoTypeForString(\"TECH_WEHRTECHNIK\")) > 0:\n iUnit = gc.getInfoTypeForString(\"UNIT_BATTERING_RAM\")\n szName = localText.getText(\"TXT_KEY_UNIT_BATTERING_RAM_PLURAL\", ())\n elif gc.getGame().countKnownTechNumTeams(gc.getInfoTypeForString(\"TECH_BELAGERUNG\")) > 0:\n iUnit = gc.getInfoTypeForString(\"UNIT_RAM\")\n szName = localText.getText(\"TXT_KEY_UNIT_RAM_PLURAL\", ())\n else:\n iUnit = -1\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN5_1\", (\"\", )), \",Art/Interface/Buttons/Process/Blank.dds,Art/Interface/Buttons/Beyond_the_Sword_Atlas.dds,8,5\")\n if iUnit != -1:\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN5_2\", (szName, 2, 50)), gc.getUnitInfo(iUnit).getButton())\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN5_2\", (szName, 4, 90)), gc.getUnitInfo(iUnit).getButton())\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN5_2\", (szName, 6, 120)), gc.getUnitInfo(iUnit).getButton())\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n # Commission Mercenaries (confirmation)\n elif iData0 == 714:\n # iData1, iData2, iData3, ...\n # 710, iTargetPlayer, iFaktor, -1, iPlayer\n # iFaktor:\n # 1000: no siege +0\n # 2000: 2x +50\n # 3000: 4x +90\n # 4000: 6x +120\n iPlayer = iData4\n pPlayer = gc.getPlayer(iPlayer)\n\n # Kosten berechnen\n sFaktor = str(iData2)\n iCost = 0\n # siege units\n if sFaktor[0] == \"2\":\n iCost += 50\n elif sFaktor[0] == \"3\":\n iCost += 90\n elif sFaktor[0] == \"4\":\n iCost += 120\n # size\n if sFaktor[2] == \"2\":\n iCost += 150\n elif sFaktor[2] == \"3\":\n iCost += 300\n elif sFaktor[2] == \"4\":\n iCost += 400\n # inter/national\n if sFaktor[3] == \"1\":\n iCost += 200\n elif sFaktor[3] == \"2\":\n iCost += 300\n elif sFaktor[3] == \"3\":\n iCost += 400\n elif sFaktor[3] == \"4\":\n iCost += 500\n # ----------\n\n szText = \"\"\n if pPlayer.isCivic(gc.getInfoTypeForString(\"CIVIC_SOELDNERTUM\")):\n iCost -= iCost/4\n szText = CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN_BONUS\", (25,))\n\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN6\", (gc.getPlayer(iData1).getCivilizationShortDescription(0), iCost, szText)))\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesAssign6\") # EntryPoints/CvScreenInterface -> 715\n popupInfo.setData1(iData1) # iTargetPlayer\n popupInfo.setData2(iData2) # iFaktor\n popupInfo.setData3(iPlayer) # iPlayer\n\n # Confirm\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_ASSIGN6_\" + str(1 + CvUtil.myRandom(13, \"TXT_KEY_POPUP_MERCENARIES_ASSIGN6_\")), (\"\", )), \",Art/Interface/Buttons/Process/Blank.dds,Art/Interface/Buttons/Beyond_the_Sword_Atlas.dds,8,5\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n # Commission Mercenaries (confirmation)\n elif iData0 == 715:\n # iData1, iData2, iData3, ...\n # 715, iTargetPlayer, iFaktor, -1, iPlayer\n # iFaktor: 1111 - 4534\n doCommissionMercenaries(iData1, iData2, iData4)\n\n # Mercenaries Torture / Folter\n elif iData0 == 716:\n # iData1, iData2, iData3\n # 716, iMercenaryCiv, iPlayer\n iPlayer = iData2\n iMercenaryCiv = iData1\n pPlayer = gc.getPlayer(iPlayer)\n \n iCosts = getTortureCosts(iPlayer)\n \n if pPlayer.getGold() < iCosts:\n if gc.getPlayer(iPlayer).isHuman():\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\",)), None, 2, None, ColorTypes(7), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\", )))\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n else:\n pPlayer.changeGold(-iCosts)\n if CvUtil.myRandom(2, \"doFailedMercenaryTortureMessage\") == 0:\n doFailedMercenaryTortureMessage(iPlayer)\n else:\n # Check neighbours\n lNeighbors = []\n iRange = gc.getMAX_PLAYERS()\n for iLoopPlayer in range(iRange):\n pLoopPlayer = gc.getPlayer(iLoopPlayer)\n if iLoopPlayer != gc.getBARBARIAN_PLAYER():\n if pLoopPlayer.isAlive():\n if gc.getTeam(pLoopPlayer.getTeam()).isHasMet(pPlayer.getTeam()) or iLoopPlayer == iPlayer:\n lNeighbors.append(iLoopPlayer)\n\n # select neighbours if more than 5\n while len(lNeighbors) > 5:\n iRand = CvUtil.myRandom(len(lNeighbors), \"select neighbours if more than 5\")\n if lNeighbors[iRand] != iMercenaryCiv:\n lNeighbors.remove(lNeighbors[iRand])\n\n szText = CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE2\", (\"\",)) + localText.getText(\"[NEWLINE]\", ())\n # List neighbors ---------\n # ATTITUDE_FRIENDLY\n # ATTITUDE_PLEASED\n # ATTITUDE_CAUTIOUS\n # ATTITUDE_ANNOYED\n # ATTITUDE_FURIOUS\n for iLoopPlayer in lNeighbors:\n #keldath fix\n if iPlayer == iLoopPlayer:\n continue\n #keldath fix\n szBuffer = {\n AttitudeTypes.ATTITUDE_FRIENDLY:\"\",\n AttitudeTypes.ATTITUDE_PLEASED:\"\",\n AttitudeTypes.ATTITUDE_CAUTIOUS:\"\",\n AttitudeTypes.ATTITUDE_ANNOYED:\"\",\n AttitudeTypes.ATTITUDE_FURIOUS:\"\"\n }[pLoopPlayer.AI_getAttitude(iPlayer)]\n \"\"\"\n pLoopPlayer = gc.getPlayer(iLoopPlayer)\n eAtt = pLoopPlayer.AI_getAttitude(iPlayer)\n if eAtt == AttitudeTypes.ATTITUDE_FRIENDLY:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_PLEASED:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_CAUTIOUS:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_ANNOYED:\n szBuffer = \"\"\n elif eAtt == AttitudeTypes.ATTITUDE_FURIOUS:\n szBuffer = \"\"\n \"\"\"\n\n szText = szText + localText.getText(\"[NEWLINE][ICON_STAR] \", ()) + pLoopPlayer.getCivilizationShortDescription(0) + szBuffer + \" (\" + localText.getText(\"TXT_KEY_\"+str(eAtt), ()) + \")\"\n\n szText = szText + localText.getText(\"[NEWLINE][NEWLINE]\", ()) + CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE2_1\", (\"\", ))\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(szText)\n popupInfo.setData1(iMercenaryCiv) # iMercenaryCiv\n popupInfo.setData2(iPlayer) # iPlayer\n popupInfo.setOnClickedPythonCallback(\"popupMercenaryTorture2\") # EntryPoints/CvScreenInterface und CvGameUtils -> 717\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE_YES1\", (iCosts/4*3, 50)), \"\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE_YES2\", (iCosts/2, 25)), \"\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE_YES3\", (iCosts/4, 10)), \"\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n\n # Mercenaries Torture 2\n elif iData0 == 717:\n # iData1, iData2, iData3, iData4\n # 717, iMercenaryCiv, iPlayer, iButtonId\n iPlayer = iData2\n iMercenaryCiv = iData1\n pPlayer = gc.getPlayer(iPlayer)\n iCosts = getTortureCosts(iPlayer)\n \n if iData3 == 0:\n iGold = iCosts / 4 * 3\n iChance = 10\n elif iData3 == 1:\n iGold = iCosts / 2\n iChance = 5\n elif iData3 == 2:\n iGold = iCosts / 4\n iChance = 2\n\n if pPlayer.getGold() < iGold:\n if gc.getPlayer(iPlayer).isHuman():\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\",)), None, 2, None, ColorTypes(7), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\", )))\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n else:\n pPlayer.changeGold(-iGold)\n if iChance < CvUtil.myRandom(20, \"doFailedMercenaryTortureMessage2\"):\n doFailedMercenaryTortureMessage(iPlayer)\n else:\n if iPlayer != iMercenaryCiv:\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE3_1\", (gc.getPlayer(iMercenaryCiv).getCivilizationShortDescription(0),)), None, 2, None, ColorTypes(8), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE3_1\", (gc.getPlayer(iMercenaryCiv).getCivilizationShortDescription(0), )))\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n else:\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE3_2\", (\"\",)), None, 2, None, ColorTypes(8), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE3_2\", (\"\", )))\n # Dies soll doppelte Popups in PB-Spielen vermeiden.\n if iPlayer == gc.getGame().getActivePlayer():\n popupInfo.addPopup(iPlayer)\n\n# Test for actually required techs and bonusses\ndef getAvailableUnits(lNeighbors, lTestUnits):\n lUnits = []\n for pNeighbor in lNeighbors:\n if len(lTestUnits) == len(lUnits):\n break\n for eLoopUnit in lTestUnits:\n if eLoopUnit not in lUnits:\n if canTrain(eLoopUnit, pNeighbor):\n lUnits.append(eLoopUnit)\n return lUnits\n\ndef getCost(eUnit, iMultiplier, bCivicSoeldner, iExtraMultiplier=1):\n iCost = gc.getUnitInfo(eUnit).getProductionCost() * iExtraMultiplier\n iCost += (iCost / 10) * 2 * iMultiplier\n if bCivicSoeldner:\n iCost -= iCost/4\n return int(iCost)\n\n# Einheiten einen Zufallsrang vergeben (max. Elite)\ndef doMercenaryRanking(pUnit, iMinRang, iMaxRang):\n lRang = [\n gc.getInfoTypeForString(\"PROMOTION_COMBAT1\"),\n gc.getInfoTypeForString(\"PROMOTION_COMBAT2\"),\n gc.getInfoTypeForString(\"PROMOTION_COMBAT3\"),\n gc.getInfoTypeForString(\"PROMOTION_COMBAT4\"),\n gc.getInfoTypeForString(\"PROMOTION_COMBAT5\"),\n ]\n # zwischen 0 und einschliesslich iMaxRang\n iRang = CvUtil.myRandom(iMaxRang+1, \"doMercenaryRanking\")\n iRang = max(iMinRang, iRang)\n iRang = min(4, iRang)\n\n for iI in range(iRang):\n #CyInterface().addMessage(pUnit.getOwner(), True, 10, str(lRang[iI]), None, 2, gc.getUnitInfo(eUnit).getButton(), ColorTypes(13), pCity.getX(), pCity.getY(), True, True)\n pUnit.setHasPromotion(lRang[iI], True)\n pUnit.setLevel(iRang+1)\n\ndef doHireMercenary(iPlayer, eUnit, iMultiplier, bCivicSoeldner, pCity, iTimer, iExtraMultiplier=1):\n iMinRanking = 1\n iMaxRanking = 3\n iPromo = gc.getInfoTypeForString(\"PROMOTION_MERCENARY\")\n\n pPlayer = gc.getPlayer(iPlayer)\n iCost = getCost(eUnit, iMultiplier, bCivicSoeldner, iExtraMultiplier)\n if pPlayer.getGold() < iCost:\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\",)), None, 2, None, ColorTypes(7), 0, 0, False, False)\n return False\n else:\n if iPlayer == gc.getGame().getActivePlayer():\n CyAudioGame().Play2DSound(\"AS2D_COINS\")\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_UNIT_HIRED\", (pCity.getName(), gc.getUnitInfo(eUnit).getDescriptionForm(0))), None, 2, gc.getUnitInfo(eUnit).getButton(), ColorTypes(13), pCity.getX(), pCity.getY(), True, True)\n pPlayer.changeGold(-iCost)\n gc.getPlayer(gc.getBARBARIAN_PLAYER()).changeGold(iCost)\n pNewUnit = pPlayer.initUnit(eUnit, pCity.getX(), pCity.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)\n\n #CyInterface().addMessage(iPlayer, True, 10, str(iPromo), None, 2, gc.getUnitInfo(eUnit).getButton(), ColorTypes(13), pCity.getX(), pCity.getY(), True, True)\n pNewUnit.setHasPromotion(iPromo, True)\n pNewUnit.setImmobileTimer(iTimer)\n # Unit Rang / Unit ranking\n doMercenaryRanking(pNewUnit, iMinRanking, iMaxRanking)\n\n return True\n\n\ndef canTrain(eUnit, pPlayer):\n if not gc.getTeam(pPlayer.getTeam()).isHasTech(gc.getUnitInfo(eUnit).getPrereqAndTech()):\n return False\n for iI in range(gc.getNUM_UNIT_AND_TECH_PREREQS()):\n if gc.getUnitInfo(eUnit).getPrereqAndTechs(iI) != TechTypes.NO_TECH:\n if not gc.getTeam(pPlayer.getTeam()).isHasTech(gc.getUnitInfo(eUnit).getPrereqAndTechs(iI)):\n return False\n\n\n if gc.getUnitInfo(eUnit).getPrereqAndBonus() != BonusTypes.NO_BONUS:\n if not pPlayer.hasBonus(gc.getUnitInfo(eUnit).getPrereqAndBonus()):\n return False\n\n bRequiresBonus = False\n bNeedsBonus = True\n\n for iI in range(gc.getNUM_UNIT_PREREQ_OR_BONUSES()):\n if gc.getUnitInfo(eUnit).getPrereqOrBonuses(iI) != BonusTypes.NO_BONUS:\n bRequiresBonus = True\n if pPlayer.hasBonus(gc.getUnitInfo(eUnit).getPrereqOrBonuses(iI)):\n bNeedsBonus = False\n break\n\n if bRequiresBonus and bNeedsBonus:\n return False\n\n return True\n\ndef startMercTorture(pLoser, iWinnerPlayer):\n pWinnerPlayer = gc.getPlayer(iWinnerPlayer)\n UnitText = CvUtil.getScriptData(pLoser, [\"U\", \"t\"])\n if UnitText != \"\":\n # Commissioned Mercenary (MercFromCIV=CivID)\n if UnitText[:11] == \"MercFromCIV\":\n iMercenaryCiv = int(UnitText[12:])\n if not pWinnerPlayer.isHuman():\n # Ein minimaler Vorteil fuer die KI\n if iWinnerPlayer != iMercenaryCiv:\n doAIMercTorture(iWinnerPlayer, iMercenaryCiv)\n else:\n szText = CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE\", (\"\",))\n szText = szText + localText.getText(\"[NEWLINE][NEWLINE][ICON_STAR] \", ()) + CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE1\", (\"\",))\n iCosts = getTortureCosts(iWinnerPlayer)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(szText)\n popupInfo.setData1(iMercenaryCiv) # iMercenaryCiv\n popupInfo.setData2(iWinnerPlayer) # iPlayer\n popupInfo.setOnClickedPythonCallback(\"popupMercenaryTorture\") # EntryPoints/CvScreenInterface und CvGameUtils -> 716\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE_YES\", (iCosts, 50)), \"\")\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.addPopup(iWinnerPlayer)\n\n# Failed Mercenary Torture (from 716 and 717)\ndef doFailedMercenaryTortureMessage(iPlayer):\n iRand = CvUtil.myRandom(8, \"TXT_KEY_POPUP_MERCENARY_TORTURE_FAILED_\") + 1\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE_FAILED_0\", (\"\",)), None, 2, None, ColorTypes(7), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARY_TORTURE_FAILED_\" + str(iRand), (\"\", )))\n popupInfo.addPopup(iPlayer)\n\n# AI Torture Mercenary Commission\ndef doAIMercTorture(iPlayer, iMercenaryCiv):\n pPlayer = gc.getPlayer(iPlayer)\n iGold = pPlayer.getGold()\n \n if iGold >= 300:\n if CvUtil.myRandom(2, \"doAIPlanAssignMercenaries\") == 1:\n iCosts = getTortureCosts(iPlayer)\n pPlayer.changeGold(-iCosts)\n pPlayer.AI_changeAttitudeExtra(iMercenaryCiv, -2)\n doAIPlanAssignMercenaries(iPlayer, iMercenaryCiv)\n\n\n# AI Mercenary Commissions\ndef doAIPlanAssignMercenaries(iPlayer, iTargetPlayer):\n pPlayer = gc.getPlayer(iPlayer)\n iFaktor = 0\n iCost = 0\n iSize = 0\n\n # Check neighbours\n # ATTITUDE_FRIENDLY\n # ATTITUDE_PLEASED\n # ATTITUDE_CAUTIOUS\n # ATTITUDE_ANNOYED\n # ATTITUDE_FURIOUS\n lNeighbors = []\n if iTargetPlayer == -1:\n iRangeMaxPlayers = gc.getMAX_PLAYERS()\n for iLoopPlayer in range(iRangeMaxPlayers):\n #keldath fix\n if iLoopPlayer == iPlayer:\n continue\n #keldath fix\n pLoopPlayer = gc.getPlayer(iLoopPlayer)\n if iLoopPlayer != gc.getBARBARIAN_PLAYER() and iLoopPlayer != iPlayer:\n if pLoopPlayer.isAlive():\n if gc.getTeam(pLoopPlayer.getTeam()).isHasMet(pPlayer.getTeam()):\n eAtt = pPlayer.AI_getAttitude(iLoopPlayer)\n if eAtt == AttitudeTypes.ATTITUDE_ANNOYED or eAtt == AttitudeTypes.ATTITUDE_FURIOUS:\n # Check: Coastal cities for naval mercenary units\n iAttackAtSea = 0\n iCoastalCities = 0\n iLandCities = 0\n iNumCities = pLoopPlayer.getNumCities()\n for i in range(iNumCities):\n if pLoopPlayer.getCity(i).isCoastal(20):\n iCoastalCities += 1\n else:\n iLandCities += 1\n if iCoastalCities > 0:\n if iCoastalCities >= iLandCities:\n if CvUtil.myRandom(2, \"iAttackAtSea\") == 1:\n iAttackAtSea = 1\n else:\n iChance = (iNumCities * 2) - iCoastalCities\n if CvUtil.myRandom(iChance, \"iAttackAtSea2\") == 0:\n iAttackAtSea = 1\n\n lNeighbors.append((iLoopPlayer, iAttackAtSea))\n\n # iFaktor: 1111 - 4434\n # ---- inter/national\n # urban 200+ iFaktor: +1\n # own 300+ iFaktor: +2\n #internat 400+ iFaktor: +3\n #elite 500+ iFaktor: +4\n\n # ---- size\n #small +0 iFaktor: +10\n #medium +150 iFaktor: +20\n #big +300 iFaktor: +30\n #huge +400 iFaktor: +40\n\n # ---- type\n #defense iFaktor: +100\n #ranged iFaktor: +200\n #offense iFaktor: +300\n #city iFaktor: +400\n #naval iFaktor: +500\n\n # ---- siege\n #0 iFaktor: +1000\n #2 +50 iFaktor: +2000\n #4 +90 iFaktor: +3000\n #6 +120 iFaktor: +4000\n\n if lNeighbors or iTargetPlayer != -1:\n if iTargetPlayer != -1:\n iTargetAtSea = 0\n else:\n iRand = CvUtil.myRandom(len(lNeighbors), \"doAIPlanAssignMercenaries select neighbour\")\n iTargetPlayer = lNeighbors[iRand][0]\n iTargetAtSea = lNeighbors[iRand][1]\n iGold = pPlayer.getGold()\n\n # inter/national\n if pPlayer.getTechScore() > gc.getPlayer(iTargetPlayer).getTechScore():\n if iGold > 1000:\n if CvUtil.myRandom(3, \"doAIPlanAssignMercenaries1\") == 1:\n iFaktor += 3\n iCost += 400\n else:\n iFaktor += 2\n iCost += 300\n elif iGold > 500:\n iFaktor += 2\n iCost += 300\n else:\n iFaktor += 1\n iCost += 200\n else:\n if iGold > 1000:\n if CvUtil.myRandom(3, \"doAIPlanAssignMercenaries2\") == 1:\n iFaktor += 3\n iCost += 400\n else:\n iFaktor += 1\n iCost += 200\n else:\n iFaktor += 1\n iCost += 200\n\n # size\n if pPlayer.getPower() > gc.getPlayer(iTargetPlayer).getPower():\n if iGold > iCost + 150:\n if CvUtil.myRandom(3, \"doAIPlanAssignMercenaries3\") == 1:\n iFaktor += 10\n iSize = 1\n else:\n iFaktor += 20\n iCost += 150\n iSize = 2\n else:\n iFaktor += 10\n iSize = 1\n else:\n if iGold > iCost + 150:\n if CvUtil.myRandom(3, \"doAIPlanAssignMercenaries4\") != 1:\n iFaktor += 10\n iSize = 1\n else:\n iFaktor += 20\n iCost += 150\n iSize = 2\n else:\n iFaktor += 10\n iSize = 1\n\n # type\n if iTargetAtSea == 1:\n iType = 5\n else:\n iType = 1 + CvUtil.myRandom(4, \"doAIPlanAssignMercenaries5\")\n iFaktor += iType * 100\n\n # siege units\n if iType == 4:\n if iSize == 1:\n iFaktor += 1000\n elif pPlayer.getPower() > gc.getPlayer(iTargetPlayer).getPower():\n if iGold > iCost + 50:\n iFaktor += 2000\n else:\n iFaktor += 1000\n else:\n if iGold > iCost + 90:\n iFaktor += 3000\n elif iGold > iCost + 50:\n iFaktor += 2000\n else:\n iFaktor += 1000\n else:\n iFaktor += 1000\n\n if iTargetPlayer != -1:\n doCommissionMercenaries(iTargetPlayer, iFaktor, iPlayer)\n else:\n return -1\n \n return iTargetPlayer\n\n\n# Commission Mercenaries\ndef doCommissionMercenaries(iTargetPlayer, iFaktor, iPlayer):\n # iTargetPlayer, iFaktor, iPlayer\n # iFaktor: 1111 - 4534\n # Naval attack: sFaktor[1] = 5\n pPlayer = gc.getPlayer(iPlayer)\n pPlayerCiv = gc.getCivilizationInfo(pPlayer.getCivilizationType())\n sFaktor = str(iFaktor)\n iCost = 0\n # iSize = 0\n\n # PAEInstanceHiringModifier per turn\n PAEMercComission.setdefault(iPlayer, 0)\n PAEMercComission[iPlayer] = 1\n\n # siege units\n # iSiegeUnitAnz = 0\n if sFaktor[0] == \"2\":\n iCost += 50\n elif sFaktor[0] == \"3\":\n iCost += 90\n elif sFaktor[0] == \"4\":\n iCost += 120\n\n # size\n if sFaktor[2] == \"2\":\n iCost += 150\n elif sFaktor[2] == \"3\":\n iCost += 300\n elif sFaktor[2] == \"4\":\n iCost += 400\n\n # inter/national/elite units\n if sFaktor[3] == \"1\":\n iCost += 200\n elif sFaktor[3] == \"2\":\n iCost += 300\n elif sFaktor[3] == \"3\":\n iCost += 400\n elif sFaktor[3] == \"4\":\n iCost += 500\n # ----------\n\n if pPlayer.isCivic(gc.getInfoTypeForString(\"CIVIC_SOELDNERTUM\")):\n iCost -= iCost/4\n\n if pPlayer.getGold() < iCost:\n if gc.getPlayer(iPlayer).isHuman():\n CyInterface().addMessage(iPlayer, True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\",)), None, 2, None, ColorTypes(7), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_NOT_ENOUGH_MONEY\", (\"\", )))\n popupInfo.addPopup(iPlayer)\n else:\n pPlayer.changeGold(-iCost)\n gc.getPlayer(gc.getBARBARIAN_PLAYER()).changeGold(iCost)\n\n # Siege Units\n iAnzSiege = 0\n iUnitSiege = -1\n if sFaktor[0] == \"2\":\n iAnzSiege = 2\n elif sFaktor[0] == \"3\":\n iAnzSiege = 4\n elif sFaktor[0] == \"4\":\n iAnzSiege = 6\n\n if iAnzSiege > 0:\n if gc.getGame().countKnownTechNumTeams(gc.getInfoTypeForString(\"TECH_MECHANIK\")) > 0:\n iUnitSiege = gc.getInfoTypeForString(\"UNIT_BATTERING_RAM2\")\n elif gc.getGame().countKnownTechNumTeams(gc.getInfoTypeForString(\"TECH_WEHRTECHNIK\")) > 0:\n iUnitSiege = gc.getInfoTypeForString(\"UNIT_BATTERING_RAM\")\n elif gc.getGame().countKnownTechNumTeams(gc.getInfoTypeForString(\"TECH_BELAGERUNG\")) > 0:\n iUnitSiege = gc.getInfoTypeForString(\"UNIT_RAM\")\n # --------\n\n # Techs for inter/national units\n lNeighbors = []\n # on-site\n if sFaktor[3] == \"1\":\n lNeighbors.append(gc.getPlayer(iTargetPlayer))\n # national (own)\n elif sFaktor[3] == \"2\":\n lNeighbors.append(pPlayer)\n # international or elite\n elif sFaktor[3] == \"3\" or sFaktor[3] == \"4\":\n iRange = gc.getMAX_PLAYERS()\n for iLoopPlayer in range(iRange):\n pLoopPlayer = gc.getPlayer(iLoopPlayer)\n # Nachbarn inkludieren\n if pLoopPlayer.isAlive() and gc.getTeam(pLoopPlayer.getTeam()).isHasMet(pPlayer.getTeam()):\n lNeighbors.append(pLoopPlayer)\n # ------------------\n\n # Unit initials\n # size and types\n iAnzSpear = 0\n iAnzAxe = 0\n iAnzSword = 0\n iAnzArcher = 0\n iAnzSlinger = 0\n iAnzShip1 = 0\n iAnzShip2 = 0\n if sFaktor[2] == \"1\":\n if sFaktor[1] == \"1\":\n iAnzSpear = 2\n iAnzAxe = 1\n iAnzSword = 0\n iAnzArcher = 1\n iAnzSlinger = 0\n elif sFaktor[1] == \"2\":\n iAnzSpear = 1\n iAnzAxe = 1\n iAnzSword = 0\n iAnzArcher = 2\n iAnzSlinger = 0\n elif sFaktor[1] == \"3\":\n iAnzSpear = 1\n iAnzAxe = 2\n iAnzSword = 0\n iAnzArcher = 1\n iAnzSlinger = 0\n elif sFaktor[1] == \"4\":\n iAnzSpear = 0\n iAnzAxe = 0\n iAnzSword = 2\n iAnzArcher = 2\n iAnzSlinger = 0\n elif sFaktor[1] == \"5\":\n iAnzShip1 = 1 # weak\n iAnzShip2 = 1 # strong\n\n elif sFaktor[2] == \"2\":\n if sFaktor[1] == \"1\":\n iAnzSpear = 3\n iAnzAxe = 2\n iAnzSword = 0\n iAnzArcher = 3\n iAnzSlinger = 0\n elif sFaktor[1] == \"2\":\n iAnzSpear = 1\n iAnzAxe = 2\n iAnzSword = 0\n iAnzArcher = 4\n iAnzSlinger = 1\n elif sFaktor[1] == \"3\":\n iAnzSpear = 2\n iAnzAxe = 4\n iAnzSword = 0\n iAnzArcher = 2\n iAnzSlinger = 0\n elif sFaktor[1] == \"4\":\n iAnzSpear = 1\n iAnzAxe = 1\n iAnzSword = 2\n iAnzArcher = 3\n iAnzSlinger = 1\n elif sFaktor[1] == \"5\":\n iAnzShip1 = 2\n iAnzShip2 = 2\n\n elif sFaktor[2] == \"3\":\n if sFaktor[1] == \"1\":\n iAnzSpear = 4\n iAnzAxe = 3\n iAnzSword = 0\n iAnzArcher = 4\n iAnzSlinger = 1\n elif sFaktor[1] == \"2\":\n iAnzSpear = 2\n iAnzAxe = 2\n iAnzSword = 0\n iAnzArcher = 5\n iAnzSlinger = 3\n elif sFaktor[1] == \"3\":\n iAnzSpear = 2\n iAnzAxe = 5\n iAnzSword = 0\n iAnzArcher = 2\n iAnzSlinger = 3\n elif sFaktor[1] == \"4\":\n iAnzSpear = 2\n iAnzAxe = 1\n iAnzSword = 4\n iAnzArcher = 3\n iAnzSlinger = 2\n elif sFaktor[1] == \"5\":\n iAnzShip1 = 3\n iAnzShip2 = 2\n\n elif sFaktor[2] == \"4\":\n if sFaktor[1] == \"1\":\n iAnzSpear = 5\n iAnzAxe = 5\n iAnzSword = 0\n iAnzArcher = 5\n iAnzSlinger = 1\n elif sFaktor[1] == \"2\":\n iAnzSpear = 3\n iAnzAxe = 3\n iAnzSword = 0\n iAnzArcher = 7\n iAnzSlinger = 3\n elif sFaktor[1] == \"3\":\n iAnzSpear = 3\n iAnzAxe = 7\n iAnzSword = 0\n iAnzArcher = 4\n iAnzSlinger = 2\n elif sFaktor[1] == \"4\":\n iAnzSpear = 2\n iAnzAxe = 2\n iAnzSword = 6\n iAnzArcher = 4\n iAnzSlinger = 2\n elif sFaktor[1] == \"5\":\n iAnzShip1 = 3\n iAnzShip2 = 3\n\n if pPlayer.getCurrentEra() > 2:\n iAnzSword += iAnzAxe\n iAnzAxe = 0\n # ----------\n\n # Set units\n\n # Elite\n lEliteUnits = []\n\n # UNIT_LIGHT_SPEARMAN: TECH_SPEERSPITZEN\n # UNIT_AXEWARRIOR: TECH_BEWAFFNUNG\n # UNIT_AXEMAN: TECH_BEWAFFNUNG2 + Bronze or Iron\n # UNITCLASS_KURZSCHWERT: TECH_BEWAFFNUNG3 + Bronze or Iron\n # UNIT_SPEARMAN: TECH_ARMOR + Bronze or Iron\n # UNIT_SCHILDTRAEGER: TECH_BEWAFFNUNG4 + Bronze or Iron\n # UNIT_SWORDSMAN: TECH_BEWAFFNUNG5 + Iron\n\n iUnitSpear = gc.getInfoTypeForString(\"UNIT_LIGHT_SPEARMAN\")\n iUnitAxe = gc.getInfoTypeForString(\"UNIT_AXEWARRIOR\")\n iUnitArcher = gc.getInfoTypeForString(\"UNIT_ARCHER\")\n iUnitSlinger = gc.getInfoTypeForString(\"UNIT_PELTIST\")\n iUnitSword = -1\n bLongsword = False\n\n iBonus1 = gc.getInfoTypeForString(\"BONUS_BRONZE\")\n iBonus2 = gc.getInfoTypeForString(\"BONUS_IRON\")\n for pNeighbor in lNeighbors:\n pNeighborTeam = gc.getTeam(pNeighbor.getTeam())\n\n # elite units\n if sFaktor[3] == \"4\":\n NeighborCapital = pNeighbor.getCapitalCity()\n kNeighborCiv = gc.getCivilizationInfo(pNeighbor.getCivilizationType())\n\n # Naval units\n if sFaktor[1] == \"5\":\n lNeighborUnits = [\n gc.getInfoTypeForString(\"UNIT_CARVEL_WAR\"),\n gc.getInfoTypeForString(\"UNIT_QUADRIREME\"),\n gc.getInfoTypeForString(\"UNIT_QUINQUEREME\"),\n gc.getInfoTypeForString(\"UNIT_ROME_DECAREME\")\n ]\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_KONTERE\")) # Gaulos\n if iUnit == -1:\n iUnit = gc.getInfoTypeForString(\"UNIT_KONTERE\")\n lNeighborUnits.append(iUnit)\n\n # Land units\n else:\n lNeighborUnits = [\n gc.getInfoTypeForString(\"UNIT_COMPOSITE_ARCHER\"),\n gc.getInfoTypeForString(\"UNIT_REFLEX_ARCHER\"),\n gc.getInfoTypeForString(\"UNIT_SWORDSMAN\")\n ]\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_SPECIAL1\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_SPECIAL2\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_SPECIAL3\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_SPECIAL4\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_ELITE1\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_ELITE2\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n iUnit = kNeighborCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_ELITE3\"))\n if iUnit != -1: \n lNeighborUnits.append(iUnit)\n\n for iUnitElite in lNeighborUnits:\n if iUnitElite is not None and iUnitElite != -1:\n if gc.getUnitInfo(iUnitElite).isMilitaryHappiness():\n # Naval units\n if sFaktor[1] == \"5\" and gc.getUnitInfo(iUnitElite).getDomainType() == DomainTypes.DOMAIN_SEA:\n if NeighborCapital.canTrain(iUnitElite, 0, 0):\n lEliteUnits.append(iUnitElite)\n # Land units\n elif gc.getUnitInfo(iUnitElite).getDomainType() != DomainTypes.DOMAIN_SEA:\n if NeighborCapital.canTrain(iUnitElite, 0, 0):\n lEliteUnits.append(iUnitElite)\n\n # normal units\n # else: Falls es keine Elite gibt, sollen normale Einheiten einspringen\n\n # Naval units\n if sFaktor[1] == \"5\":\n # UNIT_KONTERE: TECH_COLONIZATION2\n # UNIT_BIREME: TECH_RUDERER2\n # UNIT_TRIREME: TECH_RUDERER3\n # UNIT_LIBURNE: TECH_WARSHIPS2\n # iAnzShip1 = weak\n # iAnzShip2 = strong\n iShip1 = -1\n iShip2 = -1\n if pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_WARSHIPS2\")):\n iShip1 = gc.getInfoTypeForString(\"UNIT_TRIREME\")\n iShip2 = gc.getInfoTypeForString(\"UNIT_LIBURNE\")\n elif pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_RUDERER3\")):\n iShip1 = gc.getInfoTypeForString(\"UNIT_BIREME\")\n iShip2 = gc.getInfoTypeForString(\"UNIT_TRIREME\")\n elif pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_RUDERER2\")):\n iShip1 = gc.getInfoTypeForString(\"UNIT_KONTERE\")\n iShip2 = gc.getInfoTypeForString(\"UNIT_BIREME\")\n elif pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_COLONIZATION2\")):\n iShip1 = gc.getInfoTypeForString(\"UNIT_KONTERE\")\n iShip2 = gc.getInfoTypeForString(\"UNIT_KONTERE\")\n\n # Land units\n # PAE V Patch 3: nun auch fuer Besatzung der Schiffe\n #else:\n #if gc.getTeam(pNeighbor.getTeam()).isHasTech(gc.getInfoTypeForString(\"TECH_ARCHERY3\")): iUnitArcher = gc.getInfoTypeForString(\"UNIT_COMPOSITE_ARCHER\")\n if pNeighbor.hasBonus(iBonus1) or pNeighbor.hasBonus(iBonus2):\n if pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_ARMOR\")):\n iUnitSpear = gc.getInfoTypeForString(\"UNIT_SPEARMAN\")\n if pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_BUERGERSOLDATEN\")):\n iUnitAxe = gc.getInfoTypeForString(\"UNIT_AXEMAN2\")\n elif pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_BEWAFFNUNG2\")):\n iUnitAxe = gc.getInfoTypeForString(\"UNIT_AXEMAN\")\n if pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_BEWAFFNUNG4\")):\n iUnitSword = gc.getInfoTypeForString(\"UNIT_SCHILDTRAEGER\")\n if iUnitSword == -1:\n if pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_BEWAFFNUNG3\")):\n iUnitSword = pPlayerCiv.getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_KURZSCHWERT\"))\n if iUnitSword == -1: \n iUnitSword = gc.getInfoTypeForString(\"UNIT_KURZSCHWERT\")\n if not bLongsword:\n if pNeighbor.hasBonus(iBonus2):\n if pNeighborTeam.isHasTech(gc.getInfoTypeForString(\"TECH_BEWAFFNUNG5\")):\n bLongsword = True\n\n # for neighbors\n\n # wenns schon langschwert gibt\n if bLongsword:\n iUnitSword = gc.getInfoTypeForString(\"UNIT_SWORDSMAN\")\n\n # wenns noch keine Schwerter gibt\n if iUnitSword == -1:\n iAnzAxe += iAnzSword\n iAnzSword = 0\n\n # Choose plots\n # Initialise CIV cultural plots\n # iMapW = gc.getMap().getGridWidth()\n # iMapH = gc.getMap().getGridHeight()\n iIce = gc.getInfoTypeForString(\"FEATURE_ICE\")\n iDarkIce = gc.getInfoTypeForString(\"FEATURE_DARK_ICE\")\n\n CivPlots = []\n iRange = CyMap().numPlots()\n for iI in range(iRange):\n pPlot = CyMap().plotByIndex(iI)\n iX = pPlot.getX()\n iY = pPlot.getY()\n if pPlot.getFeatureType() == iDarkIce or pPlot.getFeatureType() == iIce:\n continue\n if pPlot.getOwner() == iTargetPlayer:\n if not pPlot.isPeak() and not pPlot.isCity() and pPlot.getNumUnits() == 0:\n # Naval units\n if sFaktor[1] == \"5\":\n # Nicht auf Seen\n if pPlot.isWater() and not pPlot.isLake():\n CivPlots.append(pPlot)\n # Land units\n elif not pPlot.isWater():\n # Nicht auf Inseln\n iLandPlots = 0\n for x2 in range(3):\n for y2 in range(3):\n loopPlot2 = gc.getMap().plot(iX - 1 + x2, iY - 1 + y2)\n if loopPlot2 and not loopPlot2.isNone():\n if not loopPlot2.isWater():\n iLandPlots += 1\n\n # earlier break\n if x2 == 1 and y2 > 0 and iLandPlots <= 1:\n break\n\n # earlier breaks\n if iLandPlots >= 5:\n CivPlots.append(pPlot)\n break\n elif x2 == 2 and iLandPlots <= 2:\n break\n\n\n # Big stacks and elite only on border plots\n if sFaktor[2] == \"4\" or sFaktor[3] == \"4\":\n if CivPlots:\n NewCivPlots = []\n x2 = 0\n y2 = 0\n for loopPlot in CivPlots:\n iLX = loopPlot.getX()\n iLY = loopPlot.getY()\n bDone = False\n for x2 in [-1, 0, 1]:\n if bDone:\n break\n for y2 in [-1, 0, 1]:\n loopPlot2 = plotXY(iLX, iLY, x2, y2)\n if loopPlot2 is None or loopPlot2.isNone() or loopPlot2.getOwner() != loopPlot.getOwner():\n NewCivPlots.append(loopPlot)\n bDone = True\n break\n\n if NewCivPlots:\n CivPlots = NewCivPlots\n\n # Plot: Nach-Check: Nicht in der Naehe des Auftraggebers\n for loopPlot in CivPlots:\n if loopPlot and not loopPlot.isNone():\n iLX = loopPlot.getX()\n iLY = loopPlot.getY()\n bDone = False\n for x2 in [-2, 0, 2]:\n for y2 in [-2, 0, 2]:\n loopPlot2 = plotXY(iLX, iLY, x2, y2)\n if loopPlot2 and not loopPlot2.isNone():\n if loopPlot2.getNumUnits() > 0:\n iRange = loopPlot2.getNumUnits()\n for iUnit in range(iRange):\n if loopPlot2.getUnit(iUnit).getOwner() == iPlayer:\n CivPlots.remove(loopPlot)\n bDone = True\n break\n if bDone:\n break\n if bDone:\n break\n # set units\n if CivPlots:\n iPlot = CvUtil.myRandom(len(CivPlots), \"doCommissionMercenaries\")\n iPromo = gc.getInfoTypeForString(\"PROMOTION_MERCENARY\")\n # Loyality disabled for elite units\n iPromo2 = gc.getInfoTypeForString(\"PROMOTION_LOYALITAT\")\n iMinRanking = 0\n iMaxRanking = 4 # 4 = Veteran\n\n # instead of UnitAITypes.NO_UNITAI\n if sFaktor[1] == \"4\":\n UnitAI_Type = UnitAITypes.UNITAI_ATTACK_CITY\n else:\n UnitAI_Type = UnitAITypes.UNITAI_ATTACK\n\n # prevents CtD in MP\n #UnitAI_Type = UnitAITypes.NO_UNITAI\n\n ScriptUnit = []\n\n pBarbPlayer = gc.getPlayer(gc.getBARBARIAN_PLAYER())\n # set units\n # elite\n if sFaktor[3] == \"4\" and lEliteUnits:\n\n # Naval units\n if sFaktor[1] == \"5\":\n if sFaktor[2] == \"1\":\n iAnz = 2\n elif sFaktor[2] == \"2\":\n iAnz = 3\n elif sFaktor[2] == \"3\":\n iAnz = 4\n else:\n iAnz = 5\n # Land units\n else:\n if sFaktor[2] == \"1\":\n iAnz = 4\n elif sFaktor[2] == \"2\":\n iAnz = 8\n elif sFaktor[2] == \"3\":\n iAnz = 10\n else:\n iAnz = 12\n\n for _ in range(iAnz):\n iRand = CvUtil.myRandom(len(lEliteUnits), \"doCommissionMercenaries2\")\n NewUnit = pBarbPlayer.initUnit(lEliteUnits[iRand], CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n NewUnit.setHasPromotion(iPromo2, False)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n ScriptUnit.append(NewUnit)\n # Goldkarren\n eGoldkarren = gc.getInfoTypeForString(\"UNIT_GOLDKARREN\")\n NewUnit = CvUtil.spawnUnit(eGoldkarren, CivPlots[iPlot], pBarbPlayer)\n NewUnit.setImmobileTimer(2)\n NewUnit = CvUtil.spawnUnit(eGoldkarren, CivPlots[iPlot], pBarbPlayer)\n NewUnit.setImmobileTimer(2)\n\n # standard units\n else:\n if iAnzSpear > 0:\n for _ in range(iAnzSpear):\n NewUnit = pBarbPlayer.initUnit(iUnitSpear, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n ScriptUnit.append(NewUnit)\n if iAnzAxe > 0:\n for _ in range(iAnzAxe):\n NewUnit = pBarbPlayer.initUnit(iUnitAxe, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n ScriptUnit.append(NewUnit)\n if iAnzSword > 0 and iUnitSword != -1:\n for _ in range(iAnzSword):\n NewUnit = pBarbPlayer.initUnit(iUnitSword, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n ScriptUnit.append(NewUnit)\n if iAnzArcher > 0:\n for _ in range(iAnzArcher):\n NewUnit = pBarbPlayer.initUnit(iUnitArcher, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n if iAnzSlinger > 0:\n for _ in range(iAnzSlinger):\n NewUnit = pBarbPlayer.initUnit(iUnitSlinger, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n if iAnzSiege > 0 and iUnitSiege != -1:\n for _ in range(iAnzSiege):\n NewUnit = pBarbPlayer.initUnit(iUnitSiege, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAITypes.UNITAI_ATTACK_CITY, DirectionTypes.DIRECTION_SOUTH)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n\n # Vessels / Naval units : get land unit\n if iAnzShip1 > 0 or iAnzShip2 > 0:\n lUnit = []\n lUnit.append(iUnitSpear)\n lUnit.append(iUnitAxe)\n if iUnitSword != -1:\n lUnit.append(iUnitSword)\n\n if iAnzShip1 > 0 and iShip1 != -1:\n for _ in range(iAnzShip1):\n NewUnit = pBarbPlayer.initUnit(iShip1, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAITypes.UNITAI_ATTACK_SEA, DirectionTypes.DIRECTION_SOUTH)\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n\n # Cargo\n iRand = CvUtil.myRandom(len(lUnit), \"doCommissionMercenaries3\")\n NewLandUnit = pBarbPlayer.initUnit(lUnit[iRand], CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewLandUnit.setTransportUnit(NewUnit)\n\n if iAnzShip2 > 0 and iShip2 != -1:\n for _ in range(iAnzShip2):\n NewUnit = pBarbPlayer.initUnit(iShip2, CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAITypes.UNITAI_ATTACK_SEA, DirectionTypes.DIRECTION_SOUTH)\n if not NewUnit.isHasPromotion(iPromo):\n NewUnit.setHasPromotion(iPromo, True)\n # Unit Rang / Unit ranking\n doMercenaryRanking(NewUnit, iMinRanking, iMaxRanking)\n NewUnit.setImmobileTimer(2)\n\n # Cargo\n iRand = CvUtil.myRandom(len(lUnit), \"doCommissionMercenaries4\")\n NewLandUnit = pBarbPlayer.initUnit(lUnit[iRand], CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), UnitAI_Type, DirectionTypes.DIRECTION_SOUTH)\n NewLandUnit.setTransportUnit(NewUnit)\n\n # Goldkarren bei Landeinheiten\n if not CivPlots[iPlot].isWater():\n NewUnit = CvUtil.spawnUnit(gc.getInfoTypeForString(\"UNIT_GOLDKARREN\"), CivPlots[iPlot], pBarbPlayer)\n NewUnit.setImmobileTimer(2)\n\n # Plot anzeigen\n CivPlots[iPlot].setRevealed(gc.getPlayer(iPlayer).getTeam(), 1, 0, -1)\n\n # Eine Einheit bekommt iPlayer als Auftraggeber\n if ScriptUnit:\n iRand = CvUtil.myRandom(len(ScriptUnit), \"doCommissionMercenaries5\")\n CvUtil.addScriptData(ScriptUnit[iRand], \"U\", \"MercFromCIV=\" + str(iPlayer))\n\n # Meldungen\n if gc.getPlayer(iPlayer).isHuman():\n CyCamera().JustLookAtPlot(CivPlots[iPlot])\n if CivPlots[iPlot].isWater():\n szText = CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_DONE_3\", (gc.getPlayer(iTargetPlayer).getCivilizationDescription(0),))\n else:\n szText = CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_DONE_1\", (gc.getPlayer(iTargetPlayer).getCivilizationDescription(0),))\n CyInterface().addMessage(iPlayer, True, 10, szText, None, 2, None, ColorTypes(8), 0, 0, False, False)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(szText)\n popupInfo.addPopup(iPlayer)\n if gc.getPlayer(iTargetPlayer).isHuman():\n CyCamera().JustLookAtPlot(CivPlots[iPlot])\n if CivPlots[iPlot].isWater():\n szText = CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_DONE_4\", (\"\",))\n else:\n szText = CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_DONE_2\", (\"\",))\n CyInterface().addMessage(iTargetPlayer, True, 15, szText, \"AS2D_THEIRDECLAREWAR\", 2, \"Art/Interface/Buttons/General/button_alert_new.dds\", ColorTypes(7), CivPlots[iPlot].getX(), CivPlots[iPlot].getY(), True, True)\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(szText)\n popupInfo.addPopup(iTargetPlayer)\n\n # TEST\n #CyInterface().addMessage(gc.getGame().getActivePlayer(), True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_TEST\",(\"Plots\",len(CivPlots))), None, 2, None, ColorTypes(10), 0, 0, False, False)\n #CyInterface().addMessage(gc.getGame().getActivePlayer(), True, 10, CyTranslator().getText(\"TXT_KEY_MESSAGE_TEST\",(\"Plots\",int(sFaktor[1]))), None, 2, None, ColorTypes(10), 0, 0, False, False)\n\n# 2) Mercenaries\n# PAE Better AI: AI has no cost malus when hiring units\ndef AI_doHireMercenaries(iPlayer, pCity, iMaintainUnits, iCityUnits, iEnemyUnits):\n pPlayer = gc.getPlayer(iPlayer)\n # Units amount 1:3\n iMultiplikator = 3\n if iMaintainUnits > 0 and iCityUnits * iMultiplikator <= iEnemyUnits and pPlayer.getGold() > 200:\n if pCity.isHasBuilding(gc.getInfoTypeForString(\"BUILDING_SOELDNERPOSTEN\")):\n if not pCity.isHasBuilding(gc.getInfoTypeForString(\"BUILDING_CIVIL_WAR\")):\n # Check neighbours\n lNeighbors = []\n iRange = gc.getMAX_PLAYERS()\n for iLoopPlayer in range(iRange):\n if pCity.isConnectedToCapital(iLoopPlayer):\n lNeighbors.append(gc.getPlayer(iLoopPlayer))\n if lNeighbors:\n lUnits = doHireMercenariesINIT(pPlayer, lNeighbors)\n\n # KI zahlt die Haelfte und kein HiringModifierPerTurn\n iExtraMultiplier = 0.5\n bCivicSoeldner = pPlayer.isCivic(gc.getInfoTypeForString(\"CIVIC_SOELDNERTUM\"))\n\n lArchers = lUnits[0]\n lList = []\n iMinCost = -1\n for eUnit in lArchers:\n iCost = getCost(eUnit, 0, bCivicSoeldner, iExtraMultiplier)\n if iCost < iMinCost or iMinCost == -1:\n iMinCost = iCost\n lList.append([eUnit, iCost])\n lArchers = lList\n\n lOtherUnits = lUnits[1]+lUnits[2]+lUnits[3]\n lList = []\n for eUnit in lOtherUnits:\n iCost = getCost(eUnit, 0, bCivicSoeldner, iExtraMultiplier)\n if iCost < iMinCost or iMinCost == -1:\n iMinCost = iCost\n lList.append([eUnit, iCost])\n lOtherUnits = lList\n\n # choose units\n # iPromo = gc.getInfoTypeForString(\"PROMOTION_MERCENARY\")\n # AI hires max 2 - 4 units per city and turn\n iHiredUnits = 0\n iHiredUnitsMax = 2 + CvUtil.myRandom(3, \"AI_doHireMercenaries1\")\n while iMaintainUnits > 0 and pPlayer.getGold() > 50 and pPlayer.getGold() > iMinCost and iHiredUnits < iHiredUnitsMax and iCityUnits * iMultiplikator < iEnemyUnits:\n eUnit = -1\n iGold = pPlayer.getGold()\n\n iTry = 0\n while iTry < 3:\n if CvUtil.myRandom(10, \"AI_doHireMercenaries2\") < 7:\n eUnit, iCost = lArchers[CvUtil.myRandom(len(lArchers), \"AI_doHireMercenaries3\")]\n else:\n eUnit, iCost = lOtherUnits[CvUtil.myRandom(len(lOtherUnits), \"AI_doHireMercenaries4\")]\n if iCost <= 0:\n iCost = 50\n if iCost <= iGold:\n if doHireMercenary(iPlayer, eUnit, 0, bCivicSoeldner, pCity, 1, iExtraMultiplier):\n iMaintainUnits -= 1\n iCityUnits += 1\n iHiredUnits += 1\n break\n else:\n iTry += 1\n\n\n\ndef doHireMercenariesPopup(iCity, iTypeButton, iUnitButton, iPlayer):\n\n pPlayer = gc.getPlayer(iPlayer)\n pCity = pPlayer.getCity(iCity)\n\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_HIRE2\", (\"\", )))\n popupInfo.setData1(iCity)\n popupInfo.setData3(iPlayer)\n\n # Check neighbours\n lNeighbors = []\n for iLoopPlayer in range(gc.getMAX_PLAYERS()):\n if pCity.isConnectedToCapital(iLoopPlayer):\n lNeighbors.append(gc.getPlayer(iLoopPlayer))\n\n # inits\n lUnits = doHireMercenariesINIT(pPlayer, lNeighbors)\n\n lImmobile = [\n 3, 4, 2, 3, 3\n ]\n\n lUCI = [\n gc.getUnitCombatInfo(gc.getInfoTypeForString(\"UNITCOMBAT_ARCHER\")),\n gc.getUnitCombatInfo(gc.getInfoTypeForString(\"UNITCOMBAT_MELEE\")),\n gc.getUnitCombatInfo(gc.getInfoTypeForString(\"UNITCOMBAT_MOUNTED\")),\n gc.getUnitCombatInfo(gc.getInfoTypeForString(\"UNITCOMBAT_ELEPHANT\")),\n gc.getUnitCombatInfo(gc.getInfoTypeForString(\"UNITCOMBAT_NAVAL\"))\n ]\n\n if iTypeButton == -1:\n if not lNeighbors:\n popupInfo = CyPopupInfo()\n popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)\n popupInfo.setText(CyTranslator().getText(\"TXT_KEY_POPUP_MERCENARIES_HIRE3\", (\"\", )))\n popupInfo.addPopup(iPlayer)\n else:\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesHire\")\n for i in range(len(lUCI)):\n if lUnits[i]:\n popupInfo.addPythonButton(lUCI[i].getDescription(), lUCI[i].getButton())\n\n #popupInfo.setData2(-1)\n else:\n popupInfo.setOnClickedPythonCallback(\"popupMercenariesHireUnits\")\n popupInfo.setData2(iTypeButton)\n\n # PAEInstanceHiringModifier per turn\n iMultiplier = PAEInstanceHiringModifier.setdefault(iPlayer, 0)\n\n # Elephants\n if iTypeButton == 3:\n iExtraMultiplier = 2\n else:\n iExtraMultiplier = 1\n\n bCivicSoeldner = pPlayer.isCivic(gc.getInfoTypeForString(\"CIVIC_SOELDNERTUM\"))\n\n lTypeUnits = lUnits[iTypeButton]\n # Hire Units\n if iUnitButton != -1:\n if doHireMercenary(iPlayer, lTypeUnits[iUnitButton], iMultiplier, bCivicSoeldner, pCity, lImmobile[iTypeButton], iExtraMultiplier):\n iMultiplier += 1\n PAEInstanceHiringModifier[iPlayer] = iMultiplier\n\n # redraw the list with new prices\n for eUnit in lTypeUnits:\n iCost = getCost(eUnit, iMultiplier, bCivicSoeldner, iExtraMultiplier)\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_MESSAGE_MERCENARIES_UNIT_COST\", (gc.getUnitInfo(eUnit).getDescriptionForm(0), iCost)), gc.getUnitInfo(eUnit).getButton())\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_MAIN_MENU_GO_BACK\", (\"\", )), \",Art/Interface/Buttons/Process/Blank.dds,Art/Interface/Buttons/Beyond_the_Sword_Atlas.dds,8,5\")\n\n popupInfo.addPythonButton(CyTranslator().getText(\"TXT_KEY_ACTION_CANCEL\", (\"\", )), \"Art/Interface/Buttons/Actions/Cancel.dds\")\n popupInfo.setFlags(popupInfo.getNumPythonButtons()-1)\n popupInfo.addPopup(iPlayer)\n\ndef doHireMercenariesINIT(pPlayer, lNeighbors):\n lArchers = [\n gc.getInfoTypeForString(\"UNIT_PELTIST\"),\n gc.getInfoTypeForString(\"UNIT_ARCHER\"),\n gc.getInfoTypeForString(\"UNIT_COMPOSITE_ARCHER\"),\n gc.getInfoTypeForString(\"UNIT_SKIRMISHER\"),\n ]\n lEarlyInfantry = [\n gc.getInfoTypeForString(\"UNIT_LIGHT_SPEARMAN\"),\n gc.getInfoTypeForString(\"UNIT_AXEWARRIOR\"),\n gc.getInfoTypeForString(\"UNIT_AXEMAN\"),\n gc.getInfoTypeForString(\"UNIT_SCHILDTRAEGER\"),\n gc.getInfoTypeForString(\"UNIT_SPEARMAN\"),\n ]\n iUnit = gc.getCivilizationInfo(pPlayer.getCivilizationType()).getCivilizationUnits(gc.getInfoTypeForString(\"UNITCLASS_KURZSCHWERT\"))\n if iUnit == -1: \n iUnit = gc.getInfoTypeForString(\"UNIT_KURZSCHWERT\")\n lEarlyInfantry.append(iUnit)\n lInfantry = [\n gc.getInfoTypeForString(\"UNIT_SCHILDTRAEGER\"),\n gc.getInfoTypeForString(\"UNIT_SPEARMAN\"),\n gc.getInfoTypeForString(\"UNIT_AXEMAN2\"),\n gc.getInfoTypeForString(\"UNIT_SWORDSMAN\"),\n gc.getInfoTypeForString(\"UNIT_WURFAXT\"),\n ]\n lEarlyMounted = [\n gc.getInfoTypeForString(\"UNIT_LIGHT_CHARIOT\"),\n gc.getInfoTypeForString(\"UNIT_CHARIOT_ARCHER\"),\n gc.getInfoTypeForString(\"UNIT_CHARIOT\"),\n ]\n lMounted = [\n gc.getInfoTypeForString(\"UNIT_CHARIOT\"),\n gc.getInfoTypeForString(\"UNIT_HORSEMAN\"),\n gc.getInfoTypeForString(\"UNIT_HORSE_ARCHER\"),\n gc.getInfoTypeForString(\"UNIT_HEAVY_HORSEMAN\"),\n ]\n lElephants = [\n gc.getInfoTypeForString(\"UNIT_WAR_ELEPHANT\")\n ]\n\n lShips = [\n gc.getInfoTypeForString(\"UNIT_KONTERE\"),\n gc.getInfoTypeForString(\"UNIT_BIREME\"),\n gc.getInfoTypeForString(\"UNIT_TRIREME\"),\n gc.getInfoTypeForString(\"UNIT_QUADRIREME\"),\n gc.getInfoTypeForString(\"UNIT_LIBURNE\"),\n ]\n\n if pPlayer.getCurrentEra() <= 2:\n lInfantry = lEarlyInfantry\n lMounted = lEarlyMounted\n\n # Archers: Peltist (Steinschleuderer?) geht immer\n lTemp = lArchers[:1]+getAvailableUnits(lNeighbors, lArchers[1:])\n ## ab Plaenkler duerfen alle Kompositbogis\n if lArchers[3] not in lTemp:\n for pNeighbor in lNeighbors:\n if gc.getTeam(pNeighbor.getTeam()).isHasTech(gc.getInfoTypeForString(\"TECH_SKIRMISH_TACTICS\")):\n lTemp.append(lArchers[3])\n break\n lArchers = lTemp\n # Melee: Speer und Axt bzw. Schildtraeger und Speerkaempfer gehen immer\n lInfantry = lInfantry[:2]+getAvailableUnits(lNeighbors, lInfantry[2:])\n lMounted = getAvailableUnits(lNeighbors, lMounted)\n lElephants = getAvailableUnits(lNeighbors, lElephants)\n lShips = getAvailableUnits(lNeighbors, lShips)\n\n lUnits = [\n lArchers, lInfantry, lMounted, lElephants, lShips\n ]\n\n return lUnits\n\ndef getTortureCosts(iPlayer):\n iEra = gc.getPlayer(iPlayer).getCurrentEra()\n if iEra > 3: \n return 44\n elif iEra == 3: \n return 28\n elif iEra == 2: \n return 16\n else: \n return 8\n","sub_path":"PieAncientEuropeVI/Assets/Python/PAE/PAE_Mercenaries.py","file_name":"PAE_Mercenaries.py","file_ext":"py","file_size_in_byte":77661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213082620","text":"from django.shortcuts import render\nfrom core.models import CustomerUser\nfrom django.views.generic import View\nfrom django.core.urlresolvers import reverse_lazy\nfrom core.forms import UserCreationForm\n\n\nclass LogIn(View):\n def get(self, request):\n return_url = request.GET.get('next', reverse_lazy('shop:home'))\n return render(request, 'core/login.html',\n {'return_url': return_url})\n\n\nclass Register(View):\n def get(self, request):\n form = UserCreationForm()\n return_url = request.GET.get('next', reverse_lazy('shop:home'))\n return render(request, 'core/register.html',\n {'form': form, 'return_url': return_url})\n\n\nclass Customer(View):\n def get(self, request):\n try:\n customer = CustomerUser.objects.get(pk=request.user.id)\n except CustomerUser.DoesNotExist:\n customer = None\n return render(request, 'customer/customer.html', {'customer':customer})","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598738774","text":"from webcam import Webcam\nimport cv2\nimport numpy as np\nimport json\n\nwebcam = Webcam()\nwebcam.start()\n\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\nobjp = np.zeros((6 * 9, 3), np.float32)\nobjp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)\nobjpoints = []\nimgpoints = []\ni = 0\n\nwhile i < 50:\n image = webcam.get_current_frame()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)\n\n if ret:\n cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)\n imgpoints.append(corners)\n objpoints.append(objp)\n cv2.drawChessboardCorners(image, (9, 6), corners, ret)\n i += 1\n\n cv2.imshow('grid', image)\n cv2.waitKey(1000)\n\ncv2.destroyAllWindows()\nret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n\nrrvecs = []\nttvecs = []\ndata = {}\ndata[\"return\"] = ret\ndata[\"cameraMatrix\"] = mtx.tolist()\ndata[\"distCoeffs\"] = dist[0].tolist()\nfor i in rvecs:\n rrvecs.append(i.tolist())\ndata[\"radialVectors\"] = rrvecs[0]\n\nfor i in tvecs:\n ttvecs.append(i.tolist())\ndata[\"translationVectors\"] = ttvecs[0]\n\nwith open(\"data.json\", \"w\") as write_file:\n json.dump(data, write_file, indent=2)\n","sub_path":"camcalib.py","file_name":"camcalib.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249181794","text":"\"\"\"\r\nScheduling Block Data Structures\r\n================================\r\n\r\n\"\"\"\r\n\r\nfrom collections import namedtuple\r\nfrom pandas import DataFrame, Series, Timestamp\r\n\r\nSCHEDBLOCK_COLUMNS = [\r\n \"SB_UID\",\r\n \"SB_NAME\",\r\n \"SB_NOTE\",\r\n \"ARRAY_REQUESTED\",\r\n \"MAXIMUM_TIME\",\r\n \"ESTIMATED_TIME\",\r\n \"DEP_DELAY\",\r\n \"DEP_SB_LIST\",\r\n \"DEP_MARGIN\",\r\n \"SB_REPFREQ\",\r\n \"BAND\",\r\n \"RA\",\r\n \"DEC\",\r\n \"MIN_AR\",\r\n \"MAX_AR\",\r\n \"IS_POLARIZATION\",\r\n \"MAX_PWVC\",\r\n \"ARRAY_12M_TYPE\",\r\n \"NOMINAL_CONFIGURATION\",\r\n \"DESIRED_SG_AR\",\r\n \"DESIREC_SG_LAS\",\r\n \"IS_SIMULTANEOUS\",\r\n \"SIMULTANEOUS_SB_LIST\",\r\n]\r\n\r\nSchedBlockT = namedtuple('SchedBlockT', SCHEDBLOCK_COLUMNS)\r\nSchedBlockT.__doc__ = \"Data structure to store SchedBlock data\"\r\nSchedBlockT.SB_UID.__doc__ = \"Scheduling Block Unique ID\"\r\nSchedBlockT.SB_NAME.__doc__ = \" \"\r\nSchedBlockT.ARRAY_REQUESTED.__doc__ = \"\"\"\r\n \"\"\"\r\nSchedBlockT.SB_NOTE.__doc__ = \" [0..1]>\"\r\nSchedBlockT.MAXIMUM_TIME.__doc__ = \"\"\"\r\n {TimeT}\"\"\"\r\nSchedBlockT.ESTIMATED_TIME.__doc__ = \"\"\"\r\n {TimeT}\"\"\"\r\nSchedBlockT.DEP_DELAY.__doc__ = \"\"\"\r\n {TimeT}\"\"\"\r\nSchedBlockT.DEP_SB_LIST.__doc__ = \"\"\"\r\n [0..inf]\"\"\"\r\nSchedBlockT.SB_REPFREQ.__doc__ = \"\"\r\n","sub_path":"src/dsa/datastructures/schedblock.py","file_name":"schedblock.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"31655100","text":"#Define la dimension de la imagen\n\"\"\"\nfrom skimage import io, color\nimg = io.imread('baboon.png')\ndimension = color.guess_spatial_dimensions(img) #Funcion descontinuada\nprint(dimension)\n\"\"\"\n#Da las dimensiones de color de la imagen \nimport skimage.io as io\nfrom skimage.color import rgb2gray \nimg = io.imread('baboon.png')\nprint(img.shape)\n\n#Convertir en gris la imagen\nimg = io.imread('baboon.png')\nimg_grayscale = rgb2gray(img)\nio.imsave('baboon-gs.png',img_grayscale)\nshow_grayscale = io.imshow(img_grayscale)\nio.show()\n\n#Filtro Sobel\nfrom skimage import data, io, filters\nimg = io.imread('baboon-gs.png')\nedges = filters.sobel(img)\nio.imshow(edges)\nio.show()","sub_path":"py/PDI.py","file_name":"PDI.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"403606923","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/realasking/python_project1_environment_pathways_OR_essential_paths/epw/einit.py\n# Compiled at: 2017-08-23 22:16:44\n# Size of source mod 2**32: 1502 bytes\nimport sys, os, re, sqlite3, shutil\nfrom epw import cmds\n\nclass einit:\n\n def __init__(self, cfolder, dbf, mname):\n self.home = os.path.expanduser('~')\n self.conf_folder = cfolder\n self.dbfile = dbf\n self.module_name = mname\n self.folder = self.home + '/' + self.conf_folder\n self.df = self.folder + '/' + self.dbfile\n self.bf = self.home + '/BEP'\n self.info = cmds.warnings()\n if not os.path.exists(self.folder):\n os.makedirs((self.folder), exist_ok=True)\n else:\n if not os.path.exists(self.bf):\n os.makedirs((self.bf), exist_ok=True)\n if not os.path.isfile(self.home + '/.modulespath'):\n self.info.Merror()\n exit()\n else:\n setmf = 0\n for modules_folder in re.split(':', os.environ['MODULEPATH']):\n if os.access(modules_folder, os.W_OK):\n setmf = 1\n self.module_file = modules_folder + '/' + self.module_name\n break\n\n if setmf == 0:\n self.info.Mnerror()\n exit()","sub_path":"pycfiles/essential-pathway-1.0.2.tar/einit.cpython-36.py","file_name":"einit.cpython-36.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"371107368","text":"# Polynomials I: String Format\n\nimport ast\n\n\ndef calc_pol(pol_str, x = None):\n # your code here\n if x is None:\n return \"There is no value for x\"\n else:\n node = ast.parse(pol_str, mode='eval')\n code_object = compile(node, filename='', mode='eval')\n result = eval(code_object)\n if result == 0:\n return \"Result = 0, so \"+str(x)+\" is a root of \"+pol_str\n else:\n return \"Result = \"+str(result)\n\nimport test\n\ntest.describe(\"Example Tests\")\n\npol_str = \"2*x**2 + 3*x\"\nx = 4\ntest.assert_equals(calc_pol(pol_str, x), \"Result = 44\")\n\npol_str = \"2*x**2 + 3*x - 44\"\nx = 4\ntest.assert_equals(calc_pol(pol_str, x), \"Result = 0, so 4 is a root of 2*x**2 + 3*x - 44\")\n\npol_str = \"2*x**2 + 3*x\"\nx = 0\ntest.assert_equals(calc_pol(pol_str, x), \"Result = 0, so 0 is a root of 2*x**2 + 3*x\")\n\npol_str = \"2*x**2 + 3*x\"\ntest.assert_equals(calc_pol(pol_str), \"There is no value for x\")","sub_path":"codewars/85.py","file_name":"85.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"324869812","text":"'''\nProject 2: Rockymon\nAuthor: Scott Schretzenmaier\nDate Created: 2/26/15\nDate Edited: 3/4/15\n\nProgram Description:\n1. Ask the user for a name\n2. Greets the user by given name\n3. Displays a message introducing the user to the program creator and a description of game instructions\n4. On enter the user rolls the dice\n5. Program determines if the user has rolled winning or losing conditions\n6. If neither the user rolls until they roll their match number or a 5\n7. Allows user to play again or quit\n'''\nimport random\nimport sys\n\nusername = input (\"Welcome to Rockymon, Please input your name.\")\n\n#introduction\nprint(\"Hello \" + username + \" my name is Scott Schretzenmaier and and you are about to play Rockymon. This is a dice \\n\"\n \"game in which you will roll two virtual dice. On the initial roll if you a 5 or 10 you win! \\n\"\n \"However if you roll a 2, 4 or 11 you lose. If you roll none of these than the number you have rolled\\n\"\n \"becomes the match number. You will then continue to roll the two dice until you either roll the match\\n\"\n \"number and win or roll a 5 and lose. Good luck.\")\n\nplayAgain = 'y'\n\nwhile (playAgain == 'y'):\n #stores game player name\n #promt the user to roll\n input(\"New Game: Hit enter to roll the dice.\")\n #big start roll\n roll = random.randint(0, 12)\n\n #display big start roll\n print(\"Your opening roll is the \" + str(roll))\n\n #determin if user has won off of big start roll\n if(roll == 5 or roll == 10):\n print(\"You win!\")\n elif(roll == 2 or roll == 4 or roll == 11):\n print(\"You lose!\")\n else:\n print(\"Your big start roll is \" + str(roll) + \" in order to win you need to roll this match number again before you roll a 5\")\n\n #store match number\n matchNumber = roll\n #Promt user to roll again\n input(\"Hit enter to roll again.\")\n roll = random.randint(0,12)\n\n #Reroll until a 5 or the match number is rolled\n while (roll != matchNumber and roll != 5):\n input(\"You rolled a \" + str(roll) + \" please hit enter to roll again.\")\n roll = random.randint(0,12)\n\n #determine if the user has won or lost\n if(roll == 5 ):\n print(\"You rolled a 5 you lose!\")\n else:\n print(\"You rolled your match number \" + str(matchNumber) + \" you win!\")\n\n #Prompt the user to play again\n playAgain = input(\"Enter 'y' in order to play again or any other key to quit\")\n","sub_path":"Project2-Rockymon/P2A4_Schretzenmaier_3562856.py","file_name":"P2A4_Schretzenmaier_3562856.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5654390","text":"import csv\nimport keyword\nfrom django.core.management.base import BaseCommand, CommandError\n\nheader_keys = (\n 'field_name',\n 'form_name',\n 'section_name',\n 'field_type',\n 'field_label',\n 'choices',\n 'field_note',\n 'validation_type',\n 'min_value',\n 'max_value',\n 'is_indentifier',\n 'branching_logic',\n 'required',\n 'custom_alignment',\n 'question number',\n)\n\nfield_types = {\n 'date_ymd': 'DateField',\n 'number': 'FloatField',\n 'integer': 'IntegerField',\n 'email': 'EmailField',\n 'text': 'CharField',\n 'textarea': 'TextField',\n 'calc': 'FloatField',\n 'radio': 'CharField',\n 'select': 'CharField',\n 'checkbox': 'CharField',\n 'yesno': 'BooleanField',\n 'truefalse': 'BooleanField',\n}\n\nclass Command(BaseCommand):\n \"\"\"\n SYNOPSIS::\n\n python manage.py redcap inspect [options...] file\n\n DESCRIPTION:\n\n Attempts to parse a REDCap data dictionary and output Django models\n that match the data dictionary's rules.\n\n OPTIONS:\n\n ``--version`` - pass the REDCap version number of the CSV file\n\n \"\"\"\n\n help = \"\"\"Attempts to parse a REDCap data dictionary and output Django\n models that match the data dictionary's rules.\n \"\"\"\n\n requires_model_validation = False\n\n db_module = 'django.db'\n\n args = 'filename'\n\n def handle(self, filename=None, *args, **options):\n if not filename:\n raise CommandError('Enter a filename')\n\n fin = open(filename)\n dialect = csv.Sniffer().sniff(fin.read(1024))\n fin.seek(0)\n reader = csv.DictReader(fin, fieldnames=header_keys, dialect=dialect)\n # Skip header\n reader.next()\n\n for line in self.handle_inspection(reader):\n self.stdout.write(\"%s\\n\" % line)\n\n def handle_inspection(self, reader):\n yield \"# This is an auto-generated Django model module.\"\n yield \"# You'll have to do the following manually to clean this up:\"\n yield \"# * Make sure each model has one field with primary_key=True\"\n yield \"# * Ensure each model has a OneToOneField with the main model\"\n yield \"# Feel free to rename the models, but don't rename db_table values or field names.\"\n yield ''\n yield 'from %s import models' % self.db_module\n yield ''\n\n table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')\n\n prev_table_name = None\n for row in reader:\n table_name = row['form_name']\n\n if table_name != prev_table_name:\n if prev_table_name:\n for meta_line in self.get_meta(prev_table_name):\n yield meta_line\n prev_table_name = table_name\n yield 'class %s(models.Model):' % table2model(table_name)\n\n column_name = row['field_name']\n att_name = column_name.lower()\n comment_notes = [] # Holds Field notes, to be displayed in a Python comment.\n extra_params = {} # Holds Field parameters such as 'db_column'.\n\n extra_params['verbose_name'] = row['field_label']\n\n if row['field_note']:\n extra_params['help_text'] = row['field_note']\n\n\n # If the column name can't be used verbatim as a Python\n # attribute, set the \"db_column\" for this Field.\n if ' ' in att_name or '-' in att_name or keyword.iskeyword(att_name) or column_name != att_name:\n extra_params['db_column'] = column_name\n\n # Modify the field name to make it Python-compatible.\n if ' ' in att_name:\n att_name = att_name.replace(' ', '_')\n comment_notes.append('Field renamed to remove spaces.')\n\n if '-' in att_name:\n att_name = att_name.replace('-', '_')\n comment_notes.append('Field renamed to remove dashes.')\n\n if column_name != att_name:\n comment_notes.append('Field name made lowercase.')\n\n # Calling `get_field_type` to get the field type string and any\n # additional paramters and notes.\n field_type, field_params, field_notes = self.get_field_type(row)\n extra_params.update(field_params)\n comment_notes.extend(field_notes)\n\n field_type += '('\n\n if keyword.iskeyword(att_name):\n att_name += '_field'\n comment_notes.append('Field renamed because it was a Python reserved word.')\n\n if att_name[0].isdigit():\n att_name = 'number_%s' % att_name\n extra_params['db_column'] = unicode(column_name)\n comment_notes.append(\"Field renamed because it wasn't a \"\n \"valid Python identifier.\")\n\n # Don't output 'id = meta.AutoField(primary_key=True)', because\n # that's assumed if it doesn't exist.\n if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}:\n continue\n\n field_desc = '%s = models.%s' % (att_name, field_type)\n if extra_params:\n if not field_desc.endswith('('):\n field_desc += ', '\n field_desc += ', '.join(['%s=%r' % (k, v) for k, v in extra_params.items()])\n field_desc += ')'\n if comment_notes:\n field_desc += ' # ' + ' '.join(comment_notes)\n yield ' %s' % field_desc\n\n # Output the final Meta class\n if prev_table_name:\n for meta_line in self.get_meta(table_name):\n yield meta_line\n\n def get_field_type(self, row):\n \"\"\"Given the database connection, the table name, and the cursor row\n description, this routine will return the given field type name, as\n well as any additional keyword parameters and notes for the field.\n \"\"\"\n field_params = {}\n field_notes = []\n\n required = row['required']\n validation_type = row['validation_type']\n field_type = row['field_type']\n\n try:\n field_type = field_types.get(validation_type, field_types[field_type])\n except KeyError:\n field_type = 'TextField'\n field_notes.append('This field type is a guess.')\n\n if not required:\n field_params['blank'] = True\n if field_type is 'BooleanField':\n field_type = 'NullBooleanField'\n else:\n field_params['null'] = True\n\n if field_type == 'CharField':\n field_params['max_length'] = 2000\n\n choices = None\n if row['choices']:\n try:\n choices = [(int(v.strip()), k.strip()) for v, k in [choice.split(',') \\\n for choice in row['choices'].split('|')]]\n field_type = 'IntegerField'\n except (ValueError, TypeError):\n pass\n\n if choices:\n field_params['choices'] = choices\n\n return field_type, field_params, field_notes\n\n def get_meta(self, table_name):\n \"\"\"Return a sequence comprising the lines of code necessary\n to construct the inner Meta class for the model corresponding\n to the given database table name.\n \"\"\"\n return ['',\n ' class Meta:',\n ' db_table = %r' % table_name,\n '',\n '']\n","sub_path":"djredcap/management/commands/redcap_inspect.py","file_name":"redcap_inspect.py","file_ext":"py","file_size_in_byte":7483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"486084264","text":"import datetime\nimport csv\nimport json\n\nclass Card:\n def __init__(self,name,id):\n self.name = name\n self.id = id\n\n def compare_name(self,name):\n return str(self.name).lower() == name.lower()\n\n def compare_id(self,id):\n return str(self.id).lower() == str(id).lower()\n\n def __eq__(self, other):\n return str(self.id) == str(other.id)\n\n def __gt__(self, other):\n return str(self.name) > str(other.name)\n\n def __hash__(self):\n return hash(self.id)\n\nclass Writer:\n def __init__(self,parsed_games,init_file_path,output_file_path):\n init_file = open(init_file_path)\n init_json = json.load(init_file)\n self.export_events = bool(init_json[\"export_event_log\"])\n if init_json[\"Classes_POV\"] and init_json[\"Classes_POV\"][0] != \"*\":\n self.classes_pov = set(init_json[\"Classes_POV\"])\n else:\n self.classes_pov = [\"Hunter\", \"Rogue\", \"Mage\", \"Priest\", \"Paladin\", \"Warrior\", \"Shaman\", \"Warlock\", \"Druid\"]\n\n if init_json[\"excluded_class_POV\"] and init_json[\"excluded_class_POV\"][0] != \"\":\n for pov_class in init_json[\"excluded_class_POV\"]:\n self.classes_pov.remove(pov_class)\n\n if init_json[\"Classes_Opponent\"] and init_json[\"Classes_Opponent\"][0] != \"*\":\n self.classes_opponent = set(init_json[\"Classes_Opponent\"])\n else:\n self.classes_opponent = [\"Hunter\", \"Rogue\", \"Mage\", \"Priest\", \"Paladin\", \"Warrior\", \"Shaman\", \"Warlock\", \"Druid\"]\n\n if init_json[\"excluded_class_Opponent\"] and init_json[\"excluded_class_Opponent\"][0] != \"\":\n for pov_class in init_json[\"excluded_class_POV\"]:\n self.classes_opponent.remove(pov_class)\n\n self.attributes = init_json[\"attributes\"]\n\n self.cards_to_count = init_json[\"count_cards\"]\n\n self.parsed_games = parsed_games\n\n self.output_path = output_file_path\n\n self.modes = init_json[\"game_mode\"]\n\n self.remove_tainted = bool(init_json[\"remove_tainted\"])\n\n def write_logs(self):\n files_path = []\n attribute_log = open(self.output_path+\"_Attribute_log.csv\", mode='w',newline='\\n')\n files_path.append(self.output_path+\"_Attribute_log.csv\")\n attribute_csvwriter = csv.writer(attribute_log,quotechar='\\'',quoting=csv.QUOTE_NONNUMERIC)\n event_log = \"\" # Forward Declaration\n event_csvwriter = \"\" # Forward Declaration\n if self.export_events:\n event_log = open(self.output_path+\"_Event_log.csv\", mode='w',newline='\\n')\n event_csvwriter = csv.writer(event_log)\n event_csvwriter.writerow(['GameId', 'Activity', 'Time', 'Extras'])\n files_path.append(self.output_path + \"_Event_log.csv\")\n\n attribute_list = self.attributes\n for card in self.cards_to_count:\n if \"name\" in card:\n attribute_list.append(str(\"Count_\")+card[\"name\"])\n elif \"id\" in card:\n attribute_list.append(str(\"Count_\")+card[\"id\"])\n\n attribute_csvwriter.writerow(attribute_list)\n\n for parsed_game in self.parsed_games:\n if parsed_game.pov_class not in self.classes_pov:\n continue\n\n if parsed_game.opponent_class not in self.classes_opponent:\n continue\n\n if parsed_game.is_tainted() and self.remove_tainted:\n continue\n\n if parsed_game.mode not in self.modes:\n continue\n\n if self.export_events:\n for line in parsed_game.event_log():\n event_csvwriter.writerow(line)\n\n export_line = []\n\n for att in self.attributes:\n if att == \"unique_id\":\n export_line.append(parsed_game.unique_id)\n elif att == \"region\":\n export_line.append(parsed_game.region)\n elif att == \"start_time\" or att == \"s_time\" or att == \"time\":\n export_line.append(parsed_game.s_time)\n elif att == \"mode\":\n export_line.append(parsed_game.mode)\n elif att == \"rank\":\n export_line.append(parsed_game.rank)\n elif att == \"pov_class\":\n export_line.append(parsed_game.pov_class)\n elif att == \"opponent_class\":\n export_line.append(parsed_game.opponent_class)\n elif att == \"pov_is_first\":\n export_line.append(int(parsed_game.pov_is_first))\n elif att == \"max_turns\":\n export_line.append(parsed_game.max_turns())\n elif att == \"result\":\n export_line.append(parsed_game.result)\n\n for card in self.cards_to_count:\n if \"name\" in card:\n export_line.append(parsed_game.count_played_cards_with_name(card[\"name\"]))\n elif \"id\" in card:\n export_line.append(parsed_game.count_played_cards_with_id(card[\"id\"]))\n else:\n export_line.append(\"ERROR\")\n\n attribute_csvwriter.writerow(export_line)\n\n attribute_log.close()\n if self.export_events:\n event_log.close()\n\n return files_path\n\n\nclass ParsedGame:\n\n def __init__(self,game,interval_time=20):\n self.game = game\n self.interval_time = interval_time\n self.user_hash = self.game['user_hash']\n self.region = self.game['region']\n self.game_id = self.game['id']\n self.unique_id = str(self.region[:2]) + str(self.user_hash) + \"-\" + str(self.game_id)\n self.mode = self.game['mode']\n self.s_time = datetime.datetime.strptime(game['added'][:19], '%Y-%m-%dT%H:%M:%S')\n if self.mode == 'ranked':\n if not self.game['rank']:\n self.rank = \"0\"\n else:\n self.rank = self.game['rank']\n self.game_quality = 'Constructed'\n elif self.mode == 'casual':\n self.rank = None\n self.game_quality = 'Constructed'\n elif self.mode == 'arena':\n self.rank = None\n self.game_quality = 'Random'\n else:\n self.rank = None\n self.game_quality = 'Tainted'\n self.pov_class = self.game['hero']\n self.opponent_class = self.game['opponent']\n self.pov_is_first = not self.game['coin']\n self.result = self.game['result']\n\n self.card_history = game['card_history']\n\n self.parsed_card_history = []\n\n self.played_cards = []\n\n def is_tainted(self):\n return (self.game_quality=='Tainted')\n\n def is_constructed(self):\n return (self.game_quality=='Constructed')\n\n def is_arena(self):\n return (self.game_quality=='Random')\n\n def __str__(self):\n return self.unique_id\n\n def atributes(self):\n return (self.unique_id,self.region,self.mode,self.rank,self.pov_class,self.opponent_class,self.pov_is_first,self.result)\n\n def max_turns(self):\n if not self.parsed_card_history:\n self.parse_cards_played(self.interval_time)\n return self.parsed_card_history[-1][2]\n\n def parse_cards_played(self,time_interval=20):\n self.current_player = None\n self.parsed_card_history = []\n current_time = self.s_time\n self.parsed_card_history.append(('GameStart',current_time.__str__(), 0, None, None, None))\n\n self.played_cards = []\n for card_played in self.card_history:\n current_time+=datetime.timedelta(seconds=time_interval)\n if card_played[\"player\"] == \"me\":\n self.current_player = \"POV\"\n else:\n self.current_player = \"Opponent\"\n turn = card_played[\"turn\"]\n card = card_played[\"card\"][\"id\"]\n card_name = card_played[\"card\"][\"name\"]\n card_mana = card_played[\"card\"][\"mana\"]\n card_id = card_played[\"card\"][\"id\"]\n self.played_cards.append(Card(card_name,card_id))\n action = self.current_player.__str__()+\" - \"+card_name.__str__()\n self.parsed_card_history.append((action, current_time.__str__(), turn, card, card_name, card_mana))\n\n def count_played_cards_with_name(self,card_name):\n if not self.played_cards:\n self.parse_cards_played()\n\n count = 0\n for card in self.played_cards:\n if card.compare_name(card_name):\n count+=1\n\n return count\n\n def count_played_cards_with_id(self, card_id):\n if not self.played_cards:\n self.parse_cards_played()\n\n count = 0\n for card in self.played_cards:\n if card.compare_id(card_id):\n count += 1\n\n return count\n\n def event_log(self,discrete_time=False):\n ret = []\n for event in self.parsed_card_history:\n loged_event = []\n loged_event.append(self.unique_id)\n loged_event.append(event[0])\n if discrete_time:\n loged_event.append(event[2])\n else:\n loged_event.append(event[1])\n loged_event.append(event[2:])\n ret.append(loged_event)\n return ret\n\n def cards_used(self):\n if not self.played_cards:\n self.parse_cards_played()\n\n ret = []\n for card in self.played_cards:\n ret.append(card)\n\n ret = set(ret)\n return ret","sub_path":"parsed_game.py","file_name":"parsed_game.py","file_ext":"py","file_size_in_byte":9496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"606548161","text":"from rest_framework import serializers\nfrom .models import *\n\nclass LibrarySerializer(serializers.ModelSerializer):\n library_name= serializers.CharField(read_only=True)\n class Meta:\n model=library\n fields = \"__all__\"\n\nclass BookSerializer(serializers.ModelSerializer):\n book_title = serializers.CharField(read_only=True)\n class Meta:\n model=book\n fields = \"__all__\"\n\nclass LibraryUserSerializer(serializers.ModelSerializer):\n library_user = serializers.CharField(read_only=True)\n class Meta:\n model=library_user\n fields = \"__all__\"\n\nclass LibraryBookSerializer(serializers.ModelSerializer):\n # book_title = serializers.CharField(source='book.title', read_only=True)\n # library_name = serializers.CharField(source='library.library_name', read_only=True)\n book = BookSerializer()\n library = LibrarySerializer()\n class Meta:\n model=library_book\n # fields = ('id', 'book_title', 'library_name', 'library','book')\n fields = ('id', 'library','book')\n\nclass LibraryActivitySerializer(serializers.ModelSerializer):\n name = serializers.CharField(source='library_user.name', read_only=True)\n library_book = LibraryBookSerializer()\n \n class Meta:\n model=library_activity\n fields = ('id', 'activity_type', 'checked_out_at', 'checked_in_at', 'library_book', 'library_user', 'name')\n\nclass LibraryActivityUserSerializer(serializers.ModelSerializer):\n name = serializers.CharField(source='library_user.name', read_only=True)\n # library_book = LibraryBookSerializer()\n \n class Meta:\n model=library_activity\n fields = ('id', 'activity_type', 'checked_out_at', 'library_book', 'name')\n\nclass ActivityByLibrarySerializer(serializers.ModelSerializer):\n name = serializers.CharField(source='library_user.name', read_only=True)\n # library_book = LibraryBookSerializer()\n \n class Meta:\n model=library_activity\n fields = ('id', 'activity_type', 'checked_out_at', 'library_book', 'name')\n\nclass CheckoutLibraryBookSerializer(serializers.ModelSerializer):\n name = serializers.CharField(source='library_user.name', read_only=True)\n class Meta:\n model=library_activity\n fields = ('id', 'activity_type', 'checked_out_at', 'library_book', 'name')\n\nclass CheckinLibraryBookSerializer(serializers.ModelSerializer):\n name = serializers.CharField(source='library_user.name', read_only=True)\n class Meta:\n model=library_activity\n fields = ('id', 'activity_type', 'checked_in_at', 'library_book', 'name')","sub_path":"src/librarybooktrackapi/librarybooks/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"435508468","text":"from Models import *\nfrom math import sqrt\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass VideoProcessor:\n\n def __init__(self, operacijaZaAgregaciju):\n self.linija = None\n self.trenutnaVrednostAgregacije = 0\n self.prethodniBoxoviSlike = []\n self.maxRastojanjeBrojeva = 120\n self.operacijaZaAgregaciju = operacijaZaAgregaciju\n pass\n\n def SetLiniju(self,linija):\n self.linija = linija\n\n def IsLinijaSet(self):\n if self.linija == None:\n return False\n else:\n return True\n\n def Process(self, boxoviSlike):\n if self.linija == None:\n raise Exception('Linija nije postavljena')\n if len(self.prethodniBoxoviSlike) == 0:\n self.prethodniBoxoviSlike.append(boxoviSlike)\n return\n for i in range(10):\n boxoviZaJedanBroj = boxoviSlike[i]\n if len(boxoviZaJedanBroj) == 0:\n continue\n\n self.proveriPresekZaBroj_i(boxoviZaJedanBroj,i)\n\n\n\n self.prethodniBoxoviSlike.append(boxoviSlike)\n\n def proveriPresekZaBroj_i(self,boxoviZaJedanBroj,i):\n for referentniBox in boxoviZaJedanBroj:\n\n najblizi = None\n rastojanje = 8000\n lenPrethodnih = len(self.prethodniBoxoviSlike)\n for ii in range(lenPrethodnih):\n if rastojanje > self.maxRastojanjeBrojeva and ii < 4: #gledam maximalno 4 koraka unazad\n najblizi, rastojanje = self.__pronadjiNajblizi(referentniBox,self.prethodniBoxoviSlike[lenPrethodnih - ii - 1][i],i)\n else:\n break\n\n\n\n if rastojanje < self.maxRastojanjeBrojeva: #znaci to je isti broj samo pomeren u ovom frejmu, sledece proveravamo dal linija sece putanju ovog broja\n #debug\n r,c = self.__srednjaVrednostRedaKolone(referentniBox)\n r1, c1 = self.__srednjaVrednostRedaKolone(najblizi)\n plt.plot([c,c1],[r,r1], 'g')\n # plt.plot([c1], [r1], 'g>')\n plt.plot([self.linija.col1], [self.linija.row1], 'bo')\n plt.plot([self.linija.col2], [self.linija.row2], 'bo')\n #end\n (rowNajblizi,colNajblizi) = self.__srednjaVrednostRedaKolone(najblizi)\n (rowReferentni, colReferentni) = self.__srednjaVrednostRedaKolone(referentniBox)\n daliSeceLiniju = self.__intersect(TackaXY(colNajblizi,rowNajblizi), TackaXY(colReferentni,rowReferentni), TackaXY(self.linija.col1,self.linija.row1), TackaXY(self.linija.col2,self.linija.row2))\n if daliSeceLiniju:\n print(\"sece : {0}\".format(i))\n self.trenutnaVrednostAgregacije = self.operacijaZaAgregaciju(self.trenutnaVrednostAgregacije, i)\n #self.sum += i\n\n # Return true if line segments AB and CD intersect\n def __intersect(self,A, B, C, D):\n return self.__ccw(A, C, D) != self.__ccw(B, C, D) and self.__ccw(A, B, C) != self.__ccw(A, B, D)\n\n def __ccw(self,A, B, C):\n return (C.y - A.y) * (B.x - A.x) > (B.y - A.y) * (C.x - A.x)\n\n def __distance(self,row1,col1,row2,col2):\n return sqrt( (row2 - row1)**2 + (col2 - col1)**2 )\n\n def __sortirajPoRedu(self,pozicije):\n return sorted(pozicije, key=lambda pozicija: (pozicija.row1 + pozicija.row2)/2)\n\n def __pronadjiNajblizi(self, referentni, brojeviPozicije,ind):\n if len(brojeviPozicije) == 0:\n return (None, 8000)\n rowReferentnog, colReferentnog = self.__srednjaVrednostRedaKolone(referentni)\n\n indexNajblizeg = -1\n rastojanjeNajblizeg = 8000 #neka velika vrednost, trazimo sto manju\n for i in range(0,len(brojeviPozicije)):\n rowTrenutnog, colTrenutnog = self.__srednjaVrednostRedaKolone(brojeviPozicije[i])\n if rowTrenutnog > rowReferentnog or colTrenutnog > colReferentnog: #jer se brojevi krecu desno dole\n continue\n rastojanje = self.__distance(rowReferentnog,colReferentnog,rowTrenutnog,colTrenutnog)\n if rastojanje < rastojanjeNajblizeg:\n indexNajblizeg = i\n rastojanjeNajblizeg = rastojanje\n \n return brojeviPozicije[indexNajblizeg], rastojanjeNajblizeg\n\n def __srednjaVrednostRedaKolone(self,pozicija):\n return ((pozicija.row1 + pozicija.row2)/2,(pozicija.col1 + pozicija.col2)/2)\n\n__name__ = \"VideoProcessor\"","sub_path":"VideoProcessor.py","file_name":"VideoProcessor.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"12792897","text":"def greaterThan(index, array, x):\n if index > len(array) - 1: # base case\n return 'No First Greater Value'\n\n if array[index] <= x:\n return greaterThan(index + 1, array, x) # recursive go to next index and return value back\n elif array[index] > x: # FOUND!!!\n return array[index] # return value greater than\n\n\ninputlst, xlst = input('Enter Input : ').split('/')\ninputlst = [int(i) for i in inputlst.split()]\nxlst = [int(i) for i in xlst.split()]\n\ninputlst.sort() # must sorted becuz ez to find with this algorithm\n\nfor i in xlst:\n print(greaterThan(0, inputlst, i)) # insert left lst and right lst\n","sub_path":"KMITL_grader_lab/ch10_Searching_02_FirstGreaterValue.py","file_name":"ch10_Searching_02_FirstGreaterValue.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"127739510","text":"import numpy as np\nimport nltk\nimport string\nimport os\nimport sys\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nnp.set_printoptions(threshold=np.inf)\ndef get_tokens():\n with open('/home/amrita/song.txt', 'r') as shakes:\n text = shakes.read()\n lowers = text.lower()\n #remove the punctuation using the character deletion step of translate\n no_punctuation = lowers.translate(str.maketrans('','',string.punctuation))\n tokens = nltk.word_tokenize(no_punctuation)\n return tokens\n\ntokens = get_tokens()\nfiltered = [w for w in tokens if not w in stopwords.words('english')]\n\ndef stem_tokens(tokens, stemmer):\n stemmed = []\n for item in tokens:\n stemmed.append(stemmer.stem(item))\n return stemmed\ntoken_dict = {}\npath = '/home/amrita/'\nstemmer = PorterStemmer()\nstemmed = stem_tokens(filtered, stemmer)\ncount = Counter(stemmed)\na1 = count.most_common(100) \na = np.array(stemmed)\nprint(a)\nfor l in a:\n print(l)\na=str(a)\ndef tokenize(text):\n tokens = nltk.word_tokenize(text)\n stems = stem_tokens(tokens, stemmer)\n return stems\n\nfor subdir, dirs, files in os.walk(path):\n for file in files: \n shakes = open('/home/amrita/song.txt', 'r')\n text = shakes.read()\n lowers = text.lower()\n no_punctuation = lowers.translate(str.maketrans(' ',' ', string.punctuation))\n token_dict[1] = no_punctuation\n \n\ntfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english')\ntfs = tfidf.fit_transform(token_dict.values())\n\nfeature_names = tfidf.get_feature_names()\nvector = []\nwords = []\nfor col in tfs.nonzero()[1]:\n print(feature_names[col], ' - ', tfs[0, col])\n vector.append(tfs[0, col])\n words.append(feature_names[col])\nb = np.array(feature_names)\nprint(vector)\nprint(words)\nprint(b)\ndicword = {}\nv = []\nfor i in range(len(words)-1):\n dicword[words[i]] = vector[i]\nprint(dicword)\n\nfor word in a:\n if word in dicword:\n v.append(dicword[word])\n else:\n v.append(\"0\")\n\n\nprint(v)\nb = b.astype(np.string)\nb=str(b)\nkeys = open('words.txt','r')\nvalues = open('tfvalues.txt','r')\ndictionary = dict(zip(keys, values))\n#print(dictionary)\nkeys.close()\nvalues.close()\nshakes.close()\nf = open('words.txt','w') \n \nb = open('axes.txt','r')\nfor line in a: \n if line.strip('\\r\\n') in dictionary:\n file_lines = str([' '.join([line, dictionary[line]])])\n f.write(file_lines) \n print(file_lines)\n else:\n file_lines = str([' '.join([line.strip(),'0'])])\n f.write(file_lines)\n","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"584034938","text":"import numpy as np\nimport cv2\n\ndef _add_ring(img, center, r1, r2, c):\n # print(img.shape)\n inner = cv2.circle(np.zeros_like(img),center, r1, (1,1,1),-1)\n outer = cv2.circle(np.zeros_like(img),center, r2, (1,1,1),-1)\n ring = outer-inner\n img[ring>0.5]=c\n\n return img \n\ndef add_glasses(pts, img, r=0.3, t=0.25, c=60):\n # range for r should be between 0.2 and 0.4\n # thickness should be between 0.1 and 0.3\n x1 = pts[0]\n x2 = pts[1]\n d = np.sum((x2-x1)**2)**0.5\n d1 = np.uint16(d*r)\n d2 = np.uint16(d*(r+t))\n _add_ring(img, (x1[0],x1[1]), d1, d2, c)\n _add_ring(img, (x2[0],x2[1]), d1, d2, c)\n\n return img \n","sub_path":"src/facenet/facenet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"519497945","text":"\"\"\"Practice with dictionaries.\"\"\"\n\n__author__ = \"730307980\"\n\n# Define your functions below\n\n\ndef invert(a: dict[str, str]) -> dict[str, str]:\n \"\"\"Inverts the keys and values in a dictionary.\"\"\"\n output = {}\n for key in a:\n if a[key] in output:\n raise KeyError(\"Duplicate keys in new list.\")\n else:\n output[a[key]] = key\n return output\n\n\ndef favorite_color(a: dict[str, str]) -> str:\n \"\"\"Returns favorite Color.\"\"\"\n output: str\n favorite = {}\n for key, value in a.items():\n if value not in favorite:\n favorite[value] = 0\n else:\n favorite[value] += 1\n output = str(max(favorite, key=favorite.get))\n return output\n\n\ndef count(a: list[str]) -> dict[str, int]:\n \"\"\"Returns count of items in a list.\"\"\"\n output: dict[str, int] = {}\n i: int = 0\n while i < len(a):\n for y in a:\n if y in output:\n if a[i] == y:\n output[y] += 1\n else:\n output[y] = 1\n i += 1\n return output","sub_path":"exercises/ex06/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392370621","text":"#todo\"\"\"-----------------import normal package-------------------------\"\"\"\nimport sys\nsys.path.append('/home/pikey/PycharmProjects/rl-vae-II-pytorch-master')\nimport torch,torchvision,os,json,argparse,setproctitle,utils\nfrom torch.utils.data import DataLoader\nfrom tqdm import trange\nfrom torch import optim\nfrom tensorboardX import SummaryWriter\n#todo\"\"\"--------------------------------import user package------------------------------------\"\"\"\nfrom vae_wgan_gp import vae_wgan_gp\nfrom datasets import datasets\n\n#todo get path\ndirname,filename = os.path.split(os.path.abspath(__file__))\n\n#todo\"\"\"--------------------------------args------------------------------------\"\"\"\nparser = argparse.ArgumentParser(description='train ae')\n\nlog = parser.add_argument_group('logger')\ntrain = parser.add_argument_group('train')\nmodel = parser.add_argument_group('model')\n\nparser.add_argument('--gpu',type=int,default=2,help='gpu id')\nparser.add_argument('--seed',type=int,default=0,help='random seed')\n\ntrain.add_argument('--epoch',type=int,default=400,metavar='TS',help='training steps')\ntrain.add_argument('--bs',type=int,default=64,metavar='BS',help='training batch size')\ntrain.add_argument('--lr',type=float,default=3*1e-4,metavar='lr',help='learning rate')\n\nlog.add_argument('--log-dir',type=str,default=os.path.join('/home/pikey/Data/II',filename),help='log directory')\n\nmodel.add_argument('--z-dim',type=int,default=8,metavar='dz',help='latent_space_dimension')\nmodel.add_argument('--gamma',type=float,default=1,metavar='gamma',help='train weight of decoder')\nmodel.add_argument('--beta',type=float,default=1,metavar='beta',help='weight of discriminator learning rate')\n\nargs = parser.parse_args()\n\n\n# save args\nconfig = vars(args)\nif not os.path.exists(args.log_dir):\n\tos.makedirs(args.log_dir)\nwith open(os.path.join(args.log_dir, 'config.json'), 'wt') as f:\n\tjson.dump(config, f, cls=utils.DataEnc, indent=2)\n\n#todo\"\"\"--------------------------------gpu preparation------------------------------------\"\"\"\nif args.gpu == -1:\n\tgpu = 'cpu'\nelse:\n\tgpu = args.gpu\nprint('gpu :{}'.format(gpu))\n\n#todo\"\"\"--------------------------------datapreparation------------------------------------\"\"\"\ndset = datasets.IIPDataset('/home/pikey/Data/II/crop_part1','train',crop_ratio=(0,0))\ndldr = DataLoader(dset,batch_size=args.bs,shuffle=True,num_workers=16,drop_last=True)\nprint('data :{}'.format('crop_part1,train'))\n\n#todo --------------------------------modelpreparation------------------------------------\ntorch.manual_seed(args.seed)\nvae = vae_wgan_gp.VAE(args.z_dim,config='vae_conv')\nvae.to(gpu)\ndis = vae_wgan_gp.Discriminator().to(gpu)\n\ndec_opt = optim.Adam(vae.decoder.parameters(),lr=args.lr)\nenc_opt = optim.Adam(vae.encoder.parameters(),lr=args.lr)\ndis_opt = optim.Adam(dis.parameters(),lr=args.lr)\nprint('model done')\n\n#todo --------------------------------logger init-------------------------------------\nif os.path.exists(os.path.join(args.log_dir, 'train_result','img')) == False:\n\tos.makedirs(os.path.join(args.log_dir, 'train_result', 'img'))\n\tos.makedirs(os.path.join(args.log_dir, 'train_result', 'img','rec'))\n\tos.makedirs(os.path.join(args.log_dir, 'train_result', 'img','gen'))\n\nwriter = SummaryWriter(log_dir=os.path.join(args.log_dir, 'train_result'))\nprint('logger dir:{}'.format(os.path.join(args.log_dir, 'train_result')))\n#todo ----------------------------------set title-----------------------------------\nsetproctitle.setproctitle('vae_conv_wgan_gp gpu:{}'.format(args.gpu))\n\n#todo\"\"\"--------------------------------train------------------------------------\"\"\"\ndef train():\n\tprint('train begin')\n\t# train\n\tstep = 0\n\tfor epoch in trange(args.epoch):\n\t\tbt = 0\n\t\tfor true, flaw, region in dldr:\n\t\t\tbt += 1\n\t\t\tstep += 1\n\t\t\t#todo\"\"\"--------------------------------forward------------------------------------\"\"\"\n\t\t\tx = true.to(gpu)\n\n\t\t\ttild_x = vae(x)\n\t\t\that_x = vae.decode(vae.prior.sample(vae.z_mean.size()).to(gpu))\n\t\t\tjudge_hat_x = dis(hat_x)\n\t\t\tjudge_tild_x = dis(tild_x)\n\t\t\tjudge_fake = torch.cat([judge_hat_x, judge_tild_x], dim=0)\n\t\t\tjudge_x = dis(x)\n\t\t\t#todo ---------------------------------train-------------------------------------\n\t\t\tenc_opt.zero_grad()\n\n\n\t\t\tloss_rec,loss_kld = vae_wgan_gp.vae_loss(tild_x,x,vae.z_mean,vae.z_logsigma,mse=True)\n\t\t\tloss_dis = vae_wgan_gp.discriminator_loss(judge_x,judge_fake)\n\n\t\t\t#train encoder\n\t\t\tenc_opt.zero_grad()\n\t\t\t(loss_rec+loss_kld).backward(retain_graph=True)\n\t\t\tenc_opt.step()\n\n\t\t\t#train decoder\n\t\t\tdec_opt.zero_grad()\n\t\t\tloss_dec = args.gamma*loss_rec-loss_dis\n\t\t\tloss_dec.backward(retain_graph=True)\n\t\t\tdec_opt.step()\n\n\t\t\t# train discriminator\n\t\t\tdis_opt.zero_grad()\n\t\t\tgp = vae_wgan_gp.gradient_penalty(dis,x,hat_x)\n\t\t\tloss_dis = vae_wgan_gp.discriminator_loss(judge_x, judge_fake)\n\t\t\tloss_dis+=gp*args.gamma\n\t\t\tloss_dis.backward()\n\t\t\tdis_opt.step()\n\n\t\t\t#todo\"\"\"--------------------------------savedata------------------------------------\"\"\"\n\t\t\t# log\n\t\t\tprint('loss_rec:{}, loss_dec:{}, loss_dis:{}'.format(loss_rec,loss_dec,loss_dis))\n\n\t\t\twriter.add_scalar('loss_rec',loss_rec,step)\n\t\t\twriter.add_scalar('loss_dec',loss_dec,step)\n\t\t\twriter.add_scalar('loss_dis',loss_dis,step)\n\t\t\tif step % 50 == 0:\\\n\t\t\t\t#todo save reconstructed image\n\t\t\t\timg = torchvision.utils.make_grid(\n\t\t\t\t\t[true[0].cpu(),\n\t\t\t\t\t tild_x[0].cpu()],\n\t\t\t\t\tnrow=2)\n\t\t\t\twriter.add_image('results', img, step)\n\t\t\t\ttorchvision.utils.save_image(img, os.path.join(args.log_dir, 'train_result', 'img','rec',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'epoch{}_batch{}.png'.format(epoch, bt)))\n\n\t\t\t\t# todo save generated image\n\t\t\t\timg = torchvision.utils.make_grid(\n\t\t\t\t\t[\n\t\t\t\t\t\that_x[0].cpu()],\n\t\t\t\t\tnrow=1)\n\t\t\t\twriter.add_image('results', img, step)\n\t\t\t\ttorchvision.utils.save_image(img, os.path.join(args.log_dir, 'train_result', 'img', 'gen',\n\t\t\t\t 'epoch{}_batch{}.png'.format(epoch, bt)))\n\n\t\t#todo save model\n\t\tutils.save_model(vae,os.path.join(args.log_dir, 'model','vae'),'epoch{}.pkl'.format(epoch))\n\t\tutils.save_model(dis,os.path.join(args.log_dir, 'model','discriminator'),'epoch{}.pkl'.format(epoch))\n\nif __name__ == '__main__':\n\ttrain()","sub_path":"train/vae/vae_conv/vae_conv_wgan_gp128.py","file_name":"vae_conv_wgan_gp128.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"118824922","text":"from kivy.app import App\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.relativelayout import RelativeLayout\nfrom kivy.properties import ObjectProperty, ListProperty\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.clock import Clock\nimport ai1\nimport ai2\nfrom board import Board\n\n\nclass InvalidMoveError(Exception):\n pass\n\n\nui = None\ngameplay = None\n\n\nclass NotificationArea(BoxLayout):\n label = ObjectProperty()\n\n def notify(self, text, timeout):\n self.label.text = text\n Clock.schedule_once(self.reset, timeout)\n\n def reset(self, *ignore):\n self.label.text = ''\n\n\nclass GamePlay():\n def __init__(self):\n self.moves = []\n\n def init_game(self):\n ui.topbar.update()\n self.reset()\n\n def reset(self):\n self.moves = []\n ui.topbar.update()\n\n def token_move(self, row, col):\n token = self.token\n num_moves = len(self.moves)\n mod = num_moves % 4\n if mod in [1, 3]:\n last_move = self.moves[-1]\n if last_move[-1] == 'token':\n raise InvalidMoveError(\"invalid move\")\n\n # print(\"token %s is put on (%s %s)\" % (token, row, col))\n self.moves.append((row, col, token, 'token'))\n ui.topbar.update()\n # print(self.moves)\n\n def rotation_move(self, row, col, clockwise):\n token = self.token\n num_moves = len(self.moves)\n mod = num_moves % 4\n if mod in [1, 3]:\n last_move = self.moves[-1]\n if last_move[-1] == 'rotate':\n raise InvalidMoveError(\"invalid move\")\n\n print(\"token %s rotated (%s %s)\" % (token, row, col))\n self.moves.append((row, col, clockwise, 'rotate'))\n ui.topbar.update()\n print(self.moves)\n\n @property\n def token(self):\n num_moves = len(self.moves)\n if num_moves % 4 in [0, 1]:\n return 0\n return 1\n\n @property\n def rotateable(self):\n num_moves = len(self.moves)\n mod = num_moves % 4\n if mod in [0, 2]:\n return True\n\n last_move = self.moves[-1]\n if last_move[-1] == 'rotate':\n return False\n return True\n\n def undo(self):\n last_move = self.moves.pop()\n ui.topbar.update()\n return last_move\n\n\nclass TopBar(BoxLayout):\n token = ObjectProperty()\n rotateable = ObjectProperty()\n btn_clockwise = ObjectProperty()\n btn_anticlockwise = ObjectProperty()\n rotation = None\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n Clock.schedule_once(self.bind_buttons, 0)\n\n def bind_buttons(self, *ignore):\n self.btn_clockwise.bind(state=self.update_rotation)\n self.btn_anticlockwise.bind(state=self.update_rotation)\n\n def undo(self):\n try:\n last_move = gameplay.undo()\n except IndexError:\n return\n\n board = ui.grid.board\n if last_move[3] == 'rotate':\n row, col, clockwise, action = last_move\n clockwise = 1 - clockwise\n board.rotate(row, col, clockwise)\n elif last_move[3] == 'token':\n row, col, token, action = last_move\n board.array[row][col] = None\n ui.grid.update()\n self.update_rotation()\n\n def update(self):\n self.token = gameplay.token\n self.rotateable = gameplay.rotateable\n self.update_rotation()\n\n def update_rotation(self, *args):\n btn1 = self.btn_anticlockwise\n btn2 = self.btn_clockwise\n if btn1.state == 'down':\n self.rotation = 0\n elif btn2.state == 'down':\n self.rotation = 1\n else:\n self.rotation = None\n\n\nclass Cell(ButtonBehavior, Widget):\n row, col = ObjectProperty(), ObjectProperty()\n token = ObjectProperty(None)\n color = {0: (.9, .9, .9, 1),\n 1: (0.1, 0, 0.5, 1),\n None: (0.1, 0.4, 0.1, 1)}\n\n def on_release(self, *args):\n self.parent.cell_clicked(self)\n\n\nclass ExampleCell(Cell):\n def on_release(self, *ignore):\n pass\n\n\nclass Grid(GridLayout):\n board = ObjectProperty()\n background_color = ListProperty([0.2, 0.5, 0.2, 1])\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.board = Board()\n self.board.empty_array()\n # self.board.array = [\n # [None, 1, None, None, None, None],\n # [None, None, 1, None, 0, None],\n # [None, 0, None, 1, None, 0],\n # [None, None, None, None, 1, None],\n # [None, None, None, 0, None, None],\n # [None, None, None, None, None, None],\n # ]\n self.update()\n\n def reset_board(self):\n self.board.empty_array()\n ui.gameplay.reset()\n self.update()\n ui.topbar.update()\n\n def update(self):\n self.clear_widgets()\n a = self.board.array\n for i, row in enumerate(a):\n for j, tk in enumerate(row):\n cell = Cell(token=tk, row=i, col=j)\n self.add_widget(cell)\n\n def ai_move(self, ai_id):\n if ai_id == 2:\n ai = ai2\n else:\n ai = ai1\n token = gameplay.token\n move = ai.move(self.board.array, token)\n coor, center, clockwise = move\n row, col = coor\n\n try:\n gameplay.token_move(*coor)\n except InvalidMoveError as e:\n ui.notification_area.notify(\"ROTATE PLEASE\", timeout=1)\n return\n for cell in self.children:\n if (cell.row, cell.col) == coor:\n break\n cell.token = token\n self.board.array[row][col] = token\n\n try:\n gameplay.rotation_move(center[0], center[1], clockwise)\n except InvalidMoveError as e:\n ui.notification_area.notify(\"Invalid move!\", timeout=1)\n return\n self.board.rotate(center[0], center[1], clockwise)\n ui.topbar.btn_clockwise.state = 'normal'\n ui.topbar.btn_anticlockwise.state = 'normal'\n\n self.update()\n\n def cell_clicked(self, cell):\n row, col = cell.row, cell.col\n rotation = ui.topbar.rotation\n if rotation is not None:\n if (row, col) not in ((1, 1), (4, 4), (1, 4), (4, 1)):\n return\n try:\n gameplay.rotation_move(row, col, rotation)\n except InvalidMoveError as e:\n ui.notification_area.notify(\"Invalid move!\", timeout=1)\n return\n self.board.rotate(row, col, rotation)\n ui.topbar.btn_clockwise.state = 'normal'\n ui.topbar.btn_anticlockwise.state = 'normal'\n else:\n if cell.token is not None:\n return\n token = gameplay.token\n try:\n gameplay.token_move(row, col)\n except InvalidMoveError as e:\n ui.notification_area.notify(\"ROTATE PLEASE\", timeout=1)\n return\n cell.token = token\n self.board.array[row][col] = token\n self.update()\n\n\nclass AIPanel(BoxLayout):\n label = ObjectProperty()\n def ai_move(self, ai_id):\n ui.grid.ai_move(ai_id)\n\n # def utility(self):\n # token = gameplay.token\n # state = ai.game.make_state(array=ui.grid.board.array, num_moves=token)\n # u = ai.game.utility(state, token)\n # self.label.text = \"Utility: %.2f\" % u\n\n\nclass UI(RelativeLayout):\n grid = ObjectProperty()\n topbar = ObjectProperty()\n notification_area = ObjectProperty()\n ai_panel = ObjectProperty()\n\n\nclass PentagoApp(App):\n def build(self):\n global gameplay, ui\n gameplay = GamePlay()\n ui = UI()\n gameplay.init_game()\n return ui\n\n\nif __name__ == '__main__':\n app = PentagoApp()\n app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94616818","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom rest_framework import serializers\nfrom .models import Usuario, Publicacion, Foto\n\nclass UsuarioSerializer(serializers.ModelSerializer):\n publicacion = serializers.HyperlinkedIdentityField(view_name='usuariopublicacion', lookup_field='username')\n\n class Meta:\n model = Usuario\n fields = ('id', 'username', 'first_name','last_name', 'publicacion', )#cambios en id\n\nclass PublicacionSerializer(serializers.ModelSerializer):\n autor = UsuarioSerializer(required = False)\n fotos = serializers.HyperlinkedIdentityField(view_name = 'listapublicacionfoto')\n\n def get_validation_exclusion(self, *args, **kwargs):\n #autor que se basa en el request\n exclusions = super(PublicacionSerializer, self).get_validation_exclusion(*args, **kwargs)\n return exclusions + ['autor']\n\n class Meta:\n model = Publicacion\n\nclass FotoSerializer(serializers.ModelSerializer):\n image = serializers.ReadOnlyField(source = 'image.url')\n\n class Meta:\n model = Foto\n","sub_path":"gp3-2-rubeb/proyecto/apps/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33952285","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n# ------------- memo ------------------\n# n : 単語数\n# z : トピック\n# m : ドキュメント\n# t : ボキャブラリー\n# -------------------------------------\n\nimport numpy as np\n\nclass LDA:\n def __init__(self, K, alpha, beta, docs, V):\n self.K = K \n self.alpha = alpha \n self.beta = beta \n self.docs = docs\n self.V = V\n\n self.z_m_n = [] # topics of words of documents\n self.n_m_z = np.zeros((len(self.docs), K)) + alpha # word count of each document and topic\n self.n_z_t = np.zeros((K, V)) + beta # word count of each topic and vocabulary\n self.n_z = np.zeros(K) + V * beta # word count of each topic\n\n self.N = 0\n for m, doc in enumerate(docs):\n self.N += len(doc)\n z_n = []\n for t in doc:\n z = np.random.randint(0, K)\n z_n.append(z)\n self.n_m_z[m, z] += 1\n self.n_z_t[z, t] += 1\n self.n_z[z] += 1\n self.z_m_n.append(np.array(z_n))\n\n def inference(self):\n \"\"\"learning once iteration\"\"\"\n for m, doc in enumerate(self.docs):\n z_n = self.z_m_n[m]\n n_m_z = self.n_m_z[m]\n for n, t in enumerate(doc):\n # discount for n-th word t with topic z\n z = z_n[n]\n n_m_z[z] -= 1\n self.n_z_t[z, t] -= 1\n self.n_z[z] -= 1\n\n # sampling topic new_z for t\n p_z = self.n_z_t[:, t] * n_m_z / self.n_z\n new_z = np.random.multinomial(1, p_z / p_z.sum()).argmax()\n\n # set z the new topic and increment counters\n z_n[n] = new_z\n n_m_z[new_z] += 1\n self.n_z_t[new_z, t] += 1\n self.n_z[new_z] += 1\n\n def worddist(self):\n \"\"\"get topic-word distribution\"\"\"\n return self.n_z_t / self.n_z[:, np.newaxis]\n\n #def perplexity(self, docs=None):\n def perplexity(self):\n docs = self.docs\n phi = self.worddist()\n log_per = 0\n N = 0\n Kalpha = self.K * self.alpha\n for m, doc in enumerate(docs):\n theta = self.n_m_z[m] / (len(self.docs[m]) + Kalpha)\n for w in doc:\n log_per -= np.log(np.inner(phi[:,w], theta))\n N += len(doc)\n return np.exp(log_per / N)\n\ndef lda_learning(lda, iteration, voca, logfile):\n\n perp = lda.perplexity()\n print (\"initial perplexity=%f\" % perp)\n logfile.write(\"\\n--------------- computation --------------------\\n\")\n logfile.write(\"\\ninitial perplexity=%f\\n\" % perp)\n\n for i in range(iteration):\n lda.inference()\n perp = lda.perplexity()\n if (i + 1)%10 == 0:\n print (\"iter%d perplexity=%f\" % (i + 1, perp))\n logfile.write(\"iter%d perplexity=%f\\n\" % (i + 1, perp))\n\n\ndef main():\n import optparse\n import vocabulary\n import output\n import os\n import time\n parser = optparse.OptionParser()\n parser.add_option(\"-f\", dest=\"filename\", help=\"filename\")\n parser.add_option(\"--alpha\", dest=\"alpha\", type=\"float\", help=\"parameter alpha\", default=0.5)\n parser.add_option(\"--beta\", dest=\"beta\", type=\"float\", help=\"parameter beta\", default=0.5)\n parser.add_option(\"-k\", dest=\"K\", type=\"int\", help=\"number of topics\", default=20)\n parser.add_option(\"-i\", dest=\"iteration\", type=\"int\", help=\"iteration count\", default=100)\n (options, args) = parser.parse_args()\n\n if not options.filename:\n parser.error(\"need filename(-f)\")\n\n if options.filename:\n corpus = vocabulary.load_file(options.filename)\n\n\n voca = vocabulary.Vocabulary()\n docs = [voca.doc_to_ids(doc) for doc in corpus]\n\n lda = LDA(options.K, options.alpha, options.beta, docs, voca.size())\n\n path = output.get_path(options.K)\n logfile = open(path+\"log.txt\", \"w\")\n output.show_options(logfile, corpus, voca, options)\n start = time.time()\n\n lda_learning(lda, options.iteration, voca, logfile)\n\n cpt = time.time() - start\n output.show_cpt(logfile, cpt)\n output.show_parameters(logfile, lda)\n logfile.flush()\n logfile.close()\n\n output.output_word_topic_dist(lda, voca, path)\n output.save_fig(lda, options.K, path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Yagi/LDA/lda/lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"360816316","text":"from random import seed\nfrom random import randrange\nfrom unicodecsv import reader\n\n'''\nThis section will be for loading csv files, converting string columns to float,\nsplitting datasets into k folds, determing an accuracy percentage, and algorithm\nevaluation by cross-validation split.\n'''\n# load a csv file\ndef load_csv(filename):\n f = open(filename, \"rb\")\n lines = reader(f)\n dataset = list(lines)\n return dataset\n\n# convert string column to float\ndef str_column_to_float(dataset, column):\n for row in dataset:\n row[column] = float(row[column].strip())\n \n# split the dataset into k folds\ndef cross_validation_split(dataset, n_folds):\n dataset_split = list()\n dataset_copy = list(dataset)\n fold_size = int(len(dataset) / n_folds)\n for i in range(n_folds):\n fold = list()\n while len(fold) < fold_size:\n index = randrange(len(dataset_copy))\n fold.append(dataset_copy.pop(index))\n dataset_split.append(fold)\n return dataset_split\n\n# calculate accuracy percentage\ndef accuracy_metric(actual, predicted):\n\tcorrect = 0\n\tfor i in range(len(actual)):\n\t\tif actual[i] == predicted[i]:\n\t\t\tcorrect += 1\n\treturn correct / float(len(actual)) * 100.0\n\n# evaluate an algorithm using a cross validation split\ndef evaluate_algorithm(dataset, algorithm, n_folds, *args):\n folds = cross_validation_split(dataset, n_folds)\n scores = list()\n for fold in folds:\n train_set = list(folds)\n train_set.remove(fold)\n train_set = sum(train_set, [])\n test_set = list()\n for row in fold:\n row_copy = list(row)\n test_set.append(row_copy)\n row_copy[-1] = None\n predicted = algorithm(train_set, test_set, *args)\n actual = [row[-1] for row in fold]\n accuarcay = accuracy_metric(actual, predicted)\n scores.append(accuarcay)\n return scores\n\n'''\nThis section will be to test then determine the splits in a given \ndataset. Then the Gini index will be calculated.\n'''\n\n# Split dataset based on an attribute and its value\ndef test_split(index, value, dataset):\n left, right = list(), list()\n for row in dataset:\n if row[index] < value:\n left.append(row)\n else:\n right.append(row)\n # note: right contains all rows with value at index\n # greater than or equal to split value\n return left, right\n\n# Calculate the Gini index (cost function used to evaluate splits)\ndef gini_index(groups, classes):\n # count all samples at a split point\n n_instances = float (sum([len(group) for group in groups]))\n # sum weighted Gini index for each group\n gini = 0.0\n for group in groups:\n size = float(len(group))\n # no divide by zero\n if size == 0:\n continue\n score = 0.0\n # score the group based on the score for each class\n for class_val in classes:\n p = [row[-1] for row in group].count(class_val) / size\n score += p * p\n # weight the group score by its relative size\n gini += (1.0 - score) * (size / n_instances)\n return gini\n\n# test Gini values\n# Worst case, 0.5\n#print (gini_index([[[1, 1], [1, 0]], [[1, 1], [1, 0]]], [0, 1]))\n# Best case, 0.0\n#print (gini_index([[[1, 0], [1, 0]], [[1, 1], [1, 1]]], [0, 1]))\n\n# Choose best split point for the dataset via exhaustive, greedy algorithm\ndef get_split(dataset):\n class_values = list(set(row[-1] for row in dataset))\n b_index, b_value, b_score, b_groups = 999, 999, 999, None\n for index in range(len(dataset[0])-1):\n for row in dataset:\n groups = test_split((index), row[index], dataset)\n gini = gini_index(groups, class_values)\n if gini < b_score:\n b_index, b_value, b_score, b_groups = index, row[index], gini, groups\n return {'index':b_index, 'value':b_value, 'score':b_score, 'groups':b_groups}\n\n'''\nThe following section will be building the tree.\n'''\n\n# create the tree's terminal node (point where we know to stop building) value\ndef to_terminal(group):\n # select a class value for a group of rows\n outcomes = [row[-1] for row in group]\n # return most common output valuein list of rows\n return max(set(outcomes), key=outcomes.count)\n\n# create child splits for a node, or make a terminal node\ndef split(node, max_depth, min_size, depth):\n left, right = node['groups']\n del(node['groups'])\n # check for a no-split\n if not left or not right:\n node['left'] = node['right'] = to_terminal(left+right)\n return\n # check for max deoth\n if depth >= max_depth:\n node['left'], node['right'] = to_terminal(left), to_terminal(right)\n return\n # process the left child\n if len(left) <= to_terminal(left):\n node['left'] = to_terminal(left)\n else:\n node['left'] = get_split(left)\n split(node['left'], max_depth, min_size, depth+1)\n # process the right child\n if len(right) <= to_terminal(right):\n node['right'] = to_terminal(right)\n else:\n node['right'] = get_split(right)\n split(node['right'], max_depth, min_size, depth+1)\n\n# build decision tree by creating the root node and use split() to recursively build\ndef build_tree(train, max_depth, min_size):\n root = get_split(train)\n split(root, max_depth, min_size, 1)\n return root\n\n# print the decision tree\ndef print_tree(node, depth=0):\n if isinstance(node, dict):\n print('%s[X%d < %.3f]' % ((depth*' ', (node['index']+1), node['value'])))\n print_tree(node['left'], depth+1)\n print_tree(node['right'], depth+1)\n else:\n print('%s[%s]' % ((depth*' ', node)))\n \n# make prediction with the decision tree\ndef predict(node, row):\n if row[node['index']] < node['value']:\n if isinstance(node['left'], dict):\n return predict(node['left'], row)\n else:\n return node['left']\n else:\n if isinstance(node['right'], dict):\n return predict(node['right'], row)\n else:\n return node['right']\n \n# classification and regression algorithm\ndef decision_tree(train, test, max_depth, min_size):\n tree = build_tree(train, max_depth, min_size)\n predictions = list()\n for row in test:\n prediction = predict(tree, row)\n predictions.append(prediction)\n return(predictions)\n\n#test CART on banknote dataset\nseed(1)\n# load and prepare data\n# using absolute path\nfilename = '/Users/azhmakin/Documents/projects/own/university/pyCART/data_banknote_authentication.csv'\ndataset = load_csv(filename)\n# convert string attributes to integers\nfor i in range(len(dataset[0])):\n\tstr_column_to_float(dataset, i)\n# evaluate algorithm\nn_folds = 5\nmax_depth = 5\nmin_size = 10\nscores = evaluate_algorithm(dataset, decision_tree, n_folds, max_depth, min_size)\nprint('Scores: %s' % scores)\nprint('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))\n\n'''\n# test datasplitting process with a contirved dataset\ndataset = [[2.771244718,1.784783929,0],\n\t[1.728571309,1.169761413,0],\n\t[3.678319846,2.81281357,0],\n\t[3.961043357,2.61995032,0],\n\t[2.999208922,2.209014212,0],\n\t[7.497545867,3.162953546,1],\n\t[9.00220326,3.339047188,1],\n\t[7.444542326,0.476683375,1],\n\t[10.12493903,3.234550982,1],\n\t[6.642287351,3.319983761,1]]\n\n# look at the decision tree\n#tree = build_tree(dataset, 1, 1)\n#print_tree(tree)\n\n#predict with a decision stump\nstump = {'index': 0, 'right': 1, 'value': 6.642287351, 'left': 0}\nfor row in dataset:\n prediction = predict(stump, row)\n print('Expected=%d, Got=%d' % (row[-1], prediction))\n'''\n","sub_path":"lab-3/classification-regression-tree/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":7609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"378310114","text":"import queue \n\ndef topological_sort(graph, result): \n indegree = [0] * (V)\n zero_indegree = queue.PriorityQueue()\n for u in range(V): \n for v in graph[u]: \n indegree[v] += 1\n \n for i in range(V): \n if indegree[i] == 0: \n zero_indegree.put(i)\n \n while not zero_indegree.empty(): \n u = zero_indegree.get()\n result.append(u)\n for v in graph[u]: \n indegree[v] -= 1\n if indegree[v] == 0: \n zero_indegree.put(v)\n\n for i in range(V): \n if indegree[i] != 0: \n return False\n\n return True\n\n\nif __name__ == \"__main__\": \n V, E = map(int, input().split())\n graph = [[] for i in range(V+5)]\n result = []\n\n for i in range(E): \n u, v = map(int, input().split())\n graph[u].append(v)\n\n if (topological_sort(graph, result)): \n print(\"yes\")\n else: \n print('no')","sub_path":"Orange/Topological_Sort/Course_Schedule.py","file_name":"Course_Schedule.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"541536339","text":"from lightgbm.sklearn import LGBMRegressor\n\ndef model4():\n '''LGBM Regressor\n '''\n best_params = {'subsample_for_bin': 55000,\n 'reg_lambda': 0.00021,\n 'num_leaves': 38,\n #'n_estimators': 4000,\n 'n_estimators': 1500,\n 'min_split_gain': 0.016541324831994497,\n 'max_depth': 8,\n 'learning_rate': 0.05,\n #'learning_rate': 0.042333333333333334,\n 'boosting_type': 'gbdt'\n }\n model = LGBMRegressor(**best_params)\n\n return model","sub_path":"src/models/model4.py","file_name":"model4.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18721390","text":"\"\"\"The main server.\"\"\"\nimport socket\nimport threading\n\n\nclass Server(threading.Thread):\n def __init__(self, host='192.168.1.201', port=26500, buffsize=1024):\n self.client_dict = dict()\n self.game_exit = False\n self.i = 0\n\n def add_client(self, ip, port):\n \"\"\"Register client.\"\"\"\n self.client_dict.setdefault(port, ip)\n self.i += 1\n if self.i == 3:\n self.game_exit = True\n\n def remove_client(self, port):\n \"\"\"Unregister client.\"\"\"\n del self.client_dict[port]\n\n\nclass UDPhandler(threading.Thread):\n \"\"\"The main server class.\"\"\"\n\n def __init__(self, host='192.168.1.201', port=26500, buffsize=1024):\n \"\"\"Set the server constants.\"\"\"\n threading.Thread.__init__(self)\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.address = (host, port)\n self.buffersize = buffsize\n self.sock.bind(self.address)\n self.server = Server()\n self.client_dict = dict()\n self.client_list = list()\n self.client_states = dict()\n\n def run(self):\n \"\"\"Run the main loop.\"\"\"\n while not self.server.game_exit:\n state, address = self.sock.recvfrom(self.buffersize)\n ip = address[0]\n port = address[1]\n self.server.add_client(ip, port)\n self.client_dict = self.server.client_dict\n print(self.client_dict)\n print(state)\n if state is None:\n break\n self.sock.sendto(state, address)\n\n def stop(self):\n self.instance.game_exit.set()\n\n\nif __name__ == '__main__':\n server = UDPhandler()\n server.start()\n","sub_path":"core/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"518991649","text":"import tempfile\nimport boto3\nfrom PIL import Image\nfrom chalice import Chalice\n\napp = Chalice(app_name='chalice_image_thumbnails-2', debug=True)\ns3_client = boto3.client('s3')\n\n@app.on_s3_event(bucket='my-imagedemo-bucket',\n suffix='.jpg')\ndef resize_image(event):\n app.log.debug('Resizing the image from s3://%s/%s', \n event.bucket, event.key)\n with tempfile.NamedTemporaryFile('w') as f:\n s3_client.download_file(event.bucket, event.key, f.name)\n resized_file = f.name + '.thumbnail.jpg'\n with Image.open(f.name) as image:\n image.thumbnail((256,256))\n image.save(resized_file)\n s3_client.upload_file(\n Filename=resized_file,\n Bucket='my-thumbnail-bucket',\n Key=resized_file.rsplit(\"/\", 1)[-1]\n )\n\n","sub_path":"img-thumb/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443303069","text":"\r\ndef notdivisible(n):\r\n le = len(str(n))\r\n digit = [None]*le\r\n for i in range(0,le):\r\n d = n%10\r\n digit[i] = d\r\n n = n - n%10\r\n n = n/10\r\n Redigit = digit[::-1]\r\n if Redigit == digit:\r\n return True\r\n else:\r\n return False\r\ndef primes(x):\r\n digit = [None]*x\r\n for i in range(0,x):\r\n digit[i] = i\r\n\r\n it = filter(notdivisible, digit)\r\n d = list(it)\r\n print (d)\r\nprimes(1911)\r\n","sub_path":"ST_python/f2.py","file_name":"f2.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"220572178","text":"import time\n\ntotientDict = dict()\n\ndef primeMaker(x):\n \"all primes under x\" \n directory = [2]\n isPrime = True\n for i in range(2,x):\n y = int(i**0.5)+1\n isPrime = True\n if i%2 == 0:\n pass\n else:\n for j in range(3, y, 2):\n if i%j == 0:\n isPrime = False\n break\n if(isPrime):\n directory.append(i)\n\n return directory\n\ndef totient(number, pVals, pValsChecker):\n global totientDict\n isPrime = True\n if number in pVals:\n totientDict[number] *= (1 - (1/number))\n return 0\n # for i in pValsChecker:\n # if number%i == 0:\n # isPrime = False\n # break\n # if isPrime:\n # totientDict[number] *= (1-(1/number))\n # return 0\n \n nummy = number\n while nummy != 1:\n if number == 2018:\n print(nummy)\n for i in pValsChecker:\n if nummy%i == 0:\n nummy /= i\n totientDict[number] *= (1 - (1/i))\n while(nummy%i == 0):\n nummy /= i\n break\n return 0 \n\ndef main():\n global totientDict\n t0 = time.time()\n print(\"hello\")\n # Hashing Procedure\n keys = range(1000000)\n totientDict = dict(zip(keys,keys))\n pValsChecker = primeMaker(1000000)\n pVals = set(pValsChecker)\n desiredval = 0 \n n = 0\n for number in range(2,1000000):\n totient(number, pVals, pValsChecker)\n print(number, totientDict[number])\n if(number/totientDict[number] > desiredval):\n n = number\n desiredval = number/totientDict[number]\n print(\"total time: \", time.time()-t0)\n print(\"answer is \", n, desiredval)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Problems 60-69/Problem69.py","file_name":"Problem69.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138800929","text":"import cv2\nimport numpy as np\n\nfrom fileHandle import *\nfrom ssim import Thumbnail_3\n\nitem_sample = load_data('.\\\\DATA\\\\dropItemSample.dat')\nfurn_sample = load_data('.\\\\DATA\\\\furnSample.dat')\n# for i in item_sample:\n# i['img'].reset()\n# furn_sample['k'].reset()\n# save_data(item_sample, '.\\\\data\\\\dropItemSample.dat')\n# save_data(furn_sample, '.\\\\data\\\\furnSample.dat')\nfor i in item_sample:\n i['img'].initial()\nfurn_sample['k'].initial()\n# print('Item sample initialed.')\n\nsample_size = 20\nfurn_sample_size = 40\ndhash_sample_size = 80\n\n\ndef item_match(item_img):\n thumbnail = Thumbnail_3(cv2.resize(item_img, (sample_size, sample_size)))\n result = np.zeros(len(item_sample), dtype=np.float64)\n for k in range(len(item_sample)):\n sample_img = item_sample[k]['img']\n result[k] = thumbnail - sample_img\n\n target = np.argmax(result)\n target_ssim = result[target]\n\n result.sort()\n\n return item_sample[target]['id'], target_ssim, result[-1] - result[-2]\n\n\ndef is_furniture(item_img):\n test = cv2.resize(item_img, (furn_sample_size, furn_sample_size))\n test = test * furn_sample['w']\n test = Thumbnail_3(test)\n test = test - furn_sample['k']\n return test\n","sub_path":"matchItem.py","file_name":"matchItem.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"621012885","text":"# -*- coding: utf-8 -*-\n# flake8: noqa\n\nfrom plone import api\nfrom zope.i18nmessageid import MessageFactory\n\nimport re\n\n_ = MessageFactory('EasyNewsletter')\n\nPROJECTNAME = 'EasyNewsletter'\n\nENL_ISSUE_TYPES = ['Newsletter Issue']\nENL_EDITHELPER_TYPES = ['Newsletter', 'Newsletter Issue']\n\nSALUTATION = {\n 'ms': _(u'label_salutation_ms', 'Ms.'),\n 'mr': _(u'label_salutation_mr', 'Mr.'),\n}\n\n# NL_LANGUAGE = DisplayList((\n# ('', _(u'label_choose_nl_language', 'Choose language...')),\n# ('de', _(u'label_salutation_de', 'DE')),\n# ('en', _(u'label_salutation_en', 'EN')),\n# ('fr', _(u'label_salutation_fr', 'FR')),\n# ))\n\nMESSAGE_CODE = {\n 'email_added': _(\n u'Your email has been registered. A confirmation email was'\n u' sent to your address. Please check your inbox and click '\n u' on the link in the email in order to confirm your'\n u' subscription.'\n ),\n 'invalid_email': _(\n u'Please enter a valid email address.'),\n 'email_exists': _(\n u'Your email address is already registered.'),\n 'invalid_hashkey': _(\n u'Please enter a valid email address.'),\n 'subscription_confirmed': _(\n u'Your subscription was successfully confirmed.'),\n}\n\nEMAIL_RE = re.compile(\n r\"(?:^|\\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\\.)+[a-z]{2,63}(?:\\s|$)\", re.IGNORECASE)\n","sub_path":"src/Products/EasyNewsletter/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"614516588","text":"\"\"\"ESTE MODULO SIRVE PARA LOS NUMEROS INGRESADOS NO SEAN LETRAS\"\"\"\nimport unittest\nfrom decimal_hexadecimal import hexad_to_decimal\n\n\nclass TestInterfaz(unittest.TestCase):\n def test_decimal_hola_to_hexadecimal_(self):\n hexad_number = hexad_to_decimal('hola')\n self.assertEqual(result, 'Disculpe, solo acepto numeros')\nif __name__ == '__main__':\n unittest.main()","sub_path":"58105-franco-santander/parcial01/test_interfaz_decimal.py","file_name":"test_interfaz_decimal.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213515127","text":"# -*- coding: utf-8 -*-\nimport pymysql\nfrom numpy import mat\nfrom ast import literal_eval\n\nclass DBConn:\n\n # 建構式\n def __init__(self):\n\n self.host = '52.78.68.151'\n self.user = 'dbm'\n self.passwd = '5j0 wu654yji4'\n self.dbname = 'warofdata'\n '''\n self.host = 'stevie.heliohost.org'\n self.user = 'datawar_user1'\n self.passwd = '[QzJUoHwFtq0'\n self.dbname = 'datawar_warofdata1'\n '''\n\n\n # 建立連線\n def open(self):\n self.db = pymysql.connect(self.host, self.user, self.passwd, self.dbname, charset='utf8')\n self.db.autocommit(True)\n self.cursor = self.db.cursor()\n self.cursor.execute(\"SET TIME_ZONE = '+08:00'\")\n\n # 關閉連線\n def close(self):\n self.cursor.close()\n self.db.close()\n\n # ========== RESTAURANT ==========\n # 傳回餐廳全部的資料\n def getRestaurantsAll(self):\n #SQL query\n self.cursor.execute(\"SELECT restaurant_id, name, address, \"\n \"(SELECT GROUP_CONCAT(has ORDER BY price_id) FROM restaurantPrice P WHERE P.restaurant_id = I.restaurant_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY ordering_id) FROM restaurantOrdering O WHERE O.restaurant_id = I.restaurant_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY cuisine_id) FROM restaurantCuisine C WHERE C.restaurant_id = I.restaurant_id), \"\n \"scenario, special, phone, hours1, remark, \"\n \"(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.restaurant_id = I.restaurant_id) FROM restaurantInfo I ORDER BY restaurant_id\")\n result = self.cursor.fetchall()\n\n # 宣告空list\n lists = []\n\n for record in result:\n # ┌─────┬──────┬─────────┬─────────┬──────────┬─────────┬──────────┬─────────┬───────┬────────┬────────┐\n # │ rid │ name │ address │ price │ ordering │ cuisine │ scenario │ special │ phone │ hours │ remark │\n # │ 編號 │ 店名 │ 地址   │ 均價區間 │ 點菜方式  │ 菜式   │ 用餐情境  │ 招牌菜  │ 電話  │ 營業時間 │ 備註  │\n # └─────┴──────┴─────────┴─────────┴──────────┴─────────┴──────────┴─────────┴───────┴────────┴────────┘\n # 字串格式為unicode\n # 電話、營業時間有可能為空值(NULL), DB會回傳None\n\n # [0~100, 100~200, 200~300, 300~500, 500~]\n price = list(literal_eval(record[3]))\n\n # [單點, 吃到飽, 套餐, 合菜, 簡餐]\n ordering = list(literal_eval(record[4]))\n\n # [中式料理, 日式料理, 韓式料理, 泰式料理, 異國料理, 燒烤, 鍋類, 小吃, 便當, 冰品、甜點、下午茶]\n cuisine = list(literal_eval(record[5]))\n\n # ['用餐情境', ...]\n scenario = literal_eval(record[6])\n\n # ['招牌菜', ...]\n special = literal_eval(record[7])\n\n # {星期幾: ['開門時間~關門時間', ...], ...}\n hours = literal_eval(record[9]) if record[9] is not None else None\n\n # ['備註', ...]\n remark = literal_eval(record[10])\n\n # ['tag', ...]\n tags = [x for x in record[11].split(',')] if record[11] is not None else []\n\n # 每筆資料用dict存\n dict = {'rid': record[0], 'name': record[1], 'address': record[2], 'price': price, 'ordering': ordering, 'cuisine': cuisine,\n 'scenario': scenario, 'special': special, 'phone': record[8], 'hours': hours, 'remark': remark, 'tags': tags}\n\n # 把每筆資料存到list\n lists.append(dict)\n\n # 回傳\n return lists\n\n # 傳回餐廳的數值化資料: ID, 價格, 點菜方式, 菜式, 營業時間\n def getRestaurantsNum(self):\n # SQL query\n self.cursor.execute(\"SELECT restaurant_id, \"\n \"(SELECT GROUP_CONCAT(has ORDER BY price_id) FROM restaurantPrice P WHERE P.restaurant_id = I.restaurant_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY ordering_id) FROM restaurantOrdering O WHERE O.restaurant_id = I.restaurant_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY cuisine_id) FROM restaurantCuisine C WHERE C.restaurant_id = I.restaurant_id), \"\n \"hours1, (SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.restaurant_id = I.restaurant_id) \"\n \"FROM restaurantInfo I ORDER BY restaurant_id\")\n result = self.cursor.fetchall()\n\n # 宣告空list\n lists = []\n\n for record in result:\n\n # [0~100, 100~200, 200~300, 300~500, 500~]\n price = list(literal_eval(record[1]))\n\n # [單點, 吃到飽, 套餐, 合菜, 簡餐]\n ordering = list(literal_eval(record[2]))\n\n # [中式料理, 日式料理, 韓式料理, 泰式料理, 異國料理, 燒烤, 鍋類, 小吃, 便當, 冰品、甜點、下午茶]\n cuisine = list(literal_eval(record[3]))\n\n # {星期幾: ['開門時間~關門時間', ...], ...}\n hours = literal_eval(record[4]) if record[4] is not None else None\n\n # ['tag', ...]\n tags = [x for x in record[5].split(',')] if record[5] is not None else []\n\n # 每筆資料用dict存\n dict = {'rid': record[0], 'price': price, 'ordering': ordering, 'cuisine': cuisine, 'hours': hours, 'tags': tags}\n\n # 把每筆資料存到list\n lists.append(dict)\n\n # 回傳\n return lists\n\n # 傳回指定餐廳的數值化資料: 價格, 點菜方式, 菜式, 營業時間\n def getRestaurantNumWithID(self, rid):\n # SQL query\n self.cursor.execute(\"SELECT restaurant_id, \"\n \"(SELECT GROUP_CONCAT(has ORDER BY price_id) FROM restaurantPrice P WHERE P.restaurant_id = I.restaurant_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY ordering_id) FROM restaurantOrdering O WHERE O.restaurant_id = I.restaurant_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY cuisine_id) FROM restaurantCuisine C WHERE C.restaurant_id = I.restaurant_id), \"\n \"hours1, (SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.restaurant_id = I.restaurant_id) \"\n \"FROM restaurantInfo I WHERE restaurant_id = %s\", rid)\n\n # DB回傳的結果為空(rid錯誤)\n if self.cursor.rowcount == 0:\n return []\n\n record = self.cursor.fetchall()[0]\n\n # [0~100, 100~200, 200~300, 300~500, 500~]\n price = list(literal_eval(record[1]))\n\n # [單點, 吃到飽, 套餐, 合菜, 簡餐]\n ordering = list(literal_eval(record[2]))\n\n # [中式料理, 日式料理, 韓式料理, 泰式料理, 異國料理, 燒烤, 鍋類, 小吃, 便當, 冰品、甜點、下午茶]\n cuisine = list(literal_eval(record[3]))\n\n # {星期幾: ['開門時間~關門時間', ...], ...}\n hours = literal_eval(record[4]) if record[4] is not None else None\n\n # ['tag', ...]\n tags = [x for x in record[5].split(',')] if record[5] is not None else []\n\n # 每筆資料用dict存\n dict = {'rid': record[0], 'price': price, 'ordering': ordering, 'cuisine': cuisine, 'hours': hours, 'tags': tags}\n\n return dict\n\n # 傳回餐廳的文字資訊\n def getRestaurantsInfo(self):\n # SQL query\n self.cursor.execute('SELECT restaurant_id, name, address, price, ordering, cuisine, scenario, special, phone, hours, remark, '\n '(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.restaurant_id = I.restaurant_id) FROM restaurantInfo I ORDER BY restaurant_id')\n result = self.cursor.fetchall()\n\n # 宣告空list\n list = []\n\n for record in result:\n\n # ['點菜方式', ...]\n ordering = literal_eval(record[4])\n\n # ['菜式', ...]\n cuisine = literal_eval(record[5])\n\n # ['用餐情境', ...]\n scenario = literal_eval(record[6])\n\n # ['招牌菜', ...]\n special = literal_eval(record[7])\n\n # ['備註', ...]\n remark = literal_eval(record[10])\n\n # ['tag', ...]\n tags = [x for x in record[11].split(',')] if record[11] is not None else []\n\n # 每筆資料用dict存\n dict = {'rid': record[0], 'name': record[1], 'address': record[2], 'price': record[3], 'ordering': ordering, 'cuisine': cuisine,\n 'scenario': scenario, 'special': special, 'phone': record[8], 'hours': record[9], 'remark': remark, 'tags': tags}\n\n # 把每筆資料存到list\n list.append(dict)\n\n # 回傳\n return list\n\n # 傳回多間餐廳的文字資訊 list:[rid1, rid2, ...]\n def getRestaurantInfoWithIDs(self, list):\n\n\n # SQL query\n self.cursor.execute('SELECT restaurant_id, name, address, price, ordering, cuisine, scenario, special, phone, hours, remark, '\n '(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.restaurant_id = I.restaurant_id) '\n 'FROM restaurantInfo I WHERE restaurant_id IN (' + ', '.join('%s' for x in range(len(list))) + ') ORDER BY restaurant_id', list)\n result = self.cursor.fetchall()\n\n # 宣告空list\n list = []\n\n for record in result:\n\n # ['點菜方式', ...]\n ordering = literal_eval(record[4])\n\n # ['菜式', ...]\n cuisine = literal_eval(record[5])\n\n # ['用餐情境', ...]\n scenario = literal_eval(record[6])\n\n # ['招牌菜', ...]\n special = literal_eval(record[7])\n\n # ['備註', ...]\n remark = literal_eval(record[10])\n\n # ['tag', ...]\n tags = [x for x in record[11].split(',')] if record[11] is not None else []\n\n # 每筆資料用dict存\n dict = {'rid': record[0], 'name': record[1], 'address': record[2], 'price': record[3], 'ordering': ordering, 'cuisine': cuisine,\n 'scenario': scenario, 'special': special, 'phone': record[8], 'hours': record[9], 'remark': remark, 'tags': tags}\n\n # 把每筆資料存到list\n list.append(dict)\n\n # 回傳\n return list\n\n # 傳回餐廳的文字資訊\n def getRestaurantInfoWithID(self, rid):\n # SQL query\n self.cursor.execute('SELECT restaurant_id, name, address, price, ordering, cuisine, scenario, special, phone, hours, remark, '\n '(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.restaurant_id = I.restaurant_id) '\n 'FROM restaurantInfo I WHERE restaurant_id = %s', rid)\n\n # DB回傳的結果為空(rid錯誤)\n if self.cursor.rowcount == 0:\n return []\n\n record = self.cursor.fetchall()[0]\n\n # ['點菜方式', ...]\n ordering = literal_eval(record[4])\n\n # ['菜式', ...]\n cuisine = literal_eval(record[5])\n\n # ['用餐情境', ...]\n scenario = literal_eval(record[6])\n\n # ['招牌菜', ...]\n special = literal_eval(record[7])\n\n # ['備註', ...]\n remark = literal_eval(record[10])\n\n # ['tag', ...]\n tags = [x for x in record[11].split(',')] if record[11] is not None else []\n\n # 每筆資料用dict存\n dict = {'rid': record[0], 'name': record[1], 'address': record[2], 'price': record[3], 'ordering': ordering, 'cuisine': cuisine,\n 'scenario': scenario, 'special': special, 'phone': record[8], 'hours': record[9], 'remark': remark, 'tags': tags}\n\n return dict\n\n # 傳回兩間餐廳的距離\n def getRestaurantDistance(self, rid1, rid2):\n # 同一間餐廳的距離為1\n if rid1 == rid2:\n return 1\n\n # DB的儲存方式為rid1 < rid2\n if rid1 > rid2:\n rid1, rid2 = rid2, rid1\n\n # SQL query\n self.cursor.execute('SELECT distance FROM restaurantDistance WHERE restaurant_id1 = %s AND restaurant_id2 = %s', (rid1, rid2))\n\n # DB回傳的結果為空(rid錯誤)\n if self.cursor.rowcount == 0:\n return -1\n\n return self.cursor.fetchall()[0][0]\n\n\n # ========== USER ==========\n # 新增使用者的基本資訊\n def insertUserInfo(self, name, gender, account, password):\n # SQL query\n self.cursor.execute('INSERT INTO userInfo(name, gender, account, password) VALUES(%s, %s, %s, %s)', (name, gender, account, password))\n\n uid = self.cursor.lastrowid\n\n # 初始化userPrice, userOrdering, userCuisine\n self.cursor.execute('INSERT INTO userPrice(user_id, price_id, has) VALUES' + ', '.join(['(%s, ' + str(id) + ', 0)' for id in range(1, 6)]) + ';'\n 'INSERT INTO userOrdering(user_id, ordering_id, has) VALUES' + ', '.join(['(%s, ' + str(id) + ', 0)' for id in range(1, 6)]) + ';'\n 'INSERT INTO userCuisine(user_id, cuisine_id, has) VALUES' + ', '.join(['(%s, ' + str(id) + ', 0)' for id in range(1, 11)]) + ';',\n ((uid, ) * 20))\n # 回傳他的uid\n return uid\n\n # 傳回所有使用者的資訊\n def getUsersInfo(self):\n # SQL query price ordering cuisine\n self.cursor.execute(\"SELECT user_id, name, gender, account, password, \"\n \"(SELECT GROUP_CONCAT(has ORDER BY price_id) FROM userPrice P WHERE P.user_id = I.user_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY ordering_id) FROM userOrdering O WHERE O.user_id = I.user_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY cuisine_id) FROM userCuisine C WHERE C.user_id = I.user_id), \"\n \"(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.user_id = I.user_id) \"\n \"FROM userInfo I ORDER BY user_id\")\n result = self.cursor.fetchall()\n\n # 宣告空list\n lists = []\n\n for record in result:\n\n price = list(literal_eval(record[5]))\n\n ordering = list(literal_eval(record[6]))\n\n cuisine = list(literal_eval(record[7]))\n\n tags = [x for x in record[8].split(',')] if record[8] is not None else []\n\n # 每筆資料用dict存\n dict = {'uid': record[0], 'name': record[1], 'gender': record[2], 'account': record[3], 'password': record[4],\n 'price': price, 'ordering': ordering, 'cuisine': cuisine, 'tags': tags}\n\n # 把每筆資料存到list\n lists.append(dict)\n\n return lists\n\n # 傳回使用者的基本資訊\n def getUserInfoWithID(self, uid):\n # SQL query price ordering cuisine\n self.cursor.execute(\"SELECT user_id, name, gender, account, password, \"\n \"(SELECT GROUP_CONCAT(has ORDER BY price_id) FROM userPrice P WHERE P.user_id = I.user_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY ordering_id) FROM userOrdering O WHERE O.user_id = I.user_id), \"\n \"(SELECT GROUP_CONCAT(has ORDER BY cuisine_id) FROM userCuisine C WHERE C.user_id = I.user_id), \"\n \"(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags T WHERE T.user_id = I.user_id) \"\n \"FROM userInfo I WHERE user_id = %s\", uid)\n\n # DB回傳的結果為空(rid錯誤)\n if self.cursor.rowcount == 0:\n return []\n\n record = self.cursor.fetchall()[0]\n\n price = list(literal_eval(record[5]))\n\n ordering = list(literal_eval(record[6]))\n\n cuisine = list(literal_eval(record[7]))\n\n tags = [x for x in record[8].split(',')] if record[8] is not None else []\n\n # 每筆資料用dict存\n dict = {'uid': record[0], 'name': record[1], 'gender': record[2], 'account': record[3], 'password': record[4],\n 'price': price, 'ordering': ordering, 'cuisine': cuisine, 'tags': tags}\n\n return dict\n\n # 傳回使用者的帳號\n def getUserAccountWithID(self, uid):\n # SQL query\n self.cursor.execute('SELECT account FROM userInfo WHERE user_id = %s', uid)\n\n return self.cursor.fetchall()[0][0]\n\n # 傳回使用者的ID\n def getUserIDWithAccount(self, account):\n # SQL query\n self.cursor.execute('SELECT user_id FROM userInfo WHERE account = %s', account)\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return None\n\n return self.cursor.fetchall()[0][0]\n\n # 修改使用者的price屬性\n def updateUserPriceWithID(self, uid, price_id, value):\n # SQL query\n self.cursor.execute('UPDATE userPrice SET has = has + %s WHERE user_id = %s AND price_id = %s', (value, uid, price_id))\n\n # 修改使用者的ordering屬性\n def updateUserOrderingWithID(self, uid, ordering_id, value):\n # SQL query\n self.cursor.execute('UPDATE userOrdering SET has = has + %s WHERE user_id = %s AND ordering_id = %s', (value, uid, ordering_id))\n\n # 修改使用者的cuisine屬性\n def updateUserCuisineWithID(self, uid, cuisine_id, value):\n # SQL query\n self.cursor.execute('UPDATE userCuisine SET has = has + %s WHERE user_id = %s AND cuisine_id = %s', (value, uid, cuisine_id))\n\n # 新增使用者的活動(run:第幾次 result:接受(1)、收藏(0)、拒絕(-1))\n def insertUserActivity(self, uid, rid, run, result):\n # 接受 price ordering cuisine增加\n if result == 1:\n self.cursor.execute('INSERT INTO userActivity(user_id, restaurant_id, run, result) VALUES(%s, %s, %s, %s);'\n 'UPDATE userPrice AS A INNER JOIN restaurantPrice AS B USING(price_id) '\n 'SET A.has = A.has + B.has WHERE user_id = %s AND restaurant_id = %s;'\n 'UPDATE userOrdering AS A INNER JOIN restaurantOrdering AS B USING(ordering_id) '\n 'SET A.has = A.has + B.has WHERE user_id = %s AND restaurant_id = %s;'\n 'UPDATE userCuisine AS A INNER JOIN restaurantCuisine AS B USING(cuisine_id) '\n 'SET A.has = A.has + B.has WHERE user_id = %s AND restaurant_id = %s;',\n (uid, rid, run, result, uid, rid, uid, rid, uid, rid))\n # 收藏\n elif result == 0:\n self.cursor.execute('INSERT INTO userActivity(user_id, restaurant_id, run, result) VALUES(%s, %s, %s, %s);'\n 'INSERT INTO userCollection(user_id, restaurant_id) VALUES(%s, %s) '\n 'ON DUPLICATE KEY UPDATE timestamp = NOW()', (uid, rid, run, result, uid, rid))\n # 拒絕\n elif result == -1:\n self.cursor.execute('INSERT INTO userActivity(user_id, restaurant_id, run, result) VALUES(%s, %s, %s, %s)', (uid, rid, run, result))\n\n # 傳回使用者最後n個接受的餐廳\n def getUserActivityAcceptWithID(self, uid, n):\n # SQL query\n self.cursor.execute('SELECT restaurant_id FROM userActivity WHERE user_id = %s AND result = 1 ORDER BY timestamp DESC LIMIT %s', (uid, n))\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return []\n\n return [x[0] for x in self.cursor.fetchall()]\n\n # 傳回使用者接受和拒絕的餐廳數量\n def getUserActivityCountWithID(self, uid):\n # SQL query\n self.cursor.execute('SELECT COUNT(*) FROM userActivity WHERE user_id = %s AND (result = 1 OR result = -1)', (uid))\n\n return self.cursor.fetchall()[0][0]\n\n # 新增/更新使用者的各項分數\n def insertUserModelWithID(self, uid, price, ordering, cuisine):\n\n priceStr = str(price)\n orderingStr = str(ordering)\n cuisineStr = str(cuisine)\n\n # SQL query\n self.cursor.execute('INSERT INTO userModel(user_id, priceScore, orderingScore, cuisineScore) VALUES(%s, %s, %s, %s)',\n (uid, priceStr, orderingStr, cuisineStr))\n\n # 傳回使用者最新的各項分數\n def getUserModelWithID(self, uid):\n # SQL query\n self.cursor.execute('SELECT user_id, priceScore, orderingScore, cuisineScore FROM userModel WHERE user_id = %s ORDER BY timestamp DESC LIMIT 1', uid)\n\n record = self.cursor.fetchall()[0]\n\n price = literal_eval(record[1])\n\n ordering = literal_eval(record[2])\n\n cuisine = literal_eval(record[3])\n\n # 每筆資料用dict存\n dict = {'uid': record[0], 'priceScore': price, 'orderingScore': ordering, 'cuisineScore': cuisine}\n\n return dict\n\n # 傳回預設的使用者起始值\n def getUserAverage(self):\n # SQL query\n self.cursor.execute('SELECT * FROM userAverage')\n\n record = self.cursor.fetchall()[0]\n\n price = literal_eval(record[1])\n\n cuisine = literal_eval(record[2])\n\n ordering = literal_eval(record[3])\n\n # 每筆資料用dict存\n dict = {'price': price, 'cuisine': cuisine, 'ordering': ordering, 'weatherPrio': record[4], 'distancePrio': record[5],\n 'pricePrio': record[6], 'cuisinePrio': record[7], 'soupPrio': record[8], 'ratePrio': record[9]}\n\n return dict\n\n # 新增使用者收藏\n def insertUserCollection(self, uid, rid):\n self.cursor.execute('INSERT INTO userCollection(user_id, restaurant_id) VALUES(%s, %s) '\n 'ON DUPLICATE KEY UPDATE timestamp = NOW()', (uid, rid))\n\n # 傳回使用者收藏的餐廳\n def getUserCollection(self, uid):\n # SQL query\n self.cursor.execute('SELECT restaurant_id FROM userCollection WHERE user_id = %s', uid)\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return []\n\n return [x[0] for x in self.cursor.fetchall()]\n\n # 刪除收藏\n def deleteUserCollection(self, uid, rid):\n # SQL query\n self.cursor.execute('DELETE FROM userCollection WHERE user_id = %s AND restaurant_id = %s', (uid, rid))\n\n def getUserRatio(self, uid):\n # SQL query\n self.cursor.execute('SELECT * FROM (SELECT GROUP_CONCAT(IFNULL(ACC / TOTAL, 0) ORDER BY price_id) FROM (SELECT price_id, SUM(has) AS ACC FROM '\n '(SELECT * FROM userActivity WHERE result = 1) AS A '\n 'NATURAL JOIN (SELECT * FROM restaurantPrice) AS B WHERE user_id = %s GROUP BY price_id) AS C '\n 'NATURAL JOIN (SELECT price_id, SUM(has) AS TOTAL FROM (SELECT * FROM userActivity WHERE result = 1 OR result = -1) AS D '\n 'NATURAL JOIN (SELECT * FROM restaurantPrice) AS E WHERE user_id = %s GROUP BY price_id) AS F) AS G, '\n '(SELECT GROUP_CONCAT(IFNULL(ACC / TOTAL, 0) ORDER BY ordering_id) FROM (SELECT ordering_id, SUM(has) AS ACC FROM '\n '(SELECT * FROM userActivity WHERE result = 1) AS A '\n 'NATURAL JOIN (SELECT * FROM restaurantOrdering) AS B WHERE user_id = %s GROUP BY ordering_id) AS C '\n 'NATURAL JOIN (SELECT ordering_id, SUM(has) AS TOTAL FROM (SELECT * FROM userActivity WHERE result = 1 OR result = -1) AS D '\n 'NATURAL JOIN (SELECT * FROM restaurantOrdering) AS E WHERE user_id = %s GROUP BY ordering_id) AS F) AS H, '\n '(SELECT GROUP_CONCAT(IFNULL(ACC / TOTAL, 0) ORDER BY cuisine_id) FROM (SELECT cuisine_id, SUM(has) AS ACC FROM '\n '(SELECT * FROM userActivity WHERE result = 1) AS A '\n 'NATURAL JOIN (SELECT * FROM restaurantCuisine) AS B WHERE user_id = %s GROUP BY cuisine_id) AS C '\n 'NATURAL JOIN (SELECT cuisine_id, SUM(has) AS TOTAL FROM (SELECT * FROM userActivity WHERE result = 1 OR result = -1) AS D '\n 'NATURAL JOIN (SELECT * FROM restaurantCuisine) AS E WHERE user_id = %s GROUP BY cuisine_id) AS F) AS I',\n (uid, uid, uid, uid, uid, uid))\n\n record = self.cursor.fetchall()[0]\n\n # 該使用者沒資料\n if record[0] is None:\n return {'price': [0.0 for i in range(5)], 'ordering': [0.0 for i in range(5)], 'cuisine': [0.0 for i in range(10)]}\n\n return {'price': list(literal_eval(record[0])), 'ordering': list(literal_eval(record[1])), 'cuisine': list(literal_eval(record[2]))}\n\n # 新增使用者的進階搜尋\n def insertUserAdvanceWithID(self, uid, price, weather, transport, lat, lng):\n\n price = str(price)\n\n # SQL query\n self.cursor.execute('INSERT INTO userAdvance(user_id, prefer_price, weather, transport, lat, lng) VALUES(%s, %s, %s, %s, %s, %s)',\n (uid, price, weather, transport, lat, lng))\n\n # 傳回使用者最近n次的進階搜尋\n def getUserAdvanceWithID(self, uid, n):\n # SQL query\n self.cursor.execute('SELECT * FROM userAdvance WHERE user_id = %s ORDER BY timestamp DESC LIMIT %s', (uid, n))\n\n result = self.cursor.fetchall()\n\n # 宣告空list\n lists = []\n\n for record in result:\n\n # 每筆資料用dict存\n dict = {'uid': record[1], 'price': list(literal_eval(record[2])), 'weather': record[3], 'transport': record[4],\n 'lat': record[5], 'lng': record[6]}\n\n lists.append(dict)\n\n return lists\n\n\n # ========== TAG ==========\n # 新增tag(type: 1喜歡 -1討厭)\n def insertTagWithID(self, uid, rid, tag, type):\n self.cursor.execute('INSERT INTO tags(user_id, restaurant_id, tag, type) VALUES(%s, %s, %s, %s)', (uid, rid, tag, type))\n\n # 新增多筆tag list:[(uid, rid, tag, type), ...]\n def insertTagsWithID(self, list):\n self.cursor.executemany('INSERT INTO tags(user_id, restaurant_id, tag, type) VALUES(%s, %s, %s, %s)', list)\n\n # 傳回某間餐廳的個別tag數量\n def getRestaurantTagCount(self, rid):\n # SQL query\n self.cursor.execute('SELECT tag, COUNT(*) FROM tags WHERE restaurant_id = %s GROUP BY tag', rid)\n return dict(self.cursor.fetchall())\n\n # 傳回有這個tag的餐廳rid\n def getRestaurantWithTag(self, tag):\n # SQL query\n self.cursor.execute('SELECT DISTINCT restaurant_id FROM tags WHERE tag = %s', tag)\n return [x[0] for x in self.cursor.fetchall()]\n\n # 傳回這個tag的總數量\n def getTagCount(self, tag):\n # SQL query\n self.cursor.execute('SELECT COUNT(*) FROM tags WHERE tag = %s', tag)\n return self.cursor.fetchall()[0][0]\n\n\n # ========== SIMILARITY ==========\n # 傳回ordering的相似矩陣\n def getOrderingSimMatrix(self):\n # 矩陣初始化\n matrix = [[0.0 if i != j else 1.0 for i in range(5)] for j in range(5)]\n\n # SQL query\n self.cursor.execute('SELECT * FROM orderingSimilarity')\n result = self.cursor.fetchall()\n\n for record in result:\n matrix[record[0] - 1][record[1] - 1] = record[2]\n matrix[record[1] - 1][record[0] - 1] = record[2]\n\n return mat(matrix)\n\n # 傳回cuisine的相似矩陣\n def getCuisineSimMatrix(self):\n # 矩陣初始化\n matrix = [[0.0 if i != j else 1.0 for i in range(10)] for j in range(10)]\n\n # SQL query\n self.cursor.execute('SELECT * FROM cuisineSimilarity')\n result = self.cursor.fetchall()\n\n for record in result:\n matrix[record[0] - 1][record[1] - 1] = record[2]\n matrix[record[1] - 1][record[0] - 1] = record[2]\n\n return mat(matrix)\n\n # 新增/更新R2R的相似度\n def updateR2RSimilarity(self, rid1, rid2, value):\n # DB的儲存方式為rid1 < rid2\n if rid1 > rid2:\n rid1, rid2 = rid2, rid1\n\n # SQL query\n self.cursor.execute('INSERT INTO R2RSimilarity(restaurant_id1, restaurant_id2, similarity) VALUES(%s, %s, %s) '\n 'ON DUPLICATE KEY UPDATE similarity = %s', (rid1, rid2, value, value))\n\n # 新增/更新多筆R2R的相似度 list:[(rid1, rid2, sim), ...] rid1 < rid2\n def updateR2RSimilarities(self, list):\n param = [((x[1], x[0]) if x[0] > x[1] else (x[0], x[1])) + (x[2], x[2], ) for x in list]\n\n # SQL query\n self.cursor.executemany('INSERT INTO R2RSimilarity(restaurant_id1, restaurant_id2, similarity) VALUES(%s, %s, %s) '\n 'ON DUPLICATE KEY UPDATE similarity = %s', param)\n\n # 傳回兩間餐廳的相似度\n def getR2RSimilarity(self, rid1, rid2):\n # DB的儲存方式為rid1 < rid2\n if rid1 > rid2:\n rid1, rid2 = rid2, rid1\n\n # SQL query\n self.cursor.execute('SELECT similarity FROM R2RSimilarity WHERE restaurant_id1 = %s AND restaurant_id2 = %s', (rid1, rid2))\n\n # DB回傳的結��為空\n if self.cursor.rowcount == 0:\n return -1\n\n return self.cursor.fetchall()[0][0]\n\n # 傳回餐廳對所有餐廳的相似度\n def getR2RSimilarities(self, rid, same=False):\n # SQL query\n if same:\n # 包含rid\n self.cursor.execute('SELECT restaurant_id2, similarity FROM R2RSimilarity WHERE restaurant_id1 = %s UNION '\n 'SELECT restaurant_id1, similarity FROM R2RSimilarity WHERE restaurant_id2 = %s '\n 'ORDER BY restaurant_id2', (rid, rid))\n else:\n # 不包含rid\n self.cursor.execute('SELECT restaurant_id2, similarity FROM R2RSimilarity WHERE restaurant_id1 = %s AND restaurant_id2 != %s UNION '\n 'SELECT restaurant_id1, similarity FROM R2RSimilarity WHERE restaurant_id2 = %s AND restaurant_id1 != %s '\n 'ORDER BY restaurant_id2', (rid, rid, rid, rid))\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return -1\n\n return {key: value for (key, value) in self.cursor.fetchall()}\n\n # 新增/更新U2R的相似度\n def updateU2RSimilarity(self, uid, rid, value):\n # SQL query\n self.cursor.execute('INSERT INTO U2RSimilarity(user_id, restaurant_id, similarity) VALUES(%s, %s, %s) '\n 'ON DUPLICATE KEY UPDATE similarity = %s', (uid, rid, value, value))\n\n # 新增/更新多筆U2R的相似度 list:[(uid, rid, sim), ...]\n def updateU2RSimilarities(self, list):\n param = [x + (x[2],) for x in list]\n\n # SQL query\n self.cursor.executemany('INSERT INTO U2RSimilarity(user_id, restaurant_id, similarity) VALUES(%s, %s, %s) '\n 'ON DUPLICATE KEY UPDATE similarity = %s', param)\n\n # 傳回使用者對餐廳的相似度\n def getU2RSimilarity(self, uid, rid):\n # SQL query\n self.cursor.execute('SELECT similarity FROM U2RSimilarity WHERE user_id = %s AND restaurant_id = %s', (uid, rid))\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return -1\n\n return self.cursor.fetchall()[0][0]\n\n # 傳回使用者對所有餐廳的相似度\n def getU2RSimilarities(self, uid):\n # SQL query\n self.cursor.execute('SELECT similarity FROM U2RSimilarity WHERE user_id = %s ORDER BY restaurant_id', uid)\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return -1\n\n return {key: value for (key, value) in self.cursor.fetchall()}\n\n # 新增/更新U2U的相似度\n def updateU2USimilarity(self, uid1, uid2, value):\n # DB的儲存方式為uid1 < uid2\n if uid1 > uid2:\n rid1, rid2 = uid2, uid1\n\n # SQL query\n self.cursor.execute('INSERT INTO U2USimilarity(user_id1, user_id2, similarity) VALUES(%s, %s, %s) '\n 'ON DUPLICATE KEY UPDATE similarity = %s', (uid1, uid2, value, value))\n\n # 新增/更新多筆U2U的相似度 list:[(uid1, uid2, sim), ...] uid1 < uid2\n def updateU2USimilarities(self, list):\n param = [((x[1], x[0]) if x[0] > x[1] else (x[0], x[1])) + (x[2], x[2], ) for x in list]\n\n # SQL query\n self.cursor.executemany('INSERT INTO U2USimilarity(user_id1, user_id2, similarity) VALUES(%s, %s, %s) '\n 'ON DUPLICATE KEY UPDATE similarity = %s', param)\n\n # 傳回兩個使用者的相似度\n def getU2USimilarity(self, uid1, uid2):\n # DB的儲存方式為uid1 < uid2\n if uid1 > uid2:\n uid1, uid2 = uid2, uid1\n\n # SQL query\n self.cursor.execute('SELECT similarity FROM U2USimilarity WHERE user_id1 = %s AND user_id2 = %s', (uid1, uid2))\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return -1\n\n return self.cursor.fetchall()[0][0]\n\n # 傳回使用者對所有使用者的相似度\n def getU2USimilarities(self, uid, n, same=False):\n # SQL query\n if same:\n # 包含uid\n self.cursor.execute('SELECT user_id2, similarity FROM U2USimilarity WHERE user_id1 = %s UNION '\n 'SELECT user_id1, similarity FROM U2USimilarity WHERE user_id2 = %s '\n 'ORDER BY similarity DESC LIMIT %s', (uid, uid, n))\n else:\n # 不包含uid\n self.cursor.execute('SELECT user_id2, similarity FROM U2USimilarity WHERE user_id1 = %s AND user_id2 != %s UNION '\n 'SELECT user_id1, similarity FROM U2USimilarity WHERE user_id2 = %s AND user_id1 != %s '\n 'ORDER BY similarity DESC LIMIT %s', (uid, uid, uid, uid, n))\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return -1\n\n return {key: value for (key, value) in self.cursor.fetchall()}\n\n # 傳回使用者對餐廳的TFIDF\n def getTFIDFWithIDs(self, uid, rid):\n # SQL query\n self.cursor.execute('SELECT SUM(TFIDF) FROM (SELECT (COUNT(*) / (SELECT COUNT(*) FROM tags WHERE restaurant_id = %s) * IDF) AS TFIDF '\n 'FROM ((SELECT tag, LOG((SELECT COUNT(*) FROM restaurantInfo) / COUNT(DISTINCT restaurant_id)) AS IDF FROM tags GROUP BY tag) AS A '\n 'NATURAL JOIN (SELECT tag FROM tags WHERE user_id = %s GROUP BY tag) AS B '\n 'NATURAL JOIN (SELECT tag FROM tags WHERE restaurant_id = %s) AS C) GROUP BY tag) AS D', (rid, uid, rid))\n\n # DB回傳的結果為空\n if self.cursor.rowcount == 0:\n return 0\n\n return self.cursor.fetchall()[0][0]\n\n # 傳回使用者對所有餐廳的TFIDF\n def getTFIDFWithID(self, uid):\n # SQL query\n self.cursor.execute('SELECT restaurant_id, IFNULL(SUM(TFIDF), 0) FROM (SELECT restaurant_id, ((COUNT(*) / TOTAL) * IDF) AS TFIDF FROM '\n '(SELECT restaurant_id FROM restaurantInfo) AS A LEFT JOIN '\n '((SELECT restaurant_id, tag FROM tags) AS B NATURAL JOIN '\n '(SELECT tag, LOG((SELECT COUNT(*) FROM restaurantInfo) / COUNT(DISTINCT restaurant_id)) AS IDF FROM tags GROUP BY tag) AS C NATURAL JOIN '\n '(SELECT tag FROM tags WHERE user_id = %s GROUP BY tag) AS D) USING(restaurant_id) LEFT JOIN '\n '(SELECT restaurant_id, COUNT(*) AS TOTAL FROM tags GROUP BY restaurant_id) AS E USING(restaurant_id) '\n 'GROUP BY restaurant_id, tag) AS F GROUP BY(restaurant_id)', uid)\n\n return {key: float(value) for (key, value) in self.cursor.fetchall()}\n\n\n # ========== WEIGHT ==========\n # 新增權重 dict:{R2R, U2R, U2U, context, ...}\n def insertWeightWithID(self, uid, dict):\n # SQL query\n self.cursor.execute('INSERT INTO weight(user_id, ' + ', '.join(dict.keys()) + ') VALUES(%s, ' + ', '.join(['%s'] * len(dict)) + ')',\n ((uid, ) + tuple(dict.values())))\n\n # 傳回使用者最新的權重\n def getWeightWithID(self, uid):\n # SQL query\n self.cursor.execute('SELECT * from weight WHERE user_id = %s ORDER BY timestamp DESC LIMIT 1', uid)\n record = self.cursor.fetchall()[0]\n return {'uid': record[1], 'R2R': record[2], 'U2R': record[3], 'U2U': record[4], 'context': record[5],\n 'R2R_distance': record[6], 'R2R_price': record[7], 'R2R_ordering': record[8], 'R2R_cuisine': record[9],\n 'U2R_TFIDF': record[10], 'U2R_price': record[11], 'U2R_ordering': record[12], 'U2R_cuisine': record[13],\n 'U2U_tag': record[14], 'U2U_price': record[15], 'U2U_ordering': record[16], 'U2U_cuisine': record[17],\n 'context_1': record[18], 'context_2': record[19], 'context_3': record[20], 'context_4': record[21]}\n\n# 常用的update? => executemany\n# timestamp? => which table?","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":37638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"531426396","text":"\nimport cv2, time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pylab import *\nfrom Drag_bar import Drag_bar\n\nclass Img_Gray():\n def __init__(self, img_gray_read):\n self.img_gray_read = img_gray_read\n#灰度直方图\n def Img_Histogram(self, img_read):\n ###输入 灰色/彩色图片 的数字矩阵都可以 ##\n while(True):\n plt.clf()\n img_array = np.array(img_read)\n rects = plt.hist(img_array.flatten(),bins = 256, color = 'blue', range = [0, 256]) # flatten转化为一维序列\n plt.show()\n return rects\n \n #plt.bar(int(x), 16000, width=3, color='r' \n \"\"\"\n for rect in rects:\n height = rect.get_height()\n print(height)\n #plt.bar(0, 16000, width=3, color='g')#添加一个Bar\n #print(hist(img_array.flatten(), 256))\n \"\"\"\n# 图像的二值化(value的范围是50-150)\n def Two_Value(self,value):\n ###!!遍历象素一定要先转化为数字矩阵!!###\n #显示灰度图\n img_array = np.array(self.img_gray_read)\n rows, cols = img_array.shape\n for i in range(rows):\n for j in range(cols):\n img_array[i, j] = 255 if img_array[i, j] > value else 0\n if img_array[i, j] >= 255:\n img_array[i, j] = 255\n elif img_array[i, j] <= 0:\n img_array[i, j] = 0\n #img = np.mat(img_array)\n return img_array\n\n def Gray_Brightness(self, a, b):\n # 灰色图像的数字矩阵\n img_array = np.array(self.img_gray_read)\n rows, cols = img_array.shape\n for i in range(rows):\n for j in range(cols):\n img_array[i, j] = int(a)*(img_array[i, j]) + int(b) # a*x+b调对比度\n if img_array[i, j] >= 255:\n img_array[i, j] = 255\n elif img_array[i, j] <= 0:\n img_array[i, j] = 0\n return img_array\n #cv2.imshow(\"Gray_Brightness\", img_array)\n\"\"\"\nimg_path = 'E:\\\\postgraduate\\\\Second semester\\\\Advanced_Image_Processing\\\\Final_Project\\\\Figures\\\\Robot.png'\nimg_gray_read = cv2.imread(img_path, 0)\ngray = Gray(img_gray_read)\ngray.Two_Value(50)\n\"\"\"\n\n\n\n\n","sub_path":"Img_Gray.py","file_name":"Img_Gray.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"615691612","text":"# python3.x\n# Requirement: python3-matplotlib\n# http://matplotlib.org/users/installing.html\n#\n# By Songmin Kim\n\nimport sys\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# User input to create sample dataset\na = float(input(\"Enter (float) a of a * x + b * y + c = 0: \"))\nb = float(input(\"Enter (float) b of %.4f * x + b * y + c = 0: \" % (a)))\nc = float(input(\"Enter (float) c of %.4f * x + %.4f * y + c = 0: \" % (a,b)))\nlen = int(input(\"Enter Maximum range (int) x axis(x=y): \"))\nmax_data = int(input(\"Enter Maximum data (int) lenght(len > 1): \"))\nmax_iter = 100\nmax_iter = int(input(\"Enter Maximum (int) iteration(>100, default 100): \"))\n\n# Initialize variables\nx = [] # x axis\ny = [] # y axis\nl = [] # label\nw = [] # weight\nstep = 0.1 # learning rate or step\n\n# Generate first weights\nprint(\"\\nRandomly initialized weights\")\nfor i in range(3):\n w.append(random.uniform(-len/2,len/2))\n print(\"w[%d] = %.4f\" % (i,w[i]))\n\n# Generate test data with 0 = a*x + b*y + c (it is not XOR data)\ndef dataGen(a, b, len, max_data):\n for i in range(max_data):\n x.append(random.uniform(-len,len))\n y.append(random.uniform(-len,len))\n\n # Remove a point that on the bias line(optional)\n while 0 == (a * x[i] + b * y[i] + c):\n x[i] = random.uniform(-len,len)\n y[i] = random.uniform(-len,len)\n\n if 0 <= (a * x[i] + b * y[i] + c):\n l.append(1)\n else:\n l.append(0)\n\ndef theta(weights,x,y):\n sum = weights[0] * x + weights[1] * y+ weights[2]\n if 0 <= sum:\n r = 1\n else:\n r = 0\n return r\n\nprint(\"\\n\\n***** Your input data *****\")\nprint(\"*\\t Linear function: %.4f * x + %.4f * y + %.4f \" % (a, b, c))\nprint(\"*\\t Maximum range (%d,%d)\" % (len,len))\nprint(\"*\\t Total dataset: %d\\n*\" % max_data)\n# test the data generation\ndataGen(a,b,len,max_data)\nprint(\"*\\t Generated dataset\")\nfor i in range(max_data):\n print (\"*\\t[% .4f,% .4f,%d]\" % (x[i],y[i],l[i]))\n\nprint(\"************************************\\n\\n\")\n\n# train\nflag = True\niter = 0\nwhile flag:\n iter += 1\n for j in range(max_data):\n out = theta(w, x[j], y[j])\n if l[j] != out: # if misclassified\n # Check code\n #print(\"misclassified.% .4f, % .4f, %d,%d,%d\" % (x[j],y[j],j,l[j],out))\n w[0] += step * (l[j] - out) * x[j]\n w[1] += step * (l[j] - out) * y[j]\n w[2] += step * (l[j] - out)\n flag = True\n elif j >= max_data : # reached without misclassified\n print(\"Finish.\")\n flag = False\n\n if iter >= max_iter:\n print(\"Reached the maximum iteration.\")\n flag = False\n\nprint (\"Total iteration: %d\" % iter)\nprint (\"The trained equation(decision boundary) is % .4f * x + % .4f * y + % .4f\" % (w[0],w[1],w[2]))\n\n\n# plot\np = input(\"Do you want to plot the data with linear lines?(y/n): \")\nif p == 'y':\n colors = np.array(l)\n colormap = np.array(['r','b'])\n plt.scatter(x, y, c=colormap[colors])\n z = np.arange(-len,len)\n h = np.arange(-len,len)\n plt.plot(z,(-a/b)*z + (-c/b) , c='g', label=\"User input linear function\")\n plt.plot(h,(-w[0]/w[1])*h + (-w[2]/w[1]), c='y', label=\"Trained linear function\")\n plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode=\"expand\", borderaxespad=0.)\n plt.show()\n","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608680347","text":"import torch\nimport numpy as np\nfrom Predictive_Tracker.iou3d import iou3d\nfrom scipy.optimize import linear_sum_assignment\nfrom Predictive_Tracker.utils import label_to_str, label_to_box\n\nclass NaiveTracker:\n def __init__(self):\n self.id_count = 0\n self.trackers = {}\n\n def update(self, detections):\n\n matched, unmatched_detections, unmatched_trackers = assign_detections_to_trackers(detections, self.trackers)\n\n print(f\"Matched {len(matched)} of {len(self.trackers)} trackers and {len(detections)} detections.\")\n\n for t, trk_id in enumerate(self.trackers.keys()):\n if trk_id not in unmatched_trackers:\n d = matched[np.where(matched[:,1] == t)[0],0][0]\n self.trackers[trk_id] = detections[d]\n\n print(f\"Creating {len(unmatched_detections)} trackers for unmatched detections.\")\n\n print(\"Unmatched: \", end='')\n for i in unmatched_detections:\n print(f\"{i} ({label_to_str[detections[i][7]]})\", end=', ')\n self.trackers[self.id_count] = detections[i]\n self.id_count += 1\n print()\n\n print(f\"Removing {len(unmatched_trackers)} unmatched trackers.\")\n \n for trk_id in unmatched_trackers:\n del self.trackers[trk_id]\n\n hypothesis = {}\n\n for id, box in self.trackers.items():\n hypothesis[id] = box\n\n return hypothesis\n\ndef assign_detections_to_trackers(detections, trackers, iou_threshold=0.1):\n \"\"\"\n Assigns detections to tracked object (both represented as bounding boxes)\n detections: N x 8 x 3\n trackers: M x 8 x 3\n Returns 3 lists of matches, unmatched_detections and unmatched_trackers\n \"\"\"\n if len(trackers) == 0:\n return np.empty((0, 2), dtype=int), range(len(detections)), [] \n\n tracker_state = np.array(list(trackers.values()))\n\n cost_matrix = iou3d(\n torch.Tensor(detections)[:,:7],\n torch.Tensor(tracker_state)[:,:7]\n ).numpy()\n\n # set overlap of boxes with different types to 0\n for d in range(cost_matrix.shape[0]):\n for p in range(cost_matrix.shape[1]):\n if detections[d,7] != tracker_state[p,7]:\n cost_matrix[d,p] = 0\n\n row_ind, col_ind = linear_sum_assignment(cost_matrix, maximize=True)\n matched_indices = np.stack((row_ind, col_ind), axis=1)\n\n unmatched_detections = []\n for d, det in enumerate(detections):\n if (d not in matched_indices[:, 0]): \n unmatched_detections.append(d)\n\n unmatched_trackers = []\n for t, trk_id in enumerate(trackers.keys()):\n if (t not in matched_indices[:, 1]): unmatched_trackers.append(trk_id)\n\n matches = []\n for m in matched_indices:\n if cost_matrix[m[0], m[1]] < iou_threshold:\n unmatched_detections.append(m[0])\n unmatched_trackers.append(list(trackers.keys())[m[1]])\n else:\n matches.append(m.reshape(1, 2))\n\n if len(matches) == 0:\n matches = np.empty((0, 2), dtype=int)\n else:\n matches = np.concatenate(matches, axis=0)\n\n return matches, unmatched_detections, unmatched_trackers\n","sub_path":"Predictive_Tracker/NaiveTracker.py","file_name":"NaiveTracker.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"49029722","text":"\n#Sklearn can work with Categorical as well\n#But if someone wants to change them to Numerical\nimport pandas as pd\nimport numpy as np\ndata=pd.read_csv('Data.csv')\nx=data.iloc[:,:-1]\ny=data.iloc[:,-1]\nx=np.array(x)\ny=np.array(y)\ni=0\ny=y.reshape(1,150)\ny_mod=np.zeros(150)\ny_mod=y_mod.reshape(1,150)\nfor i in range(150):\n if(y[0][i]=='Iris-versicolor'):\n y_mod[0][i]=1\n elif(y[0][i]=='Iris-virginica'):\n y_mod[0][i]=2\n \n \ny_mod=y_mod.reshape(150,1)\n \n \n","sub_path":"To_Numerics.py","file_name":"To_Numerics.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"589136438","text":"import tensorflow as tf\nimport numpy as np\n\n'''\nTuan Anh's tensorflow book\n'''\n\n# data I/O\ninput_file = \"shakespeare.txt\"\ndata = open(input_file, 'r').read()\nchars = list(set(data))\ndata_size, vocab_size = len(data), len(chars)\n\nchar_to_ix = { ch:i for i,ch in enumerate(chars) }\nix_to_char = { i:ch for i,ch in enumerate(chars) }\ndata_in_int = [char_to_ix[c] for c in data]\ndata_in_onehot = np.zeros([len(data),len(chars)])\ndata_in_onehot[np.arange(len(data)),data_in_int] = 1\nprint ('data has %d characters, %d unique.' % (data_size, vocab_size))\n\n#hyper parameters\nn_inputs = len(chars)\nn_outputs = len(chars)\nseq_length = 50\nn_neurons_1 = 50\nn_neurons_2 = 50\nlearning_rate = 0.001\ntrain_size = int(1e6)\nbatch_size = int(train_size/seq_length)\nepochs = int(1)\n\n#model\nX = tf.placeholder(tf.float32,[None,seq_length,n_inputs])\n\ncell_1 = tf.nn.rnn_cell.LSTMCell(num_units=n_neurons_1,use_peepholes=True,name=\"cell_1\")\ncell_2 = tf.nn.rnn_cell.LSTMCell(num_units=n_neurons_2,use_peepholes=True,name=\"cell_2\")\n\nmulti_layer_cell = tf.nn.rnn_cell.MultiRNNCell([cell_1,cell_2])\nh_states, fin_state = tf.nn.dynamic_rnn(multi_layer_cell,X,dtype=tf.float32) #h_states: None*seq_length*n_neurons_2, fin_state: tupple of last c and h states[None*n_neurons_2, None*n_neurons_2]\noutputs = tf.layers.dense(h_states,n_outputs,name=\"dense\") #None*seq_length*n_outputs\n#softmax_outputs = tf.nn.softmax(outputs,axis=2) #None*seq_length*n_outputs\n\n#loss\nY = tf.placeholder(tf.int32, [None, seq_length, n_outputs]) #None*seq_length*n_outputs\n\nloss = tf.losses.softmax_cross_entropy(Y,outputs)\noptimizer = tf.train.AdamOptimizer(learning_rate)\ntraining_op = optimizer.minimize(loss)\n\n#predict\npredict = tf.argmax(outputs,axis=2) #None*seq_length\npredict_onehot = tf.one_hot(predict,depth=n_outputs) #None*seq_length*n_outputs\n\n#save\nsaver = tf.train.Saver()\n\n#train\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(epochs):\n start_i = np.random.randint(0,seq_length)\n X_train = np.reshape(data_in_onehot[start_i:start_i+train_size],[-1,seq_length,n_inputs])\n Y_train = np.reshape(data_in_onehot[start_i+1:start_i+1+train_size],[-1,seq_length,n_outputs])\n\n _train, _loss = sess.run([training_op,loss], feed_dict={X:X_train,Y:Y_train})\n\n print(\"epoch: %d CEL: %f\"%(epoch, _loss))\n if(epoch%100==0):\n # save\n save_path = saver.save(sess, \"./checkpoints_LSTM/model.ckpt\")\n print(\"Model saved in path: %s\" % save_path)\n # generate sequence\n seq_onehot = np.zeros([seq_length, n_inputs])\n story_length = 500\n for i_char in range(story_length):\n X_batch = np.reshape(seq_onehot[-seq_length:], [1, seq_length, n_inputs])\n gen_onehot = sess.run(predict_onehot, feed_dict={X: X_batch})\n seq_onehot = np.append(seq_onehot, gen_onehot[0, -1, :].reshape([1, -1]), axis=0)\n\n # print result:\n story = \"\"\n for i in range(seq_onehot.shape[0]):\n story += ix_to_char[np.argmax(seq_onehot[i])]\n print(story)\n\n\n\n\n","sub_path":"rnn_Shakespeare_LSTM.py","file_name":"rnn_Shakespeare_LSTM.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"10180113","text":"def say(numeral):\n numeral = int(numeral)\n\n if numeral < 0 or numeral >= 1000000000000:\n raise AttributeError\n if numeral == 0:\n return \"zero\"\n elif numeral >= 1000000000:\n return billions(numeral)\n elif numeral >= 1000000:\n return millions(numeral)\n elif numeral >= 1000:\n return thousands(numeral)\n else:\n return ones_tens_hundreds(numeral)\n\n\ndef ones(numeral):\n if 0 <= numeral < 10:\n return {\n 0: '',\n 1: 'one',\n 2: 'two',\n 3: 'three',\n 4: 'four',\n 5: 'five',\n 6: 'six',\n 7: 'seven',\n 8: 'eight',\n 9: 'nine'\n }[numeral]\n\n\ndef tens(numeral):\n if 10 <= numeral <= 19:\n return {\n 10: 'ten',\n 11: 'eleven',\n 12: 'twelve',\n 13: 'thirteen',\n 14: 'fourteen',\n 15: 'fifteen',\n 16: 'sixteen',\n 17: 'seventeen',\n 18: 'eighteen',\n 19: 'nineteen'\n }[numeral]\n\n tens_str = {\n 2: 'twenty',\n 3: 'thirty',\n 4: 'forty',\n 5: 'fifty',\n 6: 'sixty',\n 7: 'seventy',\n 8: 'eighty',\n 9: 'ninety'\n }[int(str(numeral)[0])]\n\n if int(str(numeral)[1]) != 0:\n tens_str += '-' + ones(int(str(numeral)[1]))\n return tens_str\n\n\ndef hundreds(numeral):\n hundreds_str = ones(int(str(numeral)[0])) + ' hundred'\n if int(str(numeral)[1:3]) != 0:\n hundreds_str += ' and ' + tens(int(str(numeral)[1:3]))\n return hundreds_str\n\n\ndef ones_tens_hundreds(numeral):\n num_str = ''\n if 100 <= numeral < 1000:\n num_str += hundreds(numeral)\n elif 10 <= numeral < 100:\n num_str += tens(numeral)\n elif 1 <= numeral < 10:\n num_str += ones(numeral)\n return num_str\n\n\ndef final_three_digits(final_three_numerals):\n num_str = ''\n if final_three_numerals != 0:\n if final_three_numerals < 100:\n num_str += ' and ' + ones_tens_hundreds(final_three_numerals)\n else:\n num_str += ' ' + ones_tens_hundreds(final_three_numerals)\n return num_str\n\n\ndef thousands(numeral):\n thou_digits = int(str(numeral)[0:-3])\n last_three_digits = int(str(numeral)[-3:])\n num_str = ones_tens_hundreds(thou_digits) + ' thousand'\n num_str += final_three_digits(last_three_digits)\n return num_str\n\n\ndef millions(numeral):\n mill_digits = int(str(numeral)[0:-6])\n thou_digits = int(str(numeral)[-6:-3])\n last_three_digits = int(str(numeral)[-3:])\n num_str = ones_tens_hundreds(mill_digits) + ' million'\n if thou_digits != 0:\n num_str += ' ' + ones_tens_hundreds(thou_digits) + ' thousand'\n num_str += final_three_digits(last_three_digits)\n return num_str\n\n\ndef billions(numeral):\n bill_digits = int(str(numeral)[0:-9])\n mill_digits = int(str(numeral)[-9:-6])\n thou_digits = int(str(numeral)[-6:-3])\n last_three_digits = int(str(numeral)[-3:])\n num_str = ones_tens_hundreds(bill_digits) + ' billion'\n if mill_digits != 0:\n num_str += ' ' + ones_tens_hundreds(mill_digits) + ' million'\n if thou_digits != 0:\n num_str += ' ' + ones_tens_hundreds(thou_digits) + ' thousand'\n num_str += final_three_digits(last_three_digits)\n return num_str\n","sub_path":"python/say/say.py","file_name":"say.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156665111","text":"from matrices import adjacency_matrix\nimport validate\n\n\ndef indexes(lst, element):\n \"\"\"Возвращает все индексы элемента в списке\"\"\"\n return [i for i, elem in enumerate(lst) if element == elem]\n\n\ndef sensors_tree(adj_matrix):\n\n def dfs(node_index):\n \"\"\"\n Обход дерева в глубину.\n При обходе сенсор сразу пытается отдать сообщение\n \"\"\"\n from_sensor = node_index\n visited_sensors.append(from_sensor)\n to_sensor = (adjacency_matrix[from_sensor].index(1)\n if adjacency_matrix[from_sensor].index(1) != from_sensor\n else adjacency_matrix[from_sensor].index(1, from_sensor + 1))\n if (blocked_sensors[to_sensor] is not True # если сенсор получатель не блокирован\n and blocked_sensors[from_sensor] is not True # и сенсор отправитель не блокирован\n and need_send_msg[from_sensor] # и сенсору необходимо послать сообщение:\n and from_sensor != 0):\n # определяем каким сенсорам необходимо блокировать передачу сообщений во избежания коллизий\n indexes_for_block = indexes(adjacency_matrix[from_sensor], 1)\n # добавляем в расписание сенсоры отправителя и получателя\n schedule[slot_num].append((from_sensor, to_sensor))\n # добавляем в очередь сообщений сенсора получателя(если не БС),\n # если БС увеличиваем количество полученных сообщений на 1\n if to_sensor != 0:\n need_send_msg[to_sensor].append(from_sensor)\n else:\n need_send_msg[to_sensor] += 1\n # блокируем сенсоры\n for i in indexes_for_block:\n blocked_sensors[i] = True\n # удаляем сообщение из очереди сообщений сенсора отправителя\n del need_send_msg[from_sensor][0]\n\n for i, edge in enumerate(adjacency_matrix[from_sensor]):\n if i not in visited_sensors and edge == 1:\n dfs(i)\n\n adjacency_matrix = adj_matrix\n need_send_msg = [[i] if i != 0 else 0 for i in range(len(adjacency_matrix))]\n schedule = []\n slot_num = 0\n while need_send_msg[0] != len(adjacency_matrix) - 1:\n blocked_sensors = [False for _ in range(len(adjacency_matrix))]\n visited_sensors = []\n schedule.append([])\n dfs(0)\n slot_num += 1\n return schedule\n\nif __name__ == '__main__':\n schedule = sensors_tree(adjacency_matrix)\n print('Длина расписания равна {}'.format(len(schedule)))\n print('Is valid? {}'.format(validate.validate_func(adjacency_matrix, schedule)))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"349982529","text":"from common.dependencies import get_token_header\nfrom fastapi import APIRouter, Depends\nfrom fastapi import APIRouter\nfrom fastapi import Depends, FastAPI\nfrom sqlalchemy.sql.sqltypes import Integer, String\n\nimport databases\nimport sqlalchemy\nfrom fastapi import FastAPI\nfrom sqlalchemy.dialects.postgresql import ARRAY\nimport glob\nfrom common.dependencies import get_query_token, get_token_header\n# from .internal import admin\n# from apps import items, user\n\nimport importlib.util\nimport logging\n# SQLAlchemy specific code, as with any other app\n# DATABASE_URL = \"sqlite:///./test.db\"\nDATABASE_URL = \"postgresql://user:password@db:5432/db\"\n\n# DATABASE_URL = \"postgresql://user:password@localhost:5432/db\"\nsecret_key = \"A-big-secret-key\"\nsecret_algorithm = \"HS256\"\ndatabase = databases.Database(DATABASE_URL)\n\nmetadata = sqlalchemy.MetaData()\n\nusers_table = sqlalchemy.Table(\n \"users\",\n metadata,\n sqlalchemy.Column(\"id\", sqlalchemy.Integer, primary_key=True),\n sqlalchemy.Column(\"first_name\", sqlalchemy.String),\n sqlalchemy.Column(\"last_name\", sqlalchemy.String),\n sqlalchemy.Column(\"hash_password\", sqlalchemy.String),\n sqlalchemy.Column(\"tags\", ARRAY(String)),\n sqlalchemy.Column(\"tags_expire_at\", sqlalchemy.DateTime, nullable=True)\n)\n\n\nengine = sqlalchemy.create_engine(\n DATABASE_URL, connect_args={\n # \"check_same_thread\": False,\n }\n)\nmetadata.create_all(engine)\n\napp = FastAPI(dependencies=[Depends(get_query_token)])\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Health is Ok\"}\n\n\n@app.on_event(\"startup\")\nasync def handle_startup():\n await database.connect()\n router_list = list()\n for file_name in glob.iglob('./**/routers.py', recursive=True):\n print('-----------------loop')\n print(file_name)\n spec = importlib.util.spec_from_file_location('routers', file_name)\n each_app = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(each_app)\n router_list += each_app.routers\n print(router_list)\n\n for rt in router_list:\n print(rt)\n app.include_router(rt)\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n await database.disconnect()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110359305","text":"import argparse\nimport os\nimport sys\nimport time\nimport re\n\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torchvision import transforms\nimport torch.onnx\n\nimport utils\nfrom transformer_net import TransformerNet\nfrom vgg import Vgg16\n\nimport cv2\nfrom PIL import Image\n\ndef load_style(model):\n device = \"cuda\" \n\n with torch.no_grad():\n style_model = TransformerNet()\n state_dict = torch.load(model)\n # remove saved deprecated running_* keys in InstanceNorm from the checkpoint\n for k in list(state_dict.keys()):\n if re.search(r'in\\d+\\.running_(mean|var)$', k):\n del state_dict[k]\n style_model.load_state_dict(state_dict)\n style_model.to(device)\n return style_model\n\n\ndef torch_to_numpy(output):\n output = output.cpu().detach()\n output = output.clone().clamp(0, 255).numpy()[0]\n output = output.transpose(1, 2, 0).astype(\"uint8\")\n output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)\n return output\n\n\ndef numpy_to_torch(img):\n img = torch.from_numpy(np.array(img))\n img = img.type('torch.FloatTensor')\n img = torch.transpose(img, 0,2)\n img = torch.transpose(img, 2,1)\n img = img.unsqueeze(0).to(\"cuda\")\n return img\n\n\ndef main():\n main_arg_parser = argparse.ArgumentParser(description=\"parser for fast-neural-style\")\n subparsers = main_arg_parser.add_subparsers(title=\"subcommands\", dest=\"subcommand\")\n\n eval_arg_parser = subparsers.add_parser(\"eval\", help=\"parser for evaluation/stylizing arguments\")\n eval_arg_parser.add_argument(\"--content-image\", type=str,\n help=\"path to content image you want to stylize\")\n eval_arg_parser.add_argument(\"--content-scale\", type=float, default=None,\n help=\"factor for scaling down the content image\")\n eval_arg_parser.add_argument(\"--output-image\", type=str,\n help=\"path for saving the output image\")\n eval_arg_parser.add_argument(\"--model\", type=str,\n help=\"saved model to be used for stylizing the image. If file ends in .pth - PyTorch path is used, if in .onnx - Caffe2 path\")\n eval_arg_parser.add_argument(\"--cuda\", type=int, required=True,\n help=\"set it to 1 for running on GPU, 0 for CPU\")\n eval_arg_parser.add_argument(\"--imagesize\", type=float, default = 1.,\n help=\"360p times imagesize\")\n\n args = main_arg_parser.parse_args()\n\n if args.subcommand is None:\n print(\"ERROR: specify either train or eval\")\n sys.exit(1)\n if args.cuda and not torch.cuda.is_available():\n print(\"ERROR: cuda is not available, try running on CPU\")\n sys.exit(1)\n\n\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n content_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Lambda(lambda x: x.mul(255))\n ])\n\n style_count = 0\n models_path = [\"saved_models/epoch_2_Sat_Nov_23_11:09:34_2019_100000.0_200000000000.0.model\", \"saved_models/epoch_8_Sat_Nov_23_05:21:07_2019_100000.0_200000000000.0.model\", \"saved_models/epoch_10_Sat_Nov_23_02:57:03_2019_100000.0_10000000000.0.model\", \"saved_models/epoch_1_Sat_Nov_23_00:18:53_2019_100000.0_10000000000.0.model\", \"saved_models/epoch_2_Fri_Nov_22_22:37:40_2019_100000.0_10000000000.0.model\", \"saved_models/rain_princess.pth\", \"saved_models/candy.pth\", \"saved_models/mosaic.pth\"]\n style_models = [load_style(model) for model in models_path]\n style_model = style_models[style_count]\n\n # some params\n upscale = 2\n width = int(640*args.imagesize) # 1280\n height = int(360*args.imagesize) # 720\n # open cam\n print('reparing video recording')\n video = cv2.VideoCapture(0)\n video.set(3, width)\n video.set(4, height)\n # prepare recording\n fourcc = cv2.VideoWriter_fourcc('F','M','P','4')\n out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (upscale*height, upscale*width))\n print((upscale*height, upscale*width))\n # out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (width, 2*height))\n count = 0\n nb_iter = 0\n avg = 0\n while True:\n # get cam image\n print('frame {}'.format(count))\n check, frame = video.read()\n frame = np.flip(frame, 1)\n\n # reformating\n content_image = numpy_to_torch(frame)\n\n # style transfer\n torch.cuda.empty_cache()\n output = style_model(content_image)\n\n # back to numpy\n output = torch_to_numpy(output)\n\n # concatenate images\n # img = np.concatenate((output, frame),axis=0)\n img = output\n img = cv2.resize(img, dsize=(int(img.shape[1]*upscale), int(img.shape[0]*upscale)), interpolation=cv2.INTER_CUBIC)\n print(img.shape)\n\n # display images\n cv2.imshow(\"WHITE MIRROR\", img)\n\n # save img\n out.write(img)\n print(img.max(), img.dtype)\n\n # controling the exit condition\n key = cv2.waitKey(1)\n print(key)\n if key == 27 : # ESC\n break\n elif key == ord('p'): # P\n while cv2.waitKey(1) != ord('p'):\n time.sleep(2)\n elif key == 100: # S\n style_count = (style_count + 1) % len(style_models)\n style_model = style_models[style_count]\n elif key == 113: # Q\n style_count = (style_count - 1) % len(style_models)\n style_model = style_models[style_count]\n elif key == 13:\n imagename = '../imfolder/{}.jpg'.format(str(time.ctime()).replace(' ', '_'))\n cv2.imwrite(imagename, img)\n elif key == 32:\n out1 = cv2.VideoWriter('output.mp4', fourcc, 20.0, (2*width, 2*height))\n count += 1\n \n # cleaning things\n video.release()\n out.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"fast_neural_style/neural_style/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185114750","text":"import serial\nimport math\nimport time\nfrom prototype import Sensor\n\nerr_res = 10000 # if it's not less than this, throw an error\nzero_res = 4300.0\ncalib_res = 3250.0\nlevel_calib = 1. / 1.\nnum_samples = 10\ntime_to_wait = .1\n\n\ndef res_to_level(line):\n return (line - zero_res) / (calib_res - zero_res)\n\n\nclass WaterLevel(Sensor):\n def __init__(self):\n self.port = serial.Serial(\"/dev/ttyAMA0\")\n\n def sense(self):\n self.port.write('R')\n return float(self.port.readline())\n\n # gets a single good reading (skips inf)\n def read_single(self):\n raw = self.sense()\n while True: # wait until there's a real reading\n if raw < err_res: return raw\n time.sleep(time_to_wait)\n raw = self.sense()\n\n # takes the average of num_samples readings\n def read(self):\n res = 0\n for sample in range(num_samples):\n this_sample = self.read_single()\n res = res + this_sample\n time.sleep(time_to_wait)\n res = res / num_samples\n\n return {\"WaterLevel\": res_to_level(res)}\n\n\ndebug = True\nif __name__ == \"__main__\":\n ws = WaterLevel()\n\n if debug:\n while True:\n raw_reading = ws.read_single()\n processed_reading = res_to_level(raw_reading)\n print\n \"Raw: %d Processed %d\" % (raw_reading, processed_reading)\n time.sleep(1)\n while True:\n print\n \"Sensing\"\n print\n ws.read()\n time.sleep(2)\n","sub_path":"aqcontrol/aqcontrol/hardware/waterlevel.py","file_name":"waterlevel.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296074633","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport uncertainties.unumpy as unp\nfrom uncertainties import ufloat\nfrom scipy.stats import stats\nimport pylab\nFigure = pylab.figure()\nAx = Figure.gca\n\nU = 960\nx, y = np.genfromtxt('B.txt', unpack=True)\ny = y/U\n\ndef f(x, a):\n return 1/np.sqrt(1+(2*np.pi*x*a)**2)\nparamsI, covarianceI = curve_fit(f, x, y)\nerrorsI = np.sqrt(np.diag(covarianceI))\n\na = ufloat(paramsI[0], errorsI[0])\nprint(a)\n\nplt.xscale(\"log\")\nL1plot = np.linspace(10, 10000, num=100000)\nplt.plot(x, y,'r*', label=\"Messwerte\")\nplt.ylabel(r\"$\\frac{A(\\nu)}{U_0}$\" )\nplt.xlabel(r\"$ \\nu / \\mathrm{Hz}$\")\nplt.plot(L1plot, f(L1plot, *paramsI) , 'b-', label='Regression')\nplt.tight_layout\nplt.legend(loc=\"best\")\n\nplt.savefig('plotB.pdf')\n","sub_path":"V353/plotB.py","file_name":"plotB.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249882895","text":"import requests\n\nfrom mope.__version__ import __version__\nfrom mope.resources.shop import ShopResource\n\n\nclass Mope:\n def __init__(self, token=None):\n self._token = token\n self._headers = {}\n self.url_base = 'https://api.mope.sr/api'\n\n self._make_headers(token, user_agent='Python Mope %s' % __version__)\n\n self.shop = ShopResource(self)\n\n def _make_headers(self, token, user_agent):\n self._headers = {\n 'User-Agent': user_agent,\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer %s' % token,\n }\n\n def call_api(self, method, endpoint, params=None, data=None, json=None):\n return requests.request(method=method, url=endpoint, params=params, data=data, json=json, headers=self._headers)\n\n def __str__(self):\n return 'Python Mope %s' % __version__\n","sub_path":"mope/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605913320","text":"from django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom django.db.models import Sum\nfrom djchoices import DjangoChoices, ChoiceItem\n\nfrom game_engine.lib.card_holders import Deck, Player as PasurPlayer\nfrom game_engine.lib.pasur import Pasur, STATUS, MAX_PLAYER_COUNT\n\n\nclass GameModel(models.Model):\n\n class Meta:\n abstract = True\n\n created = models.DateTimeField(auto_now_add=True)\n modified = models.DateTimeField(auto_now=True)\n\n\n# noinspection PyPep8Naming\nclass MATCH_STATUS(DjangoChoices):\n joinable = ChoiceItem()\n ongoing = ChoiceItem()\n finished = ChoiceItem()\n\n\nclass Match(GameModel):\n def get_latest_game(self, select_for_update=False) -> \"Game\":\n if select_for_update:\n query = self.games.select_for_update()\n else:\n query = self.games\n return query.latest('created')\n\n def status(self):\n games = self.games.order_by('-modified')\n if len(games) <= 1 and games[0].status == STATUS.pending and self.game_players.count() <= MAX_PLAYER_COUNT:\n return MATCH_STATUS.joinable\n elif self.has_a_player_reached_goal(current_game=games[0]):\n return MATCH_STATUS.finished\n else:\n return MATCH_STATUS.ongoing\n\n def has_a_player_reached_goal(self, current_game=None):\n for player, values in self.count_player_points(current_game=current_game or self.get_latest_game()).items():\n try:\n if values['total'] >= MAX_PLAYER_COUNT:\n return True\n except Exception as e:\n print(e)\n return False\n\n def count_player_points(self, current_game: \"Game\"=None):\n current_game = current_game or self.get_latest_game()\n points = {}\n for player in self.game_players.all():\n pms = GameMatchPlayerScore.objects \\\n .filter(match_player__player__name=player.player.name) \\\n .filter(match_player__match=self)\n points[player.player.name] = {\n 'total': pms.aggregate(Sum('score')).get('score__sum') or 0,\n 'current_game': pms.filter(game_id=current_game.id).aggregate(Sum('score')).get('score__sum') or 0\n }\n return points\n\n\nclass GameField(JSONField):\n description = \"A field to save decks as jsonb in postgres db, but acts like a Deck-object\"\n\n def to_python(self, value):\n value = super(GameField, self).to_python(value)\n if isinstance(value, Deck):\n return value\n\n if value is None:\n return value\n\n return Pasur.load_json(value)\n\n def get_prep_value(self, value: Pasur):\n return super(GameField, self).get_prep_value(value.dump_json())\n\n def from_db_value(self, value, *_):\n return self.to_python(value)\n\n def formfield(self, **kwargs):\n raise NotImplementedError('This is not yet supported')\n\n\nclass Game(GameModel):\n\n status = models.CharField(max_length=30, choices=STATUS.choices, default=STATUS.pending)\n pasur: Pasur = GameField()\n match = models.ForeignKey(to=Match, on_delete=models.CASCADE, related_name='games')\n\n def __init__(self, *args, **kwargs):\n super(Game, self).__init__(*args, **kwargs)\n if self.id is None and self.pasur is None:\n self.pasur: Pasur = Pasur.create_new_game()\n\n for player in self.match.game_players.order_by('created'): # type: MatchPlayer\n self.pasur.add_player(player=player.player.get_pasur_player())\n\n self.pasur.status = self.status\n\n def save(self, *args, **kwargs):\n self.status = self.pasur.status\n super(Game, self).save(*args, **kwargs)\n\n\nclass Player(GameModel):\n name = models.CharField(max_length=120, unique=True, blank=False)\n\n def get_pasur_player(self):\n return PasurPlayer(player_id=self.name)\n\n\nclass MatchPlayer(GameModel):\n match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='game_players')\n player = models.ForeignKey(Player, on_delete=models.CASCADE)\n\n\nclass GameMatchPlayerScore(GameModel):\n game = models.ForeignKey(to=Game, on_delete=models.CASCADE)\n match_player = models.ForeignKey(to=MatchPlayer, on_delete=models.CASCADE)\n score = models.IntegerField(default=0)\n","sub_path":"backend/django/game_engine/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"70856527","text":"import re\nfrom unittest import mock\n\nimport pytest\nfrom urllib3.exceptions import HTTPError\n\nfrom lightning.app.core import constants\nfrom lightning.app.utilities.network import _retry_wrapper, find_free_network_port, LightningClient\n\n\ndef test_find_free_network_port():\n \"\"\"Tests that `find_free_network_port` gives expected outputs and raises if a free port couldn't be found.\"\"\"\n assert find_free_network_port()\n\n with mock.patch(\"lightning.app.utilities.network.socket\") as mock_socket:\n mock_socket.socket().getsockname.return_value = [0, 8888]\n assert find_free_network_port() == 8888\n\n with pytest.raises(RuntimeError, match=\"Couldn't find a free port.\"):\n find_free_network_port()\n\n mock_socket.socket().getsockname.return_value = [0, 9999]\n assert find_free_network_port() == 9999\n\n\n@mock.patch(\"lightning.app.utilities.network.socket\")\n@pytest.mark.parametrize(\n \"patch_constants\",\n [{\"LIGHTNING_CLOUDSPACE_HOST\": \"any\", \"LIGHTNING_CLOUDSPACE_EXPOSED_PORT_COUNT\": 10}],\n indirect=True,\n)\ndef test_find_free_network_port_cloudspace(_, patch_constants):\n \"\"\"Tests that `find_free_network_port` gives expected outputs and raises if a free port couldn't be found when\n cloudspace env variables are set.\"\"\"\n ports = set()\n num_ports = 0\n\n with pytest.raises(RuntimeError, match=\"All 10 ports are already in use.\"):\n for _ in range(11):\n ports.add(find_free_network_port())\n num_ports = num_ports + 1\n\n # Check that all ports are unique\n assert len(ports) == num_ports\n\n # Shouldn't use the APP_SERVER_PORT\n assert constants.APP_SERVER_PORT not in ports\n\n\ndef test_lightning_client_retry_enabled():\n client = LightningClient() # default: retry=True\n assert hasattr(client.auth_service_get_user_with_http_info, \"__wrapped__\")\n\n client = LightningClient(retry=False)\n assert not hasattr(client.auth_service_get_user_with_http_info, \"__wrapped__\")\n\n client = LightningClient(retry=True)\n assert hasattr(client.auth_service_get_user_with_http_info, \"__wrapped__\")\n\n\n@mock.patch(\"time.sleep\")\ndef test_retry_wrapper_max_tries(_):\n mock_client = mock.MagicMock()\n mock_client.test.__name__ = \"test\"\n mock_client.test.side_effect = HTTPError(\"failed\")\n\n wrapped_mock_client = _retry_wrapper(mock_client, mock_client.test, max_tries=3)\n\n with pytest.raises(Exception, match=re.escape(\"The test request failed to reach the server, error: failed\")):\n wrapped_mock_client()\n\n assert mock_client.test.call_count == 3\n","sub_path":"tests/tests_app/utilities/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"57523273","text":"import jinja2\nimport netmiko\nimport pyscreenshot as ImageGrab\n\nconfig_template = \"config_template.j2\"\ncsv_file = \"parameters.csv\"\ncsv_list = []\n\ncsv = (open(csv_file).read()).splitlines() #split lines into a list\ncsv_key = (csv[0]).split(';') #remove comma and separate into a list for header row\n\nfor row in range(1,len(csv)): #iterate through rows excluding header\n csv_dict = {}\n csv_value = (csv[row]).split(';') #remove comma and separate into a list for parameter row\n for parameter in range(0,len(csv_value)): #iterate through parameters\n csv_dict[csv_key[parameter]] = csv_value[parameter] #create dictionary by using header as key and parameter as value\n csv_list.append(csv_dict) #append all values to empty list\n\nenv = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=\".\"))\ntemplate = env.get_template(config_template)\n\nfor device in csv_list:\n config = template.render(device)\n with open(device['hostname']+'.cfg','w') as f:\n f.write(config)\n f.close()\n dev = device['management']\n print('### CONFIGURING ' + device['hostname'] + ' ###')\n\n connection = netmiko.ConnectHandler(ip=dev, device_type='cisco_ios', username='admin', password='admin')\n cfg = connection.send_config_from_file(device['hostname']+'.cfg')\n print(connection.find_prompt())\n ss = connection.send_command('show ip int brief')\n print(ss)\n\n screenWidth, screenHeight = pyautogui.size() # Get the size of the primary monitor.\n currentMouseX, currentMouseY = pyautogui.position() # Get the XY position of the mouse.\n pyautogui.moveTo(100, 150) # Move the mouse to XY coordinates.\n pyautogui.click() # Click the mouse.\n pyautogui.click(100, 200) # Move the mouse to XY coordinates and click it.\n pyautogui.click('button.png') # Find where button.png appears on the screen and click it.\n im = ImageGrab.grab()\n im.save(device['hostname']+'.png')\n","sub_path":"config_generator/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393260236","text":"\"\"\"\nEnzo Busseti, Walaa Moursi, Stephen Boyd, 2018\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport numpy as np\nimport scs\nimport ecos\nimport scipy.sparse as sp\n\nfrom numba import jit, njit\n\n\nfrom .cones import *\nfrom .problem import *\n\n\ndef dim2cones(dim):\n \"\"\"Transform dict in scs format to cones.\"\"\"\n cones = []\n if 'z' in dim and dim['z'] > 0:\n cones.append([zero_cone, dim['z']])\n if 'f' in dim and dim['f'] > 0:\n cones.append([free_cone, dim['f']])\n if 'l' in dim and dim['l'] > 0:\n cones.append([non_neg_cone, dim['l']])\n if 'q' in dim:\n for q in dim['q']:\n if q > 0:\n cones.append([sec_ord_cone, q])\n if 's' in dim:\n for s in dim['s']:\n if s > 0:\n cones.append([semi_def_cone, s * (s + 1) // 2])\n if 'ep' in dim:\n for i in range(dim['ep']):\n cones.append([exp_pri_cone, 3])\n if 'ed' in dim:\n for i in range(dim['ed']):\n cones.append([exp_dua_cone, 3])\n # if 'e' in dim:\n # assert (not 'ep' in dim)\n # for i in range(dim['e']):\n # cones.append([exp_pri_cone, 3])\n return cones\n\n\ndef generate_problem(dim_dict, density=.1, mode='solvable', nondiff_point=False, random_scale_max=10.):\n \"\"\"Generate random problem with given cone and density.\"\"\"\n cones = dim2cones(dim_dict)\n m = sum([el[1] for el in cones])\n n = m\n\n r = np.zeros(m) if nondiff_point else np.random.randn(m)\n\n s, cache = prod_cone.Pi(r, cones)\n y = s - r\n A = sp.rand(m, n, density=density, format='csc')\n A.data = np.random.randn(\n A.nnz) * np.random.uniform(1., 1. + random_scale_max)\n\n x = np.random.randn(n) * np.random.uniform(1., 1. + random_scale_max)\n\n if mode == 'solvable':\n b = A@x + s\n c = -A.T@y\n return A, b, c, x, s, y\n\n if mode == 'unbounded':\n A = A - np.outer(s + A@x, x) / np.linalg.norm(x)**2 # dense...\n c = np.random.randn(n) * np.random.uniform(1., 1. + random_scale_max)\n c = -c / (c@x)\n b = np.random.randn(m)\n y *= 0.\n return sp.csc_matrix(A), b, c, x, s, y\n\n if mode == 'infeasible':\n A = A - np.outer(y, A.T@y) / np.linalg.norm(y)**2 # dense...\n b = np.random.randn(m) * np.random.uniform(1., 1. + random_scale_max)\n b = - b / (b@y)\n c = np.random.randn(n)\n x *= 0.\n s *= 0.\n return sp.csc_matrix(A), b, c, x, s, y\n\n else:\n raise Exception('Invalid mode.')\n","sub_path":"cone_prog_refine/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624181697","text":"# -*- coding: UTF-8 -*-\n\n# Copyright (c) 2007 Daniele Favara .\n#\n# This is free software you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 2, or (at your option) any\n# later version.\n#\n# This software is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this software; see the file COPYING. If not, write to the Free\n# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA\n\n\nfrom turbogears import expose, flash\nfrom tginvoice.controllers import ControllerObj\n\nfrom turbogears import identity, redirect\nfrom cherrypy import request, response\n\n\nimport logging\nlog = logging.getLogger(\"tginvoice.controllers.root\")\n\nfrom tginvoice.controllers.biller import Biller\nfrom tginvoice.controllers.customers import Customers\nfrom tginvoice.controllers.invoices import Invoices\nfrom tginvoice.controllers.projects import Projects\n\n\nclass Root(ControllerObj):\n\n def _set_child(self, name):\n real_name = name\n name = name.lower()\n\n childobj=None\n\n kw = {}\n if name == 'biller':\n name = name+'/'\n childobj = Biller\n elif name == 'customers':\n name = name+'/'\n childobj = Customers\n elif name == 'invoices':\n name = name+'/'\n childobj = Invoices\n elif name == 'projects':\n name = name+'/'\n childobj = Projects\n kw['parent'] = self\n kw['name'] = name\n kw['real_name'] = real_name\n\n if childobj:\n child = childobj(**kw)\n self._map[real_name] = child\n self._childs.append(child)\n setattr(self, real_name, child)\n\n def _set_childs(self):\n\n all = self.iterator_tab\n for name in all:\n self._set_child(name)\n\n @identity.require(identity.not_anonymous())\n @expose(template=\"tginvoice.templates.index\")\n def index(self, *kw, **args):\n self._set_childs()\n if len(args)==0:\n raise redirect(self.map['biller'].name)\n #return dict(this=self)\n\n\n @expose(template=\"tginvoice.templates.login\")\n def login(self, forward_url=None, previous_url=None, *args, **kw):\n\n if not identity.current.anonymous \\\n and identity.was_login_attempted() \\\n and not identity.get_identity_errors():\n raise redirect(forward_url)\n\n forward_url=None\n previous_url= request.path\n\n if identity.was_login_attempted():\n msg=_(\"The credentials you supplied were not correct or \"\n \"did not grant access to this resource.\")\n elif identity.get_identity_errors():\n msg=_(\"You must provide your credentials before accessing \"\n \"this resource.\")\n else:\n msg=_(\"Please log in.\")\n forward_url= request.headers.get(\"Referer\", \"/\")\n\n response.status=403\n return dict(message=msg, previous_url=previous_url, logging_in=True,\n original_parameters=request.params,\n forward_url=forward_url)\n\n @expose()\n def logout(self):\n identity.current.logout()\n raise redirect(\"/\")\n\n","sub_path":"tginvoice/controllers/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53906829","text":"import re\n\n\nclass Router:\n def __init__(self):\n self.routes = []\n self._default = None\n\n def route(self, path):\n route = parse_route(path)\n\n def decorator(func):\n self.routes.append((route, func))\n return func\n\n return decorator\n\n def default(self, func):\n self._default = func\n return func\n\n def find_handler(self, path):\n for route, func in self.routes:\n route_params = route.match(path)\n if route_params is None:\n continue\n return func, route_params\n return self._default, {}\n\n\ndef parse_route(path):\n pos = 0\n parts = [\"^\"]\n parameters = []\n while True:\n m = PARAM_PATTERN.search(path, pos=pos)\n if m:\n parts.append(re.escape(path[pos : m.start()]))\n name, _, type_ = m.group(1).partition(\":\")\n type_ = type_ or \"str\"\n if not name:\n raise ValueError(f\"Parameter name required: {m.group(1)!r}\")\n name = name or str(len(parameters))\n try:\n param_type_pattern, param_parser = PARAM_TYPES[type_]\n except IndexError:\n raise ValueError(f\"Unknown param type: {type_}\")\n parts.append(\"(\" + param_type_pattern + \")\")\n parameters.append(Parameter(name, param_parser))\n pos = m.end()\n else:\n parts.append(re.escape(path[pos:]))\n break\n\n parts.append(\"$\")\n pattern = re.compile(\"\".join(parts))\n return Route(pattern, parameters)\n\n\nclass Route:\n def __init__(self, pattern, parameters):\n self._pattern = pattern\n self._parameters = parameters\n\n def match(self, path):\n m = self._pattern.search(path)\n if not m:\n return None\n result = {}\n for parameter, value in zip(self._parameters, m.groups()):\n result[parameter.name] = parameter.parser(value)\n return result\n\n\nclass Parameter:\n def __init__(self, name, parser):\n self.name = name\n self.parser = parser\n\n\nPARAM_PATTERN = re.compile(r\"\\<(.+?)\\>\")\n\nPARAM_TYPES = {\n \"int\": (r\"\\d+?\", int),\n \"str\": (r\"[^/]+?\", str),\n \"path\": (r\".*?\", str),\n}\n","sub_path":"faat/granger/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34344328","text":"from typing import List\nfrom sys import maxsize as MAXINT\nfrom mido import MidiFile\n\nfrom pyprone.core import PrObj\nfrom pyprone.core.enums.midifile import DEFAULT_TEMPO\n\nfrom .msg import PrMidiMsg\nfrom .track import PrMidiTrack\nfrom .tempotrack import PrMidiTempotrack as PrTempo\n\nclass PrMidiFile(PrObj):\n \"\"\"\n entity for midifile (mido wrapper)\n - midi file data\n - midi cursor data\n \"\"\"\n\n def __init__(self, name: str):\n super().__init__(name)\n self._midifile: MidiFile = None\n self._tempo: int = DEFAULT_TEMPO\n self._tracks: List[PrMidiTrack] = []\n self._tempotrack: PrTempo = None\n\n # properties\n @property\n def tempo(self):\n return self._tempo\n @property\n def tempotrack(self) -> PrTempo:\n return self._tempotrack if self._tempotrack else None\n @property\n def tracks(self):\n return self._tracks\n @tracks.setter\n def tracks(self, tracks: List[PrMidiTrack]):\n self._tracks = tracks\n @property\n def tpb(self): # ticks per beat\n if self._midifile:\n return self._midifile.ticks_per_beat\n\n # private methods\n def __next_track(self) -> PrMidiTrack:\n '''\n [return 1st]\\n\n None: stuck, can't go anymore | PrMidiTrack: the track that has next message\\n\n '''\n csr_abs_tick, csr_track = MAXINT, None\n for track in self.tracks:\n if not track.stuck:\n if csr_abs_tick > track.tick:\n csr_abs_tick = track.tick\n csr_track = track\n return csr_track\n\n def __rewind(self, tick=0):\n ''' set playhead to the given tick '''\n for track in self.tracks:\n track.rewind(tick)\n\n # public methods\n def load(self, path: str):\n \"\"\" load a midifile \"\"\"\n # open midifile\n self._midifile = MidiFile(path)\n # create a tempo track\n self._tempotrack = PrTempo(self._midifile)\n # create other tracks\n for n, msgs in enumerate(self._midifile.tracks):\n if n > 0: # skip the tempo track\n csr_abs_tick, csr_abs_secs = 0, 0\n track = PrMidiTrack(n)\n for msg in msgs:\n if msg.type == 'track_name':\n track.name = msg.name\n if msg.time > 0:\n csr_abs_tick += msg.time\n delta = self.tempotrack.cursor(csr_abs_tick)[PrTempo.SECS] - csr_abs_secs\n csr_abs_secs += delta\n else:\n delta = 0\n track.append(PrMidiMsg(msg.copy(), tick=msg.time, secs=delta))\n track.rewind()\n self.tracks.append(track)\n print(track)\n\n def run(self, tick=0):\n \"\"\" return iterator from the given tick \"\"\"\n self.__rewind(tick)\n track = PrMidiTrack()\n while track:\n track = self.__next_track() # choosing a next track\n if track:\n yield track\n track.forward()\n yield None\n\ndef factory(target_obj: any) -> PrMidiFile:\n \"\"\" create PrText from any givn object \"\"\"\n if isinstance(target_obj, PrMidiFile):\n return target_obj\n if isinstance(target_obj, str):\n name: str = target_obj\n return PrMidiFile(name)\n if isinstance(target_obj, tuple):\n name: str = target_obj[0]\n path: str = target_obj[1]\n pr_midifile = PrMidiFile(name)\n pr_midifile.load(path)\n return pr_midifile\n return PrMidiFile(\"this is not a PrMidiFile obj\")\n","sub_path":"pyprone/entities/midifile/midifile.py","file_name":"midifile.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"469834406","text":"from werkzeug.datastructures import ImmutableMultiDict\nfrom flask import (\n Blueprint, render_template, session, request, redirect, url_for, abort,\n)\nfrom flask.ext.login import current_user, login_required\n\nfrom eshop.models.database import db\nfrom eshop.models.models import (\n User, Product, Category, Order, Payment, Shipment,\n)\nfrom eshop.forms import (\n Form, ProfileInfoForm, CardForm, SelectField, Required, SubmitField,\n TextField,\n)\nfrom eshop.utils import Card, crypt_args, decrypt_args_or_404\n\nfrom wtforms.widgets import HiddenInput\n\norder_app = Blueprint('order', __name__)\n\n\nclass ClientInfoForm(ProfileInfoForm):\n next_step = SubmitField('Next step')\n street = TextField('Street', validators=[Required()])\n town = TextField('Town', validators=[Required()])\n country = TextField('Country', validators=[Required()])\n postal_code = TextField('Postal code', validators=[Required()])\n tel_number = TextField('Tel. number')\n\n\nclass PayAndShipmentForm(Form):\n payment_id = SelectField('Payment', coerce=int, validators=[Required()])\n shipment_id = SelectField('Shipment', coerce=int, validators=[Required()])\n next_step = SubmitField('Next step', default='next')\n\n def payment_id_choices(self):\n return db.session.query(Payment.id, Payment.name).\\\n order_by(Payment.name)\n\n def shipment_id_choices(self):\n return db.session.query(Shipment.id, Shipment.name).\\\n order_by(Shipment.name)\n\n\n@order_app.route('/client_info', methods=('GET', 'POST'))\ndef client_info():\n card = Card()\n form = ClientInfoForm(**card.client_info)\n if form.validate_on_submit():\n card.update_client_info(form.data)\n if request.form.get('next_step'):\n return redirect(url_for('order.shipping_and_payment'))\n return render_template(\"order/client_info.html\", form=form, card=card)\n\n\n@order_app.route('/shipping_and_payment', methods=('GET', 'POST'))\ndef shipping_and_payment():\n card = Card()\n form = PayAndShipmentForm(**card.pay_and_ship)\n\n if form.validate_on_submit():\n card.update_pay_and_ship(form.data)\n if request.form.get('next_step'):\n return redirect(url_for('order.summary'))\n\n return render_template(\"order/shipping_and_payment.html\", form=form, card=card)\n\n\n@order_app.route('/summary', methods=('GET', 'POST'))\ndef summary():\n card = Card()\n form = Form()\n\n message = None\n url = None\n sent = False\n if form.validate_on_submit():\n message = card.commit(db.session)\n if message is None:\n if current_user.is_anonymous():\n crypted_text = crypt_args(card.order.id)\n url = url_for(\n 'order.anonymous_detail', crypted_text=crypted_text)\n card.clear()\n sent = True\n\n return render_template(\"order/summary.html\", form=form, card=card,\n message=message, url=url, sent=sent)\n\n\n@order_app.route('/card', methods=('GET', 'POST'))\ndef card():\n card = Card()\n form = CardForm(products=card.products.values())\n\n if form.validate_on_submit():\n card.update_products(form.data['products'])\n form = CardForm(ImmutableMultiDict(), products=card.products.values())\n if request.form.get('next_step'):\n return redirect(url_for('order.client_info'))\n\n return render_template(\"order/card.html\", form=form, card=card)\n\n\n@order_app.route('/list', methods=('GET', ))\n@login_required\ndef list_():\n orders = Order.query.filter_by(user_id=current_user.id)\n return render_template(\"order/list.html\", orders=orders, card=None)\n\n\n@order_app.route('/detail/', methods=('GET', ))\n@login_required\ndef detail(id):\n order = Order.query.get_or_404(id)\n if order.user_id != current_user.id:\n abort(403)\n return render_template(\"order/detail.html\", order=order, card=None,\n back=True)\n\n\n@order_app.route('/detail/', methods=('GET', ))\ndef anonymous_detail(crypted_text):\n args = decrypt_args_or_404(crypted_text)\n order = Order.query.get_or_404(args[0])\n\n return render_template(\"order/detail.html\", order=order, card=None)\n","sub_path":"eshop/views/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292182535","text":"# 푸는 중\n# 1062 - BOJ 가르침\nfrom sys import stdin\nfrom itertools import combinations\n\n\n# bin_dict : a/c/i/t/n을 제외한 알파벳 각각에 임의의 고유 번호를 부여한 딕셔너리\nbin_dict = {'b': 20, 'd': 19, 'e': 18, 'f': 17, 'g': 16, 'h': 15, 'j': 14,\n 'k': 13, 'l': 12, 'm': 11, 'o': 10, 'p': 9, 'q': 8, 'r': 7,\n 's': 6, 'u': 5, 'v': 4, 'w': 3, 'x': 2, 'y': 1, 'z': 0}\n\n\n# 알파벳 배열을 2진수로 바꾸어주는 함수\ndef word_to_bin(word):\n answer = 0b0\n for x in word:\n answer = answer | (1 << bin_dict[x])\n\n return answer\n\n\nn, k = map(int, stdin.readline().split())\nwords = []\n# 각 입력 단어에 대하여\n# 1. 앞의 anta와 뒤의 tica를 슬라이스한 뒤 set로 만들고\n# 2. 그중 a/c/i/t/n을 제외한 뒤 words 리스트에 저장\nfor _ in range(n):\n words.append(set(stdin.readline().rstrip()[4:-4]).difference('a', 'c', 'i', 't', 'n'))\n\n# k가 5 미만이라면 어떤 단어도 만들 수 없음.\nif k < 5:\n print(0)\nelse:\n bin_list = [word_to_bin(x) for x in words]\n max_count = 0\n\n # 2의 0제곱부터 2의 20제곱까지 저장한 리스트\n power_of_2 = [2 ** i for i in range(21)]\n\n # 현재 순회 중인 k - 5개의 알파벳 조합(comb)으로\n for comb in combinations(power_of_2, k - 5):\n current = sum(comb)\n count = 0\n for bin_number in bin_list:\n # 현재 순회 중인 단어를 만들 수 있다면\n if bin_number & current == bin_number:\n # count에 1을 더한다.\n count += 1\n\n # count = comb로 만들 수 있는 단어의 개수\n max_count = max(max_count, count)\n\n print(max_count)\n","sub_path":"BOJ-Solving/Implement/1062.py","file_name":"1062.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"626732737","text":"def fastest_horse(races: list) -> int:\n winners = list()\n for race in races:\n race_times = list()\n for time in race:\n minutes, seconds = time.split(':')\n race_times.append(int(minutes) * 60 + int(seconds))\n winners.append(race_times)\n print(winners)\n winners = list(map(sum, zip(*winners)))\n print(winners)\n return winners.index(min(winners)) + 1\n\n\nif __name__ == '__main__':\n print(\"Example:\")\n print(fastest_horse([['1:13', '1:26', '1:11']]))\n\n # These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert fastest_horse([['1:13', '1:26', '1:11'], ['1:10', '1:18', '1:14'], ['1:20', '1:23', '1:15']]) == 3\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")","sub_path":"the-fastest-horse.py","file_name":"the-fastest-horse.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"359830206","text":"# -*- coding: utf-8 -*-\nimport pytesseract\nfrom PIL import Image\n\n\nimg = Image.open('imagem2.jpg')\npytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract'\n\nresult = pytesseract.image_to_string(img)\n\n\nprint(\" A mágica do tesseract \")\nprint(\"********************************\\n\")\nprint(result)\n\n","sub_path":"Principal.py","file_name":"Principal.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240806546","text":"from suntime import Sun, SunTimeException\nfrom datetime import datetime\nfrom utils import text, fonts, config\n\n\nclass Clock:\n duration: int\n sun: Sun\n sunrise: str\n sunset: str\n\n def __init__(self, duration):\n self.duration = duration\n self.sun = Sun(config.data[\"lat\"], config.data[\"lon\"])\n\n def prepare(self):\n # Get sunrise and sunset times; do nothing if an exception is thrown (e.g. sun never rises)\n try:\n self.sunrise = self.sun.get_local_sunrise_time().strftime(\"%H:%M\")\n except SunTimeException:\n self.sunrise = \"-\"\n\n try:\n self.sunset = self.sun.get_local_sunset_time().strftime(\"%H:%M\")\n except SunTimeException:\n self.sunset = \"-\"\n\n def render(self, canvas):\n # Build and draw time and date\n time = text.Text(datetime.now().strftime(\"%H:%M\"), fonts.large, canvas)\n date = text.Text(datetime.now().strftime(\"%a, %b %-d\"), fonts.regular, canvas)\n\n time.draw((128 - time.size[0], 0))\n date.draw((128 - date.size[0], time.size[1] + 4))\n\n sunset = text.Text(self.sunset, fonts.regular, canvas)\n sunrise = text.Text(self.sunrise, fonts.regular, canvas)\n\n ic_down = text.Text(\"\\uf063\", fonts.fa, canvas)\n ic_up = text.Text(\"\\uf062\", fonts.fa, canvas)\n ic_sun = text.Text(\"\\uf185\", fonts.faLarge, canvas)\n\n sun_position = 128 # Y position at which the first bit of sun information is displayed\n\n sun_position -= sunset.size[0]\n sunset.draw((sun_position, 62 - sunset.size[1]))\n\n sun_position -= ic_down.size[0] + 1\n ic_down.draw((sun_position, 62 - ic_down.size[1]))\n\n sun_position -= sunrise.size[0] + 8\n sunrise.draw((sun_position, 62 - sunrise.size[1]))\n\n sun_position -= ic_up.size[0] + 1\n ic_up.draw((sun_position, 62 - ic_up.size[1]))\n\n sun_position -= ic_sun.size[0] + 6\n ic_sun.draw((sun_position, 64 - ic_sun.size[1]))\n","sub_path":"widgets/clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407441341","text":"\n# Utility function\ndef convert_html_to_pdf(source_html, output_filename):\n\tfrom xhtml2pdf import pisa # import python module\n\n\t# open output file for writing (truncated binary)\n\tresult_file = open(output_filename, \"w+b\")\n\n\t# convert HTML to PDF\n\tpisa_status = pisa.CreatePDF(\n\t\t\tsource_html, # the HTML to convert\n\t\t\tdest=result_file) # file handle to recieve result\n\n\t# close output file\n\tresult_file.close() # close output file\n\n\t# return True on success and False on errors\n\treturn pisa_status.err\n\ndef makePDF(name=\"name\", nVertices=\"nVertices\", nEdges=\"nEdges\", maxValency=\"maxValency\", avgValency=\"avgValency\", curve=\"curve\",diameter=\"not computed\"):\n\tprint(\" * Building PDF report\")\n\n\timport matplotlib.pyplot as plt\n\tfrom matplotlib.collections import EventCollection\n\timport io\n\timport base64\n\n\t# plot the data\n\tfig = plt.figure()\n\tax = fig.add_subplot(1, 1, 1)\n\tax.plot(curve['x'], curve['y'], color='tab:red')\n\n\txevents1 = EventCollection(curve['x'], color='tab:blue', linelength=0.5)\n\tyevents1 = EventCollection(curve['y'], color='tab:blue', linelength=0.5,orientation='vertical')\n\n\t# add the events to the axis\n\tax.add_collection(xevents1)\n\tax.add_collection(yevents1)\n\n\n\tif not diameter:\n\t\tdiameter = \"not computed\"\n\n\t# set the limits\n\tax.set_xlim([0, maxValency+1])\n\tax.set_ylim([0, max(curve['y'])+5])\n\n\tax.set_title('Distribution des degrés')\n\tplt.xlabel('Degré')\n\tplt.ylabel('Frequence d\\'apparition (%)')\n\n\t# display the plot\n\t# plt.show()\n\n\tmy_stringIObytes = io.BytesIO()\n\tplt.savefig(my_stringIObytes, format='jpg')\n\tmy_stringIObytes.seek(0)\n\tmy_base64_jpgData = base64.b64encode(my_stringIObytes.read())\n\n\twith open('template/index.html') as template:\n\n\t\treport_html = template.read().replace('\\n', '').replace('\\t', '').format(image=my_base64_jpgData, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcaption='Salut', width=600, height=400, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tname=name, nVertices=nVertices, nEdges=nEdges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaxValency=maxValency, avgValency=avgValency,diameter=diameter)\n\n\t\tconvert_html_to_pdf(report_html, name + '-report.pdf')\n\n\t\treturn \"report-2.pdf\"\n","sub_path":"src/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"610250587","text":"def unitImpulse(lb, up):\n assert(lb<=up), \"Lower Bound can't be greater than Upper bound\"\n # Talking the samples range\n n = np.arange(lb, up+1, 1)\n x_n = []\n for i in n:\n if i == 0:\n x_n.append(1)\n else:\n x_n.append(0) \n x_n = np.array(x_n)\n \n return (n, x_n)\n","sub_path":"Unit Impulse/Impulse.py","file_name":"Impulse.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98401411","text":"import os, sys\npathname = os.path.dirname(sys.argv[0])\nfull_pathname = os.path.abspath(pathname)\nsplit_pathname = full_pathname.split(sep=\"mvesc\")\nbase_pathname = os.path.join(split_pathname[0], \"mvesc\")\n\nimport estimate_prediction_model\nfrom generate_yaml import generate_yaml\nfrom my_timer import Timer\nimport time\n\n\n# setting options that will stay constant for this batch\ntemplate_options = {\n 'batch_name' : '08_09_2016_grade_10', \n 'model_classes': ['logit','DT','RF','ET','SVM','GB'],\n 'write_to_database': True,\n 'user': 'ht',\n 'test_set_type': 'temporal_cohort',\n 'cv_criterions': ['custom_precision_5','custom_precision_10',\n 'custom_recall_5', 'f1'],\n # if cv_scheme = 'k_fold', need 'n_folds' key \n 'n_folds': 5,\n 'prediction_grade': 10, \n 'cohorts_test': [2013],\n 'cohorts_val': [2012],\n 'debug': False,\n 'features': 'all',\n 'imputation': 'median_plus_dummies',\n 'scaling': 'robust'\n}\n\ncv_scheme_list = ['leave_cohort_out', 'past_cohorts_only', 'k_fold']\noutcome_list = ['not_on_time', 'is_dropout', 'definite']\ncohorts = [range(a, 2012) for a in range(2007,2012)]\ngrade_ranges = [range(a,10) for a in reversed(range(5,10))]\ntime_scales = list(zip(cohorts,grade_ranges)) # change for different predictions\n\nwith Timer('batch {}'.format(template_options['batch_name'])) as batch_timer:\n c = 0; #counter for yaml naming\n for cv_scheme in cv_scheme_list:\n template_options['cv_scheme'] = cv_scheme\n for outcome in outcome_list:\n template_options['outcome'] = outcome\n for years, grades in time_scales:\n if len(years)==1 and 'cohort' in cv_scheme:\n continue\n template_options['cohorts_training']=years\n template_options['feature_grade_range']=grades\n # innermost layer of loop\n template_options['random_seed'] = time.time()\n template_options['name'] = template_options\\\n ['batch_name']+\\\n '_param_set_'+str(c)\n template_options['description'] = \"running second pass for grade 10\"\n generate_yaml(template_options)\n model_option_path = os.path.join(base_pathname,\n 'Models_Results',\n 'model_options',\n template_options\\\n ['batch_name'],\n template_options['name']\n +'.yaml')\n grid_option_path = os.path.join(base_pathname,\n 'Models_Results',\n 'grid_options',\n 'grid_options_small.yaml')\n try:\n estimate_prediction_model.main(['-m', model_option_path,\n '-g', grid_option_path])\n except:\n print(template_options)\n raise\n print('param set {0} finished: run for {1} seconds so far'\\\n .format(c, batch_timer.time_check()))\n c = c+1\n","sub_path":"Models_Results/08_09_2016_grade_10.py","file_name":"08_09_2016_grade_10.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"507382597","text":"from flask import Flask\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\n\nimport datetime\nfrom slugify import slugify\nfrom resources.jsonEncoder import DateTimeEncoder\n\nfrom modelos.person import PersonModel\n\n\nposts = []\n\nclass PersonResource(Resource):\n\n\tparser = reqparse.RequestParser()\n\tparser.add_argument('login', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('password', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('nicename', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('email', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('image', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('status', type=int, help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('key_activate', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('id_person_type', type=int, help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('description', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('facebook', help='Whoooo - This field cannot be left blank!')\n\tparser.add_argument('twitter', help='Whoooo - This field cannot be left blank!')\n\n\t#@jwt_required()\n\tdef post(self):\n\n\t\tresult = PersonResource.parser.parse_args()\n\n\t\tp = PersonModel(\n\t\t\tlogin = result['login'],\n\t\t\tpassword = result['password'],\n\t\t\tnicename = result['nicename'],\n\t\t\temail = result['email'],\n\t\t\timage = result['image'],\n\t\t\tstatus = result['status'],\n\t\t\tkey_activate = result['key_activate'],\n\t\t\tid_person_type = result['id_person_type'],\n\t\t\tdescription = result['description'],\n\t\t\tfacebook = result['facebook'],\n\t\t\ttwitter = result['twitter']\t\n\t\t)\n\t\treturn p.save_to_db()\n\n\tdef get(self, email_author):\n\t\tdata = PersonModel.find_by_email(email_author)\t\n\t\tif data:\n\t\t\tpersons = data.json()\n\t\t\treturn {\"author\": persons},200\n\t\telse:\n\t\t\treturn {'message': 'Not found person'}, 404\t\n\t\t\n\n\t\n\n\n\n\n","sub_path":"resources/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590573380","text":"import youtube_dl\n\noptions = {\n \"outtmpl\":\"/mp3/%(title)s.%(ext)s\",\n \"format\":\"bestaudio/best\",\n \"postprocessors\":[{\n \"key\":\"FFmpegExtractAudio\",\n \"preferredcodec\":\"mp3\",\n \"preferredquality\":\"320\"\n }]\n }\n\nwith youtube_dl.YoutubeDL(options) as ydl:\n ydl.download([\"https://www.youtube.com/watch?v=0yW7w8F2TVA\"])","sub_path":"practice/download_mp3.py","file_name":"download_mp3.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259630036","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nData file class\n\nData File structure is:\nyyyy-mm-dd\n Client\n Flies\n Fly_n\n epoch_runs\n series_00n (attrs = protocol_parameters)\n acquisition\n epochs\n epoch_001 (attrs = epoch_parameters, convenience_parameters)\n epoch_002\n rois\n stimulus_timing\n Notes\n\n\"\"\"\nimport h5py\nimport os\nfrom datetime import datetime, timezone\nimport numpy as np\n\n\nclass Data():\n def __init__(self, cfg):\n self.experiment_file_name = None\n self.series_count = 1\n self.fly_metadata = {} # populated in GUI or user protocol\n self.current_fly = None\n self.user_name = cfg.get('user_name')\n self.rig_name = cfg.get('rig_name')\n self.cfg = cfg\n\n # # # Metadata defaults # # #\n self.experimenter = self.cfg.get('experimenter', '')\n\n # # # Lists of fly metadata # # #\n self.prepChoices = self.cfg.get('prep_choices', [])\n self.driverChoices = self.cfg.get('driver_choices', [])\n self.indicatorChoices = self.cfg.get('indicator_choices', [])\n self.effectorChoices = self.cfg.get('effector_choices', [])\n\n # load rig-specific metadata things\n self.data_directory = self.cfg.get('rig_config').get(self.rig_name).get('data_directory', os.getcwd())\n self.rig = self.cfg.get('rig_config').get(self.rig_name).get('rig', '(rig)')\n self.screen_center = self.cfg.get('rig_config').get(self.rig_name).get('screen_center', [0, 0])\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# # # # # # # # # Creating experiment file and groups # # # # # # # # # # # #\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n def initializeExperimentFile(self):\n \"\"\"\n Create HDF5 data file and initialize top-level hierarchy nodes\n \"\"\"\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'w-') as experiment_file:\n # Experiment date/time\n init_now = datetime.now()\n date = init_now.isoformat()[:-16]\n init_time = init_now.strftime(\"%H:%M:%S\")\n init_unix_time = init_now.astimezone(timezone.utc).timestamp()\n\n # Write experiment metadata as top-level attributes\n experiment_file.attrs['date'] = date\n experiment_file.attrs['init_time'] = init_time\n experiment_file.attrs['init_unix_time'] = init_unix_time\n experiment_file.attrs['data_directory'] = self.data_directory\n experiment_file.attrs['experimenter'] = self.experimenter\n experiment_file.attrs['rig'] = self.rig\n\n # Create a top-level group for epoch runs and user-entered notes\n experiment_file.create_group('Client')\n experiment_file.create_group('Flies')\n experiment_file.create_group('Notes')\n\n def createFly(self, fly_metadata):\n \"\"\"\n \"\"\"\n if fly_metadata.get('fly_id') in [x.get('fly_id') for x in self.getExistingFlyData()]:\n print('A fly with this ID already exists')\n return\n\n if self.experimentFileExists():\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r+') as experiment_file:\n fly_init_now = datetime.now()\n fly_init_time = fly_init_now.strftime('%H:%M:%S.%f')[:-4]\n fly_init_unix_time = fly_init_now.astimezone(timezone.utc).timestamp()\n flies_group = experiment_file['/Flies']\n new_fly = flies_group.create_group(fly_metadata.get('fly_id'))\n new_fly.attrs['init_time'] = fly_init_time\n new_fly.attrs['init_unix_time'] = fly_init_unix_time\n for key in fly_metadata:\n new_fly.attrs[key] = fly_metadata.get(key)\n\n new_fly.create_group('epoch_runs')\n\n self.selectFly(fly_metadata.get('fly_id'))\n else:\n print('Initialize a data file before defining a fly')\n\n def createEpochRun(self, protocol_object):\n \"\"\"\"\n \"\"\"\n # create a new epoch run group in the data file\n if (self.currentFlyExists() and self.experimentFileExists()):\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r+') as experiment_file:\n run_start_now = datetime.now()\n run_start_time = run_start_now.strftime('%H:%M:%S.%f')[:-4]\n run_start_unix_time = run_start_now.astimezone(timezone.utc).timestamp()\n fly_group = experiment_file['/Flies/{}/epoch_runs'.format(self.current_fly)]\n new_epoch_run = fly_group.create_group('series_{}'.format(str(self.series_count).zfill(3)))\n new_epoch_run.attrs['run_start_time'] = run_start_time\n new_epoch_run.attrs['run_start_unix_time'] = run_start_unix_time\n for key in protocol_object.run_parameters: # add run parameter attributes\n new_epoch_run.attrs[key] = protocol_object.run_parameters[key]\n\n for key in protocol_object.protocol_parameters: # add user-entered protocol params\n new_epoch_run.attrs[key] = protocol_object.protocol_parameters[key]\n\n # add subgroups:\n new_epoch_run.create_group('acquisition')\n new_epoch_run.create_group('epochs')\n new_epoch_run.create_group('rois')\n new_epoch_run.create_group('stimulus_timing')\n\n else:\n print('Create a data file and/or define a fly first')\n\n def createEpoch(self, protocol_object):\n \"\"\"\n \"\"\"\n if (self.currentFlyExists() and self.experimentFileExists()):\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r+') as experiment_file:\n epoch_now = datetime.now()\n epoch_time = epoch_now.strftime('%H:%M:%S.%f')\n epoch_unix_time = epoch_now.astimezone(timezone.utc).timestamp()\n epoch_run_group = experiment_file['/Flies/{}/epoch_runs/series_{}/epochs'.format(self.current_fly, str(self.series_count).zfill(3))]\n new_epoch = epoch_run_group.create_group('epoch_{}'.format(str(protocol_object.num_epochs_completed+1).zfill(3)))\n new_epoch.attrs['epoch_time'] = epoch_time\n new_epoch.attrs['epoch_unix_time'] = epoch_unix_time\n\n epochParametersGroup = new_epoch\n if type(protocol_object.epoch_parameters) is tuple: # stimulus is tuple of multiple stims layered on top of one another\n num_stims = len(protocol_object.epoch_parameters)\n for stim_ind in range(num_stims):\n for key in protocol_object.epoch_parameters[stim_ind]:\n prefix = 'stim{}_'.format(str(stim_ind))\n epochParametersGroup.attrs[prefix + key] = hdf5ifyParameter(protocol_object.epoch_parameters[stim_ind][key])\n\n elif type(protocol_object.epoch_parameters) is dict: # single stim class\n for key in protocol_object.epoch_parameters:\n epochParametersGroup.attrs[key] = hdf5ifyParameter(protocol_object.epoch_parameters[key])\n\n convenienceParametersGroup = new_epoch\n for key in protocol_object.convenience_parameters: # save out convenience parameters\n convenienceParametersGroup.attrs[key] = hdf5ifyParameter(protocol_object.convenience_parameters[key])\n\n else:\n print('Create a data file and/or define a fly first')\n\n def endEpoch(self, protocol_object):\n \"\"\"\n Save the timestamp when the epoch ends\n \"\"\"\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r+') as experiment_file:\n epoch_end_now = datetime.now()\n epoch_end_time = epoch_end_now.strftime('%H:%M:%S.%f')\n epoch_end_unix_time = epoch_end_now.astimezone(timezone.utc).timestamp()\n epoch_run_group = experiment_file['/Flies/{}/epoch_runs/series_{}/epochs'.format(self.current_fly, str(self.series_count).zfill(3))]\n epoch_group = epoch_run_group['epoch_{}'.format(str(protocol_object.num_epochs_completed+1).zfill(3))]\n epoch_group.attrs['epoch_end_time'] = epoch_end_time\n epoch_group.attrs['epoch_end_unix_time'] = epoch_end_unix_time\n\n def createNote(self, noteText):\n \"\"\n \"\"\n if self.experimentFileExists():\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r+') as experiment_file:\n note_now = datetime.now()\n note_time = note_now.strftime('%H:%M:%S.%f')[:-4]\n note_unix_time = note_now.astimezone(timezone.utc).timestamp()\n notes = experiment_file['/Notes']\n notes.attrs[note_time] = f'[{note_unix_time}] {noteText}'\n else:\n print('Initialize a data file before writing a note')\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# # # # # # # # # Retrieve / query data file # # # # # # # # # # # # # # # # #\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n def experimentFileExists(self):\n if self.experiment_file_name is None:\n tf = False\n else:\n tf = os.path.isfile(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'))\n return tf\n\n def currentFlyExists(self):\n if self.current_fly is None:\n tf = False\n else:\n tf = True\n return tf\n\n def getExistingSeries(self):\n all_series = []\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r') as experiment_file:\n for fly_id in list(experiment_file['/Flies'].keys()):\n new_series = list(experiment_file['/Flies/{}/epoch_runs'.format(fly_id)].keys())\n all_series.append(new_series)\n all_series = [val for s in all_series for val in s]\n series = [int(x.split('_')[-1]) for x in all_series]\n return series\n\n def getHighestSeriesCount(self):\n series = self.getExistingSeries()\n if len(series) == 0:\n return 0\n else:\n return np.max(series)\n\n def getExistingFlyData(self):\n # return list of dicts for fly metadata already present in experiment file\n fly_data_list = []\n if self.experimentFileExists():\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r') as experiment_file:\n for fly in experiment_file['/Flies']:\n new_fly = experiment_file['/Flies'][fly]\n new_dict = {}\n for at in new_fly.attrs:\n new_dict[at] = new_fly.attrs[at]\n\n fly_data_list.append(new_dict)\n return fly_data_list\n\n def selectFly(self, fly_id):\n self.current_fly = fly_id\n\n def advanceSeriesCount(self):\n self.series_count += 1\n\n def updateSeriesCount(self, val):\n self.series_count = val\n\n def getSeriesCount(self):\n return self.series_count\n\n def reloadSeriesCount(self):\n all_series = []\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r') as experiment_file:\n for fly_id in list(experiment_file['/Flies'].keys()):\n new_series = list(experiment_file['/Flies/{}/epoch_runs'.format(fly_id)].keys())\n all_series.append(new_series)\n all_series = [val for s in all_series for val in s]\n series = [int(x.split('_')[-1]) for x in all_series]\n\n if len(series) == 0:\n self.series_count = 0 + 1\n else:\n self.series_count = np.max(series) + 1\n\n\nclass AODscopeData(Data):\n def __init__(self, cfg):\n super().__init__(cfg)\n self.poi_scan = True\n self.poi_count = 1\n self.xyt_count = 1\n\n def advanceSeriesCount(self):\n self.series_count += 1\n if self.poi_scan:\n self.poi_count += 1\n else:\n self.xyt_count += 1\n\n def updateSeriesCount(self, val):\n if self.poi_scan:\n self.poi_count = val\n else:\n self.xyt_count = val\n\n def getSeriesCount(self):\n if self.poi_scan:\n return self.poi_count\n else:\n return self.xyt_count\n\n def getExistingSeries(self):\n poi_series = []\n xyt_series = []\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r') as experiment_file:\n for fly_id in list(experiment_file['/Flies'].keys()):\n for series_id in experiment_file['/Flies/{}/epoch_runs'.format(fly_id)]:\n acq_group = experiment_file['/Flies/{}/epoch_runs/{}/acquisition'.format(fly_id, series_id)]\n if acq_group.attrs['poi_scan']:\n poi_series.append(acq_group.attrs['poi_count'])\n else:\n xyt_series.append(acq_group.attrs['xyt_count'])\n\n poi_series = [int(x) for x in poi_series]\n xyt_series = [int(x) for x in xyt_series]\n\n if self.poi_scan:\n return poi_series\n else:\n return xyt_series\n\n def createEpochRun(self, protocol_object):\n \"\"\"\"\n \"\"\"\n # create a new epoch run group in the data file\n if (self.currentFlyExists() and self.experimentFileExists()):\n with h5py.File(os.path.join(self.data_directory, self.experiment_file_name + '.hdf5'), 'r+') as experiment_file:\n run_start_now = datetime.now()\n run_start_time = run_start_now.strftime('%H:%M:%S.%f')[:-4]\n run_start_unix_time = run_start_now.astimezone(timezone.utc).timestamp()\n fly_group = experiment_file['/Flies/{}/epoch_runs'.format(self.current_fly)]\n new_epoch_run = fly_group.create_group('series_{}'.format(str(self.series_count).zfill(3)))\n new_epoch_run.attrs['run_start_time'] = run_start_time\n new_epoch_run.attrs['run_start_unix_time'] = run_start_unix_time\n for key in protocol_object.run_parameters: # add run parameter attributes\n new_epoch_run.attrs[key] = protocol_object.run_parameters[key]\n\n for key in protocol_object.protocol_parameters: # add user-entered protocol params\n new_epoch_run.attrs[key] = protocol_object.protocol_parameters[key]\n\n # add subgroups:\n new_epoch_run.create_group('acquisition')\n new_epoch_run.create_group('epochs')\n new_epoch_run.create_group('rois')\n new_epoch_run.create_group('stimulus_timing')\n\n # AODscope-specific data stuff:\n new_epoch_run['acquisition'].attrs['poi_scan'] = self.poi_scan\n if self.poi_scan:\n new_epoch_run['acquisition'].attrs['poi_count'] = self.poi_count\n else:\n new_epoch_run['acquisition'].attrs['xyt_count'] = self.xyt_count\n else:\n print('Create a data file and/or define a fly first')\n\n# %% Useful functions. Outside classes.\n\n\ndef hdf5ifyParameter(value):\n if value is None:\n value = 'None'\n if type(value) is dict: # TODO: Find a way to split this into subgroups. Hacky work around.\n value = str(value)\n if type(value) is np.str_:\n value = str(value)\n\n return value\n","sub_path":"visprotocol/clandinin_data.py","file_name":"clandinin_data.py","file_ext":"py","file_size_in_byte":15995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"116983509","text":"\nfrom typing_extensions import Final\n\nfrom . import ProxyProtocolWantRead, ProxyProtocol, ProxyProtocolResult\nfrom .result import ProxyProtocolResultUnknown\nfrom .typing import StreamReaderProtocol\n\n__all__ = ['ProxyProtocolReader']\n\n\nclass ProxyProtocolReader:\n \"\"\"Read a PROXY protocol header from a stream.\n\n Args:\n pp: The PROXY protocol implementation.\n\n \"\"\"\n\n def __init__(self, pp: ProxyProtocol) -> None:\n super().__init__()\n self.pp: Final = pp\n\n def _parse(self, data: bytearray) -> ProxyProtocolResult:\n view = memoryview(data)\n try:\n return self.pp.parse(view)\n finally:\n view.release()\n\n async def _handle_want(self, reader: StreamReaderProtocol,\n want_read: ProxyProtocolWantRead) -> bytes:\n if want_read.want_bytes is not None:\n return await reader.readexactly(want_read.want_bytes)\n elif want_read.want_line:\n return await reader.readline()\n raise ValueError() from want_read\n\n async def read(self, reader: StreamReaderProtocol) -> ProxyProtocolResult:\n \"\"\"Read a complete PROXY protocol header from the input stream and\n return the result.\n\n Args:\n reader: The input stream.\n\n \"\"\"\n data = bytearray()\n while True:\n try:\n return self._parse(data)\n except ProxyProtocolWantRead as want_read:\n try:\n data += await self._handle_want(reader, want_read)\n except (EOFError, ConnectionResetError) as exc:\n return ProxyProtocolResultUnknown(exc)\n","sub_path":"proxyprotocol/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296884709","text":"import warnings\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Model(nn.Module):\n \"\"\"Model with same padding\n Conv5 uses a large filter size to aggregate the features from the whole box\"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n self.conv1 = nn.Conv3d(8, 32, 3, padding=\"same\")\n self.conv2 = nn.Conv3d(32, 64, 3, padding=\"same\")\n self.conv3 = nn.Conv3d(64, 80, 3, padding=\"same\")\n self.conv4 = nn.Conv3d(80, 20, 3, padding=\"same\")\n self.conv5 = nn.Conv3d(20, 20, 20, padding=\"same\")\n self.conv6 = nn.Conv3d(20, 16, 3, padding=\"same\")\n self.conv7 = nn.Conv3d(16, 1, 3, padding=\"same\")\n self.dropout1 = nn.Dropout(0.2)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = self.conv3(x)\n x = F.relu(x)\n\n x = self.conv4(x)\n x = F.relu(x)\n\n x = self.conv5(x)\n x = F.relu(x)\n x = self.dropout1(x)\n x = self.conv6(x)\n x = F.relu(x)\n\n x = self.conv7(x)\n x = torch.sigmoid(x)\n return x\n","sub_path":"Metal3D/utils/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128200366","text":"import unittest\nimport mock\n\nimport ngi_pipeline.engines.piper_ngi.workflows as workflows\n\n\nclass TestWorkflows(unittest.TestCase):\n\n def test_get_subtasks_for_level(self):\n sample_subtask = workflows.get_subtasks_for_level('sample')\n self.assertEqual(sample_subtask, ('merge_process_variantcall',))\n\n genotype_subtask = workflows.get_subtasks_for_level('genotype')\n self.assertEqual(genotype_subtask, ('genotype_concordance',))\n\n unknown_subtask = workflows.get_subtasks_for_level('unkown')\n self.assertEqual(unknown_subtask, [])\n\n @mock.patch('ngi_pipeline.engines.piper_ngi.workflows.workflow_genotype_concordance')\n def test_return_cl_for_workflow(self, mock_workflow):\n mock_workflow.return_value = 'some_command --option'\n workflow_name = 'genotype_concordance'\n qscripts_dir_path = 'path'\n setup_xml_path = 'other/path'\n config = {'some': 'config'}\n got_command_line = workflows.return_cl_for_workflow(workflow_name, \n qscripts_dir_path, \n setup_xml_path, \n config=config)\n expected_command_line = 'some_command --option'\n self.assertEqual(got_command_line, expected_command_line)\n mock_workflow.assert_called_once_with(config={'some': 'config'}, \n exec_mode='local', \n genotype_file=None, \n output_dir=None, \n qscripts_dir_path='path', \n setup_xml_path='other/path')\n\n with self.assertRaises(NotImplementedError):\n missing_workflow_name = 'not_implemented'\n got_command_line = workflows.return_cl_for_workflow(missing_workflow_name, \n qscripts_dir_path, \n setup_xml_path)\n\n def test_workflow_merge_process_variantcall(self):\n qscripts_dir_path = 'path'\n setup_xml_path = 'other/path'\n config = {'slurm': {'time': '1-00:00:00'},\n 'piper': {'threads': 2,\n 'jobNative': ['A', 'B'],\n 'gatk_key' : 'gatk_file.txt'\n }\n } \n exec_mode = 'sbatch'\n output_dir = 'path'\n got_command_line = workflows.workflow_merge_process_variantcall(qscripts_dir_path, \n setup_xml_path,\n config, \n exec_mode, \n output_dir=output_dir)\n\n expected_command_line = ('piper -Djava.io.tmpdir=$SNIC_TMP/java_tempdir '\n '-S path/DNABestPracticeVariantCalling.scala '\n '--xml_input other/path '\n '--global_config $PIPER_CONF '\n '--number_of_threads 2 '\n '--scatter_gather 1 '\n '--job_scatter_gather_directory $SNIC_TMP/scatter_gather '\n '--temp_directory $SNIC_TMP/piper_tempdir '\n '--run_directory $SNIC_TMP/piper_rundir '\n '-jobRunner ParallelShell '\n '--super_charge '\n '--ways_to_split 4 '\n '--job_walltime 86400 '\n '--disableJobReport '\n '-run '\n '--skip_recalibration '\n '--output_directory path '\n '-jobNative A B '\n '--variant_calling '\n '--analyze_separately '\n '--retry_failed 2 '\n '--keep_pre_bqsr_bam')\n self.assertEqual(got_command_line, expected_command_line)\n\n def test_workflow_dna_variantcalling(self):\n qscripts_dir_path = 'path'\n setup_xml_path = 'other/path'\n config = {'slurm': {'time': '1-00:00:00'},\n 'piper': {'threads': 2,\n 'jobNative': ['A', 'B'],\n 'gatk_key' : 'gatk_file.txt'\n }\n } \n exec_mode = 'sbatch'\n output_dir = 'path'\n got_command_line = workflows.workflow_dna_variantcalling(qscripts_dir_path, \n setup_xml_path,\n config, \n exec_mode, \n output_dir=output_dir)\n\n expected_command_line = ('piper -Djava.io.tmpdir=$SNIC_TMP/java_tempdir '\n '-S path/DNABestPracticeVariantCalling.scala '\n '--xml_input other/path '\n '--global_config $PIPER_CONF '\n '--number_of_threads 2 '\n '--scatter_gather 1 '\n '--job_scatter_gather_directory $SNIC_TMP/scatter_gather '\n '--temp_directory $SNIC_TMP/piper_tempdir '\n '--run_directory $SNIC_TMP/piper_rundir '\n '-jobRunner ParallelShell '\n '--super_charge '\n '--ways_to_split 4 '\n '--job_walltime 86400 '\n '--disableJobReport '\n '-run '\n '--skip_recalibration '\n '--output_directory path '\n '-jobNative A B')\n self.assertEqual(got_command_line, expected_command_line)","sub_path":"ngi_pipeline/tests/engines/piper_ngi/test_workflows.py","file_name":"test_workflows.py","file_ext":"py","file_size_in_byte":6494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"285236579","text":"import string\nimport secrets\n\ndef encrypt(input):\n encrypted = []\n soup = string.ascii_uppercase + string.ascii_lowercase + string.digits\n for i in input:\n i += secrets.choice(soup)\n encrypted.append(i)\n return \"\".join(encrypted)\n\ndef decrypt(input):\n decrypted = []\n for i in input:\n if input.index(i) is 0 or input.index(i) % 2 is 0:\n decrypted.append(i)\n return \"\".join(decrypted)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"175843657","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nfrom flask import Flask, request, jsonify\napp = Flask(__name__)\n\n@app.route('/hello',methods=['POST'])\ndef hello():\n print(request)\n message = request.get_json(force=True)\n print(message)\n name = message['name']\n response = {\n 'greeting':'Hello, '+ name + '!'\n \n }\n return jsonify(response)\n\n@app.route('/test')\ndef test():\n response = {'test':'Test Successfull'}\n return jsonify(response)\n\n","sub_path":"sample_app.py","file_name":"sample_app.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323710946","text":"\"\"\"\nFunctions that are shared by several (all) backends.\n\n\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\n\n\ndef get_data(h, density=False, cumulative=False, flatten=False):\n if density:\n if cumulative:\n data = (h / h.total).cumulative_frequencies\n else:\n data = h.densities\n else:\n if cumulative:\n data = h.cumulative_frequencies\n else:\n data = h.frequencies\n\n if flatten:\n data = data.flatten()\n return data\n\n\ndef get_err_data(h, density=False, cumulative=False, flatten=False):\n if cumulative:\n raise RuntimeError(\"Error bars not supported for cumulative plots.\")\n if density:\n data = h.errors / h.bin_sizes\n else:\n data = h.errors\n if flatten:\n data = data.flatten()\n return data\n","sub_path":"physt/plotting/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"516554266","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/10/31 下午5:32\n# @Author : czw@rich-f.com\n# @Site : www.rich-f.com\n# @File : utils.py\n# @Software: 富融钱通\n# @Function: 通用工具类\nimport logging\nimport random\nimport socket\nimport time\nimport sys\nimport traceback\nfrom flask import flash\n\nfrom test.settings import Config\n\nISOTIMEFORMAT = '%Y-%m-%d %X'\n\n\ndef flash_errors(form, category='warning'):\n '''\n Flash all errors for a form\n :param form: 表单\n :param category: 类别,此处错误类型\n :return:\n '''\n for field, errors in form.errors.items():\n for error in errors:\n flash('{0} - {1}'.format(getattr(form, field).label.text, error), category)\n\n\nclass TreeNode:\n def __int__(self, id=None, pid=None, children=None, merchant_code=None):\n \"\"\"\n 树节点信息\n :param id:\n :param pid:\n :param children:\n :return:\n \"\"\"\n self.id = id\n self.pid = pid\n self.children = children\n self.name = \"\"\n self.merchant_code = merchant_code\n\n def dict(self):\n return {'id': self.id, 'name': self.name,\n 'children': self.children, 'open': True}\n\n\ndef get_tree_node_by_sys_org(org_list, sys_org):\n \"\"\"\n 获取机构树子集\n :param org_list:\n :param sys_org:\n :return:\n \"\"\"\n try:\n tree_node_list = []\n tree_node = TreeNode()\n if sys_org:\n tree_node.id = sys_org.org_id\n tree_node.name = sys_org.org_name\n child_list = get_tree_nodes_ds(org_list, sys_org.org_code)\n tree_node.children = child_list\n tree_node_list.append(tree_node.dict())\n return tree_node_list\n except Exception as e:\n raise e\n\n\ndef get_tree_nodes_ds(org_list, pid):\n \"\"\"\n 获取树的子节点\n :param org_list:\n :param pid:\n :return:\n \"\"\"\n try:\n tree_node_list = []\n for sys_org in org_list:\n org_code = sys_org.org_code\n if pid == org_code:\n pass\n elif pid in org_code:\n tree_node = TreeNode()\n tree_node.id = sys_org.org_id\n tree_node.name = sys_org.org_name\n child_list = get_tree_nodes_ds(org_list, org_code)\n tree_node.children = child_list\n tree_node_list.append(tree_node.dict())\n return tree_node_list\n except Exception as e:\n raise e\n\n\ndef get_current_time():\n \"\"\"\n 获取当前时间点\n :return:\n \"\"\"\n return time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))\n\n\ndef generate_verification_code():\n \"\"\"\n 随机生成6位数\n :return:\n \"\"\"\n code_list = []\n for i in range(10): # 0-9数字\n code_list.append(str(i))\n myslice = random.sample(code_list, 6) # 从list中随机获取6个元素,作为一个片断返回\n verification_code = ''.join(myslice) # list to string\n return verification_code\n\n\ndef import_class(import_str):\n \"\"\"\n 动态引入类\n Returns a class from a string including module and class.\n ersionadded:: 0.3\n :param import_str: 引入类的路径字符串\n e.g richwecsweb.sysadmin.forms.OrgForm\n :return:\n \"\"\"\n logging.info('动态引入FORM表单')\n mod_str, _sep, class_str = import_str.rpartition('.')\n __import__(mod_str)\n try:\n __import__(mod_str)\n return getattr(sys.modules[mod_str], class_str)\n except AttributeError:\n raise ImportError('Class %s cannot be found (%s)' %\n (class_str,\n traceback.format_exception(*sys.exc_info())))\n\n\ndef socket_query_param(data):\n \"\"\"\n 向tcp_server 发送报文指令\n data: 指令内容\n :return:\n \"\"\"\n try:\n param_query = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n param_query.connect((Config.TCP_SERVER_URL, 25000))\n data = str(data).encode('utf-8')\n param_query.send(data)\n revc_data = param_query.recv(1024)\n revc_data = revc_data.decode()\n return eval(revc_data)\n except BaseException as e:\n logging.debug(e)\n return e","sub_path":"test/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"27110497","text":"import time\nimport krpc\n\nturn_start_altitude = 250\nturn_end_altitude = 45000\n\nconn = krpc.connect(name='Orbital flight')\nvessel = conn.space_center.active_vessel\nap = vessel.auto_pilot\n\naltitude = conn.add_stream(getattr, vessel.flight(), 'mean_altitude')\nsrb_fuel = conn.add_stream(vessel.resources.amount, 'SolidFuel')\nengine_fuel = conn.add_stream(vessel.resources.amount, 'LiquidFuel')\nperiapsis_altitude = conn.add_stream(getattr, vessel.orbit, 'periapsis_altitude')\napoapsis_altitude = conn.add_stream(getattr, vessel.orbit, 'apoapsis_altitude')\nprograde_direction = conn.add_stream(getattr, vessel.flight(), 'prograde')\nretrograde_direction = conn.add_stream(getattr, vessel.flight(), 'retrograde')\n\nvessel.control.sas = True\nvessel.control.throttle = 1.0\n\nprint('Launch in:\\n3')\ntime.sleep(1)\nprint('2')\ntime.sleep(1)\nprint('1')\ntime.sleep(1)\nprint('Go!')\n\nap.target_pitch_and_heading(90, 90)\nap.engage()\nvessel.control.activate_next_stage()\n\nboosters_separated = False\nin_orbit = False\nangle = 0.0\nwhile True:\n if altitude() >= turn_start_altitude and altitude() < turn_end_altitude:\n turn = (altitude() - turn_start_altitude)/(turn_end_altitude - turn_start_altitude)\n new_angle = 85.0 * turn\n if abs(new_angle - angle) > 0.5:\n angle = new_angle\n print(f'Turning to\\t{90 - angle} degrees.')\n ap.target_pitch_and_heading(90 - angle, 90)\n if srb_fuel() < 0.01 and boosters_separated == False:\n print('Separating boosters...')\n vessel.control.activate_next_stage()\n print('Activating engine...')\n vessel.control.throttle = 0.75\n vessel.control.activate_next_stage()\n boosters_separated = True\n in_orbit = True\n if altitude() > turn_end_altitude or apoapsis_altitude() > 100000:\n vessel.control.throttle = 0.0\n if engine_fuel() < 0.01:\n print('Separating engine...')\n vessel.control.activate_next_stage()\n if abs(altitude() - apoapsis_altitude()) < 500 and in_orbit:\n print('Rising periapsis...')\n ap.target_direction = prograde_direction()\n ap.wait()\n vessel.control.throttle = 1.0\n while abs(periapsis_altitude() - 100000) > 2000:\n ap.target_direction = prograde_direction()\n print(f'Periapsis altitude: {periapsis_altitude()} m')\n print(f'Complete! Periapsis altitude: {periapsis_altitude()} m')\n vessel.control.throttle = 0.0\n break\nwhile True:\n if abs(altitude() - apoapsis_altitude()) < 500:\n print('Falling periapsis...')\n ap.target_direction = retrograde_direction()\n ap.wait()\n while periapsis_altitude() > 0:\n vessel.control.throttle = 0.25\n ap.target_direction = retrograde_direction()\n print(f'Periapsis altitude: {periapsis_altitude()} m')\n vessel.control.throttle = 0.0\n if vessel.flight(vessel.orbit.body.reference_frame).vertical_speed < -0.01 and altitude() < 10000:\n ap.target_pitch_and_heading(90, 90)\n vessel.control.activate_next_stage()\n break","sub_path":"mission4.py","file_name":"mission4.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"71622811","text":"from blog.views.generic.article import (\n ArticleDetailView,\n ArticleListView,\n IndexView,\n)\nfrom blog.views.generic.category import CategoryDetailView, CategoryListView\nfrom blog.views.generic.comment import ArticleCommentView\nfrom django.urls import path\n\nurlpatterns = [\n path(\"\", IndexView.as_view(), name=\"index\"),\n path(\"article/\", ArticleListView.as_view(), name=\"articles\"),\n path(\"article//\", ArticleDetailView.as_view(), name=\"article\"),\n path(\"category/\", CategoryListView.as_view(), name=\"categories\"),\n path(\n \"category//\", CategoryDetailView.as_view(), name=\"category\"\n ),\n path(\n \"article//comments/\",\n ArticleCommentView.as_view(),\n name=\"comment\",\n ),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605528308","text":"import FWCore.ParameterSet.Config as cms\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\noptions = VarParsing('standard')\noptions.register('runOnMC', True, VarParsing.multiplicity.singleton, VarParsing.varType.bool, \"decide if running on MC or data\")\noptions.register('runOnElectrons', True, VarParsing.multiplicity.singleton, VarParsing.varType.bool, \"decide if running on electrons\")\noptions.register('runOnMuons', True, VarParsing.multiplicity.singleton, VarParsing.varType.bool, \"decide if running on muons\")\noptions.parseArguments()\n\nprocess = cms.Process(\"BToDLv\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\nprocess.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')\nprocess.load('Configuration.StandardSequences.GeometryDB_cff')\nprocess.load('TrackingTools.TransientTrack.TransientTrackBuilder_cfi')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nif(options.runOnMC):\n process.GlobalTag.globaltag = 'START53_V7A::All'\nelse:\n process.GlobalTag.globaltag = 'GR_R_53_V16::All'\n\nimport HLTrigger.HLTfilters.triggerResultsFilter_cfi as hlt\nprocess.HLTFilter = hlt.triggerResultsFilter.clone(\n triggerConditions = cms.vstring(\n 'HLT_DoubleMu4_Jpsi_Displaced_v*'\n ),\n hltResults = cms.InputTag(\"TriggerResults\",\"\",\"HLT\"),\n l1tResults = cms.InputTag( \"\" ),\n throw = cms.bool( False) #set to false to deal with missing triggers while running over different trigger menus\n)\n\nprocess.scrapingFilter = cms.EDFilter('FilterOutScraping',\n applyfilter = cms.untracked.bool( True ),\n debugOn = cms.untracked.bool( False ),\n numtrack = cms.untracked.uint32( 10 ),\n thresh = cms.untracked.double( 0.25 ),\n)\n\nprocess.load('CommonTools.RecoAlgos.HBHENoiseFilter_cfi')\n# s. https://hypernews.cern.ch/HyperNews/CMS/get/JetMET/1196.html\nprocess.HBHENoiseFilter.minIsolatedNoiseSumE = 999999.\nprocess.HBHENoiseFilter.minNumIsolatedNoiseChannels = 999999\nprocess.HBHENoiseFilter.minIsolatedNoiseSumEt = 999999.\n\nprocess.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')\nprocess.goodOfflinePrimaryVertices.filter = cms.bool(True)\n\nprocess.eventCleaning = cms.Sequence(process.goodOfflinePrimaryVertices)\nif not options.runOnMC:\n process.eventCleaning += process.scrapingFilter\n process.eventCleaning += process.HBHENoiseFilter\n\nprocess.load('CommonTools.ParticleFlow.PF2PAT_cff')\nprocess.pfPileUp.Vertices = cms.InputTag('goodOfflinePrimaryVertices')\nprocess.pfNoPileUp.Vertices = cms.InputTag('goodOfflinePrimaryVertices')\nprocess.pfPileUpIso.Vertices = cms.InputTag('goodOfflinePrimaryVertices')\nprocess.pfNoPileUpIso.Vertices = cms.InputTag('goodOfflinePrimaryVertices')\nprocess.pfMuonsFromVertex.vertices = cms.InputTag('goodOfflinePrimaryVertices')\nprocess.pfIsolatedMuons.doDeltaBetaCorrection = True\nprocess.pfElectronsFromVertex.vertices = cms.InputTag('goodOfflinePrimaryVertices')\nprocess.pfIsolatedElectrons.doDeltaBetaCorrection = True\n\nprocess.pfMuonsForB = process.pfAllMuons.clone(\n src = 'pfNoElectron'\n)\nprocess.pfSelectedMuonsForB = process.pfSelectedMuons.clone(\n src = 'pfMuonsForB',\n cut = 'pt > 5.0 && abs(eta) < 2.5 && muonRef.isGlobalMuon && muonRef.isTrackerMuon && muonRef.globalTrack.normalizedChi2 < 10.0 && muonRef.innerTrack.hitPattern.trackerLayersWithMeasurement > 5 && muonRef.globalTrack.hitPattern.numberOfValidMuonHits > 0 && muonRef.innerTrack.hitPattern.numberOfValidPixelHits > 0 && muonRef.numberOfMatchedStations > 1'\n)\n\nprocess.pfElectronsForB = process.pfAllElectrons.clone(\n src = 'pfNoElectron'\n)\nprocess.pfSelectedElectronsForB = process.pfSelectedElectrons.clone(\n src = 'pfElectronsForB',\n cut = 'pt > 5.0 && abs(eta) < 2.5 && gsfTrackRef.hitPattern.numberOfValidHits > 10 && gsfTrackRef.hitPattern.numberOfValidPixelHits > 1 && gsfTrackRef.normalizedChi2 < 10.0'\n)\n\nprocess.pfChargedHadronsFromVertex = cms.EDFilter(\"IPCutPFCandidateSelector\",\n src = cms.InputTag(\"pfAllChargedHadrons\"), # PFCandidate source\n vertices = cms.InputTag(\"goodOfflinePrimaryVertices\"), # vertices source\n d0Cut = cms.double(0.2), # transverse IP\n dzCut = cms.double(0.5), # longitudinal IP\n d0SigCut = cms.double(99.), # transverse IP significance\n dzSigCut = cms.double(99.), # longitudinal IP significance\n)\nprocess.pfSelectedChargedHadrons = cms.EDFilter(\"GenericPFCandidateSelector\",\n src = cms.InputTag(\"pfChargedHadronsFromVertex\"),\n cut = cms.string(\"pt > 0.6 && trackRef.isNonnull() && trackRef.numberOfValidHits() > 7 && trackRef.hitPattern.numberOfValidPixelHits > 1 && trackRef.normalizedChi2 < 5.0\")\n)\nprocess.pfChargedHadronsForAnalysis = cms.Sequence(\n process.pfChargedHadronsFromVertex *\n process.pfSelectedChargedHadrons\n)\n\nprocess.PF2PAT = cms.Sequence(\n process.pfNoPileUpSequence +\n process.pfParticleSelectionSequence + \n process.pfMuonSequence + \n process.pfNoMuon +\n process.pfElectronSequence +\n process.pfNoElectron +\n process.pfChargedHadronsForAnalysis\n)\nif options.runOnElectrons:\n process.PF2PAT += process.pfElectronsForB\n process.PF2PAT += process.pfSelectedElectronsForB\nif options.runOnMuons:\n process.PF2PAT += process.pfMuonsForB\n process.PF2PAT += process.pfSelectedMuonsForB\n\nprocess.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True))\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )\n\nprocess.source = cms.Source(\"PoolSource\",\n # replace 'myfile.root' with the source file you want to use\n fileNames = cms.untracked.vstring(\n #'/store/mc/Summer12_DR53X/TTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola/AODSIM/PU_S10_START53_V7A-v1/0000/FCB7FB42-ACE1-E111-B8AB-0025901D4936.root',\n #'/store/mc/Summer12_DR53X/TTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola/AODSIM/PU_S10_START53_V7A-v1/0000/C6577DA8-32E2-E111-AC51-0030487E55BB.root'\n '/store/mc/Summer12_DR53X/TTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola/AODSIM/PU_S10_START53_V7A-v1/0000/ACCEC445-28E2-E111-8950-003048C692CA.root'\n #'/store/mc/Summer12_DR53X/BJets_HT-1000ToInf_8TeV-madgraph/AODSIM/PU_S10_START53_V7A-v1/00000/006690BD-DD07-E211-AB31-001BFCDBD130.root'\n ),\n #eventsToProcess = cms.untracked.VEventRange('1:17043:5111631','1:17055:5115372','1:18017:5403811','1:32878:9861389')\n)\n\nprocess.load('GenTruth.TrackGenMatchProducer.trackgenmatchproducer_cfi')\nprocess.genEMatch = process.trackGenMatch.clone()\nprocess.genMuMatch = process.trackGenMatch.clone(\n Tracks = cms.InputTag('generalTracks'),\n PdgID = 13\n)\nprocess.genKMatch = process.trackGenMatch.clone(\n Tracks = cms.InputTag('generalTracks'),\n PdgID = 321\n)\nprocess.genPiMatch = process.genKMatch.clone(\n PdgID = 211\n)\nprocess.ctfTrackElecMatch = process.genEMatch.clone(\n Tracks = cms.InputTag(\"generalTracks\")\n)\nprocess.gsfTrackMuMatch = process.trackGenMatch.clone(\n PdgID = 13\n)\nprocess.genMatches = cms.Sequence(\n process.genKMatch +\n process.genPiMatch\n)\nif options.runOnElectrons:\n process.genMatches += process.genEMatch\n process.genMatches += process.ctfTrackElecMatch\nif options.runOnMuons:\n process.genMatches += process.genMuMatch\n process.genMatches += process.gsfTrackMuMatch\n\nfrom JPsiK.JPsiKAnalyzer.trackclusterizer_cfi import *\nprocess.btodenu = cms.EDAnalyzer('BMesonAnalyzer',\n ClusterizerBlock,\n PFLeptons = cms.InputTag('pfSelectedElectronsForB'),\n MCLepMatch = cms.string('genEMatch'),\n MCKMatch = cms.string('genKMatch'),\n MCPiMatch = cms.string('genPiMatch'),\n MC = cms.bool(options.runOnMC)\n)\nprocess.btodmunu = process.btodenu.clone(\n PFLeptons = cms.InputTag('pfSelectedMuonsForB'),\n MCLepMatch = cms.string('genMuMatch')\n)\nprocess.btodlnu = cms.Sequence()\nif options.runOnElectrons:\n process.btodlnu += process.btodenu\nif options.runOnMuons:\n process.btodlnu += process.btodmunu\n\nprocess.load(\"Electron.ElectronEfficiencyAnalyzer.electronmcefficiencyanalyzer_cfi\")\nprocess.electronMCEfficiency.PFLeptons = cms.InputTag(\"pfSelectedElectronsForB\")\nprocess.electronMCEfficiency.GsfTrackMatch = cms.string('genEMatch')\nprocess.electronMCEfficiency.UseSimTracks = False\n\nprocess.goodMuons = cms.EDFilter('MuonSelector',\n src = cms.InputTag('muons'),\n cut = cms.string('isTrackerMuon && isGlobalMuon'),\n filter = cms.bool(False)\n)\n\nprocess.muonMCEfficiency = process.electronMCEfficiency.clone(\n RecoCandidates = cms.InputTag('goodMuons'),\n PFLeptons = cms.InputTag('pfSelectedMuonsForB'),\n GsfTrackMatch = cms.string('gsfTrackMuMatch'),\n CtfTrackMatch = cms.string('genMuMatch'),\n IsElectron = False,\n)\n\nprocess.mcEfficiency = cms.Sequence()\nif options.runOnElectrons:\n process.mcEfficiency += process.electronMCEfficiency\nif options.runOnMuons:\n process.mcEfficiency += process.goodMuons\n process.mcEfficiency += process.muonMCEfficiency\n\nprocess.TFileService = cms.Service(\"TFileService\", \n fileName = cms.string(options.output),\n closeFileFast = cms.untracked.bool(True)\n)\n\nprocess.p = cms.Path(\n process.eventCleaning *\n process.PF2PAT\n)\nif options.runOnMC:\n process.p += process.genMatches\n process.p += process.mcEfficiency\n\nprocess.p += process.btodlnu \n","sub_path":"BMeson/BMesonAnalyzer/bmesonanalyzer_cfg.py","file_name":"bmesonanalyzer_cfg.py","file_ext":"py","file_size_in_byte":9158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"207693507","text":"#-*- coding: utf-8 -*-\r\n'''\r\nCreated on 2016年10月23日\r\n\r\n@author: 武明辉\r\n'''\r\nfrom django import template\r\n\r\nregister=template.Library()\r\n\r\n@register.assignment_tag\r\ndef pagination(current_page,num_of_display=12,num_of_backpages=5):\r\n ''' 1.Paginator.Page 实例\r\n 2.paginator 是实例 \r\n '''\r\n front_page=num_of_display-num_of_backpages-1\r\n html=r''\r\n #当总页数小于等于显示页数时候全部显示\r\n if current_page.paginator.num_pages<=num_of_display:\r\n for i in range(1,current_page.paginator.num_pages+1):\r\n if current_page.number==i: \r\n html+='
  • %s
  • '%(i,i)\r\n else:\r\n html+='
  • %s
  • '%(i,i)\r\n return html\r\n else:\r\n #的一种情况:当页数1到5,没有省略页,切位置内容不变\r\n if current_page.number<=num_of_display-num_of_backpages:\r\n for i in range(1,num_of_display+1):\r\n if current_page.number==i:\r\n html+='
  • %s
  • '%(i,i)\r\n else:\r\n html+='
  • %s
  • '%(i,i)\r\n html+='
  • ...
  • '\r\n return html\r\n elif current_page.number<=current_page.paginator.num_pages-num_of_backpages:\r\n #当前页大于5但是没有超过最后的5页时候。位置1,2不变,当前页码一直处于5\r\n html='
  • ...
  • '\r\n for i in range(current_page.number-front_page,current_page.number+num_of_backpages+1):\r\n if current_page.number==i:\r\n html+='
  • %s
  • '%(i,i)\r\n else:\r\n html+='
  • %s
  • '%(i,i)\r\n html+='
  • ...
  • '\r\n return html\r\n else:\r\n #当接近末尾时候:\r\n html='
  • ...
  • '\r\n for i in range(current_page.paginator.num_pages-num_of_backpages-front_page,current_page.paginator.num_pages+1):\r\n if current_page.number==i:\r\n html+='
  • %s
  • '%(i,i)\r\n else:\r\n html+='
  • %s
  • '%(i,i)\r\n return html \r\n \r\n \r\n \r\n \r\n ","sub_path":"fa/templatetags/mytags.py","file_name":"mytags.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288603546","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 29 16:21:45 2017\n\n@author: nice142\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nn = 3 # choose column index - date\nsize_index = 1 # choose size grouping number\n\nraw_data = pd.read_excel('exercise_v01.xlsx',sheetname='Raw_data1',header=None)\n\ndata_big = raw_data[(raw_data[n] == size_index)]\ndata_big = data_big.loc[:,[1,n]]\n\nsize = pd.read_excel('exercise_v01.xlsx',sheetname='시가총액1',header=None)\nni = pd.read_excel('exercise_v01.xlsx',sheetname='당기순이익1',header=None)\nadjprc = pd.read_excel('exercise_v01.xlsx',sheetname='수정주가1',header=None)\n\ndata = pd.concat([data_big, size[n], ni[n], adjprc[n]], axis = 1, join = 'inner', ignore_index = True)\ndata.columns = ['name', 'group', 'size', 'ni', 'adjprc']\ndata['1/per'] = data['ni'] / data['size'] \n\ndata=data[data['1/per'].notnull()]\ndata_size= len(data) \ndata=data.assign(rnk=np.floor(data['1/per'].rank(method='first')/((data_size+1)/5)))\n\ndata_top=data.query('rnk == 0')\ndata_bottom=data.query('rnk == 4')\n","sub_path":"기존자료/lshlsh.py","file_name":"lshlsh.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375031407","text":"from unittest import TestCase\nimport unittest\nimport tempfile\nimport os\n\nfrom traktor_nowplaying.core import TrackWriter\n\n\nclass TestTrackWriter(TestCase):\n def test_file_output(self):\n writer = TrackWriter()\n\n writer.update({\n 'title': 'Title',\n 'artist': 'Artist'\n })\n writer.update({\n 'title': '音楽',\n 'artist': 'Artist'\n })\n\n\nclass TestFileWriter(TestCase):\n def test_multiline_template_windows(self):\n with tempfile.TemporaryDirectory() as d:\n test_file_path = os.path.join(d, 'test.txt')\n\n writer = TrackWriter(\n output_format='{{artist}}\\r\\n{{title}}',\n outfile=test_file_path,\n quiet=True,\n append=True\n )\n writer.update([('artist', 'foo'), ('title', 'bar')])\n\n with open(test_file_path) as f:\n self.assertEqual(len(f.readlines()), 2)\n\n writer.update([('artist', 'foo2'), ('title', 'bar2')])\n\n with open(test_file_path) as f:\n self.assertEqual(len(f.readlines()), 4)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166237520","text":"# This file is part of atooms\n# Copyright 2010-2018, Daniele Coslovich\n\n\"\"\"Base correlation function.\"\"\"\n\nimport os\nimport logging\nfrom collections import defaultdict\n\nimport numpy\nfrom atooms.trajectory import Trajectory\nfrom atooms.trajectory.decorators import Unfolded\nfrom atooms.trajectory.decorators import change_species\nfrom atooms.system.particle import distinct_species\nfrom atooms.core.utils import Timer\ntry:\n from medepy.metadata import dump as _dump\nexcept ImportError:\n from .helpers import _dump\n\nfrom . import core\nfrom .helpers import adjust_skip\nfrom .progress import progress\n\n__all__ = ['acf', 'gcf', 'gcf_offset', 'Correlation']\n\n_log = logging.getLogger(__name__)\n#pp_output_path = '{trajectory.filename}.pp.{symbol}.{tag}'\n#pp_trajectory_format = None\n\n\ndef acf(grid, skip, t, x):\n \"\"\"\n Auto correlation function.\n\n Calculate the correlation between time t(i0) and t(i0+i)\n for all possible pairs (i0,i) provided by grid.\n \"\"\"\n cf = defaultdict(float)\n cnt = defaultdict(int)\n xave = numpy.average(x)\n for i in grid:\n for i0 in range(0, len(x)-i, skip):\n # Get the actual time difference\n dt = t[i0+i] - t[i0]\n cf[dt] += (x[i0+i]-xave) * (x[i0]-xave)\n cnt[dt] += 1\n\n # Return the ACF with the time differences sorted\n dt = sorted(cf.keys())\n return dt, [cf[ti] / cnt[ti] for ti in dt], cnt\n\n\ndef gcf(f, grid, skip, t, x):\n \"\"\"\n Generalized correlation function.\n\n Pass a function to apply to the data.\n Exemple: mean square displacement.\n \"\"\"\n # Calculate the correlation between time t(i0) and t(i0+i)\n # for all possible pairs (i0,i) provided by grid\n cf = defaultdict(float)\n cnt = defaultdict(int)\n for i in grid:\n # Note: len(x) gives x.shape[0]\n for i0 in progress(range(0, len(x)-i-1, skip)):\n # Get the actual time difference\n dt = t[i0+i] - t[i0]\n cf[dt] += f(x[i0+i], x[i0])\n cnt[dt] += 1\n\n # Return the ACF with the time differences sorted\n dt = sorted(cf.keys())\n return dt, [cf[ti] / cnt[ti] for ti in dt], [cnt[ti] for ti in dt]\n\n\ndef gcf_offset(f, grid, skip, t, x, mask=None):\n \"\"\"\n Generalized correlation function\n\n Pass a function `f` to apply to the data `x`.\n Optionally, filter the entries at time `t[i0]` according to `mask[i0]`.\n\n Exemple: mean square displacement.\n \"\"\"\n # Calculate the correlation between time t(i0) and t(i0+i)\n # for all possible pairs (i0,i) provided by grid\n if mask is None:\n cf = defaultdict(float)\n cnt = defaultdict(int)\n # Standard calculation\n for off, i in progress(grid, total=len(grid)):\n for i0 in range(off, len(x)-i, skip):\n # Get the actual time difference\n dt = t[i0+i] - t[i0]\n cf[dt] += f(x[i0+i], x[i0])\n cnt[dt] += 1\n\n # Return the ACF with the time differences sorted\n dt = sorted(cf.keys())\n return dt, [cf[ti] / cnt[ti] for ti in dt]\n\n else:\n cf = defaultdict(float)\n cnt = defaultdict(list)\n # Filter data at time t_0 according to boolean mask\n for off, i in grid:\n for i0 in range(off, len(x)-i-skip, skip):\n # Get the actual time difference\n dt = t[i0+i] - t[i0]\n cf[dt] += f(x[i0+i][mask[i0]], x[i0][mask[i0]])\n cnt[dt].append(1) #len(mask[i0]))\n\n # Return the ACF with the time differences sorted\n dt = sorted(cf.keys())\n return dt, [cf[ti] / sum([cnt[ti] for ti in dt])]\n\n\ndef _subtract_mean(weight):\n mean = 0\n for current_field in weight:\n mean += current_field.mean()\n mean /= len(weight)\n for current_field in weight:\n current_field -= mean\n return weight\n\n\nclass Correlation(object):\n \"\"\"\n Base class for correlation functions.\n\n The correlation function is calculated for the trajectory `trj`. This can be:\n\n - an object implementing the atooms `Trajectory` interface\n - the path to a trajectory file in a format recognized by atooms\n\n A correlation function A(x) is defined over a grid of real\n entries {x_i} given by the list `grid`. To each entry of the grid,\n the correlation function has a corresponding value A_i=A(x_i). The\n latter values are stored in the `value` list.\n\n Correlation functions that depend on several variables, A(x,y,...)\n must provide a list of grids, one for each variable. The order is\n one specified by the `symbol` class variable, see below.\n\n The correlation function A is calculated as a statistical average\n over several time origins in the trajectory `trj`. The `norigins`\n variable can be used to tune the number of time origins used to\n carry out the average. `norigins` can take the following values:\n\n - `norigins=-1`: all origins are used\n - an integer >= 1: use only `n_origins` time origins\n - a float in the interval (0,1): use only a fraction `norigins` of frames as time origins\n - `None`: a heuristics is used to keep the product of steps times particles constant\n\n Subclasses must provide a symbolic expression of the correlation\n function through the `symbol` class variable. The following\n convention is used: if a correlation function A depends on\n variables x and y, then `symbol = 'A(x,y)'`.\n\n The `phasespace` variable allow subclasses to access a list of 2d\n numpy arrays with particles coordinates via the following private\n variables:\n\n - if `nbodies` is 1: `self._pos` for positions, `self._vel` for\n velocities, `self._unf_pos` for PBC-unfolded positions\n\n - if `nbodies` is 2, an additional suffix that take values 0 or 1\n is added to distinguish the two sets of particles,\n e.g. `self._pos_0` and `self._pos_1`\n \"\"\"\n\n nbodies = 1\n \"\"\"\n Class variable that controls the number of bodies, i.e. particles,\n associated to the correlation function. This variable controls the\n internal arrays used to compute the correlation, see `phasespace`.\n \"\"\"\n static = False\n \"\"\"\n Turn this to `True` is the correlation function is static,\n i.e. not time-dependent. This may enable some optimizations.\n \"\"\"\n symbol = ''\n \"\"\"Example: fskt\"\"\"\n short_name = ''\n \"\"\"Example: F_s(k,t)\"\"\"\n long_name = ''\n \"\"\"Example: Self intermediate scattering function\"\"\"\n phasespace = ['pos', 'pos-unf', 'vel']\n \"\"\"\n List of strings or string among ['pos', 'pos-unf', 'vel']. It\n indicates which variables should be read from the trajectory file.\n They will be available as self._pos, self._pos_unf, self._vel.\n \"\"\"\n\n def __init__(self, trj, grid, output_path=None, norigins=None, fix_cm=False):\n # Accept a trajectory-like instance or a path to a trajectory\n if isinstance(trj, str):\n self.trajectory = Trajectory(trj, mode='r', fmt=core.pp_trajectory_format)\n else:\n self.trajectory = trj\n self._fix_cm = fix_cm\n self._unfolded = None\n self.grid = grid\n self.value = []\n self.analysis = {}\n self.comments = None # can be modified by user at run time\n self.tag = ''\n self.tag_description = 'the whole system'\n self.output_path = output_path if output_path is not None else core.pp_output_path\n self.skip = adjust_skip(self.trajectory, norigins)\n\n # Callbacks\n self._cbk = []\n self._cbk_args = []\n self._cbk_kwargs = []\n\n # Lists for one body correlations\n self._pos = []\n self._vel = []\n self._ids = []\n self._pos_unf = []\n\n # Lists for two-body correlations\n self._pos_0, self._pos_1 = [], []\n self._vel_0, self._vel_1 = [], []\n self._ids_0, self._ids_1 = [], []\n self._pos_unf_0, self._pos_unf_1 = [], []\n\n # Weights\n self._weight = None\n self._weight_0, self._weight_1 = None, None\n self._weight_field = None\n self._weight_fluctuations = False\n \n def __str__(self):\n return '{} at <{}>'.format(self.long_name, id(self))\n\n def add_weight(self, trajectory=None, field=None, fluctuations=False):\n \"\"\"\n Add weight from the given `field` in `trajectory`\n\n If `trajectory` is `None`, `self.trajectory` will be used and\n `field` must be a particle property.\n \n If `field` is `None`, `trajectory` is assumed to be a path an\n xyz trajectory and we use the data in last column as a weight.\n\n If both `field` and `trajectory` are `None` the function\n returns immediately and the weight is not set.\n\n The optional `fluctuations` option subtracts the mean,\n calculated from the ensemble average, from the weight.\n \"\"\"\n if trajectory is None and field is None:\n return\n\n self._weight = []\n self._weight_fluctuations = fluctuations\n\n # Guessing the field from the last column of an xyz file is\n # not supported anymore\n if field is None:\n raise ValueError('provide field to use as weight')\n else:\n self._weight_field = field\n\n # By default we use the same trajectory as for the phasespace\n if trajectory is None:\n self._weight_trajectory = self.trajectory\n else:\n self._weight_trajectory = trajectory \n # Copy over the field\n from .helpers import copy_field\n self.trajectory.add_callback(copy_field, self._weight_field, self._weight_trajectory)\n\n # Make sure the steps are consistent\n if self._weight_trajectory.steps != self.trajectory.steps:\n raise ValueError('inconsistency between weight trajectory and trajectory')\n \n # Modify tag\n fluct = 'fluctuations' if self._weight_fluctuations else ''\n self.tag_description += ' with {} {} field'.format(self._weight_field.replace('_', ' '), fluct)\n self.tag_description = self.tag_description.replace(' ', ' ')\n self.tag += '.{}_{}'.format(self._weight_field, fluct)\n self.tag.strip('_.')\n \n def add_filter(self, cbk, *args, **kwargs):\n \"\"\"Add filter callback `cbk` along with positional and keyword arguments\"\"\"\n if len(self._cbk) > self.nbodies:\n raise ValueError('number of filters cannot exceed n. of bodies')\n self._cbk.append(cbk)\n self._cbk_args.append(args)\n self._cbk_kwargs.append(kwargs)\n\n def need_update(self):\n \"\"\"Check if the trajectory file is newer than the output file\"\"\"\n need = True\n if os.path.exists(self._output_file) and self._output_file != '/dev/stdout':\n if os.path.getmtime(self.trajectory.filename) < \\\n os.path.getmtime(self._output_file):\n need = False\n return need\n\n def _setup_arrays(self):\n \"\"\"\n Dump positions and/or velocities at different time frames as a\n list of numpy array.\n \"\"\"\n # TODO: what happens if we call compute twice?? Shouldnt we reset the arrays?\n # Ensure phasespace is a list.\n # It may not be a class variable anymore after this\n if not isinstance(self.phasespace, list) and \\\n not isinstance(self.phasespace, tuple):\n self.phasespace = [self.phasespace]\n\n # Setup arrays \n if self.nbodies == 1:\n self._setup_arrays_onebody()\n self._setup_weight_onebody()\n elif self.nbodies == 2:\n self._setup_arrays_twobody()\n self._setup_weight_twobody()\n\n def _setup_arrays_onebody(self):\n \"\"\"\n Setup list of numpy arrays for one-body correlations.\n \n We also take care of dumping the weight if needed, see\n `add_weight()`.\n \"\"\"\n if 'pos' in self.phasespace or 'vel' in self.phasespace or 'ids' in self.phasespace:\n ids = distinct_species(self.trajectory[0].particle)\n for s in progress(self.trajectory):\n # Apply filter if there is one\n if len(self._cbk) > 0:\n s = self._cbk[0](s, *self._cbk_args[0], **self._cbk_kwargs[0])\n if 'pos' in self.phasespace:\n self._pos.append(s.dump('pos'))\n if 'vel' in self.phasespace:\n self._vel.append(s.dump('vel'))\n if 'ids' in self.phasespace:\n _ids = s.dump('species')\n _ids = numpy.array([ids.index(_) for _ in _ids], dtype=numpy.int32)\n self._ids.append(_ids)\n \n # Dump unfolded positions if requested\n if 'pos-unf' in self.phasespace:\n if self._unfolded is None:\n self._unfolded = Unfolded(self.trajectory, fixed_cm=self._fix_cm)\n for s in progress(self._unfolded):\n # Apply filter if there is one\n if len(self._cbk) > 0:\n s = self._cbk[0](s, *self._cbk_args[0], **self._cbk_kwargs[0])\n self._pos_unf.append(s.dump('pos'))\n \n def _setup_weight_onebody(self):\n \"\"\"\n Setup list of numpy arrays for the weight, see `add_weight()`\n \"\"\"\n if self._weight is None:\n return\n\n # Dump arrays of weights\n for s in progress(self.trajectory):\n # Apply filter if there is one\n # TODO: fix when weight trajectory does not contain actual particle info\n # It should be possible to link the weight trajectory to the trajectory\n # and return the trajectory particles with the weight\n if len(self._cbk) > 0:\n s = self._cbk[0](s, *self._cbk_args[0], **self._cbk_kwargs[0]) \n current_weight = s.dump('particle.%s' % self._weight_field)\n self._weight.append(current_weight)\n\n # Subtract global mean\n if self._weight_fluctuations:\n _subtract_mean(self._weight)\n \n def _setup_weight_twobody(self):\n \"\"\"\n Setup list of numpy arrays for the weight, see `add_weight()`\n \"\"\"\n if self._weight is None:\n return\n\n self._weight = []\n self._weight_0 = []\n self._weight_1 = []\n\n # TODO: add checks on number of filters\n if len(self._cbk) <= 1:\n self._setup_weight_onebody()\n self._weight_0 = self._weight\n self._weight_1 = self._weight\n return\n\n # Dump arrays of weights\n for s in progress(self.trajectory):\n # Apply filters\n if len(self._cbk) == 2:\n s0 = self._cbk[0](s, *self._cbk_args[0], **self._cbk_kwargs[0])\n s1 = self._cbk[1](s, *self._cbk_args[1], **self._cbk_kwargs[1])\n self._weight_0.append(s0.dump('particle.%s' % self._weight_field))\n self._weight_1.append(s1.dump('particle.%s' % self._weight_field))\n\n # Subtract global mean\n if self._weight_fluctuations:\n _subtract_mean(self._weight_0)\n _subtract_mean(self._weight_1)\n \n def _setup_arrays_twobody(self):\n \"\"\"Setup list of numpy arrays for two-body correlations.\"\"\"\n if len(self._cbk) <= 1:\n self._setup_arrays_onebody()\n self._pos_0 = self._pos\n self._pos_1 = self._pos\n self._vel_0 = self._vel\n self._vel_1 = self._vel\n self._ids_0 = self._ids\n self._ids_1 = self._ids\n return\n\n if 'pos' in self.phasespace or 'vel' in self.phasespace or 'ids' in self.phasespace:\n ids = distinct_species(self.trajectory[0].particle)\n for s in progress(self.trajectory):\n s0 = self._cbk[0](s, *self._cbk_args[0], **self._cbk_kwargs[0])\n s1 = self._cbk[1](s, *self._cbk_args[1], **self._cbk_kwargs[1])\n if 'pos' in self.phasespace:\n self._pos_0.append(s0.dump('pos'))\n self._pos_1.append(s1.dump('pos'))\n if 'vel' in self.phasespace:\n self._vel_0.append(s0.dump('vel'))\n self._vel_1.append(s1.dump('vel'))\n if 'ids' in self.phasespace:\n _ids_0 = s0.dump('species')\n _ids_1 = s1.dump('species')\n _ids_0 = numpy.array([ids.index(_) for _ in _ids_0], dtype=numpy.int32)\n _ids_1 = numpy.array([ids.index(_) for _ in _ids_1], dtype=numpy.int32)\n self._ids_0.append(_ids_0)\n self._ids_1.append(_ids_1)\n \n # Dump unfolded positions if requested\n if 'pos-unf' in self.phasespace:\n for s in progress(Unfolded(self.trajectory)):\n s0 = self._cbk[0](s, *self._cbk_args[0], **self._cbk_kwargs[0])\n s1 = self._cbk[1](s, *self._cbk_args[1], **self._cbk_kwargs[1])\n self._pos_unf_0.append(s0.dump('pos'))\n self._pos_unf_1.append(s1.dump('pos'))\n\n def compute(self):\n \"\"\"\n Compute the correlation function.\n\n It wraps the _compute() method implemented by subclasses.\n This method sets the `self.grid` and `self.value` variables,\n which are also returned.\n \"\"\"\n _log.info('setup arrays for %s', self.tag_description)\n t = [Timer(), Timer()]\n t[0].start()\n self._setup_arrays()\n t[0].stop()\n\n _log.info('computing %s for %s', self.long_name, self.tag_description)\n _log.info('using %s time origins out of %s',\n len(range(0, len(self.trajectory), self.skip)),\n len(self.trajectory))\n t[1].start()\n self._compute()\n t[1].stop()\n\n _log.info('output file %s', self._output_file)\n _log.info('done %s for %s in %.1f sec [setup:%.0f%%, compute: %.0f%%]',\n self.long_name,\n self.tag_description, t[0].wall_time + t[1].wall_time,\n t[0].wall_time / (t[0].wall_time + t[1].wall_time) * 100,\n t[1].wall_time / (t[0].wall_time + t[1].wall_time) * 100)\n _log.info('')\n\n return self.grid, self.value\n\n def _compute(self):\n \"\"\"Subclasses must implement this\"\"\"\n pass\n\n def analyze(self):\n \"\"\"\n Subclasses may implement this and store the results in the\n self.analysis dictonary\n \"\"\"\n pass\n\n @property\n def _output_file(self):\n \"\"\"Returns path of output file\"\"\"\n # Interpolate the output path string\n if self.output_path is None:\n filename = None\n else:\n filename = self.output_path.format(symbol=self.symbol,\n short_name=self.short_name,\n long_name=self.long_name.replace(' ', '_'),\n tag=self.tag,\n tag_description=self.tag_description.replace(' ', '_'),\n trajectory=self.trajectory)\n # Strip unpleasant punctuation from basename path\n for punct in ['.', '_', '-']:\n subpaths = filename.split('/')\n subpaths[-1] = subpaths[-1].replace(punct * 2, punct)\n subpaths[-1] = subpaths[-1].strip(punct)\n filename = '/'.join(subpaths)\n return filename\n\n def read(self):\n \"\"\"Read correlation function from existing file\"\"\"\n with open(self._output_file, 'r') as inp:\n x = numpy.loadtxt(inp, unpack=True)\n if len(x) == 3:\n _log.warn(\"cannot read 3-columns files yet in %s\", self._output_file)\n elif len(x) == 2:\n self.grid, self.value = x\n else:\n self.grid, self.value = x[0: 2]\n _log.warn(\"Ignoring some columns in %s\", self._output_file)\n\n @property\n def grid_name(self):\n \"\"\"\n Return the name of the grid variables\n\n Example:\n -------\n If `self.name` is `F_s(k,t)`, the function returns `['k', 't']`\n \"\"\"\n variables = self.short_name.split('(')[1][:-1]\n return variables.split(',')\n\n def write(self):\n \"\"\"\n Write the correlation function and the analysis data to file\n\n The `output_path` instance variable is used to define the\n output files by interpolating the following variables:\n\n - symbol\n - short_name\n - long_name\n - tag\n - tag_description\n - trajectory\n\n The default is defined by core.pp_output_path, which currently\n looks like '{trajectory.filename}.pp.{symbol}.{tag}'\n \"\"\"\n def is_iterable(maybe_iterable):\n try:\n iter(maybe_iterable)\n except TypeError:\n return False\n else:\n return True\n\n # Pack grid and value into arrays to dump\n if is_iterable(self.grid[0]) and len(self.grid) == 2:\n x = numpy.array(self.grid[0]).repeat(len(self.value[0]))\n y = numpy.array(self.grid[1] * len(self.grid[0]))\n z = numpy.array(self.value).flatten()\n dump = numpy.transpose(numpy.array([x, y, z]))\n else:\n dump = numpy.transpose(numpy.array([self.grid, self.value]))\n\n # Comment line\n # Extract variables from parenthesis in symbol\n variables = self.short_name.split('(')[1][:-1]\n variables = variables.split(',')\n columns = variables + [self.short_name] #[self.symbol]\n if len(self.tag_description) > 0:\n conj = 'of'\n else:\n conj = ''\n comments = _dump(title='%s %s %s %s' % (self.long_name, self.short_name, conj, self.tag_description),\n columns=columns,\n command='atooms-pp', version=core.__version__,\n description=None, note=None,\n parents=self.trajectory.filename,\n inline=False)\n if self.comments is not None:\n comments += self.comments\n\n # Results of analysis\n analysis = \"\"\n for x, f in self.analysis.items():\n if f is not None:\n analysis += '# %s: %s\\n' % (x, f)\n\n # Put it all together\n # and make sure the path to the output file exists\n import os\n from atooms.core.utils import mkdir\n mkdir(os.path.dirname(self._output_file))\n with open(self._output_file, 'w') as fh:\n fh.write(comments)\n if len(analysis) > 0:\n fh.write(analysis)\n numpy.savetxt(fh, dump, fmt=\"%g\")\n fh.flush()\n\n def do(self, update=False):\n \"\"\"\n Do the full template pattern: compute, analyze and write the\n correlation function.\n \"\"\"\n if update and not self.need_update():\n self.read()\n return\n\n self.compute()\n\n try:\n self.analyze()\n except ImportError as e:\n _log.warn('Could not analyze due to missing modules, continuing...')\n _log.warn(e.message)\n\n self.write()\n\n def __call__(self):\n self.do()\n","sub_path":"atooms/postprocessing/correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":23509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537070861","text":"'''\r\nCreated on Apr 12, 2016\r\n\r\n@author: kakan\r\n'''\r\n\r\nclass UrlCollector():\r\n __urls = []\r\n __instance = None\r\n \r\n @staticmethod\r\n def instance():\r\n if UrlCollector.__instance == None:\r\n UrlCollector.__instance = UrlCollector()\r\n return UrlCollector.__instance\r\n \r\n @property\r\n def list_url(self):\r\n return self.__urls\r\n \r\n def collect(self,url):\r\n if type(url) == list:\r\n self.__urls += url\r\n elif type(url) == tuple:\r\n self.__urls.append(url)\r\n else:\r\n raise TypeError(\"Url should be list or tuple.\",type(url),\"given.\")\r\n #print(self.__urls)\r\n \r\n \r\n","sub_path":"core/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235602053","text":"import pandas as pd \n#import numpy as np\n\n\ndef get_stock_df( stockno ):\n #for mpl use ,candlestick\n columns=['Time', 'Match_count', 'Match_value', 'Open', 'High', 'Low', 'Close', 'Diff', 'Volume']\n df = pd.read_csv(stockno +'.csv', parse_dates=[0], names = columns)\n #df['Symbol'] = stockno , 'Symbol'\n #TimeSeries index?\n #df = df.loc['2010-01-04':'2020-06-30',:]\n \n df[['Volume', 'Match_count', 'Match_value']] = df[['Volume', 'Match_count', 'Match_value']].astype('float64')\n df = df[['Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Match_count', 'Match_value']]\n df.set_index( \"Time\" , inplace=True)\n #pd.set_option('display.max_columns', None)\n return df \n \ndef transform_dict( df ):\n #for talib use, title lowercase\n stock_dict ={ 'time': df.index }\n for key in df.columns:\n stock_dict[key.lower()] = df[key].to_numpy()\n return stock_dict\n \n#-----------------------------------------------------------------------------\n\n\n \ndef performance(trade_record):\n\n total_profit = []\n for i in trade_record:\n if i[0] == 'B':\n total_profit.append(i[4]-i[2])\n #elif i[0] == 'S':\n # total_profit.append(i[2]-i[4])\n \n earn_total_profit=[ i for i in total_profit if i > 0 ]\n loss_total_profit=[ i for i in total_profit if i <= 0 ]\n\n # 最大連續虧損\n max_loss=0\n current_max_loss=0\n for i in total_profit:\n if i <= 0:\n current_max_loss += i\n if current_max_loss < max_loss:\n max_loss = current_max_loss\n else:\n current_max_loss = 0 \n \n print('\\n總績效',sum(total_profit),'總次數',len(total_profit))\n print('平均績效',sum(total_profit)/len(total_profit))\n print('平均獲利',sum(earn_total_profit)/len(earn_total_profit))\n print('平均損失',sum(loss_total_profit)/len(loss_total_profit))\n print('勝率',len(earn_total_profit) / len(total_profit))\n print('最大連續虧損',max_loss)\n print('獲利因子',sum(earn_total_profit)/abs(sum(loss_total_profit)))\n#-----------------------------------------------------------------------------","sub_path":"new/Processing.py","file_name":"Processing.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195894712","text":"import os\nimport tensorflow as tf\nfrom utils import *\nimport re\n\n\n########################################################################################################\ndef lrelu(x, leak=0.2, name=\"lrelu\"):\n return tf.maximum(x, leak*x)\n\ndef linear(input_, output_size, scope=None, stddev=0.02,):\n shape = input_.get_shape().as_list()\n\n with tf.variable_scope(scope or \"Linear\"):\n matrix = tf.get_variable(\"Matrix\", [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev))\n bias = tf.get_variable(\"bias\", [output_size],initializer=tf.constant_initializer(0.0))\n # 이름 진짜 중요 다 이름을 생략하면 학습이 안돼 모든 거 다\n\n return tf.matmul(input_, matrix) + bias\n\ndef batch_norm(inputs, scope_name, train=True ):\n return tf.contrib.layers.batch_norm(inputs, decay=0.9, updates_collections=None,epsilon=1e-5, scale=True, is_training = train, scope = scope_name)\n\ndef conv2d(input_, output_dim, stddev=0.02, name=\"conv2d\"):\n with tf.variable_scope(name):\n conv_w = tf.get_variable('conv_w', [5, 5, input_.get_shape()[-1], output_dim],initializer=tf.truncated_normal_initializer(stddev=stddev))\n conv = tf.nn.conv2d(input_, conv_w, strides=[1, 2, 2, 1], padding='SAME')\n biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0))\n conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape())\n return conv\n\ndef deconv2d(input_, output_shape, stddev=0.02, name=\"deconv2d\"):\n with tf.variable_scope(name):\n input_shape = input_.get_shape().as_list()\n deconv_w = tf.get_variable('deconv_w', [5, 5, output_shape[-1], input_shape[-1]],initializer=tf.random_normal_initializer(stddev=stddev))\n deconv = tf.nn.conv2d_transpose(input_, deconv_w, output_shape=output_shape, strides=[1, 2, 2, 1])\n biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0))\n deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())\n return deconv\n\n########################################################################################################\n############################# Checkpoint #############################\ndef checkpoint_save(sess, saver, checkpoint_path_dir, counter):\n model_name = \"DCGAN.model\"\n # checkpoint_path_dir = os.path.join('checkpoint', 'wikiart')\n if not os.path.exists(checkpoint_path_dir):\n os.makedirs(checkpoint_path_dir)\n saver.save(sess, os.path.join(checkpoint_path_dir, model_name), global_step=counter)\n\ndef checkpoint_load(sess, saver, checkpoint_dir, checkpoint_dir_model):\n print(\" [*] Reading checkpoints...\")\n checkpoint_dir = os.path.join(checkpoint_dir, checkpoint_dir_model)\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n saver.restore(sess, os.path.join(checkpoint_dir, ckpt_name))\n # 체크포인트 파일 counter 부분 가져오기\n counter = int(next(re.finditer(\"(\\d+)(?!.*\\d)\",ckpt_name)).group(0))\n print(\" [*] Success to read {}\".format(ckpt_name))\n return True, counter\n else:\n print(\" [*] Failed to find a checkpoint\")\n return False, 0\n","sub_path":"DCGAN/layer4_in_out/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115543665","text":"import moviepy.editor as mpe\nimport numpy as np\n\nclip = mpe.VideoFileClip('sample.mp4')\nx = 1\nlogo = (mpe.ImageClip('tbcarrow.png').set_pos((x,0.9), relative=True))\n\nwhile x != 0.05:\n x -= 0.05\n x = round(x,2)\n print('>> '+str(x))\n logo = logo.set_pos((x,0.9), relative=True)\n\n\naudio_bg = mpe.AudioFileClip('./songs/roundabout_short.mp3').set_start(t=10)\n\n\nfinal_audio = mpe.CompositeAudioClip([audio_bg, clip.audio])\nfinal_clip = mpe.CompositeVideoClip([clip, logo.set_start(10).set_duration(5)])\nfca = final_clip.set_audio(final_audio)\nfca.write_videofile('editedsample.mp4')\n","sub_path":"versions/v1.0/JoJoTBCBot/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"450775333","text":"import random\n\n\nclass Card:\n \"\"\"\n A class representing a standard playing card, with a Rank and a Suit\n \"\"\"\n def __init__(self, rank, suit, faceup=True):\n self.rank = rank\n self.suit = suit\n self.faceup = faceup\n\n def __str__(self): # Returns a string of the rank and suit of the card\n if self.faceup:\n return \"{} of {}\".format(self.rank, self.suit)\n else:\n return \"Face down card\"\n\n def getrank(self): # Returns the rank of the card\n if self.faceup:\n return self.rank\n else:\n return \"face down\"\n\n\nclass Deck:\n \"\"\"\n Creates list of cards, from the Card class, representing a deck\n functions:\n - shuffle the deck\n - draw a card\n \"\"\"\n\n def __init__(self):\n suits = ('Spades', 'Hearts', 'Diamonds', 'Clubs')\n ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n self.deck = [Card(rank, suit) for suit in suits for rank in ranks]\n self.shuffle()\n\n def __str__(self): # A string representation of all the cards in the deck\n return ' \\n'.join((x.__str__() for x in self.deck))\n\n def shuffle(self, times=5): # Shuffles the deck 'times' amount of times.\n for i in range(0, times):\n random.shuffle(self.deck)\n\n def draw_card(self): # returns the top card of the deck if possible\n return self.deck.pop(-1)\n\n\nclass Hand:\n \"\"\"\n Creates a list of cards drawn from a deck\n Keeps track of the total hand value\n keeps track of the number of aces\n \"\"\"\n\n def __init__(self):\n self.cards = [] # List of cards in this hand\n self.value = 0 # Total value of the cards in the hand\n self.aces = 0\n self.bust = False # Boolean to keep track of if the hand is bust or not\n\n def __str__(self): # The hands string representation is its total value\n return str(self.value)\n\n def __int__(self): # The int representation is the total value as an integer\n return self.value\n\n def add_card(self, deck):\n # Dict with the blackjack value for each rank in the deck\n values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9,\n 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11, 'face down': 0}\n card = deck.draw_card() # Draws a card from the specified deck\n self.cards.append(card) # Appends the drawn card to the hands list of cards\n self.value += values[card.getrank()] # Adds the value of the drawn card to the total hand value\n if values[card.getrank()] == 11:\n self.aces += 1\n if self.value > 21 and self.aces > 0:\n self.value -= 10\n self.aces -= 1\n elif self.value > 21:\n print(\"Hand value is {} and have exceeded 21, busted\".format(self.value))\n self.bust = True\n\n def show_hand(self):\n print(\"hand consists of these cards: \")\n for x in self.cards:\n print(\" \" + x.__str__())\n\n\nclass Chips:\n \"\"\"\n A class to handle the players pile of chips\n \"\"\"\n def __init__(self, amount_of_chips=1000):\n self.amount_of_chips = amount_of_chips\n\n def __str__(self): # Returns a string with the amount of chips you have\n return str(self.amount_of_chips)\n\n def bet(self, amount): # Reduces the amount of chips you\n # have and returns the amount withdrawn\n self.amount_of_chips -= amount\n return amount\n\n def collect(self, amount): # Adds your winnings to your chips total\n self.amount_of_chips += amount\n\n\ndef blackjack():\n players_chips = Chips()\n while True:\n\n # -------------------------------------------\n # Setting up a new game\n # -------------------------------------------\n deck = Deck()\n player = Hand()\n dealer = Hand()\n\n # -------------------------------------------\n # Betting at the beginning of the game\n # -------------------------------------------\n\n print(\"You have {} chips to bet\".format(players_chips.__str__()))\n print(\"Place your bet: \")\n pot = players_chips.bet(int(input()))\n print(\"There are now {} chips in the pot\".format(pot))\n\n # -------------------------------------------\n # Giving the players their starting cards\n # -------------------------------------------\n\n dealer.add_card(deck)\n player.add_card(deck)\n dealer.add_card(deck)\n dealer.cards[1].faceup = False\n\n while True:\n # -------------------------------------------\n # Player gets another card and the hands are shown\n # -------------------------------------------\n if players_chips.amount_of_chips <= 0:\n print(\"You are broke, better luck next time\")\n break\n player.add_card(deck)\n print(\"\\n The Dealers\")\n dealer.show_hand()\n if dealer.value == 21:\n break\n print(\"\\n Your\")\n player.show_hand()\n if player.value == 21:\n break\n print(\"\\n You have a total hand value of {}\".format(player.__str__()))\n\n if player.bust:\n print(\"Your hand is busted\")\n break\n\n # -------------------------------------------\n # Menu\n # -------------------------------------------\n print(\"Menu\")\n print(\"To stand input 's'\")\n print(\"To hit input 'h'\")\n print(\"To double input 'd'\")\n print(\"To surrender input 'I suck'\")\n menu_choice = input()\n\n if menu_choice == \"s\":\n break\n elif menu_choice == \"h\":\n continue\n elif menu_choice == \"d\":\n print(\"You have {} chips to bet\".format(players_chips.__str__()))\n pot += players_chips.bet(pot)\n print(\"There are now {} chips in the pot\".format(pot))\n player.add_card(deck)\n print(\"\\nYour\")\n player.show_hand()\n break\n else:\n print(\"You suck...\")\n break\n\n dealer.cards[1].faceup = True\n print(\"The Dealers\")\n dealer.show_hand()\n while dealer.value <= 16:\n dealer.add_card(deck)\n print(\"The Dealers\")\n dealer.show_hand()\n\n # -------------------------------------------\n # Decide who wins the hand\n # -------------------------------------------\n if player.value > dealer.value and not player.bust or dealer.bust:\n players_chips.collect(pot * 2)\n print(\"You won {} and now have {} chips\".format(pot * 2, players_chips.__str__()))\n\n print(\"Menu\")\n print(\"To play another hand input 'p'\")\n print(\"To leave the table input 'l'\")\n menu_choice = input()\n if menu_choice == \"l\":\n break\n\n\nblackjack()\n","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":7512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"70798474","text":"from backend import SteamHttpClient\nfrom galaxy.api.types import FriendInfo\nfrom galaxy.api.errors import AuthenticationRequired\nfrom tests.async_mock import AsyncMock, MagicMock\nimport pytest\n\n\n@pytest.mark.asyncio\nasync def test_not_authenticated(plugin):\n with pytest.raises(AuthenticationRequired):\n await plugin.get_friends()\n\n\n@pytest.mark.asyncio\nasync def test_no_friends(authenticated_plugin, backend_client, steam_id):\n backend_client.get_friends.return_value = {}\n\n assert [] == await authenticated_plugin.get_friends()\n backend_client.get_friends.assert_called_once_with(steam_id)\n\n\n@pytest.mark.asyncio\nasync def test_multiple_friends(authenticated_plugin, backend_client, steam_id):\n backend_client.get_friends.return_value = {\n \"76561198040630463\": \"crak\",\n \"76561198053830887\": \"Danpire\"\n }\n\n result = await authenticated_plugin.get_friends()\n assert result == [\n FriendInfo(\"76561198040630463\", \"crak\"),\n FriendInfo(\"76561198053830887\", \"Danpire\")\n ]\n backend_client.get_friends.assert_called_once_with(steam_id)\n\n\n@pytest.fixture\ndef http_response_mock():\n mock = MagicMock(spec=())\n mock.text = AsyncMock()\n return mock\n\n\n@pytest.fixture\ndef http_client_mock():\n mock = MagicMock(spec=())\n mock.get = AsyncMock()\n return mock\n\n\n@pytest.mark.asyncio\nasync def test_profile_parsing(http_client_mock, http_response_mock, steam_id):\n http_response_mock.text.return_value = '''\n
    \n
    \n
    На камазе!
    \n \n Last Online 189 days ago\n
    \n
    \n
    '''\n http_client_mock.get.return_value = http_response_mock\n\n assert {\"76561198056089614\": \"На камазе!\"} == await SteamHttpClient(http_client_mock).get_friends(steam_id)\n","sub_path":"tests/test_friends.py","file_name":"test_friends.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443072763","text":"\nfrom flask import Flask, render_template, jsonify, request\nfrom pymongo import MongoClient\n\napp = Flask(__name__)\n\nclient = MongoClient(\"mongodb://localhost:27017/\")\ndb = client.dbStock\n\nimport datetime\n\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/post', methods=['POST'])\ndef save_post():\n title_receive = request.form['title_give']\n content_receive = request.form['content_give']\n now = datetime.datetime.now()\n doc = {'제목': title_receive, '내용': content_receive, '날짜' : now}\n db.lists.insert_one(doc)\n return jsonify({'result': '포스팅 성공!'})\n\n@app.route('/post', methods=['GET'])\ndef get_post():\n lists = list(db.lists.find({},{'_id':False}))\n return jsonify({'lists': lists})\n\n\n@app.route('/post', methods=['DELETE'])\ndef delete_post():\n return {\"result\": \"success\"}\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419559896","text":"# coding: utf-8\n\n\"\"\"\n validateapi\n\n The validation APIs help you validate data. Check if an E-mail address is real. Check if a domain is real. Check up on an IP address, and even where it is located. All this and much more is available in the validation API. # noqa: E501\n\n OpenAPI spec version: v1\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass ValidatePostalCodeResponse(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'valid_postal_code': 'bool',\n 'city': 'str',\n 'state_or_province': 'str',\n 'latitude': 'float',\n 'longitude': 'float'\n }\n\n attribute_map = {\n 'valid_postal_code': 'ValidPostalCode',\n 'city': 'City',\n 'state_or_province': 'StateOrProvince',\n 'latitude': 'Latitude',\n 'longitude': 'Longitude'\n }\n\n def __init__(self, valid_postal_code=None, city=None, state_or_province=None, latitude=None, longitude=None): # noqa: E501\n \"\"\"ValidatePostalCodeResponse - a model defined in Swagger\"\"\" # noqa: E501\n\n self._valid_postal_code = None\n self._city = None\n self._state_or_province = None\n self._latitude = None\n self._longitude = None\n self.discriminator = None\n\n if valid_postal_code is not None:\n self.valid_postal_code = valid_postal_code\n if city is not None:\n self.city = city\n if state_or_province is not None:\n self.state_or_province = state_or_province\n if latitude is not None:\n self.latitude = latitude\n if longitude is not None:\n self.longitude = longitude\n\n @property\n def valid_postal_code(self):\n \"\"\"Gets the valid_postal_code of this ValidatePostalCodeResponse. # noqa: E501\n\n True if the Postal Code is valid, false otherwise # noqa: E501\n\n :return: The valid_postal_code of this ValidatePostalCodeResponse. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._valid_postal_code\n\n @valid_postal_code.setter\n def valid_postal_code(self, valid_postal_code):\n \"\"\"Sets the valid_postal_code of this ValidatePostalCodeResponse.\n\n True if the Postal Code is valid, false otherwise # noqa: E501\n\n :param valid_postal_code: The valid_postal_code of this ValidatePostalCodeResponse. # noqa: E501\n :type: bool\n \"\"\"\n\n self._valid_postal_code = valid_postal_code\n\n @property\n def city(self):\n \"\"\"Gets the city of this ValidatePostalCodeResponse. # noqa: E501\n\n If valid, City corresponding to the input postal code, such as 'Walnut Creek' # noqa: E501\n\n :return: The city of this ValidatePostalCodeResponse. # noqa: E501\n :rtype: str\n \"\"\"\n return self._city\n\n @city.setter\n def city(self, city):\n \"\"\"Sets the city of this ValidatePostalCodeResponse.\n\n If valid, City corresponding to the input postal code, such as 'Walnut Creek' # noqa: E501\n\n :param city: The city of this ValidatePostalCodeResponse. # noqa: E501\n :type: str\n \"\"\"\n\n self._city = city\n\n @property\n def state_or_province(self):\n \"\"\"Gets the state_or_province of this ValidatePostalCodeResponse. # noqa: E501\n\n If valid; State or province corresponding to the input postal code, such as 'CA' or 'California' # noqa: E501\n\n :return: The state_or_province of this ValidatePostalCodeResponse. # noqa: E501\n :rtype: str\n \"\"\"\n return self._state_or_province\n\n @state_or_province.setter\n def state_or_province(self, state_or_province):\n \"\"\"Sets the state_or_province of this ValidatePostalCodeResponse.\n\n If valid; State or province corresponding to the input postal code, such as 'CA' or 'California' # noqa: E501\n\n :param state_or_province: The state_or_province of this ValidatePostalCodeResponse. # noqa: E501\n :type: str\n \"\"\"\n\n self._state_or_province = state_or_province\n\n @property\n def latitude(self):\n \"\"\"Gets the latitude of this ValidatePostalCodeResponse. # noqa: E501\n\n If the postal code is valid, the degrees latitude of the centroid of the postal code, null otherwise # noqa: E501\n\n :return: The latitude of this ValidatePostalCodeResponse. # noqa: E501\n :rtype: float\n \"\"\"\n return self._latitude\n\n @latitude.setter\n def latitude(self, latitude):\n \"\"\"Sets the latitude of this ValidatePostalCodeResponse.\n\n If the postal code is valid, the degrees latitude of the centroid of the postal code, null otherwise # noqa: E501\n\n :param latitude: The latitude of this ValidatePostalCodeResponse. # noqa: E501\n :type: float\n \"\"\"\n\n self._latitude = latitude\n\n @property\n def longitude(self):\n \"\"\"Gets the longitude of this ValidatePostalCodeResponse. # noqa: E501\n\n If the postal code is valid, the degrees longitude of the centroid of the postal code, null otherwise # noqa: E501\n\n :return: The longitude of this ValidatePostalCodeResponse. # noqa: E501\n :rtype: float\n \"\"\"\n return self._longitude\n\n @longitude.setter\n def longitude(self, longitude):\n \"\"\"Sets the longitude of this ValidatePostalCodeResponse.\n\n If the postal code is valid, the degrees longitude of the centroid of the postal code, null otherwise # noqa: E501\n\n :param longitude: The longitude of this ValidatePostalCodeResponse. # noqa: E501\n :type: float\n \"\"\"\n\n self._longitude = longitude\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(ValidatePostalCodeResponse, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ValidatePostalCodeResponse):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"cloudmersive_validate_api_client/models/validate_postal_code_response.py","file_name":"validate_postal_code_response.py","file_ext":"py","file_size_in_byte":7570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"477499508","text":"def pellsD(d):\n continuedFraction = []\n ao = floor(numerical_approx(sqrt(d)))\n decimal = numerical_approx(sqrt(d)) - floor(numerical_approx(sqrt(d)))\n continuedFraction.append(ao)\n finished = False\n\n while finished == False:\n continuedFraction.append(floor(numerical_approx(1/decimal)))\n if floor(numerical_approx(1/decimal)) == 2*ao:\n finished = True\n else: \n decimal = 1/decimal - floor(1/decimal)\n \n pList = [0,1]\n qList = [1,0]\n for i in continuedFraction:\n p = i*pList[-1] + pList[-2]\n pList.append(p)\n q = i*qList[-1] + qList[-2]\n qList.append(q)\n if (pList[-2]^2) - d*(qList[-2]^2) == -1:\n x = (pList[-2]^2)+(qList[-2]^2)*(d)\n y = 2*(pList[-2])*(qList[-2])\n return 'x:', x, 'y:', y\n else:\n return 'x:', pList[-2], 'y:', qList[-2]\n \npellsD(61)\n","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"289112177","text":"from __future__ import print_function, division\n\n__all__ = [\n 'Node',\n 'BinaryTree',\n 'BinarySearchTree'\n]\n\nclass Node(object):\n \"\"\"\n Represents node in trees.\n\n Parameters\n ==========\n\n data\n Any valid data to be stored in the node.\n key\n Required for comparison operations.\n left: int\n Optional, index of the left child node.\n right: int\n Optional, index of the right child node.\n \"\"\"\n\n __slots__ = ['key', 'data', 'left', 'right', 'is_root']\n\n def __new__(cls, key, data):\n obj = object.__new__(cls)\n obj.data, obj.key = data, key\n obj.left, obj.right = None, None\n obj.is_root = False\n return obj\n\n def __str__(self):\n \"\"\"\n Used for printing.\n \"\"\"\n return str((self.left, self.key, self.data, self.right))\n\nclass BinaryTree(object):\n \"\"\"\n Abstract binary tree.\n\n Parameters\n ==========\n\n root_data\n Optional, the root node of the binary tree.\n If not of type Node, it will consider\n root as data and a new root node will\n be created.\n key\n Required if tree is to be instantiated with\n root otherwise not needed.\n comp: lambda\n Optional, A lambda function which will be used\n for comparison of keys. Should return a\n bool value. By default it implements less\n than operator.\n\n References\n ==========\n\n .. [1] https://en.wikipedia.org/wiki/Binary_tree\n \"\"\"\n\n __slots__ = ['root_idx', 'comparator', 'tree', 'size']\n\n def __new__(cls, key=None, root_data=None, comp=None):\n obj = object.__new__(cls)\n if key == None and root_data != None:\n raise ValueError('Key required.')\n key = None if root_data == None else key\n root = Node(key, root_data)\n root.is_root = True\n obj.root_idx = 0\n obj.tree, obj.size = [root], 1\n obj.comparator = lambda key1, key2: key1 < key2 \\\n if comp == None else comp\n return obj\n\n def __str__(self):\n return str([(node.left, node.key, node.data, node.right)\n for node in self.tree])\n\n\nclass BinarySearchTree(BinaryTree):\n \"\"\"\n Represents binary search trees.\n\n Examples\n ========\n\n >>> from pydatastructs.trees import BinarySearchTree as BST\n >>> b = BST()\n >>> b.insert(1, 1)\n >>> b.insert(2, 2)\n >>> child = b.tree[b.root_idx].right\n >>> b.tree[child].data\n 2\n >>> b.search(1)\n 0\n >>> b.search(-1) == None\n True\n >>> b.delete(1) == True\n True\n >>> b.search(1) == None\n True\n >>> b.delete(2) == True\n True\n >>> b.search(2) == None\n True\n\n References\n ==========\n\n .. [1] https://en.wikipedia.org/wiki/Binary_search_tree\n \"\"\"\n def insert(self, key, data):\n \"\"\"\n Inserts data by the passed key using iterative\n algorithm.\n\n Parameters\n ==========\n\n key\n The key for comparison.\n data\n The data to be inserted.\n\n Returns\n =======\n\n None\n \"\"\"\n walk = self.root_idx\n if self.tree[walk].key == None:\n self.tree[walk].key = key\n self.tree[walk].data = data\n return None\n new_node = Node(key, data)\n while True:\n if self.tree[walk].key == key:\n self.tree[walk].data = data\n return None\n if not self.comparator(key, self.tree[walk].key):\n if self.tree[walk].right == None:\n self.tree.append(new_node)\n self.tree[walk].right = self.size\n self.size += 1\n return None\n walk = self.tree[walk].right\n else:\n if self.tree[walk].left == None:\n self.tree.append(new_node)\n self.tree[walk].left = self.size\n self.size += 1\n return None\n walk = self.tree[walk].left\n\n def search(self, key, **kwargs):\n \"\"\"\n Searches for the data in the binary search tree\n using iterative algorithm.\n\n Parameters\n ==========\n\n key\n The key for searching.\n parent: bool\n If true then returns index of the\n parent of the node with the passed\n key.\n By default, False\n\n Returns\n =======\n\n int\n If the node with the passed key is\n in the tree.\n tuple\n The index of the searched node and\n the index of the parent of that node.\n None\n In all other cases.\n \"\"\"\n ret_parent = kwargs.get('parent', False)\n parent = None\n walk = self.root_idx\n if self.tree[walk].key == None:\n return None\n while walk != None:\n if self.tree[walk].key == key:\n break\n parent = walk\n if self.comparator(key, self.tree[walk].key):\n walk = self.tree[walk].left\n else:\n walk = self.tree[walk].right\n return (walk, parent) if ret_parent else walk\n\n def delete(self, key):\n \"\"\"\n Deletes the data with the passed key\n using iterative algorithm.\n\n Parameters\n ==========\n\n key\n The key of the node which is\n to be deleted.\n\n Returns\n =======\n\n True\n If the node is deleted successfully.\n None\n If the node to be deleted doesn't exists.\n\n Note\n ====\n\n The node is deleted means that the connection to that\n node are removed but the it is still in three. This\n is being done to keep the complexity of deletion, O(logn).\n \"\"\"\n (walk, parent) = self.search(key, parent=True)\n if walk == None:\n return None\n if self.tree[walk].left == None and \\\n self.tree[walk].right == None:\n if parent == None:\n self.tree[self.root_idx].data = None\n self.tree[self.root_idx].key = None\n else:\n if self.tree[parent].left == walk:\n self.tree[parent].left = None\n else:\n self.tree[parent].right = None\n\n elif self.tree[walk].left != None and \\\n self.tree[walk].right != None:\n twalk = self.tree[walk].right\n par = walk\n while self.tree[twalk].left != None:\n par = twalk\n twalk = self.tree[twalk].left\n self.tree[walk].data = self.tree[twalk].data\n self.tree[walk].key = self.tree[twalk].key\n self.tree[par].left = self.tree[twalk].right\n\n else:\n if self.tree[walk].left != None:\n child = self.tree[walk].left\n else:\n child = self.tree[walk].right\n if parent == None:\n self.tree[self.root_idx].left = self.tree[child].left\n self.tree[self.root_idx].right = self.tree[child].right\n self.tree[self.root_idx].data = self.tree[child].data\n self.tree[self.root_idx].key = self.tree[child].key\n self.tree[child].left = None\n self.tree[child].right = None\n else:\n if self.tree[parent].left == walk:\n self.tree[parent].left = child\n else:\n self.tree[parent].right = child\n\n return True\n","sub_path":"pydatastructs/trees/binary_trees.py","file_name":"binary_trees.py","file_ext":"py","file_size_in_byte":7630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"541583720","text":"def repeat_good(text):\r\n \"\"\"\r\n Takes in a string and returns a new string where every character is repeated \r\n according to it’s position in the original string.\r\n The first occurence is always capitalized, and the other ones are always lower\r\n case\r\n \r\n Arguments:\r\n text {str} -- desired string to replicate\r\n \r\n Returns:\r\n str -- replicated version of the string\r\n\r\n Examples:\r\n >>> repeat_good('abcd')\r\n 'A-Bb-Ccc-Dddd'\r\n >>> repeat_good('abcBd')\r\n 'A-Bb-Ccc-Bbbb-Ddddd'\r\n \"\"\"\r\n\r\n # First char is empty\r\n if text == \"\":\r\n return \"\"\r\n # Capitalize first string\r\n output = text[0].upper()\r\n # For loop to concatinate output with next char * its index\r\n for count, char in enumerate(text[1:], 1):\r\n output +=\"{}{}{}\".format(\"-\", char.upper(), char.lower()*(count))\r\n return output\r\n\r\n\r\ndef repeat_bad(text):\r\n \"\"\"\r\n Takes in a string and returns a new string where every character is repeated\r\n according to it’s position in the original string.\r\n The first occurence is always capitalized, and the other ones are always lower\r\n case\r\n\r\n Arguments:\r\n text {str} -- desired string to replicate\r\n\r\n Returns:\r\n str -- replicated version of the string\r\n\r\n Examples:\r\n >>> repeat_good('abcd')\r\n 'A-Bb-Ccc-Dddd'\r\n >>> repeat_good('abcBd')\r\n 'A-Bb-Ccc-Bbbb-Ddddd'\r\n \"\"\"\r\n\r\n output = \"\"\r\n First = True\r\n\r\n # first char is empty\r\n if text == \"\":\r\n return \"\"\r\n\r\n # for char in text\r\n for char in range(len(text)):\r\n # if first, dont add '-', just char\r\n if First:\r\n output += text[char].upper()\r\n # not first\r\n else:\r\n output += '-'\r\n for repetition in range (char + 1):\r\n if repetition == 0:\r\n output += text[char].upper()\r\n else:\r\n output += text[char].lower()\r\n First = False\r\n return output\r\n\r\nprint(repeat_good(\"abcD\"))\r\nprint(repeat_bad(\"abcd\"))\r\n","sub_path":"assignment4/replicator.py","file_name":"replicator.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"426706901","text":"from matplotlib.legend_handler import HandlerLine2D\nfrom clean_travel_times import clean_travel_times\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ndata = clean_travel_times()\nprint(data)\ndata = data.drop(['actualTravelTimeMin', 'delay'], axis=1)\nprint(data)\nyVar = data.loc[:, 'delay_label']\nprint(yVar)\nxVar = data.drop(['delay_label'], axis=1)\nx_train, x_test, y_train, y_test = train_test_split(xVar, yVar, test_size=0.2)\nclf = RandomForestClassifier()\n\nclf.fit(x_train, y_train)\n\npreds = clf.predict(x_test)\n# print(pd.crosstab(y_test, preds, rownames=[\n# 'Actual Result'], colnames=['Predicted Result']))\n# print(list(zip(x_train, clf.feature_importances_)))\n# data.to_csv(\n# 'C:/Users/nkukushkina/Documents/GitHub/MBTAAnalysis/data3.csv', index=False)\nfalse_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, preds)\nroc_auc = auc(false_positive_rate, true_positive_rate)\nprint(roc_auc)\n\n# n_estimators = [1, 2, 4, 8, 16, 32, 64, 100, 200]\n# train_results = []\n# test_results = []\n# for estimator in n_estimators:\n# rf = RandomForestClassifier(n_estimators=estimator, n_jobs=-1)\n# rf.fit(x_train, y_train)\n# train_pred = rf.predict(x_train)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_train, train_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# train_results.append(roc_auc)\n# y_pred = rf.predict(x_test)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_test, y_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# test_results.append(roc_auc)\n# line1, = plt.plot(n_estimators, train_results, 'b', label='Train AUC')\n# line2, = plt.plot(n_estimators, test_results, 'r', label='Test AUC')\n# plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)})\n# plt.ylabel('AUC score')\n# plt.xlabel('n_estimators')\n# plt.show()\n\n\n# max_depths = np.linspace(1, 32, 32, endpoint=True)\n# train_results = []\n# test_results = []\n# for max_depth in max_depths:\n# rf = RandomForestClassifier(max_depth=max_depth, n_jobs=-1)\n# rf.fit(x_train, y_train)\n# train_pred = rf.predict(x_train)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_train, train_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# train_results.append(roc_auc)\n# y_pred = rf.predict(x_test)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_test, y_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# test_results.append(roc_auc)\n# line1, = plt.plot(max_depths, train_results, 'b', label='Train AUC')\n# line2, = plt.plot(max_depths, test_results, 'r', label='Test AUC')\n# plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)})\n# plt.ylabel('AUC score')\n# plt.xlabel('Tree depth')\n# plt.show()\n\n\n# min_samples_splits = np.linspace(0.1, 1.0, 10, endpoint=True)\n# train_results = []\n# test_results = []\n# for min_samples_split in min_samples_splits:\n# rf = RandomForestClassifier(min_samples_split=min_samples_split)\n# rf.fit(x_train, y_train)\n# train_pred = rf.predict(x_train)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_train, train_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# train_results.append(roc_auc)\n# y_pred = rf.predict(x_test)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_test, y_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# test_results.append(roc_auc)\n# line1, = plt.plot(min_samples_splits, train_results, 'b', label='Train AUC')\n# line2, = plt.plot(min_samples_splits, test_results, 'r', label='Test AUC')\n# plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)})\n# plt.ylabel('AUC score')\n# plt.xlabel('min samples split')\n# plt.show()\n\n\n# min_samples_leafs = np.linspace(0.1, 0.5, 5, endpoint=True)\n# train_results = []\n# test_results = []\n# for min_samples_leaf in min_samples_leafs:\n# rf = RandomForestClassifier(min_samples_leaf=min_samples_leaf)\n# rf.fit(x_train, y_train)\n# train_pred = rf.predict(x_train)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_train, train_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# train_results.append(roc_auc)\n# y_pred = rf.predict(x_test)\n# false_positive_rate, true_positive_rate, thresholds = roc_curve(\n# y_test, y_pred)\n# roc_auc = auc(false_positive_rate, true_positive_rate)\n# test_results.append(roc_auc)\n# line1, = plt.plot(min_samples_leafs, train_results, 'b', label='Train AUC')\n# line2, = plt.plot(min_samples_leafs, test_results, 'r', label='Test AUC')\n# plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)})\n# plt.ylabel('AUC score')\n# plt.xlabel('min samples leaf')\n# plt.show()\n\n\nmax_features = list(range(1, xVar.shape[1]))\ntrain_results = []\ntest_results = []\nfor max_feature in max_features:\n rf = RandomForestClassifier(max_features=max_feature)\n rf.fit(x_train, y_train)\n train_pred = rf.predict(x_train)\n false_positive_rate, true_positive_rate, thresholds = roc_curve(\n y_train, train_pred)\n roc_auc = auc(false_positive_rate, true_positive_rate)\n train_results.append(roc_auc)\n y_pred = rf.predict(x_test)\n false_positive_rate, true_positive_rate, thresholds = roc_curve(\n y_test, y_pred)\n roc_auc = auc(false_positive_rate, true_positive_rate)\n test_results.append(roc_auc)\nline1, = plt.plot(max_features, train_results, 'b', label='Train AUC')\nline2, = plt.plot(max_features, test_results, 'r', label='Test AUC')\nplt.legend(handler_map={line1: HandlerLine2D(numpoints=2)})\nplt.ylabel('AUC score')\nplt.xlabel('max features')\nplt.show()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326484740","text":"# Copyright 2019, OpenCensus Authors\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 sys\nimport time\n\nfrom opencensus.metrics.export.gauge import DerivedDoubleGauge\nif sys.version_info < (3,):\n from BaseHTTPServer import HTTPServer\nelse:\n from http.server import HTTPServer\n\nrequests_map = dict()\nORIGINAL_CONSTRUCTOR = HTTPServer.__init__\n\n\ndef request_patch(func):\n def wrapper(self=None):\n func(self)\n count = requests_map.get('count', 0)\n requests_map['count'] = count + 1\n return wrapper\n\n\ndef server_patch(*args, **kwargs):\n if len(args) >= 3:\n handler = args[2]\n if handler:\n # Patch the handler methods if they exist\n if \"do_DELETE\" in dir(handler):\n handler.do_DELETE = request_patch(handler.do_DELETE)\n if \"do_GET\" in dir(handler):\n handler.do_GET = request_patch(handler.do_GET)\n if \"do_HEAD\" in dir(handler):\n handler.do_HEAD = request_patch(handler.do_HEAD)\n if \"do_OPTIONS\" in dir(handler):\n handler.do_OPTIONS = request_patch(handler.do_OPTIONS)\n if \"do_POST\" in dir(handler):\n handler.do_POST = request_patch(handler.do_POST)\n if \"do_PUT\" in dir(handler):\n handler.do_PUT = request_patch(handler.do_PUT)\n result = ORIGINAL_CONSTRUCTOR(*args, **kwargs)\n return result\n\n\ndef setup():\n # Patch the HTTPServer handler to track request information\n HTTPServer.__init__ = server_patch\n\n\nclass RequestsRateMetric(object):\n NAME = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Requests/Sec\"\n\n def __init__(self):\n setup()\n\n @staticmethod\n def get_value():\n current_count = requests_map.get('count', 0)\n current_time = time.time()\n last_count = requests_map.get('last_count', 0)\n last_time = requests_map.get('last_time')\n last_result = requests_map.get('last_result', 0)\n\n try:\n # last_time is None the very first time this function is called\n if last_time is not None:\n elapsed_seconds = current_time - last_time\n interval_count = current_count - last_count\n result = interval_count / elapsed_seconds\n else:\n result = 0\n requests_map['last_time'] = current_time\n requests_map['last_count'] = current_count\n requests_map['last_result'] = result\n return result\n except ZeroDivisionError:\n # If elapsed_seconds is 0, exporter call made too close to previous\n # Return the previous result if this is the case\n return last_result\n\n def __call__(self):\n \"\"\" Returns a derived gauge for incoming requests per second\n\n Calculated by obtaining by getting the number of incoming requests\n made to an HTTPServer within an elapsed time and dividing that value\n over the elapsed time.\n\n :rtype: :class:`opencensus.metrics.export.gauge.DerivedLongGauge`\n :return: The gauge representing the incoming requests metric\n \"\"\"\n gauge = DerivedDoubleGauge(\n RequestsRateMetric.NAME,\n 'Incoming Requests per second',\n 'rps',\n [])\n gauge.create_default_time_series(RequestsRateMetric.get_value)\n return gauge\n","sub_path":"contrib/opencensus-ext-azure/opencensus/ext/azure/metrics_exporter/standard_metrics/http_requests.py","file_name":"http_requests.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"490481420","text":"import gc\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\nfrom tensorflow.keras.layers import Average, Input\nfrom tensorflow.keras.models import load_model\n\nDEVMODE = os.getenv(\"KAGGLE_MODE\") == \"DEV\"\nprint(f\"DEV MODE: {DEVMODE}\")\n\nINPUT_FOLDER = \"/kaggle/input/cassava-leaf-disease-classification/\"\nWORK_DIR = \"/kaggle/working\"\n\nIMAGE_SIZE = (512, 512)\n\nN_FOLD = 3\n\n\ndef store_predictions(predictions, image_names):\n submission_file = os.path.join(WORK_DIR, \"submission.csv\")\n pd.DataFrame({\"image_id\": image_names, \"label\": predictions}).to_csv(submission_file, index=False)\n print(pd.read_csv(submission_file).head())\n\n\ndef softmax(x):\n e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))\n return e_x / e_x.sum(axis=-1, keepdims=True)\n\n\ndef run_predictions(model: Model):\n predictions = []\n test_image_names = []\n\n test_dir = os.path.join(INPUT_FOLDER, \"test_images\")\n\n datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input,\n horizontal_flip=True,\n vertical_flip=True,\n rotation_range=45,\n zoom_range=0.2,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n brightness_range=(0.8, 1.2),\n fill_mode=\"nearest\",\n )\n\n for image_idx, image_name in enumerate(os.listdir(test_dir)):\n image = tf.keras.preprocessing.image.load_img(os.path.join(test_dir, image_name), target_size=IMAGE_SIZE)\n image = tf.keras.preprocessing.image.img_to_array(image)\n image = np.expand_dims(image, axis=0)\n\n images = np.broadcast_to(image, (N_FOLD,) + image.shape[1:])\n # Use predict_on_batch since looks like predict has a memory leak...\n prediction = model.predict_on_batch(next(datagen.flow(images)))\n prediction = softmax(prediction)\n prediction = np.mean(prediction, axis=0, keepdims=True)\n\n predictions.append(int(np.argmax(prediction, axis=-1).squeeze()))\n test_image_names.append(image_name)\n\n if image_idx % 100 == 0: # Only run every so many images.\n gc.collect()\n\n return predictions, test_image_names\n\n\ndef define_ensemble_model(models):\n # Wrap each model so that names are different and do not collide.\n models = [\n Model(inputs=model.input, outputs=model.output, name=f\"{model.name}_{model_idx}\")\n for model_idx, model in enumerate(models)\n ]\n\n input = Input(IMAGE_SIZE + (3,))\n\n ensemble_outputs = [model(input) for model in models]\n\n avg = Average()(ensemble_outputs)\n\n model = Model(inputs=input, outputs=avg)\n\n return model\n\n\nif __name__ == \"__main__\":\n models_location = \"/kaggle/input/cassava-model\"\n models_info = [\"cassava_best.h5\", \"cassava_best_tempered.h5\", \"cassava_best_tempered_2.h5\"]\n\n models = [\n load_model(\n os.path.join(models_location, model_name),\n custom_objects={\"bi_tempered_loss\": None}, # Loss is not used for inference, so assign to whatever.\n )\n for model_name in models_info\n ]\n\n model = define_ensemble_model(models)\n print(model.summary())\n\n predictions, test_image_names = run_predictions(model)\n store_predictions(predictions, test_image_names)\n","sub_path":"cassava-leaf-disease-classification/cassava-inference.py","file_name":"cassava-inference.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"303374713","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom lxml import html\nimport pandas as pd\nimport os.path\n\n\nsession_requests = requests.session()\nlogin_url = \"https://www.gradescope.com/login\"\nresult = session_requests.get(login_url)\ntree = html.fromstring(result.text)\nauthenticity_token = list(set(tree.xpath(\"//input[@name='authenticity_token']/@value\")))[0]\n\npayload = {\n \"session[email]\": \"\",\n \"session[password]\": \"\",\n \"authenticity_token\": authenticity_token\n}\n\nresult = session_requests.post(\n login_url,\n data = payload,\n headers = dict(referer=login_url)\n)\n\nurl = 'https://www.gradescope.com/account'\nresult = session_requests.get(\n url,\n headers = dict(referer = url)\n)\n\nc = result.content\nsoup = BeautifulSoup(c, features=\"lxml\")\n\n# Creates a list of course names\ncourse_names = []\nraw_course_names = soup.find_all('h3', {\"class\": \"courseBox--shortname\"})\n\nfor each in raw_course_names:\n each = str(each)\n \n new_each = each.lstrip('

    ')\n new_each = new_each.rstrip('

    ')\n course_names.append(new_each)\n\n# Creates a list of the unique course number identifier to be used in the course url\ncourse_numbers = []\nraw_course_numbers = soup.find_all('a', {\"class\": \"courseBox\"}, )\n\nfor each in raw_course_numbers:\n each = str(each)\n\n new_each = each[36:42]\n course_numbers.append(new_each)\n\n# Creates a list of unique course urls\ncourse_urls = []\nurl_header = \"https://www.gradescope.com/courses/\"\n\nfor each in course_numbers:\n url = url_header + each\n course_urls.append(url)\n\n# Initializing a list for dictionaries of key-value pairs of {assignment name : due_date}\nassignments = []\n\n# Here, we want to go through each course page and create a list of assignments for each page\n# We can add these assignments to a list and then add this list to their respective place in the dictionary course_with_assignments\nfor each in course_urls:\n \n result = session_requests.get(\n each,\n headers = dict(referer = each)\n )\n\n c = result.content\n soup = BeautifulSoup(c, features=\"lxml\")\n tables = soup.find('table', {\"class\":\"table\"})\n assignment_lists = pd.read_html(str(tables))[0]\n \n course_assignments = {}\n\n names = assignment_lists['Name'].tolist()\n due_dates = assignment_lists['Due Date'].tolist()\n\n for i in range(0,len(names)):\n course_assignments[str(names[i])] = str(due_dates[i])\n\n assignments.append(course_assignments)\n\n\n# This creates a list of courses with their course numbers\nlist_of_courses = []\nfor i in range(0, len(course_names)):\n list_of_courses.append(course_names[i] + \" | \" + course_numbers[i])\n\n# Creates a dictionary with the key-value pair of {course : list_of_assignments}\ncourse_with_assignments = {}\n\n# Bringing everything together! Dictionary with key-value pairs of {course : course_assignments}\nfor i in range(0,len(list_of_courses)):\n course_with_assignments[list_of_courses[i]] = assignments[i]\n\n\n# Now converting our dictionary to the text file gsParser_results so we can put it into js database..\nimport json\n\ncourse_with_assignments = json.dumps(course_with_assignments)\nsave_path = os.path.abspath(\".\\\\App\\\\scripts\")\ncompleteName = os.path.join(save_path, 'gsParser_results.txt')\nwith open(completeName, 'w') as file:\n file.write(course_with_assignments)\n","sub_path":"App/scripts/gsParser.py","file_name":"gsParser.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244141893","text":"from pip.req import parse_requirements\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom subprocess import call\nfrom setuptools.command.install import install as _install\n\n\ninstall_requirements = parse_requirements('requirements.txt', session=False)\nrequirements = [str(ir.req) for ir in install_requirements]\n\n\nclass install(_install):\n\n def run(self):\n _install.run(self)\n\n\nsetup(\n name='lights',\n version='0.1.1',\n author='Karim Mango',\n author_email='karim.mango@magine.com',\n description=\"\"\"\n This is a Raspberry Pi experiment, utilizing the addon Piface to the\n Raspberry Pi to connect speakers, warning tower light, and siren\n combined with code in Python to simultaneously fire off the lights\n and play an mp3 file.\"\"\",\n packages=find_packages(),\n include_package_data=True,\n install_requires=requirements,\n cmdclass={'install': install},\n license='MIT',\t\t\t\t\t\n zip_safe=False,\n entry_points={\n 'console_scripts': [\n 'lights=lights.server:run',\n ]},\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"539230278","text":"import numpy as np\nimport pandas as pd\n\nclass Grid(object):\n '''\n Represents a grid as a vector\n '''\n def __init__(self, grid):\n self.rows = len(grid)\n self.cols = len(grid[0])\n self.length = self.rows*self.cols\n self.ls = [j for i in grid for j in i]\n\n def loc(self, i, j):\n index = self.two_to_one_coords(i, j)\n if index is not None:\n return self.ls[index]\n else:\n # off the grid\n return None\n\n def two_to_one_coords(self, i, j):\n if 0 <= i and i < self.rows and 0 <= j and j < self.cols:\n return i * self.cols + j\n else:\n return None\n\n def one_to_two_coords(self, k):\n '''\n :param k: location in grid\n :return: (i, j)th location on grid\n '''\n if k < self.length:\n i = k // self.cols\n j = k % self.cols\n return i, j\n else:\n assert 0, 'Grid.loc_inv: invalid location.'\n\n\n'''\nDefines MDP data structure\n'''\n\n\nclass MDP(object):\n '''\n MDP class. Contains:\n - An m by n grid world and the available actions.\n - A list of states, labeling the grid in increasing order from left to right,\n not including inaccesible locations.\n - A list of actions (possible states to go to) to take from any given state.\n - A transition function.\n '''\n def __init__(self, policy_grid, probs):\n '''\n :param policy_grid: m x n list of lists that denotes the policy.\n '''\n self.probs = probs\n self.policy_grid = Grid(policy_grid)\n # Locations of inaccessible tiles.\n self.blocked_locations = []\n # Maps states to location on grid.\n self.state2location = {}\n self.transition_dict = {}\n j = 0\n for i in range(self.policy_grid.length):\n if self.policy_grid.ls[i] != 'NA':\n self.state2location[j] = i\n j += 1\n else:\n self.blocked_locations.append(i)\n\n # Maps location on grid to states.\n self.location2state = {v:k for k, v in self.state2location.items()}\n # States labeled as 1,2,3,...,n\n self.states = list(self.state2location)\n # Terminal states\n self.terminal_states = [i for i in self.states\n if self.policy_grid.ls[self.state2location[i]] == 0]\n # state:[available actions]\n self.actions = {i:[] for i in self.states}\n self.construct_actions()\n\n def transition(self, s, a, s_next):\n if (s, a, s_next) in self.transition_dict.keys(): \n return(self.transition_dict[(s,a,s_next)])\n else: \n adjacent = self.actions[s]\n # Check if s_next is possible and at a terminal state.\n if s_next in adjacent and len(adjacent) > 1:\n adjacent.remove(a)\n adjacent.insert(0, a)\n adjacent = pd.Series(adjacent)\n probs = pd.Series(self.probs)\n # Join both series, group together duplicate states and sum their probabilities.\n # Retrieve probability corresponding to s_next in probabilities.\n prob = pd.concat([adjacent, probs],\n axis=1).groupby(0).sum().loc[s_next, 1]\n self.transition_dict[(s, a, s_next)] = prob \n return prob\n else:\n self.transition_dict[(s, a, s_next)] = 0\n return 0\n\n def features(self, state):\n '''Return feature vector for given state (a dummy variable for location)'''\n feature = np.zeros(len(self.states))\n feature[state] = 1\n return feature\n\n # Helper functions below.\n def construct_actions(self):\n '''\n :return: Nothing\n Constructs available actions available at each state.\n '''\n for state in self.states:\n if self.policy_grid.ls[self.state2location[state]] == 0:\n self.actions[state].append(state)\n else:\n self.cardinal_assignment(state)\n\n def cardinal_assignment(self, state):\n '''\n :param state: Single-coordinate location on grid\n :return: Nothing\n Assigns possible actions to a state based on desired direction.\n Note 1 is north, 2 is south, 3 is east, 4 is west.\n '''\n # Get (i, j)th coordinate on grid.\n location = self.state2location[state]\n i, j = self.policy_grid.one_to_two_coords(location)\n # x and y coordinates for four actions (1: preferred direction,\n # 2: left, 3: right, 4: backward).\n x = [i] * 4\n y = [j] * 4\n\n if self.policy_grid.ls[location] == 1:\n # go north\n x[0] -= 1\n y[1] -= 1\n y[2] += 1\n x[3] += 1\n\n elif self.policy_grid.ls[location] == 2:\n # go south\n x[0] += 1\n y[1] += 1\n y[2] -= 1\n x[3] -= 1\n\n elif self.policy_grid.ls[location] == 3:\n # go east\n y[0] += 1\n x[1] -= 1\n x[2] += 1\n y[3] -= 1\n\n elif self.policy_grid.ls[location] == 4:\n # go west\n y[0] -= 1\n x[1] += 1\n x[2] -= 1\n y[3] += 1\n\n else:\n assert 0, 'MDP.cardinal_assignment: Invalid direction.'\n\n new_locations = [self.policy_grid.two_to_one_coords(x[0], y[0]),\n self.policy_grid.two_to_one_coords(x[1], y[1]),\n self.policy_grid.two_to_one_coords(x[2], y[2]),\n self.policy_grid.two_to_one_coords(x[3], y[3])]\n # Check for movement off the grid.\n new_locations = [location if i is None else i for i in new_locations]\n # Both check for movement to blocked locations and convert to state.\n new_states = [self.location2state[location] if i in self.blocked_locations\n else self.location2state[i] for i in new_locations]\n for i in new_states: self.actions[state].append(i)\n\n\ndef simulate_trajectories(mdps, sample_size, probs = None):\n '''\n :param mdps: List of mdps with each agents preferred actions\n :param sample_size: Number of trajectories to simulate\n :param probs: Vector of desired probabilities of observing each agent (mdp),\n e.g. [agent1, agent2] has probs [0.7, 0.3]\n :return: List of trajectories (list of lists of tuples)\n '''\n # If no probability is specified, use uniform distribution.\n if probs is None:\n probs = [1/len(mdps)] * len(mdps)\n\n assert len(mdps) == len(probs), '''Number of agents doesn't match\n number of probabilities.'''\n # Initialize sample.\n D_s = []\n D_sa = []\n # The following four variables are shared amongst all MDPs.\n actions = mdps[0].actions\n states = mdps[0].states\n terminal_states = mdps[0].terminal_states\n starting_states = states.copy()\n for i in terminal_states:\n starting_states.remove(i)\n\n for i in range(sample_size):\n # Pick agent according to probs.\n mdp = np.random.choice(mdps, 1, p = probs)[0]\n D_s.append([])\n D_sa.append([])\n # Pick a starting state.\n current_state = starting_states[np.random.randint(len(starting_states))]\n # Simulate agent's trajectory.\n while current_state not in terminal_states:\n try:\n # An agent's mdp.actions[state] are ordered by\n # [go in preferred direction, go left, go right]\n D_s[i].append(current_state) \n D_sa[i].append((current_state, mdp.actions[current_state][0]))\n \n except:\n assert 0, 'Invalid state reached'\n current_state = np.random.choice(mdp.actions[current_state], 1, p=[0.7, 0.1, 0.1, 0.1])[0]\n D_s[i].append(current_state) \n\n return D_s, D_sa \n","sub_path":"MDP.py","file_name":"MDP.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299288715","text":"# -*- coding: utf-8 -*-\n\nfrom .dataproxy import *\nfrom .account import *\nfrom .agenda import *\nfrom .user import *\nfrom .resource import *\nfrom .group import *\nfrom .notification import *\nfrom .typedict import *\n\nimport re\n\nclass Collection:\n\t\"\"\" Collection de toutes les données du système.\n\tÀ chaque accès à un data proxy n'ayant pas chargé sa data\n\tla collection est appellé pour la charger.\n\n\tCeci est possible depuis une BDD ou par réseau, d'où deux\n\tclasses filles de la classe Collection.\n\t\"\"\"\n\n\t# Tous les types supportés.\n\tsupported_types = [\n\t\tAccount,\n\t\tAgenda,\n\t\tEvent,\n\t\tGroup,\n\t\tUser,\n\t\tResource,\n\t\tNotification\n\t]\n\n\tdef __init__(self):\n\t\t# Toutes les données existant dynamiquement ou dans le base et chargé.\n\t\tself._datas = TypeDict(self.supported_types)\n\t\tself._new_datas = TypeDict(self.supported_types)\n\t\t# Tous les proxies de données fournis.\n\t\tself._data_proxies = TypeDict(self.supported_types)\n\n\t\t# Liste d'attente pour l'écriture et la modification.\n\t\tself.new_queue = set()\n\t\tself.update_queue = set()\n\t\tself.update_relations_queue = set()\n\t\tself.delete_queue = set()\n\n\tdef _register_data(self, data):\n\t\tassert(data.id != -1)\n\n\t\tself._datas[data.data_type][data.id] = data\n\n\tdef _unregister_data(self, data):\n\t\tassert(data.id != -1)\n\n\t\t#print(\"unregister\", data.id)\n\t\tself._datas[data.data_type].pop(data.id)\n\n\tdef _register_proxy(self, proxy):\n\t\tself._data_proxies[proxy.data_type][proxy.id] = proxy\n\n\tdef _unregister_proxy(self, proxy):\n\t\tself._data_proxies[proxy.data_type].pop(proxy.id)\n\n\tdef _delete_proxies(self, proxies):\n\t\tfor proxy in proxies:\n\t\t\tproxy.delete()\n\n\tdef load(self, proxy):\n\t\t\"\"\" Charge une données d'un proxy \"\"\"\n\t\traise NotImplementedError\n\n\tdef load_events(self, agenda, from_date, to_date):\n\t\t\"\"\" Charge des événements débutant entre deux dates \"\"\"\n\t\traise NotImplementedError\n\n\tdef load_last_events(self, agenda, from_date, to_date):\n\t\traise NotImplementedError\n\n\tdef load_groups(self, sub_name):\n\t\tgroups = set()\n\n\t\tregex = re.compile(\".*{}.*\".format(sub_name))\n\t\tfor group in self._datas[Group].values():\n\t\t\tif regex.match(group.name):\n\t\t\t\tgroups.add(group)\n\n\t\tfor group in self._new_datas[Group].values():\n\t\t\tif regex.match(group.name):\n\t\t\t\tgroups.add(group)\n\n\t\treturn groups\n\n\tdef new(self, type, args, kwargs):\n\t\t_type = self._datas.key(type)\n\t\tdata = _type(-1, self, *args, **kwargs)\n\t\tself.new_queue.add(data)\n\t\tself._new_datas[type][id(data)] = data\n\n\t\treturn data\n\n\tdef _data_or_proxy(self, id, _type):\n\t\t\"\"\" Conversion d'un identifiant en donné ou proxy \"\"\"\n\t\tif id is None:\n\t\t\treturn None\n\n\t\t# Recherche d'une donnée déjà existante.\n\t\tdata = self._datas[_type].get(id, None)\n\t\tif data is not None:\n\t\t\treturn data\n\n\t\t# Recherche d'un proxy déjà existant.\n\t\tproxy = self._data_proxies[_type].get(id, None)\n\t\tif proxy is not None:\n\t\t\treturn proxy\n\n\t\t# Création d'un nouveau proxy.\n\t\tproxy = DataProxy(id, _type, self)\n\t\t# Enregistrement du proxy.\n\t\tself._data_proxies[_type][id] = proxy\n\n\t\treturn proxy\n\n\tdef find_proxies(self, _type, _id):\n\t\t\"\"\" Détection des proxies qui devrait être supprimés\n\t\taprès la suppression d'une donnée parent.\n\t\tPar exemple la suppression d'un Account doit supprimer\n\t\tles proxies User obtenus par les groupes.\n\t\t\"\"\"\n\n\t\traise NotImplementedError\n\n\tdef delete(self, data, delete_proxies):\n\t\tself.delete_queue.add(data)\n\n\t\tif data.id != -1:\n\t\t\t# Désenregistrement de la donnée.\n\t\t\tself._unregister_data(data)\n\n\t\t\tif delete_proxies:\n\t\t\t\tproxies = self.find_proxies(data.data_type, data.id)\n\t\t\t\tself._delete_proxies(proxies)\n\n\t\t\t\treturn proxies\n\n\t\treturn set()\n\n\tdef delete_proxy(self, proxy, delete_proxies):\n\t\tself.delete_queue.add(proxy)\n\t\t# Désenregistrement du proxy.\n\t\tself._unregister_proxy(proxy)\n\n\t\tif delete_proxies:\n\t\t\tproxies = self.find_proxies(proxy.data_type, proxy.id)\n\t\t\tself._delete_proxies(proxies)\n\n\t\t\treturn proxies\n\n\tdef update(self, data):\n\t\tself.update_queue.add(data)\n\n\tdef update_relations(self, data):\n\t\tself.update_relations_queue.add(data)\n\n\tdef flush(self):\n\t\traise NotImplementedError\n","sub_path":"Source/core/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151818250","text":"\nimport os\nimport sys\n\nsys.path.append('.')\nsys.path.append('../')\n\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\n\nfrom dataset.mnist import MNIST \n\nif __name__ == '__main__':\n\tconfig = {\n\t\t'batch_size' : 16,\n\t\t'output shape' : [28, 28]\n\t}\n\n\tdataset = MNIST(config)\n\n\tfor ind, x_batch in dataset.iter_images():\n\t\tplt.figure(0)\n\t\tplt.imshow(x_batch[0, :, :])\n\t\tplt.pause(1)\n\n","sub_path":"test/test_mnist.py","file_name":"test_mnist.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156021896","text":"# -*- mode:python; coding:utf-8 -*-\n\n# Copyright (c) 2020 IBM Corp. 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\"\"\"Tests for models util module.\"\"\"\n\nimport pathlib\n\nimport trestle.core.validator_helper as validator_helper\nimport trestle.oscal.catalog as catalog\nimport trestle.oscal.target as ostarget\n\nimport yaml\n\ncatalog_path = pathlib.Path('nist-content/nist.gov/SP800-53/rev4/json/NIST_SP-800-53_rev4_catalog.json')\n\n\ndef test_has_no_duplicate_values_generic() -> None:\n \"\"\"Test presence of duplicate uuid.\"\"\"\n # test with pydantic catalog\n cat = catalog.Catalog.oscal_read(catalog_path)\n assert validator_helper.has_no_duplicate_values_generic(cat, 'uuid')\n\n yaml_path = pathlib.Path('tests/data/yaml')\n\n # test with valid pydantic target\n good_target_path = yaml_path / 'good_target.yaml'\n good_target = ostarget.TargetDefinition.oscal_read(good_target_path)\n validator_helper.find_values_by_name(good_target, 'uuid')\n assert validator_helper.has_no_duplicate_values_by_name(good_target, 'uuid')\n\n # test with pydantic target containing duplicates\n bad_target_path = yaml_path / 'bad_target_dup_uuid.yaml'\n bad_target = ostarget.TargetDefinition.oscal_read(bad_target_path)\n assert not validator_helper.has_no_duplicate_values_by_name(bad_target, 'uuid')\n\n # test duplicates with raw yaml target, non-pydantic\n read_file = bad_target_path.open('r', encoding='utf8')\n bad_target_yaml = yaml.load(read_file, Loader=yaml.Loader)\n assert not validator_helper.has_no_duplicate_values_generic(bad_target_yaml, 'uuid')\n\n\ndef test_has_no_duplicate_values_pydantic() -> None:\n \"\"\"Test presence of duplicate values in pydantic objects.\"\"\"\n # test with pydantic catalog - only one instance of Metadata\n cat = catalog.Catalog.oscal_read(catalog_path)\n assert validator_helper.has_no_duplicate_values_by_type(cat, catalog.Metadata)\n\n yaml_path = pathlib.Path('tests/data/yaml')\n\n # test presence of many duplicate properties\n good_target_path = yaml_path / 'good_target.yaml'\n good_target = ostarget.TargetDefinition.oscal_read(good_target_path)\n assert not validator_helper.has_no_duplicate_values_by_type(good_target, ostarget.Property)\n","sub_path":"tests/trestle/core/validator_helper_test.py","file_name":"validator_helper_test.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240600711","text":"\"\"\"\r\nvotenext.py by IAmYourFriend https://twitter.com/1AmYF\r\n\r\nvotenext.py is a simple way for players to vote for loading the next map in\r\nthe rotation by only typing /next. Unlike votekick or votemap, the votes will be\r\nremembered and the progress will be checked again everytime someone types /next\r\nor disconnects from the server.\r\n\r\nConfig Options:\r\n\r\n [votenext]\r\n # Percentage of votes necessary for the next map to load\r\n vote_percentage = 80\r\n\r\n # How long players have to wait to be able to vote on a newly loaded map\r\n min_map_uptime = \"1min\"\r\n\"\"\"\r\n\r\nimport time\r\nfrom pyspades.constants import *\r\nfrom piqueserver.commands import command\r\nfrom piqueserver.config import config, cast_duration\r\n\r\nVOTENEXT_CONFIG = config.section(\"votenext\")\r\nVOTE_PERCENTAGE = VOTENEXT_CONFIG.option(\"vote_percentage\", default=80, cast=int)\r\nMIN_MAP_UPTIME = VOTENEXT_CONFIG.option(\"min_map_uptime\", default=\"1min\", cast=cast_duration)\r\n\r\n\r\n@command()\r\ndef next(connection):\r\n if not connection.voted_next:\r\n if not allow_votes(connection.protocol):\r\n msg = \"Please wait %s seconds before requesting the next map.\"\r\n connection.send_chat(msg % (connection.protocol.mapstarttime +\r\n MIN_MAP_UPTIME.get() - get_now_in_secs()))\r\n else:\r\n connection.voted_next = True\r\n check_for_map_change(connection.protocol)\r\n connection.protocol.irc_say(\"%s voted for next map\" % connection.name)\r\n if not connection.protocol.vote_next_successful:\r\n msg = \"%s voted to load the next map, if you agree type /next\"\r\n connection.protocol.broadcast_chat(msg % connection.name)\r\n else:\r\n connection.send_chat(\"You have voted already.\")\r\n\r\n\r\ndef allow_votes(protocol):\r\n if protocol.mapstarttime is not None and not protocol.vote_next_successful:\r\n return (protocol.mapstarttime + MIN_MAP_UPTIME.get()) < get_now_in_secs()\r\n else:\r\n return False\r\n\r\n\r\ndef get_now_in_secs():\r\n return int(time.time())\r\n\r\n\r\ndef reset_player_votes(protocol):\r\n protocol.vote_next_successful = False\r\n if protocol.players is not None and len(protocol.players) > 0:\r\n for p in protocol.players.values():\r\n p.voted_next = False\r\n\r\n\r\ndef is_bot(connection):\r\n try:\r\n return connection.local\r\n except AttributeError:\r\n return False\r\n\r\n\r\ndef check_for_map_change(protocol, ignore_player_id=None):\r\n if protocol.players is not None and len(protocol.players) > 0 and allow_votes(protocol):\r\n valid_voters = 0\r\n valid_votes = 0\r\n for p in protocol.players.values():\r\n ignore_player = False\r\n if is_bot(p) or (ignore_player_id is not None and (p.player_id == ignore_player_id)):\r\n ignore_player = True\r\n if not ignore_player:\r\n valid_voters += 1\r\n if p.voted_next:\r\n valid_votes += 1\r\n if valid_voters > 0 and valid_votes >= VOTE_PERCENTAGE.get() * valid_voters / float(100):\r\n protocol.vote_next_successful = True\r\n protocol.advance_rotation(\"Vote successful.\")\r\n\r\n\r\ndef apply_script(protocol, connection, config):\r\n class VoteNextProtocol(protocol):\r\n mapstarttime = None\r\n vote_next_successful = False\r\n\r\n def on_map_change(self, map):\r\n reset_player_votes(self)\r\n self.mapstarttime = get_now_in_secs()\r\n protocol.on_map_change(self, map)\r\n\r\n class VoteNextConnection(connection):\r\n voted_next = False\r\n\r\n def on_disconnect(self):\r\n if not is_bot(self):\r\n check_for_map_change(self.protocol, self.player_id)\r\n connection.on_disconnect(self)\r\n\r\n return VoteNextProtocol, VoteNextConnection\r\n","sub_path":"scripts/piqueserver/votenext.py","file_name":"votenext.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"640600858","text":"import itertools\nwith open ('/home/xela/py/77.txt', 'r') as a: a=a.read().lower().split(); ff = open('/home/xela/py/777.txt','w')\nw,zz=[],[]\na.insert(0,'text');a.insert(0,'text');del a[::3];a.pop(0)\ntot = [a[i:i+2] for i in range(0, len(a), 2)]\nn=[list(item[1]) for item in itertools.groupby(sorted(tot), key=lambda x: x[0])]\nfor s in n: w.append(list(itertools.chain.from_iterable(s)))\nfor ww in w:\n s=ww[0];zz.append(int(s))\n del ww[::2];ww.insert(0, s)\n ww = list(map(int, ww));ww=(sum(ww[1:])/ (len(ww) - 1));zz.append(ww)\nzz = [zz[i:i+2] for i in range(0, len(zz),2)]\nfor zzz in sorted(zz):\n if len(zzz) == 1: print(*zzz, '-',file=ff)\n else: print(*zzz,file=ff)\n# print(sorted(zz))fi\n # ww.pop(0)\n # print(s, ww,file=ff)","sub_path":"Black Box(Smoke)/scratches/3.7.5.py","file_name":"3.7.5.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125514276","text":"\"\"\"def add(x):\n\treturn x * 2\"\"\"\n\"\"\"nums = [11, 22, 33, 44, 55]\nresult = list(filter(lambda x: x%2==0, nums))\nprint(result)\"\"\"\n\n\"\"\"def countdown():\n\ti = 5\n\twhile i > 0:\n\t\tprint(\"+\",i)\n\t\ti -= 1\ncountdown()\"\"\"\n\n\"\"\"def reverse():\n\ti = 0\n\twhile i > -6:\n\t\tyield i\n\t\ti -= 1\nfor i in reverse():\n\tprint(i)\"\"\"\n\n\"\"\"def crazy():\n\twhile True:\n\t\tyield \"this shit crazy\"\nfor iz in crazy():\n\tprint(iz, \"we aint even pose be here\")\"\"\"\n\ndef prime(x):\n\tfor i in range(x):\n\t\tif i%2 == 0:\n\t\t\tyield i\nprint(list(prime(11)))","sub_path":"python/rev.py","file_name":"rev.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385485194","text":"import wan_optimizer\nimport utils\nfrom tcp_packet import Packet\n\n\nclass WanOptimizer(wan_optimizer.BaseWanOptimizer):\n \"\"\" WAN Optimizer that divides data into fixed-size blocks.\n\n This WAN optimizer should implement part 1 of project 4.\n \"\"\"\n\n # Size of blocks to store, and send only the hash when the block has been\n # sent previously\n BLOCK_SIZE = 8000\n\n def __init__(self):\n wan_optimizer.BaseWanOptimizer.__init__(self)\n # Add any code that you like here (but do not add any constructor arguments).\n\n # Some kind of dictionary for seen blocks\n # {hash : block}\n self.hash_to_data = {}\n\n # Buffer for each client \"dest\"\n # {[packet.src, packet.dest] : {'packets' : [], 'length' : Int}}\n self.buffers = {}\n\n # Need different result_packets for WAN-to-WAN and WAN-to-CLIENT\n # How come?\n\n # Also when creating packets to send, must differentiate between if youre sending\n # to another client or if you are sending to another WAN\n\n def receive(self, packet):\n \"\"\" Handles receiving a packet.\n\n Right now, this function simply forwards packets to clients (if a packet\n is destined to one of the directly connected clients), or otherwise sends\n packets across the WAN. You should change this function to implement the\n functionality described in part 1. You are welcome to implement private\n helper fuctions that you call here. You should *not* be calling any functions\n or directly accessing any variables in the other middlebox on the other side of\n the WAN; this WAN optimizer should operate based only on its own local state\n and packets that have been received.\n \"\"\"\n if not packet.is_raw_data:\n if packet.dest in self.address_to_port:\n # Can't we assume that we have the hash?\n block = self.hash_to_data[packet.payload]\n packets = []\n while len(block) > utils.MAX_PACKET_SIZE:\n packets.append(Packet(packet.src, packet.dest, True, False, block[:utils.MAX_PACKET_SIZE]))\n block = block[utils.MAX_PACKET_SIZE:]\n packets.append(Packet(packet.src, packet.dest, True, packet.is_fin, block))\n for pack in packets:\n self.send(pack, self.address_to_port[packet.dest])\n else:\n packet_to_send = packet\n packet_for_later = None\n if (packet.src, packet.dest) not in self.buffers.keys():\n self.buffers[(packet.src, packet.dest)] = {}\n self.buffers[(packet.src, packet.dest)][\"packets\"] = []\n self.buffers[(packet.src, packet.dest)][\"length\"] = 0\n\n # Checking if packet needs to be split\n if packet.size() + self.buffers[(packet.src, packet.dest)][\"length\"] > WanOptimizer.BLOCK_SIZE:\n diff = WanOptimizer.BLOCK_SIZE - self.buffers[(packet.src, packet.dest)][\"length\"]\n # Result should not be True ever\n packet_to_send = Packet(packet.src, packet.dest, packet.is_raw_data, False, packet.payload[:diff])\n packet_for_later = Packet(packet.src, packet.dest, packet.is_raw_data, packet.is_fin, packet.payload[diff:])\n\n # Checking if source, destination has been seen before:\n self.buffers[(packet.src, packet.dest)]['packets'].append(packet_to_send)\n self.buffers[(packet.src, packet.dest)]['length'] += packet.size()\n\n # Checking if we have met block size limit and must therefore send\n if packet.is_fin or self.buffers[(packet.src, packet.dest)]['length'] >= WanOptimizer.BLOCK_SIZE:\n packets = self.buffers[(packet.src, packet.dest)]['packets']\n\n # Create block\n block = \"\"\n for pack in packets:\n block += pack.payload\n\n # If block is in our self.hash_to_data\n if block in self.hash_to_data.values():\n if packet.dest in self.address_to_port:\n for pack in packets:\n self.send(pack, self.address_to_port[pack.dest])\n else:\n for hash_key, block_val in self.hash_to_data.iteritems():\n if block == block_val:\n hash_packet = Packet(packet.src, packet.dest, False, packet.is_fin, hash_key)\n break\n self.send(hash_packet, self.wan_port)\n\n # If seeing packets for the first time\n else:\n # Store hash and block to self.hash_to_data\n self.hash_to_data[utils.get_hash(block)] = block\n\n # Send the packets\n for pack in packets:\n if packet.dest in self.address_to_port:\n self.send(pack, self.address_to_port[pack.dest])\n else:\n self.send(pack, self.wan_port)\n\n # Reset after sending out buffer\n self.buffers[(packet.src, packet.dest)]['packets'] = []\n self.buffers[(packet.src, packet.dest)]['length'] = 0\n if packet_for_later:\n self.buffers[(packet.src, packet.dest)]['packets'] = [packet_for_later]\n self.buffers[(packet.src, packet.dest)]['length'] = packet_for_later.size()\n","sub_path":"projects/proj4_wanoptimizer/gg.py","file_name":"gg.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470769244","text":"\n\"\"\"\nThis script provides the environment for a quadrotor runway inspection simulation.\n\nThree 4-dof quadrotors are tasked with inspecting a runway. They must learn to \nwork together as a team. Each cell of the runway needs to be inspected by any of \nthe three quadrotors. Rewards are only given when a new cell has been inspected.\n\nEach quadrotor knows where the other ones are. They all use the same policy network.\nThey also all know the state of the runway and they all receive rewards when a \nnew cell is explored.\n\nAltitude is considered but heading is not considered.\n\nAll dynamic environments I create will have a standardized architecture. The\nreason for this is I have one learning algorithm and many environments. All\nenvironments are responsible for:\n - dynamics propagation (via the step method)\n - initial conditions (via the reset method)\n - reporting environment properties (defined in __init__)\n - seeding the dynamics (via the seed method)\n - animating the motion (via the render method):\n - Rendering is done all in one shot by passing the completed states\n from a trial to the render() method.\n\nOutputs:\n Reward must be of shape ()\n State must be of shape (OBSERVATION_SIZE,)\n Done must be a bool\n\nInputs:\n Action input is of shape (ACTION_SIZE,)\n\nCommunication with agent:\n The agent communicates to the environment through two queues:\n agent_to_env: the agent passes actions or reset signals to the environment\n env_to_agent: the environment returns information to the agent\n\nReward system:\n - A reward of +1 is given for finding an unexplored runway element\n - Penaltys may be given for collisions or proportional to the distance \n between the quadrotors.\n\nState clarity:\n - TOTAL_STATE contains all relevant information describing the problem, and all the information needed to animate the motion\n TOTAL_STATE is returned from the environment to the agent.\n A subset of the TOTAL_STATE, called the 'observation', is passed to the policy network to calculate acitons. This takes place in the agent\n The TOTAL_STATE is passed to the animator below to animate the motion.\n The chaser and target state are contained in the environment. They are packaged up before being returned to the agent.\n The total state information returned must be as commented beside self.TOTAL_STATE_SIZE.\n\n\nStarted May 19, 2020\n@author: Kirk Hovell (khovell@gmail.com)\n\"\"\"\nimport numpy as np\nimport os\nimport signal\nimport multiprocessing\nimport queue\nfrom scipy.integrate import odeint # Numerical integrator\nfrom shapely.geometry import Polygon, LineString\n\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.gridspec as gridspec\nimport matplotlib.cm as cm\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection # to shade the runway in a 3D plot\n\n\"\"\"\nNote: \n - \n\"\"\"\n\nclass Environment:\n\n def __init__(self):\n ##################################\n ##### Environment Properties #####\n ##################################\n self.NUMBER_OF_QUADS = 2 # Number of quadrotors working together to complete the task\n self.THREE_QUAD_GENERIC_MODEL = False # whether to train a model that works on 3/2/1 quads equally well, while accounting for all failures\n self.BASE_STATE_SIZE = self.NUMBER_OF_QUADS * 6 # [my_x, my_y, my_z, my_Vx, my_Vy, my_Vz, other1_x, other1_y, other1_z, other1_Vx, other1_Vy, other1_Vz, other2_x, other2_y, other2_z, other2_Vx, other2_Vy, other2_Vz] \n self.INDOORS = False # True = indoors; False = outdoors\n self.QUAD_FAILURE_PERCENTAGE = 0.5 # [0-1] fraction of the episodes where a quadrotor failure will occur.\n if self.INDOORS:\n self.RUNWAY_WIDTH = 4 # [m] in Y (West)\n self.RUNWAY_LENGTH = 4 # [m] in X (North)\n self.MAX_NUMBER_OF_TIMESTEPS = 300 # per episode\n else:\n self.RUNWAY_WIDTH = 12.5 # [m] in Y (West)\n self.RUNWAY_LENGTH = 124 # [m] in X (North) \n self.MAX_NUMBER_OF_TIMESTEPS = 500 # per episode\n self.RUNWAY_WIDTH_ELEMENTS = 4 # 4[elements]\n self.RUNWAY_LENGTH_ELEMENTS = 8 # 8[elements]\n self.IRRELEVANT_STATES = [2,5] # indices of states who are irrelevant to the policy network\n self.ACTION_SIZE = 2 # [my_x_dot_dot, my_y_dot_dot]\n self.NORMALIZE_STATE = True # Normalize state on each timestep to avoid vanishing gradients\n self.RANDOMIZE = True # whether or not to RANDOMIZE the state & target location\n self.POSITION_RANDOMIZATION_SD = np.array([self.RUNWAY_LENGTH*2/3, self.RUNWAY_WIDTH*2/3, 1.0]) # [m, m, m]\n self.INITIAL_QUAD_POSITION = np.array([.0, .0, 3.0]) # [m, m, m] \n self.MIN_V = 0.\n self.MAX_V = self.RUNWAY_LENGTH_ELEMENTS*self.RUNWAY_WIDTH_ELEMENTS\n self.N_STEP_RETURN = 2\n self.DISCOUNT_FACTOR = 0.95**(1/self.N_STEP_RETURN)\n self.TIMESTEP = 0.2 # [s]\n self.DYNAMICS_DELAY = 3 # [timesteps of delay] how many timesteps between when an action is commanded and when it is realized\n self.AUGMENT_STATE_WITH_ACTION_LENGTH = 3 # [timesteps] how many timesteps of previous actions should be included in the state. This helps with making good decisions among delayed dynamics.\n self.ADDITIONAL_VALUE_INFO = False # whether or not to include additional reward and value distribution information on the animations\n self.TOP_DOWN_VIEW = True # Animation property\n self.SKIP_FAILED_ANIMATIONS = True # Error the program or skip when animations fail?\n\n # Test time properties\n self.TEST_ON_DYNAMICS = True # Whether or not to use full dynamics along with a PD controller at test time\n self.KINEMATIC_NOISE = False # Whether or not to apply noise to the kinematics in order to simulate a poor controller\n self.KINEMATIC_NOISE_SD = [0.02, 0.02, 0.02] # The standard deviation of the noise that is to be applied to each element in the state\n self.FORCE_NOISE_AT_TEST_TIME = False # [Default -> False] Whether or not to force kinematic noise to be present at test time\n\n # PD Controller Gains\n self.KI = 0.5 # Integral gain for the integral-linear acceleration controller\n \n # Physical properties\n self.LENGTH = 0.3 # [m] side length\n self.MASS = 0.5 # [kg]\n \n # Target collision properties\n self.COLLISION_DISTANCE = self.LENGTH # [m] how close chaser and target need to be before a penalty is applied\n self.COLLISION_PENALTY = 15 # [rewards/second] penalty given for colliding with target \n\n # Additional properties\n self.ACCELERATION_PENALTY = 0.0 # [factor] how much to penalize all acceleration commands\n if self.INDOORS: \n self.VELOCITY_LIMIT = 4 # [m/s] maximum allowable velocity, a hard cap is enforced if this velocity is exceeded. Note: Paparazzi must also supply a hard velocity cap \n self.MINIMUM_CAMERA_ALTITUDE = 0 # [m] minimum altitude above the runway to get a reliable camera shot. If below this altitude, the runway element is not considered explored\n self.MAXIMUM_CAMERA_ALTITUDE = 10 # [m] maximum altitude above the runway to get a reliable camera shot. If above this altitude, the runway element is not considered explored\n self.PROXIMITY_PENALTY_MAXIMUM = 1 # how much to penalize closeness of the quadrotors to encourage them not to bunch up; penalty = -PROXIMITY_PENALTY_MAXIMUM*exp(-distance/PROXIMITY_PENALTY_FACTOR)\n self.PROXIMITY_PENALTY_FACTOR = 0.43 # how much the penalty decays with distance -> a penalty of 0.01 when they are 2 m apart. To change: = -distance/ln(desired_penalty)\n self.LOWER_ACTION_BOUND = np.array([-2.0, -2.0]) # [m/s^2, m/s^2]\n self.UPPER_ACTION_BOUND = np.array([ 2.0, 2.0]) # [m/s^2, m/s^2]\n self.LOWER_STATE_BOUND_PER_QUAD = np.array([ -3. - self.RUNWAY_LENGTH/2, -3. - self.RUNWAY_WIDTH/2, 0., -self.VELOCITY_LIMIT, -self.VELOCITY_LIMIT, -self.VELOCITY_LIMIT]) # [m, m, m, m/s, m/s, m/s]\n self.UPPER_STATE_BOUND_PER_QUAD = np.array([ 3. + self.RUNWAY_LENGTH/2, 3. + self.RUNWAY_WIDTH/2, 10., self.VELOCITY_LIMIT, self.VELOCITY_LIMIT, self.VELOCITY_LIMIT]) # [m, m, m, m/s, m/s, m/s]\n \n else:\n self.VELOCITY_LIMIT = 5 # [m/s] maximum allowable velocity, a hard cap is enforced if this velocity is exceeded. Note: Paparazzi must also supply a hard velocity cap\n self.MINIMUM_CAMERA_ALTITUDE = 0 # [m] minimum altitude above the runway to get a reliable camera shot. If below this altitude, the runway element is not considered explored\n self.MAXIMUM_CAMERA_ALTITUDE = 2000 # [m] maximum altitude above the runway to get a reliable camera shot. If above this altitude, the runway element is not considered explored\n self.PROXIMITY_PENALTY_MAXIMUM = 1 # how much to penalize closeness of the quadrotors to encourage them not to bunch up; penalty = -PROXIMITY_PENALTY_MAXIMUM*exp(-distance/PROXIMITY_PENALTY_FACTOR)\n #self.PROXIMITY_PENALTY_FACTOR = 4.3 # how much the penalty decays with distance -> a penalty of 0.01 when they are 20 m apart. To change: = -distance/ln(desired_penalty)\n self.PROXIMITY_PENALTY_FACTOR = 2.15 # how much the penalty decays with distance -> a penalty of 0.01 when they are 5 m apart. To change: = -distance/ln(desired_penalty)\n self.LOWER_ACTION_BOUND = np.array([-2.5, -2.5]) # [m/s^2, m/s^2, m/s^2]\n self.UPPER_ACTION_BOUND = np.array([ 2.5, 2.5]) # [m/s^2, m/s^2, m/s^2]\n self.LOWER_STATE_BOUND_PER_QUAD = np.array([ -10. - self.RUNWAY_LENGTH/2, -10. - self.RUNWAY_WIDTH/2, 0., -self.VELOCITY_LIMIT, -self.VELOCITY_LIMIT, -self.VELOCITY_LIMIT]) # [m, m, m, m/s, m/s, m/s]\n self.UPPER_STATE_BOUND_PER_QUAD = np.array([ 10. + self.RUNWAY_LENGTH/2, 10. + self.RUNWAY_WIDTH/2, 20., self.VELOCITY_LIMIT, self.VELOCITY_LIMIT, self.VELOCITY_LIMIT]) # [m, m, m, m/s, m/s, m/s] \n \n\n # Generate Polygons for runway tiles\n # The size of each runway grid element\n each_runway_length_element = self.RUNWAY_LENGTH/self.RUNWAY_LENGTH_ELEMENTS\n each_runway_width_element = self.RUNWAY_WIDTH/self.RUNWAY_WIDTH_ELEMENTS\n self.tile_polygons = []\n for i in range(self.RUNWAY_LENGTH_ELEMENTS):\n this_row = []\n for j in range(self.RUNWAY_WIDTH_ELEMENTS):\n # make the polygon\n this_row.append(Polygon([[each_runway_length_element*i - self.RUNWAY_LENGTH/2, each_runway_width_element*j - self.RUNWAY_WIDTH/2],\n [each_runway_length_element*(i+1) - self.RUNWAY_LENGTH/2, each_runway_width_element*j - self.RUNWAY_WIDTH/2],\n [each_runway_length_element*(i+1) - self.RUNWAY_LENGTH/2, each_runway_width_element*(j+1) - self.RUNWAY_WIDTH/2],\n [each_runway_length_element*i - self.RUNWAY_LENGTH/2, each_runway_width_element*(j+1) - self.RUNWAY_WIDTH/2]]))\n \n self.tile_polygons.append(this_row)\n\n\n # Performing some calculations \n self.RUNWAY_STATE_SIZE = self.RUNWAY_WIDTH_ELEMENTS * self.RUNWAY_LENGTH_ELEMENTS # how big the runway \"grid\" is \n self.TOTAL_STATE_SIZE = self.BASE_STATE_SIZE + self.RUNWAY_STATE_SIZE\n self.LOWER_STATE_BOUND = np.concatenate([np.tile(self.LOWER_STATE_BOUND_PER_QUAD, self.NUMBER_OF_QUADS), np.tile(self.LOWER_ACTION_BOUND, self.AUGMENT_STATE_WITH_ACTION_LENGTH), np.zeros(self.RUNWAY_STATE_SIZE)]) # lower bound for each element of TOTAL_STATE\n self.UPPER_STATE_BOUND = np.concatenate([np.tile(self.UPPER_STATE_BOUND_PER_QUAD, self.NUMBER_OF_QUADS), np.tile(self.UPPER_ACTION_BOUND, self.AUGMENT_STATE_WITH_ACTION_LENGTH), np.ones(self.RUNWAY_STATE_SIZE)]) # upper bound for each element of TOTAL_STATE \n self.OBSERVATION_SIZE = self.TOTAL_STATE_SIZE - len(self.IRRELEVANT_STATES)*self.NUMBER_OF_QUADS # the size of the observation input to the policy\n\n\n ######################################\n ##### Resettings the Environment #####\n ######################################\n def reset(self, use_dynamics, test_time):\n # This method resets the state and returns it\n \"\"\" NOTES:\n - if use_dynamics = True -> use dynamics\n - if test_time = True -> do not add \"exploration noise\" to the kinematics or actions\n \"\"\" \n # Reset the seed for max randomness\n np.random.seed()\n \n # Logging whether it is test time for this episode\n self.test_time = test_time\n \n self.quad_positions = np.zeros([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n\n # If we are randomizing the initial conditions and state\n if self.RANDOMIZE:\n # Randomizing initial state\n for i in range(self.NUMBER_OF_QUADS):\n self.quad_positions[i] = self.INITIAL_QUAD_POSITION + np.random.uniform(low = -1, high = 1, size = len(self.POSITION_RANDOMIZATION_SD))*self.POSITION_RANDOMIZATION_SD\n else:\n # Constant initial state\n for i in range(self.NUMBER_OF_QUADS):\n self.quad_positions[i] = self.INITIAL_QUAD_POSITION\n\n # Quadrotors' initial velocity is not randomized\n self.quad_velocities = np.zeros([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n \n # Initializing the previous velocity and control effort for the integral-acceleration controller\n self.previous_quad_velocities = np.zeros([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n self.previous_linear_control_efforts = np.zeros([self.NUMBER_OF_QUADS, self.ACTION_SIZE + 1]) \n \n # Initializing the previous quad position (used for runway exploration calculation)\n self.previous_quad_positions = self.quad_positions\n \n if use_dynamics: \n self.dynamics_flag = True # for this episode, dynamics will be used\n else:\n self.dynamics_flag = False # the default is to use kinematics\n\n # Resetting the time\n self.time = 0.\n \n # Decide whether to have one quad fail and at what time\n if self.NUMBER_OF_QUADS > 1:\n self.time_for_quad_failure = []\n self.quad_to_fail = []\n if self.THREE_QUAD_GENERIC_MODEL:\n scenario = np.random.uniform(low = 0.0, high = 1.0)\n if scenario < 1/6:\n ## 1 quad only, no fails ##\n # quad 1 fails at t=0\n self.time_for_quad_failure.append(0)\n self.quad_to_fail.append(0)\n # quad 2 fails at t=0\n self.time_for_quad_failure.append(0)\n self.quad_to_fail.append(1)\n if test_time:\n print(\"1 quad alone\")\n elif scenario < 1/2:\n ## 2 quads, 50% chance of quad0 failing ##\n if np.random.uniform(low=0.0,high=1.0) < 0.5:\n self.time_for_quad_failure.append(np.random.uniform(low = 0.0, high = 150*self.TIMESTEP)) # 150 timesteps seems to be the steady-state value\n self.quad_to_fail.append(0)\n if test_time:\n print(\"2 quads, but quad %i will fail at %.1f\"%(0, self.time_for_quad_failure[0]))\n else:\n if test_time:\n print(\"2 quads no failures\")\n # quad 2 fails at t=0\n self.time_for_quad_failure.append(0)\n self.quad_to_fail.append(1)\n else:\n ## 3 quads, 33% change of quad0 failing & 33% change of quad0 & quad1 failing\n sub_scenario = np.random.uniform(low = 0.0, high = 1.0)\n if sub_scenario < 1/3:\n # 1 quad fails!\n self.time_for_quad_failure.append(np.random.uniform(low = 0.0, high = 150*self.TIMESTEP)) # 150 timesteps seems to be the steady-state value\n self.quad_to_fail.append(0)\n if test_time:\n print(\"3 quads, but quad%i will fail at %.1f\"%(0, self.time_for_quad_failure[0]))\n elif sub_scenario < 2/3:\n # 2 quads fail!\n self.time_for_quad_failure.append(np.random.uniform(low = 0.0, high = 150*self.TIMESTEP)) # 150 timesteps seems to be the steady-state value\n self.quad_to_fail.append(0)\n self.time_for_quad_failure.append(np.random.uniform(low = 0.0, high = 150*self.TIMESTEP)) # 150 timesteps seems to be the steady-state value\n self.quad_to_fail.append(1)\n if test_time:\n print(\"3 quads, but quad %i will fail at %.1f and quad %i will fail at %.1f\"%(0, self.time_for_quad_failure[0], 1, self.time_for_quad_failure[1]))\n else:\n if test_time:\n print(\"3 quads no failures\")\n # all 3 quads survive!!\n else:\n # not building a generic model\n for i in range(self.NUMBER_OF_QUADS - 1): \n if np.random.uniform(low=0.0,high=1.0) < self.QUAD_FAILURE_PERCENTAGE:\n self.time_for_quad_failure.append(np.random.uniform(low = 0.0, high = 150*self.TIMESTEP)) # 150 timesteps seems to be the steady-state value\n self.quad_to_fail.append(i)\n if test_time:\n print(\"Test time quad %i will fail at %.1f\"%(i, self.time_for_quad_failure[i]))\n \n # Resetting the runway state\n self.runway_state = np.zeros([self.RUNWAY_LENGTH_ELEMENTS, self.RUNWAY_WIDTH_ELEMENTS])\n self.previous_runway_value = 0\n \n # Resetting the action delay queue \n if self.DYNAMICS_DELAY > 0:\n self.action_delay_queue = queue.Queue(maxsize = self.DYNAMICS_DELAY + 1)\n for i in range(self.DYNAMICS_DELAY):\n self.action_delay_queue.put(np.zeros([self.NUMBER_OF_QUADS, self.ACTION_SIZE + 1]), False)\n\n #####################################\n ##### Step the Dynamics forward #####\n #####################################\n def step(self, actions):\n\n # Stepping the environment forward one time step.\n # Returns initial condition on first row then next TIMESTEP on the next row\n #########################################\n ##### PROPAGATE KINEMATICS/DYNAMICS #####\n #########################################\n if self.dynamics_flag:\n ############################\n #### PROPAGATE DYNAMICS ####\n ############################\n\n # Next, calculate the control effort\n control_efforts = self.controller(actions) \n\n # Anything additional that needs to be sent to the dynamics integrator\n dynamics_parameters = [control_efforts, self.MASS, self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)]\n\n # Propagate the dynamics forward one timestep\n next_states = odeint(dynamics_equations_of_motion, np.concatenate([self.quad_positions.reshape(-1), self.quad_velocities.reshape(-1)]), [self.time, self.time + self.TIMESTEP], args = (dynamics_parameters,), full_output = 0)\n\n # Saving the new state\n self.quad_positions = next_states[1,:self.NUMBER_OF_QUADS*len(self.INITIAL_QUAD_POSITION)].reshape([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n self.quad_velocities = next_states[1,self.NUMBER_OF_QUADS*len(self.INITIAL_QUAD_POSITION):].reshape([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n # Note: the controller is supposed to limit the quad velocity at test time\n \n else:\n\n # Additional parameters to be passed to the kinematics\n kinematics_parameters = [actions, self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)]\n\n ###############################\n #### PROPAGATE KINEMATICS #####\n ###############################\n next_states = odeint(kinematics_equations_of_motion, np.concatenate([self.quad_positions.reshape(-1), self.quad_velocities.reshape(-1)]), [self.time, self.time + self.TIMESTEP], args = (kinematics_parameters,), full_output = 0)\n\n # Saving the new state\n self.quad_positions = next_states[1,:self.NUMBER_OF_QUADS*len(self.INITIAL_QUAD_POSITION)].reshape([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n self.quad_velocities = next_states[1,self.NUMBER_OF_QUADS*len(self.INITIAL_QUAD_POSITION):].reshape([self.NUMBER_OF_QUADS, len(self.INITIAL_QUAD_POSITION)])\n self.quad_velocities = np.clip(self.quad_velocities, -self.VELOCITY_LIMIT, self.VELOCITY_LIMIT) # clipping the linear velocity to be within the limits\n\n # Done the differences between the kinematics and dynamics\n # Increment the timestep\n self.time += self.TIMESTEP\n \n # Check if any quads have failed\n if self.NUMBER_OF_QUADS > 1:\n self.check_for_quad_failures()\n \n # Update the state of the runway\n self.check_runway()\n\n # Calculating the reward for this state-action pair\n reward = self.reward_function(actions)\n\n # Check if this episode is done\n done = self.is_done()\n\n # Return the (reward, done)\n return reward, done\n \n def check_for_quad_failures(self):\n # Checks and enforces a quad failure if it exists\n for i in range(len(self.time_for_quad_failure)): \n if self.time > self.time_for_quad_failure[i]:\n #print(\"Quad %i has failed at time %.1f\" %(self.quad_to_fail[i], self.time))\n \n # Force the position and velocity to their 'failed' states\n self.quad_positions[self.quad_to_fail[i],:] = self.LOWER_STATE_BOUND_PER_QUAD[:3]\n self.previous_quad_positions[self.quad_to_fail[i],:] = self.quad_positions[self.quad_to_fail[i],:]\n self.quad_velocities[self.quad_to_fail[i],:] = 0\n\n def controller(self, actions):\n # This function calculates the control effort based on the state and the\n # desired acceleration (action)\n \n ###############################################################\n ### Acceleration control (integral-acceleration controller) ###\n ###############################################################\n desired_linear_accelerations = actions\n \n current_velocities = self.quad_velocities\n current_linear_accelerations = (current_velocities - self.previous_quad_velocities)/self.TIMESTEP # Approximating the current acceleration [a_x, a_y, a_z]\n \n # Checking whether our velocity is too large AND the acceleration is trying to increase said velocity... in which case we set the desired_linear_acceleration to zero.\n desired_linear_accelerations[(np.abs(current_velocities) > self.VELOCITY_LIMIT) & (np.sign(desired_linear_accelerations) == np.sign(current_velocities))] = 0 \n \n # Calculating acceleration error\n linear_acceleration_error = desired_linear_accelerations - current_linear_accelerations\n \n # Integral-acceleration control\n linear_control_effort = self.previous_linear_control_efforts + self.KI * linear_acceleration_error\n \n # Saving the current velocity for the next timetsep\n self.previous_quad_velocities = current_velocities\n \n # Saving the current control effort for the next timestep\n self.previous_linear_control_efforts = linear_control_effort\n \n return linear_control_effort\n\n def check_runway(self):\n # This method updates the runway state based off the current quadrotor positions\n \"\"\" The runway is \n self.RUNWAY_WIDTH (East)\n self.RUNWAY_LENGTH (North)\n self.RUNWAY_WIDTH_ELEMENTS\n self.RUNWAY_LENGTH_ELEMENTS\n \n \"\"\"\n\n \n \"\"\" New runway method where each tile is a Polygon and the motion from the last timestep is a LineString and \n the intersecting tiles are considered explored. This fixes the experimental problems where corners of tiles\n were being flown over but not considered explored\n \"\"\"\n # Generate quadrotor LineStrings\n for i in range(self.NUMBER_OF_QUADS):\n quad_line = LineString([self.quad_positions[i,:-1], self.previous_quad_positions[i,:-1]])\n \n for j in range(self.RUNWAY_LENGTH_ELEMENTS):\n for k in range(self.RUNWAY_WIDTH_ELEMENTS): \n # If this element has already been explored, skip it\n if self.runway_state[j,k] == 0 and quad_line.intersects(self.tile_polygons[j][k]):\n self.runway_state[j,k] = 1\n #print(\"Quad %i traced the line %s and explored runway element length = %i, width = %i with coordinates %s\" %(i,list(quad_line.coords),j,k,self.tile_polygons[j][k].bounds))\n \n # Storing current quad positions for the next timestep\n self.previous_quad_positions = self.quad_positions\n \n \n def check_quad_distances(self):\n # Checks the scalar distance from each quad to its neighbours in X and Y ONLY (altitude is ignored)\n # If there are more than 2 quads, the distance of the nearest one is returned\n \n # Initializing the distances (to large numbers incase there is only one quad)\n minimum_distances = np.ones(self.NUMBER_OF_QUADS)*1000.0\n \n # For this quad\n for i in range(self.NUMBER_OF_QUADS): \n # Check all the other quads\n for j in range(i + 1, self.NUMBER_OF_QUADS + i):\n this_distance = np.linalg.norm([self.quad_positions[i,0] - self.quad_positions[j % self.NUMBER_OF_QUADS,0], self.quad_positions[i,1] - self.quad_positions[j % self.NUMBER_OF_QUADS,1]])\n \n # check if the minimum distance is because two quads are failed near each other\n if ((self.quad_positions[i,0] == self.LOWER_STATE_BOUND_PER_QUAD[0]) and (self.quad_positions[i,1] == self.LOWER_STATE_BOUND_PER_QUAD[1])) or ((self.quad_positions[j % self.NUMBER_OF_QUADS,0] == self.LOWER_STATE_BOUND_PER_QUAD[0]) and (self.quad_positions[j % self.NUMBER_OF_QUADS,1] == self.LOWER_STATE_BOUND_PER_QUAD[1])):\n # one of these quads is failed, do not count this distance!\n this_distance = 1000\n\n # Replace the minimum distance with this if it's smaller\n if this_distance < minimum_distances[i]:\n minimum_distances[i] = this_distance\n\n return minimum_distances\n\n def reward_function(self, action):\n # Returns the reward for this TIMESTEP as a function of the state and action\n \n # Initializing the rewards to zero for all quads\n rewards = np.zeros(self.NUMBER_OF_QUADS)\n \n # Give rewards according to the change in runway state. A newly explored tile will yield a reward of +1\n rewards += np.sum(self.runway_state) - self.previous_runway_value\n \n # Storing the current runway state for the next timestep\n self.previous_runway_value = np.sum(self.runway_state)\n\n # Penalizing acceleration commands (to encourage fuel efficiency)\n rewards -= np.sum(self.ACCELERATION_PENALTY*np.abs(action), axis = 1)\n\n # Penalizing quadrotor proximity (to discourage grouping)\n rewards -= self.PROXIMITY_PENALTY_MAXIMUM*np.exp(-self.check_quad_distances()/self.PROXIMITY_PENALTY_FACTOR)\n\n return rewards\n\n def is_done(self):\n # Checks if this episode is done or not\n \"\"\"\n NOTE: THE ENVIRONMENT MUST RETURN done = True IF THE EPISODE HAS\n REACHED ITS LAST TIMESTEP\n \"\"\"\n # Initializing\n done = False\n \n # If we've explored the entire runway\n if np.sum(self.runway_state) == self.RUNWAY_STATE_SIZE:\n done = True\n\n # If we've run out of timesteps\n if round(self.time/self.TIMESTEP) == self.MAX_NUMBER_OF_TIMESTEPS:\n done = True\n\n return done\n\n\n def generate_queue(self):\n # Generate the queues responsible for communicating with the agent\n self.agent_to_env = multiprocessing.Queue(maxsize = 1)\n self.env_to_agent = multiprocessing.Queue(maxsize = 1)\n\n return self.agent_to_env, self.env_to_agent\n \n\n def run(self):\n ###################################\n ##### Running the environment #####\n ###################################\n \"\"\"\n This method is called when the environment process is launched by main.py.\n It is responsible for continually listening for an input action from the\n agent through a Queue. If an action is received, it is to step the environment\n and return the results.\n \"\"\"\n # Instructing this process to treat Ctrl+C events (called SIGINT) by going SIG_IGN (ignore).\n # This permits the process to continue upon a Ctrl+C event to allow for graceful quitting.\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n # Loop until the process is terminated\n while True:\n # Blocks until the agent passes us an action\n actions, *test_time = self.agent_to_env.get() \n\n if np.any(type(actions) == bool):\n # The signal to reset the environment was received\n self.reset(actions, test_time[0])\n \n # Return the TOTAL_STATE \n self.env_to_agent.put((self.quad_positions, self.quad_velocities, self.runway_state))\n\n else:\n # Delay the action by DYNAMICS_DELAY timesteps. The environment accumulates the action delay--the agent still thinks the sent action was used.\n if self.DYNAMICS_DELAY > 0:\n self.action_delay_queue.put(actions,False) # puts the current action to the bottom of the stack\n actions = self.action_delay_queue.get(False) # grabs the delayed action and treats it as truth. \n \n ################################\n ##### Step the environment #####\n ################################ \n rewards, done = self.step(actions)\n\n # Return (TOTAL_STATE, reward, done, guidance_position)\n self.env_to_agent.put((self.quad_positions, self.quad_velocities, self.runway_state, rewards, done))\n\n###################################################################\n##### Generating kinematics equations representing the motion #####\n###################################################################\ndef kinematics_equations_of_motion(state, t, parameters):\n \"\"\" \n Returns the first derivative of the state\n The state is [position, velocity]; its derivative is [velocity, acceleration]\n \"\"\"\n \n # Unpacking the action from the parameters\n actions = parameters[0]\n NUMBER_OF_QUADS = parameters[1]\n QUAD_POSITION_LENGTH = parameters[2]\n \n # state = quad_positions, quad_velocities concatenated\n #quad_positions = state[:NUMBER_OF_QUADS*QUAD_POSITION_LENGTH]\n quad_velocities = state[NUMBER_OF_QUADS*QUAD_POSITION_LENGTH:]\n \n # Flattening the accelerations into a column\n accelerations = actions.reshape(-1) # [x_dot_dot, y_dot_dot, x_dot_dot, y_dot_dot....]\n\n # Building the derivative matrix.\n derivatives = np.concatenate([quad_velocities, accelerations])\n\n return derivatives\n\n\n#####################################################################\n##### Generating the dynamics equations representing the motion #####\n#####################################################################\ndef dynamics_equations_of_motion(state, t, parameters):\n \"\"\" \n Returns the first derivative of the state\n The state is [position, velocity]; its derivative is [velocity, acceleration]\n \"\"\"\n # Unpacking the parameters\n control_efforts, mass, NUMBER_OF_QUADS, QUAD_POSITION_LENGTH = parameters\n\n # Unpacking the state\n #quad_positions = state[:NUMBER_OF_QUADS*QUAD_POSITION_LENGTH]\n quad_velocities = state[NUMBER_OF_QUADS*QUAD_POSITION_LENGTH:]\n \n # Calculating accelerations = F/m\n accelerations = control_efforts.reshape(-1)/mass\n\n # Building derivatives array\n derivatives = np.concatenate([quad_velocities, accelerations]) #.squeeze()?\n\n return derivatives\n\n\n##########################################\n##### Function to animate the motion #####\n##########################################\ndef render(states, actions, instantaneous_reward_log, cumulative_reward_log, critic_distributions, target_critic_distributions, projected_target_distribution, bins, loss_log, episode_number, filename, save_directory):\n \"\"\"\n states = [# timesteps, # quads, total_state_size]\n action = [# timesteps, # quads, action_size]\n instantaneous_reward_log = [# timesteps, # quads]\n cumulative_reward_log = [# timesteps, # quads]\n \n ===FOR QUAD 0 ONLY===\n critic_distributions\n target_critic_distributions\n projected_target_distribution\n \n \n Animate a variable number of quadrotors inspecting a runway.\n - Plot 3D cube of any number of quads\n - Plot the runway and shade in elements as they become discovered (as listed in the state)\n \n \"\"\"\n\n # Load in a temporary environment, used to grab the physical parameters\n temp_env = Environment()\n\n # Checking if we want the additional reward and value distribution information\n extra_information = temp_env.ADDITIONAL_VALUE_INFO\n\n # Extracting physical properties\n length = temp_env.LENGTH\n\n ### Calculating quadrotor corner locations through time ###\n \n # Corner locations in body frame \n quad_body_body_frame = length/2.*np.array([[[1],[-1],[1]],\n [[-1],[-1],[1]],\n [[-1],[-1],[-1]],\n [[1],[-1],[-1]],\n [[1],[-1],[1]],\n [[1],[1],[1]],\n [[-1],[1],[1]],\n [[-1],[-1],[1]],\n [[-1],[-1],[-1]],\n [[-1],[1],[-1]],\n [[-1],[1],[1]],\n [[-1],[1],[-1]],\n [[1],[1],[-1]],\n [[1],[1],[1]],\n [[1],[1],[-1]],\n [[1],[-1],[-1]]]).squeeze()\n\n # Generating figure window\n figure = plt.figure(constrained_layout = True)\n figure.set_size_inches(5, 4, True)\n\n if extra_information:\n grid_spec = gridspec.GridSpec(nrows = 2, ncols = 3, figure = figure)\n subfig1 = figure.add_subplot(grid_spec[0,0], projection = '3d', aspect = 'equal', autoscale_on = False, xlim3d = (temp_env.LOWER_STATE_BOUND_PER_QUAD[0], temp_env.UPPER_STATE_BOUND_PER_QUAD[0]), ylim3d = (temp_env.LOWER_STATE_BOUND_PER_QUAD[1], temp_env.UPPER_STATE_BOUND_PER_QUAD[1]), zlim3d = (temp_env.LOWER_STATE_BOUND_PER_QUAD[2], temp_env.UPPER_STATE_BOUND_PER_QUAD[2]), xlabel = 'X (m)', ylabel = 'Y (m)', zlabel = 'Z (m)')\n subfig2 = figure.add_subplot(grid_spec[0,1], xlim = (np.min([np.min(instantaneous_reward_log[:,0]), 0]) - (np.max(instantaneous_reward_log[:,0]) - np.min(instantaneous_reward_log[:,0]))*0.02, np.max([np.max(instantaneous_reward_log[:,0]), 0]) + (np.max(instantaneous_reward_log[:,0]) - np.min(instantaneous_reward_log[:,0]))*0.02), ylim = (-0.5, 0.5))\n subfig3 = figure.add_subplot(grid_spec[0,2], xlim = (np.min(loss_log)-0.01, np.max(loss_log)+0.01), ylim = (-0.5, 0.5))\n subfig4 = figure.add_subplot(grid_spec[1,0], ylim = (0, 1.02))\n subfig5 = figure.add_subplot(grid_spec[1,1], ylim = (0, 1.02))\n subfig6 = figure.add_subplot(grid_spec[1,2], ylim = (0, 1.02))\n\n # Setting titles\n subfig1.set_xlabel(\"X (m)\", fontdict = {'fontsize': 8})\n subfig1.set_ylabel(\"Y (m)\", fontdict = {'fontsize': 8})\n subfig2.set_title(\"Timestep Reward\", fontdict = {'fontsize': 8})\n subfig3.set_title(\"Current loss\", fontdict = {'fontsize': 8})\n subfig4.set_title(\"Q-dist\", fontdict = {'fontsize': 8})\n subfig5.set_title(\"Target Q-dist\", fontdict = {'fontsize': 8})\n subfig6.set_title(\"Bellman projection\", fontdict = {'fontsize': 8})\n\n # Changing around the axes\n subfig1.tick_params(labelsize = 8)\n subfig2.tick_params(which = 'both', left = False, labelleft = False, labelsize = 8)\n subfig3.tick_params(which = 'both', left = False, labelleft = False, labelsize = 8)\n subfig4.tick_params(which = 'both', left = False, labelleft = False, right = True, labelright = False, labelsize = 8)\n subfig5.tick_params(which = 'both', left = False, labelleft = False, right = True, labelright = False, labelsize = 8)\n subfig6.tick_params(which = 'both', left = False, labelleft = False, right = True, labelright = True, labelsize = 8)\n\n # Adding the grid\n subfig4.grid(True)\n subfig5.grid(True)\n subfig6.grid(True)\n\n # Setting appropriate axes ticks\n subfig2.set_xticks([np.min(instantaneous_reward_log[:,0]), 0, np.max(instantaneous_reward_log[:,0])] if np.sign(np.min(instantaneous_reward_log[:,0])) != np.sign(np.max(instantaneous_reward_log[:,0])) else [np.min(instantaneous_reward_log[:,0]), np.max(instantaneous_reward_log[:,0])])\n subfig3.set_xticks([np.min(loss_log), np.max(loss_log)])\n subfig4.set_xticks([bins[i*5] for i in range(round(len(bins)/5) + 1)])\n subfig4.tick_params(axis = 'x', labelrotation = -90)\n subfig4.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.])\n subfig5.set_xticks([bins[i*5] for i in range(round(len(bins)/5) + 1)])\n subfig5.tick_params(axis = 'x', labelrotation = -90)\n subfig5.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.])\n subfig6.set_xticks([bins[i*5] for i in range(round(len(bins)/5) + 1)])\n subfig6.tick_params(axis = 'x', labelrotation = -90)\n subfig6.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.])\n\n else:\n subfig1 = figure.add_subplot(1, 1, 1, projection = '3d', aspect = 'equal', autoscale_on = False, xlim3d = (temp_env.LOWER_STATE_BOUND_PER_QUAD[0], temp_env.UPPER_STATE_BOUND_PER_QUAD[0]), ylim3d = (temp_env.LOWER_STATE_BOUND_PER_QUAD[1], temp_env.UPPER_STATE_BOUND_PER_QUAD[1]), zlim3d = (temp_env.LOWER_STATE_BOUND_PER_QUAD[2], temp_env.UPPER_STATE_BOUND_PER_QUAD[2]), xlabel = 'X (m)', ylabel = 'Y (m)', zlabel = 'Z')\n \n # Since matplotlib doesn't have 'aspect = 'equal'' implemented, I have to manually\n # do it. I adjust the limits so that they're the same length in all directions,\n # centred at the right location.\n x_limits = subfig1.get_xlim3d()\n y_limits = subfig1.get_ylim3d()\n z_limits = subfig1.get_zlim3d()\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n plot_radius = 0.5*max([x_range, y_range, z_range])\n subfig1.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n subfig1.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n subfig1.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius]) \n \n # Setting the proper view\n if temp_env.TOP_DOWN_VIEW:\n subfig1.view_init(90,180)\n else:\n subfig1.view_init(25, 190) \n \n # Defining the runway element coordinates\n runway_elements = []\n width_vertices = np.linspace(-temp_env.RUNWAY_WIDTH/2, temp_env.RUNWAY_WIDTH/2, temp_env.RUNWAY_WIDTH_ELEMENTS + 1)\n length_vertices = np.linspace(-temp_env.RUNWAY_LENGTH/2, temp_env.RUNWAY_LENGTH/2, temp_env.RUNWAY_LENGTH_ELEMENTS + 1)\n for i in range(temp_env.RUNWAY_LENGTH_ELEMENTS):\n for j in range(temp_env.RUNWAY_WIDTH_ELEMENTS):\n runway_element_vertices = np.array([[length_vertices[i],width_vertices[j]],\n [length_vertices[i],width_vertices[j+1]],\n [length_vertices[i+1],width_vertices[j+1]],\n [length_vertices[i+1],width_vertices[j]],\n [length_vertices[i],width_vertices[j]]])\n runway_elements.append(runway_element_vertices)\n full_runway = np.array([[length_vertices[0],width_vertices[0]],\n [length_vertices[0],width_vertices[-1]],\n [length_vertices[-1],width_vertices[-1]],\n [length_vertices[-1],width_vertices[0]],\n [length_vertices[0],width_vertices[0]]])\n runway_plot, = subfig1.plot([], [], [], color = 'k', linestyle = '-', linewidth = 3)\n runway_plot.set_data(full_runway[:,0], full_runway[:,1])\n runway_plot.set_3d_properties(np.zeros(5)) \n\n # Defining plotting objects that change each frame\n quad_bodies = []\n all_colours = cm.rainbow(np.linspace(0,1,temp_env.NUMBER_OF_QUADS))\n for i in range(temp_env.NUMBER_OF_QUADS):\n this_quad_body, = subfig1.plot([], [], [], color = all_colours[i], linestyle = '-', linewidth = 2, zorder=10) # Note, the comma is needed\n quad_bodies.append(this_quad_body)\n\n if extra_information:\n reward_bar = subfig2.barh(y = 0, height = 0.2, width = 0)\n loss_bar = subfig3.barh(y = 0, height = 0.2, width = 0)\n q_dist_bar = subfig4.bar(x = bins, height = np.zeros(shape = len(bins)), width = bins[1]-bins[0])\n target_q_dist_bar = subfig5.bar(x = bins, height = np.zeros(shape = len(bins)), width = bins[1]-bins[0])\n projected_q_dist_bar = subfig6.bar(x = bins, height = np.zeros(shape = len(bins)), width = bins[1]-bins[0])\n time_text = subfig1.text2D(x = 0.2, y = 0.91, s = '', fontsize = 8, transform=subfig1.transAxes)\n reward_text = subfig1.text2D(x = 0.0, y = 1.02, s = '', fontsize = 8, transform=subfig1.transAxes)\n else: \n time_text = subfig1.text2D(x = 0.1, y = 0.9, s = '', fontsize = 8, transform=subfig1.transAxes)\n reward_text = subfig1.text2D(x = 0.62, y = 0.9, s = '', fontsize = 8, transform=subfig1.transAxes)\n episode_text = subfig1.text2D(x = 0.4, y = 0.96, s = '', fontsize = 8, transform=subfig1.transAxes)\n episode_text.set_text('Episode ' + str(episode_number))\n\n # Function called repeatedly to draw each frame\n def render_one_frame(frame, *fargs):\n temp_env = fargs[0] # Extract environment from passed args\n\n # Shade the runway, where appropriate\n runway_state = states[frame,0,-temp_env.RUNWAY_STATE_SIZE:]\n if frame > 0:\n last_runway_state = states[frame-1,0,-temp_env.RUNWAY_STATE_SIZE:]\n else:\n last_runway_state = np.zeros(len(runway_state))\n \n for i in range(len(runway_state)):\n # Only update the runway if it's changed\n if runway_state[i] == 1 and last_runway_state[i] == 0:\n these_vertices = [list(zip(runway_elements[i][:,0], runway_elements[i][:,1], np.zeros(5)))]\n subfig1.add_collection3d(Poly3DCollection(these_vertices, color='grey', alpha = 0.5), zs = 0, zdir='z')\n print(\"Runway element changed! Frame: %i, Previous reward: %f, Current reward: %f\" %(frame, cumulative_reward_log[frame-1,0], cumulative_reward_log[frame,0]))\n \n # Draw the quads\n for i in range(temp_env.NUMBER_OF_QUADS):\n quad_bodies[i].set_data(quad_body_body_frame[:,0] + states[frame,i,0], quad_body_body_frame[:,1] + states[frame,i,1])\n quad_bodies[i].set_3d_properties(quad_body_body_frame[:,2] + states[frame,i,2])\n \n # Update the time text\n time_text.set_text('Time = %.1f s' %(frame*temp_env.TIMESTEP))\n \n # Update the reward text\n reward_text.set_text('Quad 0 reward = %.1f' %cumulative_reward_log[frame,0])\n\n # If we want extra information AND we aren't on the last state (because the last state doesn't have value information)\n if extra_information and (frame < len(states)-1):\n # Updating the instantaneous reward bar graph\n reward_bar[0].set_width(instantaneous_reward_log[frame,0])\n # And colouring it appropriately\n if instantaneous_reward_log[frame,0] < 0:\n reward_bar[0].set_color('r')\n else:\n reward_bar[0].set_color('g')\n\n # Updating the loss bar graph\n loss_bar[0].set_width(loss_log[frame])\n\n # Updating the q-distribution plot\n for this_bar, new_value in zip(q_dist_bar, critic_distributions[frame,:]):\n this_bar.set_height(new_value)\n\n # Updating the target q-distribution plot\n for this_bar, new_value in zip(target_q_dist_bar, target_critic_distributions[frame, :]):\n this_bar.set_height(new_value)\n\n # Updating the projected target q-distribution plot\n for this_bar, new_value in zip(projected_q_dist_bar, projected_target_distribution[frame, :]):\n this_bar.set_height(new_value)\n#\n # Since blit = True, must return everything that has changed at this frame\n return time_text, quad_bodies \n\n # Generate the animation!\n fargs = [temp_env] # bundling additional arguments\n animator = animation.FuncAnimation(figure, render_one_frame, frames = np.linspace(0, len(states)-1, len(states)).astype(int),\n blit = False, fargs = fargs)\n\n \"\"\"\n frames = the int that is passed to render_one_frame. I use it to selectively plot certain data\n fargs = additional arguments for render_one_frame\n interval = delay between frames in ms\n \"\"\"\n # Save the animation!\n if temp_env.SKIP_FAILED_ANIMATIONS:\n try:\n # Save it to the working directory [have to], then move it to the proper folder\n animator.save(filename = filename + '_episode_' + str(episode_number) + '.mp4', fps = 30, dpi = 100)\n # Make directory if it doesn't already exist\n os.makedirs(os.path.dirname(save_directory + filename + '/videos/'), exist_ok=True)\n # Move animation to the proper directory\n os.rename(filename + '_episode_' + str(episode_number) + '.mp4', save_directory + filename + '/videos/episode_' + str(episode_number) + '.mp4')\n except:\n print(\"Skipping animation for episode %i due to an error\" %episode_number)\n # Try to delete the partially completed video file\n try:\n os.remove(filename + '_episode_' + str(episode_number) + '.mp4')\n except:\n pass\n else:\n # Save it to the working directory [have to], then move it to the proper folder\n animator.save(filename = filename + '_episode_' + str(episode_number) + '.mp4', fps = 30, dpi = 100)\n # Make directory if it doesn't already exist\n os.makedirs(os.path.dirname(save_directory + filename + '/videos/'), exist_ok=True)\n # Move animation to the proper directory\n os.rename(filename + '_episode_' + str(episode_number) + '.mp4', save_directory + filename + '/videos/episode_' + str(episode_number) + '.mp4')\n\n del temp_env\n plt.close(figure)","sub_path":"environment_quad1_runway.py","file_name":"environment_quad1_runway.py","file_ext":"py","file_size_in_byte":49689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374810709","text":"from scipy.cluster.hierarchy import linkage, dendrogram, fcluster\nimport matplotlib.pyplot as plt\n\ndata = [[1, 1], [2, 2], [3, 1], [10, 14], [11, 14], [13, 12],\n [9, 11], [2, 3], [11, 12], [1, 12], [2, 14], [3, 13], [5, 8]]\n\nx_axis = list(x[0] for x in data)\ny_axis = list(x[1] for x in data)\nplt.scatter(x_axis, y_axis)\nfor i, txt in enumerate(data):\n plt.annotate(i, (x_axis[i], y_axis[i]), xytext=(10,10), textcoords='offset points')\n \nlinked = linkage(data, 'single')\nprint('Distances between merged clusters:\\n', linked[:, 2])\n\nplt.figure(figsize=(10, 7))\ndendrogram(linked, orientation='top',\n distance_sort='descending', show_leaf_counts=True)\n# plt.axhline(y=4, c='k')\n\nmax_d = 4\n# by clusters: fcluster(linked, k, criterion='maxclust')\nclusters = fcluster(linked, max_d, criterion='distance')\nprint('Dots to clusters: ', clusters)\n\nplt.figure(figsize=(10, 7))\nplt.scatter(x_axis, y_axis, c=clusters, cmap='prism', label=list(x for x in range(len(data))))\nfor i, txt in enumerate(data):\n plt.annotate(i, (x_axis[i], y_axis[i]), xytext=(10,10), textcoords='offset points')\n\nplt.show()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"378701575","text":"import torch.nn as nn\nfrom flare.algorithm_zoo.simple_algorithms import SimpleAC\nfrom flare.framework.manager import Manager\nfrom flare.model_zoo.simple_models import SimpleModelAC\nfrom flare.agent_zoo.simple_rl_agents import SimpleRLAgent\nfrom flare.framework.agent import OnlineHelper\nfrom flare.env_zoo.gym_env import GymEnv\n\nif __name__ == '__main__':\n \"\"\"\n A demo of how to run a simple RL experiment\n \"\"\"\n game = \"CartPole-v0\"\n\n num_agents = 16\n num_games = 8000\n # 1. Create environments\n envs = []\n for _ in range(num_agents):\n envs.append(GymEnv(game))\n state_shape = envs[-1].observation_dims()[0]\n num_actions = envs[-1].action_dims()[0]\n\n # 2. Construct the network and specify the algorithm.\n # Here we use a small MLP and apply the Actor-Critic algorithm\n mlp = nn.Sequential(\n nn.Linear(state_shape[0], 128),\n nn.ReLU(),\n nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU())\n\n alg = SimpleAC(model=SimpleModelAC(\n dims=state_shape, num_actions=num_actions, perception_net=mlp))\n\n # 3. Specify the settings for learning: data sampling strategy\n # (OnlineHelper here) and other settings used by\n # ComputationTask.\n ct_settings = {\n \"RL\": dict(\n algorithm=alg,\n hyperparas=dict(lr=5e-5),\n # sampling\n agent_helper=OnlineHelper,\n # each agent will call `learn()` every `sample_interval` steps\n sample_interval=4,\n num_agents=num_agents)\n }\n\n # 4. Create Manager that handles the running of the whole pipeline\n manager = Manager(\n ct_settings, log_settings=dict(\n model_dir=\"/tmp/test\", pass_num=0)\n ) ## if pass_num is less than 1, then load the newest model\n\n # 5. Spawn one agent for each instance of environment.\n # Agent's behavior depends on the actual algorithm being used. Since we\n # are using SimpleAC, a proper type of Agent is SimpleRLAgent.\n reward_shaping_f = lambda x: x / 100.0\n for env in envs:\n agent = SimpleRLAgent(env, num_games, reward_shaping_f)\n # An Agent has to be added into the Manager before we can use it to\n # interact with environment and collect data\n manager.add_agent(agent)\n\n manager.start()\n","sub_path":"flare/examples/ac_example.py","file_name":"ac_example.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"551297190","text":"from typing import Callable, Generator, Tuple, List, Dict, Set, Optional, Hashable\nfrom collections import defaultdict\n\nfrom convokit.transformer import Transformer\nfrom convokit.model import Corpus, User, Utterance, Conversation\nimport re\nimport numpy as np\n\nclass AvgQuestions(Transformer):\n\n def __init__(self, verbose: bool=False):\n self.ATTR_NAME = \"AvgQuestions\"\n self.verbose = verbose\n\n def transform(self, corpus: Corpus) -> Corpus:\n \"\"\"Computes the average number of questions asked in a conversation\n \n :param corpus: the corpus to compute features for.\n :type corpus: Corpus\n \"\"\"\n\n if self.verbose: print(\"Finding questions per utterance\")\n \n questions = []\n allutterids = corpus.get_utterance_ids()\n for i in list(range(0, len(allutterids))):\n utter_id = allutterids[i]\n text = corpus.get_utterance(utter_id).text\n nquestions = len(re.findall(r'\\?+', text))\n questions.append(nquestions) #gives number of questions in each utterance\n \n if self.verbose: print(\"Finding questions per conversation\")\n allconvoids = corpus.get_conversation_ids()\n for i in list(range(0, len(allconvoids))):\n convo_id = allconvoids[i]\n convo_utters = corpus.get_conversation(convo_id)._utterance_ids\n avgquestion = np.mean(np.asarray(questions)[np.asarray(convo_utters)])\n corpus.get_conversation(convo_id)._meta[self.ATTR_NAME] = avgquestion \n #adds average questions per conversation to conversation metadata\n\n return corpus\n\n def _preprocess_utterances(self, corpus: Corpus) -> Tuple[List[Hashable], List[Dict]]:\n \"\"\"Preprocessing won't be needed.\n \n :param corpus: the corpus to compute features for.\n :type corpus: Corpus\n \"\"\"\n \n return corpus","sub_path":"convokit/avgQuestions/avgQuestions.py","file_name":"avgQuestions.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462762808","text":"\n# https://github.com/log0/video_streaming_with_flask_example\n\nimport numpy as np\nimport cv2\nfrom flask import Flask, render_template, Response\nimport time\nimport cv2\nimport time\nimport core.utils as utils\nimport tensorflow as tf\nfrom PIL import Image\n\n\n\napp = Flask(__name__)\n\n\n# use gpu-0 if there are multiple gpus\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nreturn_elements = [\"input/input_data:0\", \"pred_sbbox/concat_2:0\", \"pred_mbbox/concat_2:0\", \"pred_lbbox/concat_2:0\"]\npb_file = \"./yolov3_coco.pb\"\nnum_classes = 3\ninput_size = 416\ngraph = tf.Graph()\nreturn_tensors = utils.read_pb_return_tensors(graph, pb_file, return_elements)\n\nsess = tf.Session(graph=graph)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\ndef gen():\n \n myrtmp_addr = \"rtmp://localhost/live/indycar live=1\"\n cap = cv2.VideoCapture(myrtmp_addr)\n \n infer_flag=True\n while True:\n ret, frame = cap.read()\n if not ret:\n print('Input source error!')\n break\n \n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image = Image.fromarray(frame)\n\n if infer_flag:\n\n frame_size = frame.shape[:2]\n image_data = utils.image_preporcess(np.copy(frame), [input_size, input_size])\n image_data = image_data[np.newaxis, ...]\n pred_sbbox, pred_mbbox, pred_lbbox = sess.run([return_tensors[1], return_tensors[2], return_tensors[3]],\n feed_dict={ return_tensors[0]: image_data})\n pred_bbox = np.concatenate([np.reshape(pred_sbbox, (-1, 5 + num_classes)), \n np.reshape(pred_mbbox, (-1, 5 + num_classes)),\n np.reshape(pred_lbbox, (-1, 5 + num_classes))], axis=0)\n\n bboxes = utils.postprocess_boxes(pred_bbox, frame_size, input_size, 0.3)\n bboxes = utils.nms(bboxes, 0.45, method='nms')\n infer_flag = not infer_flag\n\n image = utils.draw_bbox(frame, bboxes)\n\n result = np.asarray(image)\n frame = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)\n \n ret, jpeg = cv2.imencode('.jpg', frame)\n frame = jpeg.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\n@app.route('/video_feed')\ndef video_feed():\n return Response(gen(),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=61521)\n","sub_path":"fall-2019/4/code/source_code/YOLO/run_flask_server.py","file_name":"run_flask_server.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117676082","text":"#!/usr/bin/python3\n#\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n\"\"\"\nCan use with ROS \nsubscribing compressed image message and\npublishing compressed image message\n\"\"\"\n#\n\nimport jetson.inference\nimport jetson.utils\nimport rospy\nimport cv2\nimport numpy as np\nimport subprocess, shlex, psutil\nfrom sensor_msgs.msg import Image, CompressedImage\nfrom cv_bridge import CvBridge, CvBridgeError\n\n\nnet = jetson.inference.detectNet(\"ssd-mobilenet-v2\", threshold=0.5)\n#camera = jetson.utils.gstCamera(1280,720,\"/dev/video0\") # '/dev/video0' for V4L2\ncompmsg = CompressedImage()\nrospy.init_node(\"visualizer\")\n\n\ndef detection_and_publish(data) :\n\tnp_arr = np.fromstring(data.data, np.uint8)\n\timage = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n\timg = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA).astype(np.float32)\n\timg = jetson.utils.cudaFromNumpy(img)\n\t#while True:\n\t#img, width, height = camera.CaptureRGBA(zeroCopy=1)\n\tjetson.utils.cudaDeviceSynchronize()\n\tdetections = net.Detect(img, image.shape[1], image.shape[0])\n\tfor list in detections :\n\t\tif list.ClassID == 1 :\n\t\t\tprint(\"find person\")\n\tnumpyImg = jetson.utils.cudaToNumpy(img, image.shape[1], image.shape[0], 4)\n\taimg1 = cv2.cvtColor(numpyImg.astype(np.uint8), cv2.COLOR_RGB2BGR)\n\tcompmsg.header.stamp = rospy.Time.now()\n\tcompmsg.format = \"jpeg\"\n\tencode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 10]\n\tcompmsg.data = np.array(cv2.imencode('.jpg', aimg1, encode_param)[1]).tostring()\n\tcomp_img_pub.publish(compmsg)\n\ndef start_cam() :\n\tcommand =\"rosparam set /camera_nano/usb_cam/image_raw/compressed/jpeg_quality 50\"\n\tcommand = shlex.split(command)\n\tsubprocess.Popen(command)\n\tcommand =\"roslaunch usb_cam usb_nano_cam.launch\"\n\tcommand = shlex.split(command)\n\tsubprocess.Popen(command)\n\nstart_cam()\nrospy.Subscriber('/camera_nano/usb_cam/image_raw/compressed', CompressedImage, detection_and_publish)\ncomp_img_pub = rospy.Publisher(\"/camera_nano/object_detect/image_raw/compressed\", CompressedImage, queue_size = 1)\nrospy.spin()\n#display.RenderOnce(img,width, height)\n#display.SetTitle(\"Object Detection | Network {:.0f} FPS\".format(net.GetNetworkFPS()))\n\n","sub_path":"python/examples/me-detection-ros.py","file_name":"me-detection-ros.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93526167","text":"import pandas as pd\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\n\n# Load CSV file from Datasets folder\ndf = pd.read_csv('../Datasets/Weather2014-15.csv')\ndf['date'] = pd.to_datetime(df['date'])\n\ndata = [go.Scatter(x=df['date'], y=df['actual_max_temp'], mode='lines', name='Max Temp')]\n\nlayout = go.Layout(title='Max Temp Each Day From 7-1-2014 through 6-30-2015', xaxis_title='Date',\n yaxis_title='Temperature')\n\nfig = go.Figure(data=data, layout=layout)\npyo.plot(fig, filename='linechart.html')\n","sub_path":"Code/Plots/linechart.py","file_name":"linechart.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"479743509","text":"import random\r\nfrom urllib.parse import urlencode\r\nimport requests\r\nfrom pyquery import PyQuery as pq\r\nimport time\r\n\r\n\r\nbase_url = 'https://m.douban.com/rexxar/api/v2/gallery/topic/17769/items?'\r\n\r\nheaders = {\r\n'Referer': 'https://www.douban.com/gallery/topic/17769/?dt_dapp=1',\r\n'User-Agent':'User-Agent\" : \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',\r\n}\r\n# user_agent_list = [\r\n# \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\",\r\n# \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\",\r\n# \"Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0\",\r\n# \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36\",\r\n# \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36\",\r\n# \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36\",\r\n# \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)\",\r\n# \"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15\",\r\n# ]\r\n# headers['User-Agent'] = random.choice(user_agent_list)\r\n\r\n\r\ndef get_page(page):\r\n params = {\r\n 'from_web': '1',\r\n 'sort': 'hot',\r\n 'start': page,\r\n 'count': '20',\r\n 'status_full_tex': '1',\r\n 'guest_only': '0',\r\n 'ck': 'null'\r\n }\r\n url = base_url + urlencode(params)\r\n print(url)\r\n try:\r\n response = requests.get(url, headers=headers)\r\n if response.status_code == 200:\r\n return response.json()\r\n except requests.ConnectionError as e:\r\n print('Error', e.args)\r\n\r\n\r\n\r\ndef parse_page(json):\r\n if json:\r\n items = json.get('items')\r\n for item in items:\r\n item = item.get('target')\r\n douban = {}\r\n try:\r\n douban['author'] = item.get('status').get('author').get('name')\r\n except AttributeError:\r\n douban['author'] = 'null'\r\n\r\n try:\r\n douban['address'] = item.get('status').get('author').get('loc').get('name')\r\n except AttributeError:\r\n douban['address'] = 'null'\r\n\r\n try:\r\n douban['douban_url'] = item.get('status').get('author').get('url')\r\n except AttributeError:\r\n douban['douban_url'] = 'null'\r\n\r\n try:\r\n douban['text'] = item.get('status').get('text').replace('\\n', '').replace('\\r', '')\r\n except AttributeError:\r\n douban['text'] = 'null'\r\n yield douban\r\n\r\nif __name__ == '__main__':\r\n for page in range(0, 500, 20):\r\n json = get_page(page)\r\n results = parse_page(json)\r\n for result in results:\r\n print(result)\r\n time.sleep(10)","sub_path":"douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"429417767","text":"from knock30 import getdata\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\nif __name__ == \"__main__\":\n mecab_file_path = \"neko.txt.mecab\"\n document = getdata(mecab_file_path)\n word_freq = defaultdict(lambda: 0)\n for sentence in document:\n for word in sentence:\n word_freq[word[\"base\"]] += 1\n counts = []\n for key, value in sorted(word_freq.items(), key=lambda x:x[1], reverse=True):\n counts.append(value)\n fp = FontProperties(fname=r\"/Users/aomi/Library/Fonts/ipaexg.ttf\")\n plt.scatter(range(1, len(counts) + 1), counts)\n plt.xlim(1, len(counts) + 1)\n plt.ylim(1, counts[0])\n plt.xscale('log')\n plt.yscale('log')\n plt.xlabel('出現頻度順位', fontproperties=fp)\n plt.ylabel('出現頻度', fontproperties=fp)\n plt.show()","sub_path":"koyama/chapter04/knock39.py","file_name":"knock39.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366077753","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n# for handling 104 error\nfrom socket import error as SocketError\nimport errno\nimport urllib.parse\nimport re\nimport ssl\nimport os\n\n# code to avoid SSL certificate error\n# ctx = ssl.create_default_context()\n# ctx.check_hostname = False\n# ctx.verify_mode = ssl.CERT_NONE\n\nmain_url = 'https://www.py4e.com/code3/'\nheaders = {}\nheaders['User-Agent'] = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0'\n\nreq = urllib.request.Request(main_url, headers=headers)\nprint('Requesting for', main_url, '...')\nhtml = urlopen(req).read()\nprint('Response Retrieved')\nsoup = BeautifulSoup(html, 'html.parser')\n\nfor tag in soup.findAll('a'):\n if re.search('.*\\.(py|txt|html)$', tag.contents[0]):\n try:\n url = main_url + tag.get('href', None)\n headers = {}\n headers['User-Agent'] = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0'\n req = urllib.request.Request(url, headers=headers)\n print('Requesting for', url, '...')\n code = urlopen(req).read().decode('utf8')\n print('Response Retrieved')\n filename = \"code1/\" + tag.contents[0]\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, \"w\") as fhand:\n print('Writing retrieved data in', tag.contents[0])\n fhand.write(code)\n fhand.close()\n except SocketError as e:\n if e.errno != errno.ECONNRESET:\n raise # Not error we are looking for\n pass # Handle error here.\n","sub_path":"Python for Everybody/3_Using Python to Access Web Data/web_srcapping/web_scapping.py","file_name":"web_scapping.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"461701868","text":"import numpy as np\nimport matplotlib.pyplot as plt\ndef period_pend(theta0,g_over_L):\n\t#% function to return the exact period for a pendulum of length L\n\t#% usage: period = exact_period(theta0,g_over_L)\n\t#% where: theta0 = inital angle in degrees\n\t#% g_over_L = ratio g to the length of the pendulum\n\t#% note -earlier version has a bug as it x sqrt(g/l) not divided 9/11\n\t#% note the squaring of the argument in the elliptic function\n\t#% matlab uses a different normalization than the book\n\tfrom scipy.special import ellipk\n\tperiod = 4/np.sqrt(g_over_L)*ellipk((np.sin(theta0*np.pi/180./2.))**2);\n\treturn period\n\ndef titler(num):\n\t# gives a string back to title a graph depending on the method input of choice\n\tmeth = ['Euler Method', 'Verlet Method', 'Euler-Cromer Method', 'Leap-Frog Method', 'Midpoint Method']\n\treturn meth[num-1]\n\nNumericalMethod = int(input(\"Choose a numerical method: Euler(1) Verlet(2) Euler-Cromer(3) Leap-Frog(4) Midpoint(5): \"));\n#%* Set initial position and velocity of pendulum\ntheta0 = float(input(\"Enter initial angle (in degrees): \"));\ntheta = theta0*np.pi/180; #% Convert angle to radians\nomega = 0; #% Set the initial velocity\n#%* Set the physical constants and other variables\ng_over_L = 1; #% The constant g/L\ntime = 0; #% Initial time\nirev = 0; #% Used to count number of reversals\ntau = float(input(\"Enter time step: \"));\n#%* Take one backward step to start Verlet\naccel = -g_over_L*np.sin(theta); #% Gravitational acceleration\ntheta_old = theta - omega*tau + 0.5*tau**2*accel;\nomega_old = omega - tau*accel \n#%* Loop over desired number of steps with given time step\n#% and numerical method\nnstep = int(input(\"Enter number of time steps: \"));\n# initialize arrays\nt_plot=np.array([])\nth_plot=np.array([])\nperiod=np.array([])\nfor istep in range(0,nstep):\n\t#%* Record angle and time for plotting\n\tt_plot = np.append(t_plot,time);\n\tth_plot = np.append(th_plot,theta*180/np.pi); #% Convert angle to degrees\n\ttime = time + tau;\n\t#%* Compute new position and velocity using\n\t#% Euler or Verlet method\n\taccel = -g_over_L*np.sin(theta); #% Gravitational acceleration\n\tif NumericalMethod == 1:\n\t\ttheta_old = theta; #% Save previous angle\n\t\ttheta = theta + tau*omega; #% Euler method\n\t\tomega = omega + tau*accel;\n\telif NumericalMethod == 2:\n\t\ttheta_new = 2*theta - theta_old + tau**2*accel;\n\t\ttheta_old = theta; #% Verlet method\n\t\ttheta = theta_new;\n\telif NumericalMethod == 3: #Euler-Cromer method\n\t\ttheta_old = theta; #% Save previous angle\n\t\tomega = omega + tau*accel\n\t\ttheta = theta + tau*omega\n\telif NumericalMethod == 4: #Leap-Frog method\n\t\t#create buffer to hold onto x_n-1\t\n\t\tt = theta\n\t\to = omega \n\t\tif istep == 0: # initial conditions\n\t\t\ttheta_nminus = theta_old\n\t\t\tomega_nminus = omega_old\n\t\ttheta_old = theta \n\t\ttheta = theta_nminus + 2*tau*omega #leap frog step\n\t\tomega = omega_nminus + 2*tau*accel \n\t\ttheta_nminus = t # assign x_n-1 for next loop\n\t\tomega_nminus = o \n\telif NumericalMethod ==5: # midpoint method\n\t\ttheta_old = theta #% Save previous angle\n\t\tomega_old = omega\n\t\tomega = omega + tau*accel\n\t\ttheta = theta + tau*(omega + omega_old)/2\n\t#%* Test if the pendulum has passed through theta = 0;\n\t#% if yes, use time to estimate period\n\tif theta*theta_old < 0: # % Test position for sign change\n\t\tprint(\"Turning point at time t= %f\" %time) ;\n\tif irev == 0: #% If this is the first change,\n\t\ttime_old = time; #% just record the time\n\telse:\n\t\tperiod = np.append(period,2*(time - time_old));\n\t\ttime_old = time;\n\t\tirev = irev + 1; # Increment the number of reversals\nif irev > 1:\n#%* Estimate period of oscillation, including error bar\n\tAvePeriod = np.mean(period);\n\tErrorBar = np.std(period)/np.sqrt(irev);\n\tprint(\"Average period = %g +/- %g\" %(AvePeriod,ErrorBar));\nelse:\n\tprint('Pendulum program could not complete a period, time =%g'%time);\nprint(\"Exact period = %g\" %period_pend(theta0,g_over_L));\n#%* Graph the oscillations as theta versus time\nplt.figure(1); #% Clear and forward figure window\nplt.plot(t_plot,th_plot,'+');\nplt.xlabel('Time')\nplt.ylabel(r'$\\theta$ (degrees)') # the 'r' means raw strings for latex\nplt.title(titler(NumericalMethod))\nplt.grid()\nplt.show()","sub_path":"Chapter 2 Work/chap2_question16.py","file_name":"chap2_question16.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317796814","text":"import numpy as np\nimport pandas as pd \nfrom sklearn.metrics import accuracy_score\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport paddle.fluid as fluid\nimport paddle\nfrom paddle.fluid.dygraph.nn import Linear\nfrom paddle.fluid.dygraph.nn import Embedding\n\n# 自定义神经网络模型\nclass Model(fluid.dygraph.Layer):\n # 先定义网络的结构\n def __init__(self, num_classes=8):\n super(Model, self).__init__()\n self.fc1 = Linear(input_dim=10, output_dim=32, act='relu') # 输入层和隐藏层的连接,隐藏层使用Sigmoid作为激活函数\n self.fc2 = Linear(input_dim=32, output_dim=16, act='relu') # 第一个隐藏层和第二个隐藏层之间的连接\n self.fc3 = Linear(input_dim=16, output_dim=num_classes, act='sigmoid') # 隐藏层和输出层的连接,输出层不使用激活函数\n\n # 网络的前向计算过程\n def forward(self, x):\n x = self.fc1(x)\n x = self.fc2(x)\n x = self.fc3(x)\n return x\n\n# 定义训练神经网络的函数\ndef train(model, x_train, y_train):\n print('start training ... ')\n model.train()\n epoch_num = 600 # 定义训练100轮\n opt = fluid.optimizer.RMSPropOptimizer(learning_rate=0.02, parameter_list=model.parameters()) #定义优化器为Momentum,学习率为0.01\n\n # 由于数据量较小,在训练时不设定batch,直接逐轮训练\n for epoch in range(epoch_num):\n # 调整输入数据形状和类型\n x_data = np.array(x_train, dtype='float32').reshape(-1, x_train.shape[1])\n y_data = np.array(y_train, dtype='int64').reshape(-1, 1)\n # 将numpy.ndarray转化成Tensor\n inputs = fluid.dygraph.to_variable(x_data)\n label = fluid.dygraph.to_variable(y_data)\n # 计算模型输出\n logits = model(inputs)\n # 计算损失函数\n loss = fluid.layers.softmax_with_cross_entropy(logits, label) # 使用Cross Entropy交叉熵作为损失函数\n avg_loss = fluid.layers.mean(loss) # 对求得的损失取平均值\n\n # print(\"epoch: {}, loss is: {}\".format(epoch, avg_loss.numpy()))\n \n avg_loss.backward()\n opt.minimize(avg_loss)\n model.clear_gradients()\n\n# 对模型进行评估的函数\ndef val(model, x_test, y_test):\n model.eval()\n accuracies = []\n \n # 调整输入数据形状和类型\n x_data = np.array(x_test, dtype='float32').reshape(-1, x_test.shape[1])\n y_data = np.array(y_test, dtype='int64').reshape(-1, 1)\n # 将numpy.ndarray转化成Tensor\n inputs = fluid.dygraph.to_variable(x_data)\n label = fluid.dygraph.to_variable(y_data)\n # 计算模型输出\n logits = model(inputs)\n pred = fluid.layers.softmax(logits)\n # 计算损失函数\n loss = fluid.layers.softmax_with_cross_entropy(logits, label)\n \n print(loss.numpy())\n \n loss_list=loss.numpy()\n \n acc = fluid.layers.accuracy(pred, label)\n accuracies.append(acc.numpy())\n\n # print(\"[validation] accuracy: {}\".format(np.mean(accuracies)))\n\n\ndef getTrainingData():\n # 读入正样本\n positive = pd.read_csv('nultural/positive_training_Id_guiyihua.csv')\n positive.drop(['学号'], axis=1, inplace=True)\n\n # 读入负样本\n negative = pd.read_csv('nultural/positive_training_Id_guiyihua.csv')\n negative.drop(['学号'], axis=1, inplace=True)\n\n # 随机打乱负样本顺序\n negative = shuffle(negative)\n\n return positive, negative\n\ndef getTestingData():\n data = pd.read_csv('nultural/positive_training_Id_guiyihua.csv')\n data.drop(['学号'], axis=1, inplace=True)\n return data\n\ndef main():\n # 从文件中读入训练集\n positive, negative = getTrainingData()\n \n # 从文件中读入测试集\n Testingdata = getTestingData()\n\n # 计算出需要模型的次数\n iter = negative.shape[0] // positive.shape[0] # iter = 5\n\n\n # 获得需要的数据\n # data = pd.concat([positive, negative.iloc[i * 228: (i+1)*228, :]], axis=0)\n data = positive\n data = shuffle(data)\n\n # 得到X, y\n y = data['获奖类别']\n X = data.iloc[:, :-1]\n # X = data.iloc[:, :12]\n # print(X, y)\n\n # 分割训练集与测试集\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\n\n # 进行标准化\n scaler = StandardScaler().fit(X_train)\n Standardized_X_train = scaler.transform(X_train)\n Standardized_X_test = scaler.transform(X_test)\n\n scaler = StandardScaler().fit(Testingdata.iloc[:, :-1])\n Standardized_Testing = scaler.transform(Testingdata.iloc[:, :-1])\n\n # 创建模型\n with fluid.dygraph.guard():\n # 我们将会发现,在训练过程中,随着迭代次数的增加,loss会逐渐降低,准确率会逐渐增高\n model = Model()\n train(model, Standardized_X_train, y_train)\n val(model, Standardized_X_test, y_test)\n\n \n \n \nif __name__ == \"__main__\":\n main()","sub_path":"Project-黄帅旺/生产实习/nultural/function2.py","file_name":"function2.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188259172","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 6 18:17:21 2020\n\n@author: israel\n\n145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.\n\nFind the sum of all numbers which are equal to the sum of the \nfactorial of their digits.\n\"\"\"\n\nfrom math import factorial\n\ndef is_sum_factorials(num):\n total = 0\n for n in str(num):\n total += factorial(int(n))\n return total == num\n\n\nsuma = 0\nfor i in range(10,1000000):\n if is_sum_factorials(i):\n suma += i\n print(f'found: {i} - total: {suma}')\n\n\n","sub_path":"Problem_034/problem_34.py","file_name":"problem_34.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"25282470","text":"comeco = False\nplacar = 0\nrecorde = 0\n\ndef variaveis():\n global pregovetor, canovetor, moedavetor, sombravetor, paradovetor, raiovetor, X, Y, velvetor, aclvetor\n global auxmouse, aux1, aux2, raio, rmoeda, angulo, veloc_angular, aceleracao, auxacl, gravidade, anguloX, anguloY, retardo\n pregovetor = PVector(int(random(200,1100)),0)\n L = list(range(100,int(pregovetor.x-299)))+list(range(int(pregovetor.x+300),1201))\n canovetor = PVector(L[int(random(0,len(L)))],700)\n moedavetor = PVector(0,0)\n sombravetor = PVector(0,0)\n paradovetor = PVector(0,0)\n raiovetor = PVector(0,0)\n X = PVector(1,0)\n Y = PVector(0,1)\n velvetor = PVector(0,0)\n aclvetor = PVector(0,0)\n auxmouse = 0\n aux1 = True\n aux2 = True\n raio = 0\n rmoeda = 25\n angulo = 0\n veloc_angular = 0\n aceleracao = 1\n auxacl = 0\n gravidade = 0.09\n anguloX = 0\n anguloY = 0\n retardo = 0.9997\n\ndef setup():\n global img1, img2\n size(1300,700)\n frameRate(180)\n img = loadImage(\"Capa_PC.png\")\n img1 = loadImage(\"Moeda.png\")\n img2 = loadImage(\"Moedinha.png\")\n background(img)\n variaveis()#Chamo a função que contém todas as variáveis que necessito\n \n\ndef draw():\n global pregovetor, canovetor, moedavetor, sombravetor, paradovetor, raiovetor, X, Y, velvetor, aclvetor\n global auxmouse, aux1, aux2, raio, rmoeda, angulo, veloc_angular, aceleracao, auxacl, gravidade, anguloX, anguloY, retardo, placar, recorde, comeco, img1, img2\n if comeco:\n background(135,206,250)\n fill(0)\n ellipse(pregovetor.x,pregovetor.y,15,15)#Prego\n \n if auxmouse == 0: #Sombra da Bola(Pré-Visualização)\n fill(0,0,0,20)\n noStroke()\n ellipse(sombravetor.x,sombravetor.y,rmoeda*2,rmoeda*2)\n \n elif auxmouse == 1: #Pêndulo\n raiovetor = moedavetor.copy().sub(pregovetor)#Vetor que vai do prego à moeda\n raio = raiovetor.mag()\n anguloX = PVector.angleBetween(raiovetor,X)\n anguloY = PVector.angleBetween(raiovetor,Y)\n if sin(anguloY) != 0:\n if aceleracao == 0:\n aceleracao = 1\n aceleracao = (gravidade/raio)*sin(anguloY) * (aceleracao/abs(aceleracao))#Fórmula pra calcular a aceleração variada ao longo da trajetória do pêndulo\n else:\n aceleracao = 0\n if anguloX < HALF_PI and aux1:#Se o pêndulo vai da esquerda pra direita\n aceleracao = -aceleracao\n aux1 = False\n elif anguloX > HALF_PI and not aux1:#Se o pêndulo vai da direita pra esquerda\n aceleracao = -aceleracao\n aux1 = True\n if moedavetor.x - rmoeda <= 0:#Reflexão do pêndulo na parede esquerda\n veloc_angular = -veloc_angular\n if moedavetor.x + rmoeda >= 1300: #Reflexão do pêndulo na parede direita\n veloc_angular = -veloc_angular\n veloc_angular += aceleracao\n veloc_angular *= retardo\n anguloX -= veloc_angular#Usando o método de Euler para aproximação\n moedavetor = pregovetor.copy().add(PVector.fromAngle(anguloX).mult(raio))#Definindo a posição da moeda\n fill(0)\n stroke(0)\n ellipse(moedavetor.x,moedavetor.y,rmoeda*2,rmoeda*2)\n image(img1,moedavetor.x-rmoeda,moedavetor.y-rmoeda)\n line(moedavetor.x,moedavetor.y,pregovetor.x,pregovetor.y)\n if moedavetor.y >= 700: #Se a bola do pêndulo for mais baixa que o chão\n textSize(100)\n textAlign(CENTER, CENTER);\n text(\"E MORREU... :v\",650,200)\n textSize(50)\n textAlign(CENTER, CENTER);\n text(\"PRESSIONE R PARA REINICIAR\",650,350)\n placar = 0\n noLoop() \n if pregovetor.x < canovetor.x:\n if moedavetor.x > canovetor.x-150: #Limite para soltar a bola (pois não pode chegar muito perto do cano)\n auxmouse = 2\n else:\n if moedavetor.x < canovetor.x+150:\n auxmouse = 2\n \n elif auxmouse == 2: #Projétil\n if aux2: #Condição para fazer o cálculo somente uma vez\n velvetor = raiovetor.normalize()*raio*veloc_angular#A velocidade linear é igual ao raio vezes a velocidade angular\n if anguloX <= HALF_PI and aceleracao <= 0:#A seguir são considerados 4 casos\n velvetor = PVector(velvetor.y,-velvetor.x)\n if anguloX <= HALF_PI and aceleracao >= 0:\n velvetor = PVector(-velvetor.y,velvetor.x)\n if anguloX >= HALF_PI and aceleracao <= 0:\n velvetor = PVector(-velvetor.y,velvetor.x)\n if anguloX >= HALF_PI and aceleracao >= 0:\n velvetor = PVector(velvetor.y,-velvetor.x)\n aclvetor = PVector(0,gravidade)\n paradovetor = moedavetor.copy()\n aux2 = False\n stroke(150)\n line(paradovetor.x,paradovetor.y,pregovetor.x,pregovetor.y)#Linha fantasma da hora que o projétil foi lançado\n velvetor.add(aclvetor)#Método de Euler\n moedavetor.add(velvetor)\n fill(0)\n stroke(0)\n ellipse(moedavetor.x,moedavetor.y,rmoeda*2,rmoeda*2)\n ellipse(pregovetor.x,pregovetor.y,15,15)\n image(img1,moedavetor.x-rmoeda,moedavetor.y-rmoeda)\n if moedavetor.x + rmoeda >= 1300:#Reflexão do projétil na parede direita\n velvetor.x = -velvetor.x\n elif moedavetor.x - rmoeda <= 0:#Reflexão do projétil na parede esquerda\n velvetor.x = -velvetor.x\n elif moedavetor.x < canovetor.x - 120 and abs(moedavetor.x - canovetor.x +120) < rmoeda and moedavetor.y >=570 and moedavetor.y <= 640:#Colisão parede Esquerda Superior do cano\n velvetor.x = -velvetor.x\n elif moedavetor.x < canovetor.x - 100 and abs(moedavetor.x - canovetor.x + 100) < rmoeda and moedavetor.y >= 650:#Colisão parede Esquerda inferior do cano\n velvetor.x = -velvetor.x\n elif moedavetor.x > canovetor.x - 70 and abs(moedavetor.x - canovetor.x + 70) < rmoeda and moedavetor.y >= 570:#Colisão parede Esquerda interna do cano\n velvetor.x = -velvetor.x\n elif moedavetor.x > canovetor.x + 120 and abs(moedavetor.x - canovetor.x-120) < rmoeda and moedavetor.y >=570 and moedavetor.y <= 640:#Colisão parede Direira Superior do canao\n velvetor.x = -velvetor.x\n elif moedavetor.x > canovetor.x + 100 and abs(moedavetor.x - canovetor.x - 100) < rmoeda and moedavetor.y >= 650:#Colisão parede Direira inferior do cano\n velvetor.x = -velvetor.x\n elif moedavetor.x < canovetor.x + 70 and abs(moedavetor.x - canovetor.x - 70) < rmoeda and moedavetor.y >= 570:#Colisão parede Direita interna do cano\n velvetor.x = -velvetor.x\n elif moedavetor.y < canovetor.y - 130 and moedavetor.y + rmoeda >= 570 and moedavetor.x >= canovetor.x - 120 and moedavetor.x <= canovetor.x - 70:#Colisão topo do cano, lado esquerdo\n velvetor.y = -velvetor.y \n elif moedavetor.y < canovetor.y - 130 and moedavetor.y + rmoeda >= 570 and moedavetor.x >= canovetor.x +70 and moedavetor.x <= canovetor.x + 120:#Colisão topo do cano, lado direito\n velvetor.y = -velvetor.y\n \n if moedavetor.y >= 650:#Testador de vitória\n if abs(canovetor.x-moedavetor.x) < 70:\n auxmouse = 0\n variaveis()\n placar += 1\n recorde = max(recorde,placar)\n else:\n if moedavetor.y >= 725: #Se a pessoa derrubar o projétil, perde\n textSize(100)\n textAlign(CENTER, CENTER);\n text(\"E MORREU... :v\",650,200)\n textSize(50)\n textAlign(CENTER, CENTER);\n text(\"PRESSIONE R PARA REINICIAR\",650,350)\n placar = 0\n noLoop()\n \n Xcentro = canovetor.x #Desenho do cano\n noStroke()\n fill(0,0,0)\n rect(Xcentro - 100, 700 - 60, 200, 60)\n rect(Xcentro - 120, 700 - 130, 240, 80, 0, 0, 30, 30)\n fill(34,149,34)\n rect(Xcentro - 90, 700 - 50, 180, 50)\n rect(Xcentro - 110, 700 - 120, 220, 60, 0, 0, 20, 20)\n fill(50,205,50)\n rect(Xcentro - 70, 700 - 50, 110, 50)\n rect(Xcentro - 90, 700 - 110, 150, 50)\n rect(Xcentro + 45, 700 - 50, 5, 50)\n rect(Xcentro + 65, 700 - 110, 5, 50)\n rect(Xcentro - 110, 700 - 120, 220, 10)\n fill(0,255,0)\n rect(Xcentro - 60, 700 - 50, 90, 50)\n rect(Xcentro - 80, 700 - 110, 130, 50)\n rect(Xcentro + 65, 700 - 120, 5, 10)\n rect(Xcentro - 90, 700 - 120, 10, 10)\n rect(Xcentro + 50, 700 - 120, 10, 10)\n fill(255,255,255)\n rect(Xcentro - 50, 700 - 50, 30, 50)\n rect(Xcentro - 70, 700 - 110, 30, 50)\n rect(Xcentro - 80, 700 - 120, 130, 10)\n \n v = PVector(50,50) #Marcador de Pontos(moedas) e Recorde\n image(img2,v.x,v.y)\n textSize(40)\n text(\"{}\".format(placar),v.x+60,v.y+7)\n text(\"RECORDE {}\".format(recorde),v.x+1090,v.y+7)\n \ndef mouseClicked():\n global auxmouse, moedavetor, comeco\n if comeco:\n if auxmouse == 1: #Os valores de auxmouse são usados para representar os passos do programa\n auxmouse = 2\n elif auxmouse == 0:\n if pregovetor.x < canovetor.x:\n if mouseX < canovetor.x-150 and mouseX > 25 and mouseX < 1275: #Limite para colocar a moeda no inicio\n moedavetor.add(PVector(mouseX,mouseY))\n auxmouse = 1\n else:\n if mouseX > canovetor.x+150 and mouseX > 25 and mouseX < 1275:\n moedavetor.add(PVector(mouseX,mouseY))\n auxmouse = 1\n\ndef mouseMoved():\n global auxmouse, sombravetor, comeco\n if comeco:\n if auxmouse == 0:\n sombravetor = PVector(mouseX,mouseY)#Rastro da moeda para mostrar onde ela ira iniciar\n \ndef keyPressed():\n global comeco, placar\n if key == 'r' or key == 'R':#Reinicia o jogo\n loop()\n variaveis()\n placar = 0\n if key == ' ':\n comeco = True\n","sub_path":"2/MF/Trabalho_A1/Trabalho_Pendulo.pyde","file_name":"Trabalho_Pendulo.pyde","file_ext":"pyde","file_size_in_byte":10663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384190436","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom preggy import expect\n\nfrom tests.unit.base import ApiTestCase\nfrom tests.fixtures import (\n DomainsViolationsPrefsFactory, DomainFactory, KeyFactory\n)\nfrom holmes.models import DomainsViolationsPrefs, Key, Domain, KeysCategory\n\n\nclass TestDomainsViolationsPrefs(ApiTestCase):\n @property\n def cache(self):\n return self.server.application.cache\n\n def tearDown(self):\n self.db.rollback()\n self.db.query(DomainsViolationsPrefs).delete()\n self.db.query(Domain).delete()\n self.db.query(Key).delete()\n self.db.query(KeysCategory).delete()\n self.db.commit()\n\n self.server.application.redis.flushdb()\n\n super(ApiTestCase, self).tearDown()\n\n def test_can_create_domains_violations_prefs(self):\n data = DomainsViolationsPrefsFactory.create(\n domain=Domain(name='globo.com'),\n key=Key(name='some.random.fact'),\n value='whatever'\n )\n\n loaded = self.db.query(DomainsViolationsPrefs).get(data.id)\n\n expect(loaded.domain.name).to_equal('globo.com')\n expect(loaded.key.name).to_equal('some.random.fact')\n expect(loaded.value).to_equal('whatever')\n\n def test_can_convert_to_dict(self):\n data = DomainsViolationsPrefsFactory.create(\n domain=Domain(name='globo.com'),\n key=Key(name='some.random.fact'),\n value='whatever'\n )\n\n expect(data.to_dict()).to_be_like({\n 'domain': 'globo.com',\n 'key': 'some.random.fact',\n 'value': 'whatever',\n })\n\n def test_domains_violations_prefs_str(self):\n data = DomainsViolationsPrefsFactory.create(\n domain=Domain(name='globo.com'),\n key=Key(name='some.random.fact'),\n value='whatever'\n )\n\n loaded = self.db.query(DomainsViolationsPrefs).get(data.id)\n\n expect(str(loaded)).to_be_like('some.random.fact (globo.com): whatever')\n\n def test_can_get_all_domains_violations_prefs(self):\n pref1 = DomainsViolationsPrefsFactory.create(value='whatever')\n pref2 = DomainsViolationsPrefsFactory.create(value='{\"test\": 10}')\n pref3 = DomainsViolationsPrefsFactory.create(value='[\"holmes\", \"ab\"]')\n\n data = DomainsViolationsPrefs.get_all_domains_violations_prefs(self.db)\n\n expect(data).not_to_be_null()\n expect(data).to_length(3)\n expect(data[0]).to_equal(pref1)\n expect(data[1]).to_equal(pref2)\n expect(data[2]).to_equal(pref3)\n\n def test_can_get_domains_violations_prefs(self):\n data = DomainsViolationsPrefsFactory.create(\n domain=Domain(name='globo.com'),\n key=Key(name='some.random.fact'),\n value='whatever'\n )\n\n data = DomainsViolationsPrefs.get_domains_violations_prefs(self.db)\n\n expect(data).to_be_like({\n 'globo.com': {\n 'some.random.fact': 'whatever'\n }\n })\n\n def test_can_insert_domains_violations_prefs(self):\n domain = DomainFactory.create()\n key = KeyFactory.create()\n value = '{\"page.size\": 100}'\n\n DomainsViolationsPrefs.insert_domains_violations_prefs(\n self.db, domain, key, value\n )\n\n data = self.db \\\n .query(DomainsViolationsPrefs) \\\n .filter(\n DomainsViolationsPrefs.key_id == key.id,\n DomainsViolationsPrefs.domain_id == domain.id,\n ) \\\n .all()\n\n expect(data).not_to_be_null()\n expect(data).to_length(1)\n expect(data[0].value).to_equal(value)\n\n def test_can_insert_default_violations_values_for_domain(self):\n domain = DomainFactory.create()\n\n page_title_size = KeyFactory.create(name='page.title.size')\n total_requests_img = KeyFactory.create(name='total.requests.img')\n\n violation_definitions = {\n 'page.title.size': {'key': page_title_size, 'default_value': 100},\n 'total.requests.img': {'key': total_requests_img, 'default_value': 5}\n }\n\n keys = violation_definitions.keys()\n\n data = DomainsViolationsPrefs.get_domains_violations_prefs_by_domain(self.db, domain.name)\n expect(data).to_length(0)\n\n DomainsViolationsPrefs.insert_default_violations_values_for_domain(\n self.db,\n domain,\n keys,\n violation_definitions,\n self.cache\n )\n\n data = DomainsViolationsPrefs.get_domains_violations_prefs_by_domain(self.db, domain.name)\n\n expect(data).not_to_be_null()\n expect(data).to_length(2)\n expect(data).to_be_like([\n {'value': 100, 'key': 'page.title.size'},\n {'value': 5, 'key': 'total.requests.img'}\n ])\n\n def test_can_insert_default_violations_values_for_all_domains(self):\n DomainsViolationsPrefsFactory.create(\n domain=Domain(name='globo.com'),\n key=Key(name='some.random.fact'),\n value='whatever'\n )\n\n for x in range(3):\n DomainFactory.create(name='g%d.com' % x)\n\n domains_violations_prefs = \\\n DomainsViolationsPrefs.get_domains_violations_prefs(self.db)\n\n expect(domains_violations_prefs).to_length(1)\n\n default_violations_values = {\n 'page.title.size': 100,\n 'total.requests.img': 5,\n }\n\n page_title_size = KeyFactory.create(name='page.title.size')\n total_requests_img = KeyFactory.create(name='total.requests.img')\n\n violation_definitions = {\n 'page.title.size': {'key': page_title_size, 'default_value': 100},\n 'total.requests.img': {'key': total_requests_img, 'default_value': 5}\n }\n\n DomainsViolationsPrefs.insert_default_violations_values_for_all_domains(\n self.db,\n default_violations_values,\n violation_definitions,\n self.cache\n )\n\n domains_violations_prefs = \\\n DomainsViolationsPrefs.get_domains_violations_prefs(self.db)\n\n expect(domains_violations_prefs).to_length(4)\n\n expect(domains_violations_prefs).to_be_like({\n 'globo.com': {\n 'some.random.fact': 'whatever',\n 'total.requests.img': 5,\n 'page.title.size': 100\n },\n 'g0.com': {'page.title.size': 100, 'total.requests.img': 5},\n 'g1.com': {'page.title.size': 100, 'total.requests.img': 5},\n 'g2.com': {'page.title.size': 100, 'total.requests.img': 5},\n })\n\n def test_can_update_by_domain(self):\n domain = DomainFactory.create(name='globo.com')\n\n DomainsViolationsPrefsFactory.create(\n domain=domain,\n key=Key(name='some.random'),\n value='whatever'\n )\n\n loaded = DomainsViolationsPrefs.get_domains_violations_prefs_by_domain(self.db, domain.name)\n\n expect(loaded).not_to_be_null()\n expect(loaded).to_length(1)\n expect(loaded).to_be_like([{'key': 'some.random', 'value': 'whatever'}])\n\n data = [\n {'key': 'some.random', 'value': '10'},\n {'invalid_key': 'some.random.1', 'invalid_value': '101'}\n ]\n\n DomainsViolationsPrefs.update_by_domain(self.db, self.cache, domain, data)\n\n loaded = DomainsViolationsPrefs.get_domains_violations_prefs_by_domain(self.db, domain.name)\n\n expect(loaded).not_to_be_null()\n expect(loaded).to_length(1)\n expect(loaded).to_be_like([{'key': 'some.random', 'value': '10'}])\n\n def test_can_update_by_domain_with_empty_data(self):\n domain = DomainFactory.create(name='globo.com')\n\n data = []\n\n DomainsViolationsPrefs.update_by_domain(self.db, self.cache, domain, data)\n\n loaded = DomainsViolationsPrefs.get_domains_violations_prefs_by_domain(self.db, domain.name)\n\n expect(loaded).to_equal([])\n","sub_path":"tests/unit/models/test_domains_violations_prefs.py","file_name":"test_domains_violations_prefs.py","file_ext":"py","file_size_in_byte":7976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578175523","text":"# coding: utf-8\n#!/usr/bin/env python3\n\"\"\"\nThe script helps guide the users to quickly understand how to use\nlibact by going through a simple active learning task with clear\ndescriptions.\n\"\"\"\n\nimport copy\nimport os\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ntry:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross_validation import train_test_split\n\n# libact classes\nfrom libact.base.dataset import Dataset, import_libsvm_sparse\nfrom libact.models import *\nfrom libact.query_strategies import *\nfrom libact.labelers import IdealLabeler\n# from cp-cnews_loader import read_vocab, read_category, batch_iter, process_file, build_vocab\nfrom dealwordindict import read_vocab, read_category, batch_iter, process_file, build_vocab\nimport time\nfrom datetime import timedelta\nimport gc\n\ndef get_time_dif(start_time):\n \"\"\"获取已使用时间\"\"\"\n end_time = time.time()\n time_dif = end_time - start_time\n return time_dif\n # return timedelta(seconds=int(round(time_dif)))\n\ndef run(trn_ds, tst_ds, lbr, model, qs, quota):\n E_in, E_out = [], []\n i = 1\n for _ in range(quota):\n # gc.disable()\n # Standard usage of libact objects\n start_time = time.time()\n ask_id = qs.make_query()\n print (str(i)+\"th times to ask.======================\")\n print (ask_id)\n time_dif = get_time_dif(start_time)\n print (\"time to ask\"+str(time_dif)) \n\n i = i + 1\n X, _ = zip(*trn_ds.data)\n\n lb = lbr.label(X[ask_id])\n trn_ds.update(ask_id, lb)\n start_time = time.time()\n model.train(trn_ds)\n time_dif = get_time_dif(start_time)\n print (\"time to train\"+str(time_dif))\n # gc.enable()\n E_in = np.append(E_in, 1 - model.score(trn_ds))\n E_out = np.append(E_out, 1 - model.score(tst_ds))\n return E_in, E_out\n\n\ndef split_train_test(dataset_filepath, test_size, n_labeled):\n #base_dir = './data/yinan'\n #train_dir = os.path.join(base_dir,'labeled.txt')\n #vocab_dir = os.path.join(base_dir,'vocab_yinan_1.txt')\n train_dir = '/home/ab/test/al/active/data/yinan/labeled1.txt'\n categories, cat_to_id = read_category()\n\n x,y = process_file(train_dir, cat_to_id,200)\n listy = []\n for i in range(np.shape(y)[0]):\n for j in range(np.shape(y)[1]):\n if y[i][j] == 1:\n listy.append(j)\n listy = np.array(listy) \n\n # X, y = import_libsvm_sparse(dataset_filepath).format_sklearn()\n\n\n X_train, X_test, y_train, y_test = \\\n train_test_split(x, listy, test_size=test_size)\n trn_ds = Dataset(X_train, np.concatenate(\n [y_train[:n_labeled], [None] * (len(y_train) - n_labeled)]))\n tst_ds = Dataset(X_test, y_test)\n fully_labeled_trn_ds = Dataset(X_train, y_train)\n# print (fully_labeled_trn_ds.get_entries()[0])\n return trn_ds, tst_ds, y_train, fully_labeled_trn_ds\n\n\ndef main():\n # Specifiy the parameters here:\n # path to your binary classification dataset\n base_dir = 'data/yinan'\n train_dir = os.path.join(base_dir,'labeled1.txt')\n vocab_dir = os.path.join(base_dir,'vocab_yinan_3.txt')\n # dataset_filepath = os.path.join(\n # os.path.dirname(os.path.realpath(__file__)), 'diabetes.txt')\n test_size = 0.3 # the percentage of samples in the dataset that will be\n # randomly selected and assigned to the test set\n n_labeled = 20 # number of samples that are initially labeled\n\n result = {'E1':[],'E2':[]}\n for i in range(2):\n # Load datas\n trn_ds, tst_ds, y_train, fully_labeled_trn_ds = \\\n split_train_test(train_dir, test_size, n_labeled)\n trn_ds2 = copy.deepcopy(trn_ds)\n lbr = IdealLabeler(fully_labeled_trn_ds)\n\n #quota = len(y_train) - n_labeled # number of samples to query\n quota = 680\n # Comparing UncertaintySampling strategy with RandomSampling.\n # model is the base learner, e.g. LogisticRegression, SVM ... etc.\n model = SVM(kernel = 'rbf',decision_function_shape='ovr')\n qs = UncertaintySampling(trn_ds, method='sm',model=SVM(decision_function_shape='ovr'))\n E_in_1, E_out_1 = run(trn_ds, tst_ds, lbr, model, qs, quota)\n result['E1'].append(E_out_1)\n qs2 = RandomSampling(trn_ds2)\n E_in_2, E_out_2 = run(trn_ds2, tst_ds, lbr, model, qs2, quota)\n result['E2'].append(E_out_2)\n E_out_1 = np.mean(result['E1'],axis=0)\n E_out_2 = np.mean(result['E2'],axis=0)\n # Plot the learning curve of UncertaintySampling to RandomSampling\n # The x-axis is the number of queries, and the y-axis is the corresponding\n # error rate.\n query_num = np.arange(1, quota + 1)\n plt.figure(figsize=(10,8))\n #plt.plot(query_num, E_in_1, 'b', label='qs Ein')\n #plt.plot(query_num, E_in_2, 'r', label='random Ein')\n plt.plot(query_num, E_out_1, 'g', label='qs Eout')\n plt.plot(query_num, E_out_2, 'k', label='random Eout')\n plt.xlabel('Number of Queries')\n plt.ylabel('Error')\n plt.title('Experiment Result')\n plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),\n fancybox=True, shadow=True, ncol=5)\n plt.savefig('resultlg_features.png')\n #plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"active/merge_gru_lstm_&&cnn_rnn/testlogic/alsvm.py","file_name":"alsvm.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"237166661","text":"\"\"\"empty message\n\nRevision ID: 0ecdd82ae075\nRevises: a0be6b288a75\nCreate Date: 2019-04-15 17:43:13.817039\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0ecdd82ae075'\ndown_revision = 'a0be6b288a75'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('phase', sa.Column('description', sa.String(length=512), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('phase', 'description')\n # ### end Alembic commands ###\n","sub_path":"dolphin/migration/versions/0ecdd82ae075_.py","file_name":"0ecdd82ae075_.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"516972762","text":"from cx_Freeze import setup,Executable\nimport os,sys\n\nos.environ['TCL_LIBRARY'] = r'C:/Users/agoum/AppData/Local/Programs/Python/Python37/tcl/tcl8.6'\nos.environ['TK_LIBRARY'] = r'C:/Users/agoum/AppData/Local/Programs/Python/Python37/tcl/tk8.6'\n\nexcludes = ['Tkinter']\nincludes = [\"sys\",\"functools\",\"time\",\"os\",\"PyQt5\",\"sys\",\"math\",\"pynput\",\"pandas\",\"numpy\"] # nommer les modules utilises\npackages = [\"py_lib\",\"public\",\"numpy\"] # nommer les packages utilises\n\nincludefiles = [\"css\",\"tcl86t.dll\",\"remote.ico\",\"tk86t.dll\",\"start.bat\"]\n\n\n# niveau d'optimisation pour la compilation en bytecodes\noptimize = 0\n\n# si True, n'affiche que les warning et les erreurs pendant le traitement cx_freeze\nsilent = True\n\npath = sys.path\npath.append('C:/Users/agoum/Documents/Programmation/python/remote_msgs')\n\n# construction du dictionnaire des options\noptions = {\"path\": path,\n \"packages\": packages,\n \"excludes\":excludes,\n \"includes\":includes,\n \"include_files\": includefiles,\n \"optimize\": optimize,\n \"silent\": silent,\n # \"namespace_packages\":['zope'],\n }\n\ntarget = Executable(\n script=\"remote_msgs.py\",\n base=\"Win32GUI\",\n icon = \"remote.ico\",\n )\n\nsetup(\n\tname = \"Remote msgs\",\n\tversion = \"3.0\",\n\tdescription = \"Envoi automatique de message sur whatsapp\",\n\tauthor=\"Jalil AGOUMI\",\n author_email=\"agoumi.jalil@gmail.com\",\n\toptions={\"build_exe\": options},\n\texecutables = [target],\n\t)","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"495640974","text":"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\nfrom sagemaker import get_execution_role\nimport sagemaker as sage\nfrom sagemaker.estimator import Estimator\nfrom sagemaker.inputs import FileSystemInput\nimport datetime\nimport subprocess\nimport sys\n\ndef get_str(cmd):\n content = subprocess.check_output(cmd, shell=True)\n return str(content)[2:-3]\n\naccount = get_str(\"echo $(aws sts get-caller-identity --query Account --output text)\")\nregion = get_str(\"echo $(aws configure get region)\")\nimage = str(sys.argv[1])\nsess = sage.Session()\nimage_name=f\"{account}.dkr.ecr.{region}.amazonaws.com/{image}\"\nsagemaker_iam_role = str(sys.argv[2])\nnum_gpus = 8\nnum_nodes = 4\ninstance_type = 'ml.p3.16xlarge'\ncustom_mpi_cmds = []\n\njob_name = \"maskrcnn-{}x{}-{}\".format(num_nodes, num_gpus, image)\n\noutput_path = 's3://mrcnn-sagemaker/sagemaker_training_release'\n\nlustre_input = FileSystemInput(file_system_id='fs-03f556d03c3c590a2',\n file_system_type='FSxLustre',\n directory_path='/fsx',\n file_system_access_mode='ro')\n\nhyperparams = {\"sagemaker_use_mpi\": \"True\",\n \"sagemaker_process_slots_per_host\": num_gpus,\n \"num_gpus\":num_gpus,\n \"num_nodes\": num_nodes,\n \"custom_mpi_cmds\": custom_mpi_cmds}\n\nestimator = Estimator(image_name, role=sagemaker_iam_role, output_path=output_path,\n train_instance_count=num_nodes,\n train_instance_type=instance_type,\n sagemaker_session=sess,\n train_volume_size=200,\n base_job_name=job_name,\n \n hyperparameters=hyperparams)\n\nestimator.fit({'train':lustre_input}, wait=False)\n","sub_path":"infra/sm/launch_sm_job.py","file_name":"launch_sm_job.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"527441879","text":"from app import app\nfrom flask import render_template, request, jsonify, make_response, session\nfrom app.models import Todo\nfrom datetime import datetime\n\nfrom query import queryfun,downitemfun\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n#add delete update list\n\n@app.route('/add', methods=['POST',])\ndef add():\n\tform = request.form\n\n\tcontent = form.get('content')\n\ttodo = Todo( content=content,time=datetime.now())\n\ttodo.save()\n\treturn jsonify( status = \"success\")\n\n@app.route('/delete/')\ndef delete(todo_id):\n\ttodo = Todo.objects.get_or_404( id = todo_id)\n\ttodo.delete()\n\treturn jsonify( status = \"success\")\n\n@app.route('/update', methods=['POST',])\ndef update():\n\tform = request.form\n\ttodo_id = form.get('id')\n\tstatus = form.get('status')\n\ttodo = Todo.objects.get_or_404( id = todo_id )\n\ttodo.status = status\n\ttodo.save()\n\treturn jsonify( status = \"success\" )\n\n@app.route('/list')\ndef list():\n\ttodos = Todo.objects\n\treturn jsonify( status = \"success\", todos = [ todo.to_json() for todo in todos ])\n\n@app.route('/query', methods=['POST',])\ndef query():\n\t#import pdb\n\t#pdb.set_trace()\n\tqueryData = request.form\n\tsession['queryData'] = queryData\n\tdata = queryfun( queryData )\n\tif data == False:\n\t\treturn jsonify( status = \"fail\" )\n\telse:\n\t\treturn jsonify( status = \"success\", books = data['list'], pager = data['pager'] )\n\n\n@app.route('/downitem')\ndef downitem():\n\t#import pdb\n\t#pdb.set_trace()\n\tqueryData = session.get('queryData')\n\tfile = downitemfun( queryData )\n\tresponse = make_response(file.getvalue())\n\tresponse.headers['Content-Type'] = 'text/csv'\n\tresponse.headers[\"Content-Disposition\"] = \"attachment; filename=myfilename.csv\"\n\treturn response","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427405738","text":"# Approximate pi using random number generator\n\nimport random\nimport time\nimport math\n\n\ndef calculate_pi(n):\n num_inside = 0\n for i in range(n):\n if random.uniform(0,1)**2 + random.uniform(0,1)**2 <= 1:\n num_inside += 1\n return num_inside/n * 4\n\n\nn = 1000\ntrials = 100\n\npi = math.pi\navg_error = 0\n\n\nfor i in range(trials):\n before = time.monotonic()\n experimental = calculate_pi(n)\n error = pi - experimental\n avg_error += error\n print(str(calculate_pi(n)) + \" with error \" + str(error))\n after = time.monotonic()\n # print(str(after - before) + \" seconds\")\n\n\navg_error /= trials\nprint(avg_error)\n","sub_path":"CalculatePi.py","file_name":"CalculatePi.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"212624886","text":"class Solution:\n def judgePoint24(self, nums) -> bool:\n eps = 0.001\n\n def help2(x, y):\n res = [x + y, x * y, x - y, y - x]\n if abs(y) > eps:\n res.append(x / y)\n if abs(x) > eps:\n res.append(y / x)\n return res\n\n def help3(a, b, c):\n res = []\n for x in help2(b, c):\n res += help2(a, x)\n for x in help2(a, c):\n res += help2(b, x)\n for x in help2(a, b):\n res += help2(c, x)\n return res\n\n def f2(a, b, c, d):\n res = []\n h2x = help2(a, b)\n h2y = help2(c, d)\n for x in h2x:\n for y in h2y:\n res += help2(x, y)\n return res\n\n def f3(a, b, c, d):\n res = []\n h3 = help3(b, c, d)\n for x in h3:\n res += help2(a, x)\n return res\n\n ans = f2(nums[0], nums[1], nums[2], nums[3])\n ans += f2(nums[0], nums[2], nums[1], nums[3])\n ans += f2(nums[0], nums[3], nums[1], nums[2])\n ans += f3(nums[0], nums[1], nums[2], nums[3])\n ans += f3(nums[1], nums[0], nums[2], nums[3])\n ans += f3(nums[2], nums[0], nums[1], nums[3])\n ans += f3(nums[3], nums[0], nums[1], nums[2])\n for x in ans:\n if abs(x - 24) < eps:\n return True\n return False\n\n\ns = Solution()\nprint(s.judgePoint24([4, 1, 8, 7]))\nprint(s.judgePoint24([1, 5, 9, 1]))\nprint(s.judgePoint24([1, 2, 1, 2]))\n","sub_path":"leetcode/2020/24-game.py","file_name":"24-game.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"417109075","text":"import sqlite3\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport sys\nimport os\nfrom os.path import expanduser\nimport platform\nimport itertools\nfrom datetime import datetime\nimport time\nfrom threading import Thread\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom chump import Application\n\n# SqlAlchemy settings\nsqlPath = os.environ.get('SQLITE_PATH')\nif (sqlPath is None):\n raise EnvironmentError(\"Env variable SQLITE_PATH is not defined\")\nsqlDatabaseName = \"scrapwiki.db\"\nDATABASE = \"sqlite:///\" + sqlPath + sqlDatabaseName\nengine = create_engine(DATABASE, echo=False)\nBase = declarative_base()\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n\n# SqlAlchemy Classes\nclass IataAirport(Base):\n __tablename__ = 'IATA_AIRPORT'\n Id = Column('ID', Integer, primary_key=True)\n CityIataCode = Column('CITY_IATA_CODE', String(3))\n CityName = Column('CITY_NAME', String(100))\n AirportName = Column('AIRPORT_NAME', String(100))\n AirportIataCode = Column('AIRPORT_IATA_CODE', String(3))\n CountryCode = Column('COUNTRY_CODE', String(2))\n\n def __repr__(self):\n return \"\" % (self.CityIataCode, self.CityName)\n\n\n# Global variables\nDEF_CHARSET = \"utf-8\"\nbaseUrl = \"http://www.iata.org/publications/Pages/code-search.aspx\"\nSCRAP_CODE = \"001\"\nSCRAP_NAME = \"Iata airlines\"\nROW_COUNT = 0;\napp = Application('aKwejyb7Mt4JqBFKAWe6x86egVcNEE')\nuser = app.get_user('uLvHB9qVSYXWAQtQvph3SL4LjKEb6V')\n\n\ndef hasBeenProcessedBefore(iataCode):\n airport = session.query(IataAirport).filter(IataAirport.AirportIataCode == iataCode).first()\n if airport is not None:\n return True\n else:\n return False\n\n\ndef updateHeartBeatStatus():\n user.send_message(title=\"Airport Scrapper Message\",\n message=\"Cities found: \" + str(ROW_COUNT),\n html=False,\n sound='magic')\n\n\ndef background_task():\n while not background_task.cancelled:\n updateHeartBeatStatus()\n time.sleep(60)\n\n\nresponse = requests.get(baseUrl)\nif (response.status_code != requests.codes.ok):\n sys.exit()\nhtmlData = response.text.encode(DEF_CHARSET)\n\nresponse_cookies = dict()\nif (len(response.cookies) > 0):\n response_cookies = response.cookies\n\nhtmlTree = BeautifulSoup(htmlData, 'html5lib')\nviewStateGenerator = htmlTree.find(\"input\", {\"id\": \"__VIEWSTATEGENERATOR\"})\nviewState = htmlTree.find(\"input\", {\"id\": \"__VIEWSTATE\"})\neventValidation = htmlTree.find(\"input\", {\"id\": \"__EVENTVALIDATION\"})\npREQUESTDIGEST = htmlTree.find(\"input\", {\"id\": \"__REQUESTDIGEST\"})\n\nrequest_headers = {'Host': 'www.iata.org',\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.8,es-ES;q=0.5,es;q=0.3\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"X-MicrosoftAjax\": \"Delta=true\",\n \"Cache-Control\": \"no-cache\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=utf-8\",\n \"Referer\": \"http://www.iata.org/publications/Pages/code-search.aspx\",\n \"Connection\": \"keep-alive\",\n \"Pragma\": \"no-cache\"\n }\n\nROW_COUNT = session.query(IataAirport).filter(IataAirport.CityName != None).count()\nbackground_task.cancelled = False\nt = Thread(target=background_task)\nt.start()\n\nfor codeItem in itertools.permutations(\n 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890QWERTYUIOPASDFGHJKLZXCVBNM1234567890QWERTYUIOPASDFGHJKLZXCVBNM1234567890',\n r=3):\n if (hasBeenProcessedBefore(codeItem[0] + codeItem[1] + codeItem[2])):\n continue\n payload = {\"ctl00$sm\": \"ctl00$sm|ctl00$SPWebPartManager1$g_e3b09024_878e_4522_bd47_acfefd1000b0$ctl00$butSearch\",\n \"__SPSCEditMenu\": \"true\",\n \"_wpcmWpid\": \"\",\n \"wpcmVal\": \"\",\n \"MSOWebPartPage_PostbackSource\": \"\",\n \"MSOTlPn_SelectedWpId\": \"\",\n \"MSOTlPn_View\": \"0\",\n \"MSOTlPn_ShowSettings\": \"False\",\n \"MSOGallery_SelectedLibrary\": \"\",\n \"MSOGallery_FilterString\": \"\",\n \"MSOTlPn_Button\": \"none\",\n \"__EVENTTARGET\": \"\",\n \"__EVENTARGUMENT\": \"\",\n \"__REQUESTDIGEST\": pREQUESTDIGEST['value'],\n \"ctl00_sm_HiddenField\": \"\",\n \"MSOSPWebPartManager_DisplayModeName\": \"Browse\",\n \"MSOSPWebPartManager_ExitingDesignMode\": \"false\",\n \"MSOWebPartPage_Shared\": \"\",\n \"MSOLayout_LayoutChanges\": \"\",\n \"MSOLayout_InDesignMode\": \"\",\n \"_wpSelected\": \"\",\n \"_wzSelected\": \"\",\n \"MSOSPWebPartManager_OldDisplayModeName\": \"Browse\",\n \"MSOSPWebPartManager_StartWebPartEditingName\": \"false\",\n \"MSOSPWebPartManager_EndWebPartEditing\": \"false\",\n \"ctl00_PlaceHolderMain_CurrentNav_tvLeftNavigation_ExpandState\": \"encnncnnnnnnncnnnnncnnnnccnnnnnnnnnnnnnccnnnnnnncnnnnnncnnnnncnnnnnncnnnnncnnnnncnnccnnnnnncnnnnnncnnnnnnnncnnnnnnnnncnnnnnnnnnnnnnnnnnnn\",\n \"ctl00_PlaceHolderMain_CurrentNav_tvLeftNavigation_SelectedNode\": \"ctl00_PlaceHolderMain_CurrentNav_tvLeftNavigationt0\",\n \"ctl00_PlaceHolderMain_CurrentNav_tvLeftNavigation_PopulateLog\": \"\",\n \"__VIEWSTATEGENERATOR\": viewStateGenerator['value'],\n \"ctl00$Header$AdvanceSearchBox$DisplayContent$SearchTextBox\": \"\",\n \"ctl00$SPWebPartManager1$g_e3b09024_878e_4522_bd47_acfefd1000b0$ctl00$ddlImLookingFor\": \"ByLocationCode\",\n \"ctl00$SPWebPartManager1$g_e3b09024_878e_4522_bd47_acfefd1000b0$ctl00$txtSearchCriteria\": codeItem[0] +\n codeItem[1] +\n codeItem[2],\n \"ctl00$SPWebPartManager1$g_e3b09024_878e_4522_bd47_acfefd1000b0$ctl00$txtSearchCriteriaRequiredValidatorCalloutExtender_ClientState\": \"\",\n \"__ASYNCPOST\": \"true\",\n \"ctl00$SPWebPartManager1$g_e3b09024_878e_4522_bd47_acfefd1000b0$ctl00$butSearch\": \"Search\"\n }\n response = None\n try:\n response = requests.post(baseUrl, data=payload, cookies=response_cookies, headers=request_headers)\n except Exception:\n pass\n\n if (response == None or response.status_code != requests.codes.ok):\n continue\n\n htmlData = None\n htmlTree = None\n try:\n htmlData = response.text.encode(DEF_CHARSET)\n htmlTree = BeautifulSoup(htmlData, 'html5lib')\n except Exception:\n continue\n\n resultTable = htmlTree.find(\"table\", {\"class\": \"resultsTable\"})\n if resultTable is None:\n continue\n resultRows = resultTable.find(\"tbody\").findAll(\"tr\")\n for rowItem in resultRows:\n cityCode = \"\"\n cityName = \"\"\n airportName = \"\"\n airportCode = \"\"\n airport = IataAirport(CityIataCode=codeItem[0] + codeItem[1] + codeItem[2],\n AirportIataCode=codeItem[0] + codeItem[1] + codeItem[2])\n if (rowItem is not None):\n cityName = rowItem.findAll(\"td\")[0]\n cityCode = rowItem.findAll(\"td\")[1]\n airportName = rowItem.findAll(\"td\")[2]\n airportCode = rowItem.findAll(\"td\")[3]\n if (cityName is not None and cityCode is not None and airportCode is not None):\n row = (cityCode.text, cityName.text, airportName.text, airportCode.text)\n print(row)\n airport = IataAirport(CityIataCode=cityCode.text, CityName=cityName.text, AirportName=airportName.text,\n AirportIataCode=airportCode.text, CountryCode=None)\n session.add(airport)\n session.commit()\n ROW_COUNT = session.query(IataAirport).filter(IataAirport.CityName != None).count()\n\nbackground_task.cancelled = True\nuser.send_message(title=\"Airport Scrapper Message\",\n message=\"Process End\",\n html=False,\n sound='magic')","sub_path":"Pandas/scrappingscripts/scrapping_iataorg.py","file_name":"scrapping_iataorg.py","file_ext":"py","file_size_in_byte":8448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"595622006","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom time import time\n\nfrom cs231n.data_utils import load_tiny_imagenet, load_models\nfrom cs231n.classifiers.convnet import *\nfrom cs231n.classifier_trainer import ClassifierTrainer\n\ntiny_imagenet = 'cs231n/datasets/tiny-imagenet-200'\n\nclass_names, X_train, y_train, X_val, y_val, X_test, y_test = load_tiny_imagenet(tiny_imagenet)\n\n# Zero-mean the data\nmean_img = np.mean(X_train, axis=0)\nX_train -= mean_img\nX_val -= mean_img\nX_test -= mean_img\n\nmodel = init_five_layer_convnet(num_classes=200)\ntrainer = ClassifierTrainer()\nlearning_rate = 1e-3\nreg = 1e-2\ndropout = 0.5\nnum_epochs = 1\nbest_model, loss_history, train_acc_history, val_acc_history = trainer.train(X_train, y_train, X_val, y_val, model, five_layer_convnet, learning_rate=learning_rate, reg=reg, update='rmsprop', dropout=dropout, num_epochs=num_epochs, verbose=True)\n","sub_path":"tinyimagenet.py","file_name":"tinyimagenet.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169608057","text":"\"\"\"\nLists with Duplicates - SOLUTION\n\"\"\"\n\n# First remove dups from a\n\n# then merge b without adding dups\n\na = [2, 4, 10, 20, 5, 2, 20, 4]\nb = [13, 2, 25, 20, 4, 8]\n\nx = []\n\nprint(a)\n\nfor i in a:\n if i not in x:\n x.append(i)\n\na = x\n\nprint(a)\n\nfor i in b:\n if i not in a:\n a.append(i)\n\nprint(a)","sub_path":"pset_loops/loop_basics/solutions/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"145504780","text":"#! /usr/local/bin/python3\nimport operator\nimport sys\nfrom collections import deque\nfrom math import prod\n\n#lns = map(lambda x: map(lambda y: int(y), filter(len, x.split('\\n')[1:])), sys.stdin.read().split('\\n\\n'))\nlns = [[int(y) for y in filter(len, x.split('\\n')[1:])] for x in sys.stdin.read().split('\\n\\n')]\n\nprint(list(map(list, lns)))\n\nplayers = list(map(deque, lns))\nprint(players)\n\ndef game(p, g = 1):\n acc = set()\n while p[0] and p[1]:\n current = tuple(p[0]), tuple(p[1])\n if current in acc:\n r = p[0] or p[1]\n r.reverse()\n return r, 0\n acc.add(current)\n v1 = p[0].popleft();\n v2 = p[1].popleft();\n if len(p[0]) >= v1 and len(p[1]) >= v2:\n d1 = deque(list(p[0])[:v1])\n d2 = deque(list(p[1])[:v2])\n _, w = game([d1, d2], g+1)\n drews = [v1, v2]\n if w == 1:\n drews.reverse()\n p[w].extend(drews)\n elif v1 > v2:\n p[0].extend([v1, v2])\n else:\n p[1].extend([v2, v1])\n\n r = p[0] or p[1]\n r.reverse()\n\n return r, 1 if len(p[0]) == 0 else 0\n\nr, _ = game(players)\n\nz = list(zip(r, range(1, len(r) + 1)))\nv = sum(list(map(prod, enumerate(r, 1))))\nprint(v)\n\n\n","sub_path":"d22/d22-2.py","file_name":"d22-2.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"263880249","text":"\ndef MakeTicTacTable():\n table = [[0,0,0],\n [0,0,0],\n [0,0,0]]\n return table\n\ndef ShowTable(table):\n for i in range(0,3) :\n for j in range(0,3) :\n print(table[i][j],end =' ')\n print()\ndef Select_Table(table,row,column,player):\n if(player == 1):\n if(table[row][column] == 0):\n table[row][column] = \"X\"\n else:\n print(\"Not empty !!\")\n return False\n else:\n if(table[row][column] == 0):\n table[row][column] = \"O\"\n else:\n print(\"Not empty !!\")\n return False\n return table\n\ndef CheackRepeate(table,row,column):\n if(table[row][column] == 0 ):\n return True\n return False\n\ndef SelectPlayer(player):\n if(player == 1):\n return \"X\"\n return \"O\"\n\n\n \ndef CalculatorScoore(table):\n win = 0 \n for player in range(1,3):\n if(row_win(table,player) or col_win(table,player) or\n diag_win(table,player)):\n win = player\n is_zero = 0\n for i in range (len(table)):\n for j in range(len(table)):\n if(table[i][j]== 0):\n is_zero +=1\n if is_zero == 0 and win ==0 :\n win =-1\n return win\n\n\n\n \ndef game_is_over(board):\n for i in range(3):\n\n if board[i][0] == board[i][1] == board[i][2] \\\n and board[i][0] != 0 :\n print(board[i][0] + \" wins!\")\n return board[i][0]\n \n\n if board[0][i] == board[1][i] == board[2][i] \\\n and board[0][i] != 0:\n print(board[0][i] + \" wins!\")\n return board[0][i]\n \n\n if board[0][0] == board[1][1] == board[2][2] \\\n and board[0][0] != 0:\n print(board[0][0] + \" wins!\")\n return board[0][0]\n \n if board[2][0] == board[1][1] == board[0][2] \\\n and board[2][0] != 0:\n print(board[2][0] + \" wins!\")\n return board[2][0]\n \n \n if 0 not in board[0] and 0 not in board[1] \\\n and 0 not in board[2]:\n print(\"Tie game!\")\n return 0\n \n return False\n \n\ndef is_valid(px,py,table):\n if px < 0 or px >2 or py < 0 or py > 2:\n return False\n elif table[px][py] != 0:\n return False\n else:\n return True\n\n\ndef play(table):\n player = \"X\"\n ShowTable(table)\n \n if player == \"X\":\n while True:\n (m,qx,qy) = min(table)\n px,py = input(\"Input [ ] [ ] : \").split()\n px = int(px)\n py = int(py)\n (qx,qy) = (px,py)\n \n if(is_valid(px,py,table)):\n table[px][py] = \"X\"\n player = \"O\"\n break\n else:\n print(\"The move is not valid ! Try again\")\n else :\n (m,px,py) = max(table)\n table[px][py] = \"O\"\n player = \"X\"\n \n \n \n \n \n \ndef play_game(): \n countscore = 0\n is_game = True\n table = MakeTicTacTable()\n ShowTable(table)\n while(is_game == True):\n \n for player in range(1,3):\n correct_input = True\n print(\"You are Player : \" , player)\n while(correct_input == True):\n if(player == 1):\n m,qx,qy = min(table)\n a,b = input(\"Choose Tictac Table in row and column : \" ).split()\n qx,qy = int(a),int(b)\n if is_valid(int(a),int(b),table):\n table[int(a)][int(b)] = \"X\"\n ShowTable(table)\n correct_input = False\n \n else:\n print(\"Tablyouselected not empty\")\n elif (player == 2):\n m,px,py = max(table)\n table[px][py] = \"O\"\n ShowTable(table)\n correct_input = False\n \n winner = game_is_over(table)\n if winner == \"X\":\n correct_input = False\n is_game = False\n countscore += 1\n break\n elif winner == \"O\":\n correct_input = False\n is_game = False\n countscore -= 1\n\ndef max(table):\n maxv = -2\n px = None\n py = None\n \n result = game_is_over(table)\n if result == 'X':\n return (-1, 0, 0)\n elif result == 'O':\n return (1, 0, 0)\n elif result == 0:\n return (0, 0, 0)\n \n for i in range(0,3):\n for j in range (0,3):\n if table[i][j] == 0:\n table[i][j] == \"0\"\n (m,min_i,min_j) = min(table)\n if m > maxv :\n maxv = m\n px = i \n py = j\n table[i][j] = 0\n return (maxv,px,py)\n\ndef min (table):\n minv =2\n qx = None\n qy = None\n \n result = game_is_over(table)\n \n if result == 'X':\n return(-1,0,0)\n elif result == 'O':\n return (1,0,0)\n elif result == 0:\n return (0,0,0)\n \n for i in range (0,3):\n for j in range (0,3):\n if table[i][j] == 0:\n table[i][j] = \"X\"\n (m,max_i,max_j) = max()\n if m < minv:\n minv = m \n qx = i \n qy = j\n table[i][j] = 0\n return (minv,qx,qy)\n\nplay_game()\n\n \n \n","sub_path":"tictac.py","file_name":"tictac.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201746352","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom Cibil.models import Credit_Card, Personal_Information, Application_History\nimport random\nfrom .forms import *\nimport datetime\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\n\n\n\n# Create your views here.\ndef credit_card_no(request): \n \n n = 6\n range_start = 100**(n - 1)\n range_end = (100**n) - 1\n credit_card_no = random.randint(range_start, range_end)\n print(credit_card_no)\n if request.method == 'POST':\n form = Information(request.POST)\n if form.is_valid():\n info = Personal_Information()\n info.Username = form.cleaned_data['username']\n info.First_Name = form.cleaned_data['firstname']\n info.Last_Name = form.cleaned_data['lastname']\n info.Email = form.cleaned_data['email']\n info.DOB = form.cleaned_data['dob']\n info.Gender = form.cleaned_data['gender']\n info.PAN_Number = form.cleaned_data['pan_number']\n info.PAN_Issue_Date = form.cleaned_data['pan_issue_date']\n info.Aadhar_Number = form.cleaned_data['aadhar_no']\n info.Aadhar_Issue_Date = form.cleaned_data['aadhar_issue_date'] \n password = form.cleaned_data['password']\n username = form.cleaned_data['username']\n email = form.cleaned_data['email']\n user = User.objects.create_user(username, email, password)\n user.last_name = form.cleaned_data['lastname']\n user.first_name = form.cleaned_data['firstname']\n user.save()\n info.save()\n application = Application_History()\n application.Username = Personal_Information.objects.latest('Username')\n application.Application_Date = datetime.datetime.now()\n print(\"***********\")\n if application.Application_Type == 'Credit Card':\n print(\"&&&&&&&&&&&&&&&&&&&&&&&&&\")\n credit = Credit_Card()\n credit.Username = Personal_Information.objects.latest('Username')\n credit.Credit_Card_No = credit_card_no\n credit.Credit_Limit = 50000\n credit.Date_Issued = datetime.datetime.now()\n credit.Date_Expired = datetime.datetime.now()\n credit.Current_Balance = 0\n credit.Rate_Of_Interest = 5\n credit.save()\n application.Status = 'approved'\n application.save()\n return HttpResponseRedirect('/application')\n else:\n form = Information()\n\n return render(request,'Credit.html', {'form': form})\n\n\n ","sub_path":"perf/Credit_Card/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"212551611","text":"from mongoengine import *\n\nconnect(\"test\", host=\"localhost\", port=27017)\n\n\nclass Users(Document):\n name = StringField(required=True, max_length=200)\n age = IntField(required=True)\n\n\nuser1 = Users(\n name=\"zz\",\n age=11\n)\nuser1.save()\n\nprint(user1.name)\nprint(user1.age)\n\nusers = Users.objects.all()\nprint([(user.name, user.age) for user in users])\ntmp = Users.objects(name=\"zz\").update(inc__age=1)\ntmp1 = Users.objects(name=\"zz\")\nprint([(u.name, u.age) for u in tmp1])\n# users = Users.objects.all() # 必须重新获取数据库对象才能获取最新的数据库数据\nprint([(user.name, user.age) for user in users])\nusers = Users.objects.order_by(\"-age\")\nprint([(user.name, user.age) for user in users])\n","sub_path":"python/standard_library/Database/mongodb_test/mongo_engine_test1.py","file_name":"mongo_engine_test1.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455992471","text":"\ndata = np.loadtxt('figData.txt', dtype=[(\"NegSD-NegSR\", np.float32), \n (\"NeuSD-NeuSR\", np.float32), (\"AmbSD-AmbSR\", np.float32)])\n\nNegMean = data[\"NegSD-NegSR\"].mean()\nNeuMean = data[\"NeuSD-NeuSR\"].mean()\nAmbMean = data[\"AmbSD-AmbSR\"].mean()\n\nNegStd = data[\"NegSD-NegSR\"].std()\nNeuStd= data[\"NeuSD-NeuSR\"].std()\nAmbStd= data[\"AmbSD-AmbSR\"].std()\n\n","sub_path":"hw3/ignore/FigureReplication.py","file_name":"FigureReplication.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304904017","text":"# -*-coding:utf-8 -*-\n#Reference:**********************************************\n# @Time    : 2019-11-14 21:13\n# @Author  : Fabrice LI\n# @File    : 20191113_394_decode_string.py\n# @User    : liyihao\n# @Software : PyCharm\n# @Description: Given an encoded string, return its decoded string.\n#\n# The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being\n# repeated exactly k times. Note that k is guaranteed to be a positive integer.\n#\n# You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed,\n# etc.\n#\n# Furthermore, you may assume that the original data does not contain any digits and that digits are only for\n# those repeat numbers, k. For example, there won't be input like 3a or 2[4].\n#Reference:**********************************************\n'''\ns = \"3[a]2[bc]\", return \"aaabcbc\".\ns = \"3[a2[c]]\", return \"accaccacc\".\ns = \"2[abc]3[cd]ef\", return \"abcabccdcdcdef\".\n'''\nclass Solution:\n def decodeString(self, s: str) -> str:\n return self.dfs(s, 0)\n\n def dfs(self, s, start_index):\n multi = 0\n res = ''\n while start_index < len(s):\n if '0' <= s[start_index] <= '9':\n multi = multi * 10 + int(s[start_index])\n elif s[start_index] == '[':\n start_index, tmp = self.dfs(s, start_index + 1)\n res += multi * tmp\n multi = 0\n elif s[start_index] == ']':\n return start_index, res\n else:\n res += s[start_index]\n start_index += 1\n return res\n\nif __name__ == '__main__':\n s = Solution()\n st = '3[a2[c]]'\n print(s.decodeString(st))\n","sub_path":"LintCode/DFS/20191113_394_decode_string.py","file_name":"20191113_394_decode_string.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54899315","text":"import os\nfrom itertools import product\n\nimport pandas as pd\n\n\ndef save_model_results(model, results_path, file_suffix, disaggregate=False, debug=False):\n results_df = model.to_dataframe()\n results_df.index.name = 'Date'\n scenario_names = [s.name for s in model.scenarios.scenarios]\n if not scenario_names:\n scenario_names = [0]\n if not os.path.exists(results_path):\n os.makedirs(results_path)\n\n # if df_planning is not None:\n # df_planning.to_csv(os.path.join(results_path, 'planning_debug.csv'))\n\n # Drop extraneous row\n has_scenarios = True\n recorder_items = set(results_df.columns.get_level_values(0))\n if len(results_df.columns) == len(recorder_items):\n has_scenarios = False\n results_df.columns = results_df.columns.droplevel(1)\n\n columns = {}\n # nodes_of_type = {}\n for c in results_df.columns:\n res_name, attr = (c[0] if has_scenarios else c).split('/')\n if res_name in model.nodes:\n node = model.nodes[res_name]\n _type = type(node).__name__\n else:\n _type = 'Other'\n key = (_type, attr)\n if key in columns:\n columns[key].append(c)\n else:\n columns[key] = [c]\n # nodes_of_type[_type] = nodes_of_type.get(_type, []) + [node]\n\n for (_type, attr), cols in columns.items():\n if attr == 'elevation':\n unit = 'm'\n elif attr == 'energy':\n unit = 'MWh'\n else:\n unit = 'mcm'\n # file_path = os.path.join(results_path, '{}_{}_{}_{}'.format(_type, attr.title(), unit, file_suffix))\n file_name = '{}_{}_{}.csv'.format(_type, attr.title(), unit)\n file_path = os.path.join(results_path, file_name)\n df = results_df[cols]\n if has_scenarios:\n if disaggregate:\n scenario_set_names = []\n for scenario_idx, scenario_set in enumerate(scenario_names):\n scenario_set_names.append(list(set(df.columns.get_level_values(scenario_idx + 1))))\n scenario_combos = list(product(*scenario_set_names))\n for scenario_combo in scenario_combos:\n scenario_name = '__'.join(scenario_combo)\n scenario_path = os.path.join(results_path, scenario_name)\n if not os.path.exists(scenario_path):\n os.makedirs(scenario_path)\n\n _df = df.copy()\n for idx, scenario_set in enumerate(scenario_names):\n _df = _df.xs(scenario_combo[idx], axis=1, level=scenario_set, drop_level=True)\n file_path = os.path.join(scenario_path, file_name)\n _df.columns = [c.split('/')[0] for c in _df.columns]\n _df.to_csv(file_path)\n\n else:\n new_cols = [tuple([col[0].split('/')[0]] + list(col[1:])) for col in cols]\n df.columns = pd.MultiIndex.from_tuples(new_cols)\n df.columns.names = [\"node\"] + scenario_names\n df.to_csv(file_path)\n\n else:\n df.columns = [c.split('/')[0] for c in df.columns]\n df.to_csv(file_path)\n","sub_path":"sierra/utilities/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62559029","text":"import sys\nimport yaml\n\nfrom ..lexemes import Lexeme\nfrom ..grammar import Node\nfrom ..utils import first\n\n\nclass Converter(object):\n def __init__(self, lmdb, mdb, paradigms):\n self.lmdb_file = lmdb_file\n self.lmdb = lmdb\n self.mdb = mdb\n self.paradigms = paradigms\n\n def build_symbols(self):\n for node in self.mdb.fields:\n symbol = node.get('symbol')\n if symbol is not None:\n yield '' % (\n '\"%s\"' % node['symbol'], node['label']\n )\n else:\n yield '' % (\n '\"%s\"' % '', node['label']\n )\n\n for paradigm in self.paradigms:\n if paradigm['type'] == 'symbol':\n yield '' % (\n '\"%s\"' % paradigm['key'], paradigm['label']\n )\n\n def get_field_values(self, node, params):\n fields = []\n for node in node.fields:\n if 'code' in node:\n code = node['code']\n n = code - 4\n assert n < len(params), ('%s not in params: %r' % (n, params))\n value_node = self.get_node_by_field(\n node.get('fields', []), 'code', params[n]\n )\n assert value_node is not None, (\n '%s not in %r' % (params[n], node))\n fields.append((node, value_node))\n else:\n fields.extend(self.get_field_values(node, params))\n return fields\n\n def build_paradigms(self):\n paradigms = {\n p['key']: p for p in self.paradigms if 'key' in p\n }\n import pprint; pprint.pprint(paradigms)\n\n for i, line in enumerate(self.lmdb):\n line = line.strip()\n #if line.endswith('1 1 1 1 3 1 1 0 0 2 0 0 0 0 1 1 0 0 0 0'):\n if line.startswith('Adomas '):\n print(line)\n lexeme = Lexeme(self.mdb, line)\n\n pardefs = []\n for node in lexeme.properties:\n pardefs.extend(lexeme.get_pardefs(node))\n\n print(list(pardefs))\n\n for node in lexeme.nodes:\n parent = first(node.parents(code__isnull=False))\n print('{:2}: {}'.format(parent.code, parent.label))\n print(' {}: {}'.format(node.code, node.label[:72]))\n print()\n\n #for node in self.mdb.\n\n yield ''\n\n # \n #

    ingas

    \n #
    \n\n break\n\n def build_dix(self):\n yield ''\n yield ''\n\n yield ' AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽaąbcčdeęėfghiįyjklmnoprsštuųūvzž'\n\n yield ' '\n #for line in self.build_symbols():\n # yield ' ' + line\n yield ' '\n\n yield ' '\n for line in self.build_paradigms():\n yield ' ' + line\n yield ' '\n\n yield '
    '\n\n #for line in gen_entries(lmdb, ' '):\n # yield line\n\n yield '
    '\n\n yield '
    '\n","sub_path":"src/morfologija/converters/lttoolbox.py","file_name":"lttoolbox.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"369035019","text":"# An isogram is a word that has no repeating letters, consecutive or non-consecutive.\n# Implement a function that determines whether a string that contains only letters is an isogram.\n# Assume the empty string is an isogram. Ignore letter case.\n\n# is_isogram(\"Dermatoglyphics\" ) == true\n# is_isogram(\"aba\" ) == false\n# is_isogram(\"moOse\" ) == false # -- ignore letter case\n\n\n# def is_isogram(string):\n# st = string.lower()\n# check = list(set(st))\n# c = 0\n# for i in check:\n# st = st.replace(i, '', 1)\n# if i in st:\n# c += 1\n# if c != 0:\n# print(False)\n# else:\n# print(True)\n\n\n# Improved Version\ndef is_isogram(str):\n print(len(str) == len(set(str.lower())))\n\n\n\n# True\nis_isogram(\"Dermatoglyphics\")\n# True\nis_isogram(\"isogram\")\n# False, \"same chars may not be same case\"\nis_isogram(\"moOse\")\n# False\nis_isogram(\"isIsogram\")\n# False, \"same chars may not be adjacent\"\nis_isogram(\"aba\")\n# True, \"an empty string is a valid isogram\"\nis_isogram(\"\")","sub_path":"Coding/Competitive_Coding/CodeWars/Isograms.py","file_name":"Isograms.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423624993","text":"# Import relevant modules\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Planets:\n # Intialize important user-input information\n def __init__(self,filename,x,y):\n \n self.file = filename\n self.x = x\n self.y = y\n\n # Function to read text files\n def Read(self,filename):\n \n # Read and return data from NASA Exoplanet Archive of confirmed exoplanets\n data = np.genfromtxt(filename,dtype=None,delimiter=',',skip_header=96,names=True,invalid_raise=False,encoding=None)\n return data\n\n # Function to plot different planet properties vs. each other\n def Plot(self):\n\n # Save data using 'Read' function\n data = self.Read(self.file)\n \n if self.x == 'mass' and self.y == 'sma':\n xdata = data['pl_bmasse']\n ydata = data['pl_orbsmax']\n plt.scatter(xdata,ydata)\n\ntest = Planets('ConfirmedExoplanets.csv','mass','sma')\ntest.Plot()\n","sub_path":"HW1/Code/HW1Class.py","file_name":"HW1Class.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563499255","text":"import numpy as np\nfrom cyvlfeat.quickshift import quickshift\nfrom cyvlfeat.quickshift import flatmap\nfrom cyvlfeat.quickshift import imseg\n\n\ndef quickseg(image, ratio, kernel_size, max_dist):\n \"\"\"\n Produce a quickshift segmentation of a greyscale image.\n\n Parameters\n ----------\n image : [H, W] or [H, W, 1] `float64` `ndarray`\n Input image, Greyscale. A single channel, greyscale,\n `float64` numpy array (ndarray).\n ratio : `double`\n Trade-off between spatial consistency and color consistency.\n Small ratio gives more importance to the spatial component.\n Note that distance calculations happen in unnormalized image\n coordinates, so RATIO should be adjusted to compensate for\n larger images.\n kernel_size : `double`\n The standard deviation of the parzen window density estimator.\n max_dist : `double`\n The maximum distance between nodes in the quickshift tree. Used\n to cut links in the tree to form the segmentation.\n\n Returns\n -------\n i_seg :\n A color image where each pixel is labeled by the mean color in its\n region.\n labels : [H, W] `float64` `ndarray`.\n Array of the same size of image.\n A labeled image where the number corresponds to the cluster identity.\n maps : [H, W] `float64` `ndarray`.\n Array of the same size of image.\n `maps` as returned by `quickshift`: For each pixel, the pointer to the\n nearest pixel which increases the estimate of the density.\n gaps : [H, W] `float64` `ndarray`.\n Array of the same size of image.\n `gaps` as returned by `quickshift`: For each pixel, the distance to\n the nearest pixel which increases the estimate of the density.\n estimate : [H, W] `float64` `ndarray`.\n Array of the same size of image.\n `estimate` as returned by `quickshift`: The estimate of the density.\n \"\"\"\n\n # validate image\n if image.dtype != np.float64:\n raise ValueError('Image array must be of Double precision')\n # image = np.asarray(image, dtype=np.float64)\n\n # Add less than one pixel noise to break ties caused by\n # constant regions in an arbitrary fashions\n noise = np.random.random(image.shape) / 2250\n image += noise\n\n # For now we're dealing with Greyscale images only.\n if image.shape[2] == 1:\n imagex = ratio * image\n\n # Perform quickshift to obtain the segmentation tree, which is already cut by\n # maxdist. If a pixel has no nearest neighbor which increases the density, its\n # parent in the tree is itself, and gaps is inf.\n\n (maps, gaps, estimate) = quickshift(image, kernel_size, max_dist)\n\n # Follow the parents of the tree until we have reached the root nodes\n # mapped: a labeled segmentation where the labels are the indices of the modes\n # in the original image.\n # labels: mapped after having been renumbered 1: nclusters and reshaped into a\n # vector\n\n (mapped, labels) = flatmap(maps)\n labels = np.resize(labels, maps.shape)\n\n # imseg builds an average description of the region by color\n\n i_seg = imseg(image, labels)\n\n return i_seg, labels, maps, gaps, estimate\n","sub_path":"cyvlfeat/quickshift/quickseg.py","file_name":"quickseg.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445414707","text":"from tkinter import Tk, Label, PhotoImage\n\nraiz = Tk()\n\n#transforma GIF em formato que o tkinter pode exibir\nphoto = PhotoImage(file='minion.gif')\n\nminion = Label(master=raiz,\n\timage=photo,\n\twidth=1300,\n\theight=800)\n\nminion.pack()\ni = 0 \n\nwhile i<5:\n\ti+=1\n\tprint(i)\n\n#raiz.mainloop()\n","sub_path":"introducao_A_computacao/gui/peace.py","file_name":"peace.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467014035","text":"from django.shortcuts import render, redirect\nfrom django.conf import settings\nfrom django.http import HttpResponse, Http404, HttpResponseBadRequest, HttpResponseForbidden\nfrom django.views.generic import View\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.core.exceptions import ObjectDoesNotExist\n\nimport os\nimport json\n\nimport mturk.utils\nfrom .models import *\n\n\ndef home(request):\n need_annotating = Video.objects.filter(id__gt=0, verified=False)[:25]\n return render(request, 'video_list.html', context={\n 'videos': need_annotating,\n 'thumbnail': True,\n })\n\ndef verify_list(request):\n need_verification = Video.objects.filter(id__gt=0, verified=False).exclude(annotation='')[:100]\n return render(request, 'video_list.html', context={\n 'videos': need_verification,\n })\n\ndef next_unannotated(request, video_id):\n id = Video.objects.filter(id__gt=video_id, annotation='')[0].id\n return redirect('video', id)\n\n@xframe_options_exempt\ndef video(request, video_id):\n try:\n video = Video.objects.get(id=video_id)\n except Video.DoesNotExist:\n raise Http404('No video with id \"{}\". Possible fixes: \\n1) Download an up to date DB, see README. \\n2) Add this video to the DB via /admin'.format(video_id))\n\n mturk_data = mturk.utils.authenticate_hit(request)\n if 'error' in mturk_data:\n return HttpResponseForbidden(mturk_data['error'])\n if not (mturk_data['authenticated'] or request.user.is_authenticated()):\n return redirect('/login/?next=' + request.path)\n\n start_time = float(request.GET['s']) if 's' in request.GET else None\n end_time = float(request.GET['e']) if 'e' in request.GET else None\n\n video_data = json.dumps({\n 'id': video.id,\n 'location': video.url,\n 'annotated': video.annotation != '',\n 'verified': video.verified,\n 'start_time': start_time,\n 'end_time' : end_time,\n })\n\n response = render(request, 'video.html', context={\n 'video_data': video_data,\n 'mturk_data': mturk_data,\n 'iframe_mode': mturk_data['authenticated'],\n 'survey': False,\n })\n if not mturk_data['authenticated']:\n response['X-Frame-Options'] = 'SAMEORIGIN'\n return response\n\n\nclass AnnotationView(View):\n \n def get(self, request, video_id):\n video = Video.objects.get(id=video_id)\n return HttpResponse(video.annotation, content_type='application/json')\n \n def post(self, request, video_id):\n data = json.loads(request.body.decode('utf-8'))\n hit_id = data.get('hitId', None)\n if not (request.user.is_authenticated()):\n if not Task.valid_hit_id(hit_id):\n return HttpResponseForbidden('Not authenticated')\n else:\n try:\n worker_id = data.get('workerId', '')\n assignment_id = data.get('assignmentId', '')\n task = Task.get_by_hit_id(hit_id)\n task.complete(worker_id, assignment_id, data['metrics'])\n except ObjectDoesNotExist:\n if not settings.DEBUG:\n raise\n video = Video.objects.get(id=video_id)\n video.annotation = json.dumps(data['annotation'])\n video.save()\n return HttpResponse('success')\n\n\n@staff_member_required\ndef verify(request, video_id):\n body = request.body.decode('utf-8')\n video = Video.objects.get(id=video_id)\n if body == 'true':\n video.verified = True\n elif body == 'false':\n video.verified = False\n else:\n print(body)\n return HttpResponseBadRequest()\n video.save()\n return HttpResponse('video verification state saved')\n","sub_path":"annotator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"369889425","text":"import sys\nsys.stdin = open(\"2817.txt\")\n\n#6) 함수를 정의해줍니다. 함수의 진행 방식은\n#6-1) numbers의 0번 index부터 더한 뒤에 1, 2, ..., N번 index까지 탐색합니다.\n#6-2) 탐색하는 index의 방문 여부를 체크하고,\n#6-3) 현재까지 더한 값인 num과 지금 탐색 중인 numbers[index]의 값을 더했을 때 목표값 K를 넘지 않는지 체크합니다.\n#6-4) 6-3까지 조건을 통과했을 때 다시 함수로 진입합니다.\n#6-5) 중복을 제외하기 위해서 현재 index의 이전 index는 탐색하지 않아요\n#예) 0번 index부터 탐색해서 0 + 1 + 2의 결과를 얻었는데, 2번 index부터 탐색할 때 2 + 0 + 1을 보는 걸 제외\n#6-6) 모든 index를 탐색한 후에 현재까지 더한 값인 num이 목표값 K와 같다면 ans를 1 추가합니다.\n\n#6-7) idx: 함수에 들어가면서 탐색을 시작할 index, num: 탐색하면서 조건을 충족하면 더하는 값(K가 될 값)\ndef sumnum(idx, num):\n\n #7) ans가 함수 진행 중에 변경되기 때문에 global로 선언해요\n global ans\n\n #8) [6-5] 현재 탐색 중인 index 이전 index는 보지 않기 위해 range(idx, N)으로 설정해줍니다.\n for i in range(idx, N):\n\n #9) [6-2] for문에서 탐색 중인 index에 방문했는지 체크하고, [6-3] num과 numbers[index]의 합이 K를 넘는지 체크해요\n if visit[i] == False and num + numbers[i] <= K:\n\n #10) 조건을 충족하면 더해야 하는 값이기 때문에 \"함수에 들어가기 전\"에 방문 체크를 해줍니다\n visit[i] = True\n\n #11) [6-4] 함수에 다시 진입해요(0번 index부터 더하고, 현재 탐색 중인 index인 i, num과 numbers[index] 값을 넘겨주면서)\n sumnum(i, num + numbers[i])\n\n #12) 함수가 끝나고 나오면 방문 체크를 다시 풀어줍니다\n visit[i] = False\n\n #13) 마지막 index까지 탐색하고 나왔을 때의 num이 K와 같다면 ans를 +1 해줍니다\n if num == K:\n ans += 1\n return\n\n\nfor T in range(int(input())):\n #1) 숫자 개수 N, 더해야 하는 값 K를 input 받습니다.\n N, K = map(int, input().split())\n\n #2) 숫자 집합(numbers)을 input 받습니다.\n numbers = list(map(int, input().split()))\n\n #3) 같은 index의 숫자를 더하는 것을 방지하기 위해서 방문 체크 리스트를 만듭니다.\n visit = [False for _ in range(N)]\n\n #4) ans는 몇 개가 더해지는지 체크하는 변수입니다.\n ans = 0\n\n #5) 함수를 실행하는 구간입니다.\n sumnum(0, 0)\n\n print(f\"#{T + 1} {ans}\")","sub_path":"SWEA/2019/190510/2817.py","file_name":"2817.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90836975","text":"import pytest\n\n\ndef pytest_configure(config):\n backend = config.getoption(\"--backend\", \"suitesparse\")\n blocking = config.getoption(\"--blocking\", True)\n import grblas\n\n grblas.init(backend, blocking=blocking)\n print(f'Running tests with \"{backend}\" backend, blocking={blocking}')\n\n\ndef pytest_runtest_setup(item):\n if \"slow\" in item.keywords and not item.config.getoption(\"--runslow\", True): # pragma: no cover\n pytest.skip(\"need --runslow option to run\")\n","sub_path":"grblas/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192699448","text":"import logging\nimport socket\nimport datetime\nimport requests\ndatetime_object = datetime.datetime.now()\nprint(datetime_object.weekday())\n\nHOST='192.168.89.231'\nPORT=7083\n\nlogging.basicConfig(level=logging.DEBUG)\n_LOGGER = logging.getLogger(__name__)\n\n \ndef main():\n s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((HOST, PORT))\n\n temp = dict()\n temp['bathroom'] = read_temp(s, 25)\n temp['michal'] = read_temp(s, 27)\n temp['pawel'] = read_temp(s, 29)\n temp['salon'] = read_temp(s, 31)\n temp['bedroom'] = read_temp(s, 33)\n temp['date'] = datetime.datetime.now()\n requests.post('http://localhost:3001/newtemp', params=temp)\n\n\ndef read_temp(socket, zones):\n _LOGGER.debug(\"Send query temp: %s\", zones)\n data = generate_query(b'\\x7d' + zones.to_bytes(1,'big'))\n send_data(socket, data)\n data = read_data(socket)\n print_hex(data)\n temp = int.from_bytes(data[2:4], byteorder='big', signed=False)/2 - 55\n _LOGGER.debug(\"Read temp: %s -> %s oC\", zones, temp)\n return temp\n \ndef generate_query(command):\n \"\"\"Add header, checksum and footer to command data.\"\"\"\n data = bytearray(command)\n c = checksum(data)\n data.append(c >> 8)\n data.append(c & 0xFF)\n data.replace(b'\\xFE', b'\\xFE\\xF0')\n\n data = bytearray.fromhex(\"FEFE\") + data + bytearray.fromhex(\"FE0D\")\n return data\n \ndef checksum(command):\n \"\"\"Function to calculate checksum as per Satel manual.\"\"\"\n crc = 0x147A\n for b in command:\n # rotate (crc 1 bit left)\n crc = ((crc << 1) & 0xFFFF) | (crc & 0x8000) >> 15\n crc = crc ^ 0xFFFF\n crc = (crc + (crc >> 8) + b) & 0xFFFF\n return crc\n\n\ndef print_hex(data):\n \"\"\"Debugging method to print out frames in hex.\"\"\"\n hex_msg = \"\"\n for c in data:\n hex_msg += \"\\\\x\" + format(c, \"02x\")\n _LOGGER.debug(hex_msg)\n\ndef send_data(socket, data):\n _LOGGER.debug(\"-- Sending data --\")\n print_hex(data)\n _LOGGER.debug(\"Sending %d bytes...\", len(data))\n socket.send(data)\n\ndef read_data(socket):\n data=socket.recv(20)\n _LOGGER.debug(\"-- Received data --\")\n print_hex(data)\n _LOGGER.debug(\"Received %d bytes...\", len(data))\n return verify_and_strip(data)\n \ndef verify_and_strip(resp):\n \"\"\"Verify checksum and strip header and footer of received frame.\"\"\"\n if resp[0:2] != b'\\xFE\\xFE':\n _LOGGER.error(\"Houston, we got problem:\")\n print_hex(resp)\n raise Exception(\"Wrong header - got %X%X\" % (resp[0], resp[1]))\n if resp[-2:] != b'\\xFE\\x0D':\n raise Exception(\"Wrong footer - got %X%X\" % (resp[-2], resp[-1]))\n output = resp[2:-2].replace(b'\\xFE\\xF0', b'\\xFE')\n\n c = checksum(bytearray(output[0:-2]))\n\n if (256 * output[-2:-1][0] + output[-1:][0]) != c:\n raise Exception(\"Wrong checksum - got %d expected %d\" % (\n (256 * output[-2:-1][0] + output[-1:][0]), c))\n\n return output[0:-2]\n \nif __name__ == '__main__':\n main() \n","sub_path":"request_temp.py","file_name":"request_temp.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628266468","text":"import unittest\nimport sys\n\nundertest = __import__(sys.argv[-1].split(\".py\")[0])\ndistribui_alunos = getattr(undertest, 'distribui_alunos', None)\n\nclass PublicTests(unittest.TestCase):\n\n def test_semelhante_ao_da_prova_esq(self):\n t1 = [10,38,87,22,25]\n t2 = [43,21,96,33,85,17,94]\n assert distribui_alunos(t1, t2, 6) == [[10, 43, 38, 21, 87, 96], [22, 33, 25, 85, 17, 94]]\n\nif __name__ == '__main__':\n loader = unittest.TestLoader()\n runner = unittest.TextTestRunner()\n runner.run(loader.loadTestsFromModule(sys.modules[__name__]))\n","sub_path":"Unidade7/distribui_alunos/public_tests.py","file_name":"public_tests.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"142999942","text":"import requests\r\nimport logging\r\n\r\n\r\ntry:\r\n def js_minifier(file_name):\r\n \"\"\"js_minifier(file_name) : requires a valid file name or address\\n\r\n Returns : a new file with \"-min.js\" format in the same directory\"\"\"\r\n\r\n temp = file_name.split('.')\r\n new_file_name = temp[0]+\"-min.\"+temp[1]\r\n url = 'https://cssminifier.com/raw'\r\n data = {'input': open(file_name, 'r').read()}\r\n response = requests.post(url, data=data)\r\n f = open(new_file_name, \"w\")\r\n f.write(response.text)\r\n f.close()\r\n\r\n # Create and configure logger\r\n logging.basicConfig(filename=\"log.txt\",\r\n format='\\n%(asctime)s %(message)s',\r\n filemode='a')\r\n\r\n # Creating an object\r\n logger = logging.getLogger()\r\n\r\n file_name = 'style.css' # SET THE INPUT FILE NAME HERE\r\n\r\n js_minifier(file_name)\r\n\r\nexcept Exception as Argument:\r\n print(\"An error. Check log.txt\")\r\n logging.exception(\"Error Message:\")\r\n","sub_path":"css_minifier_script.py","file_name":"css_minifier_script.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"519579703","text":"#!/usr/bin/env python3\n\n# command line program\nimport argparse\n# deepcopy\nimport copy\n# numpy\nimport numpy as np\nimport scipy as sp\nimport scipy.optimize\n# internal modules\nimport libpost\n\ndef fit_func(x, a, b, c, d):\n return a + b * x + c * x**2 + d * x**3\n\ndef parse():\n parser = argparse.ArgumentParser(description='Computes the average velocity along a specific direction')\n parser.add_argument('--number-average', '-n', nargs='?', type=int, default=30, help='number of time steps for wich average quantities are computed, default: 30')\n return parser.parse_args()\n\ndef fit_func(t, d):\n return np.sqrt(6 * d * t)\n\ndef main(n_average):\n print(\"INFO: Post processing the dispersion.\", flush=True)\n print(\"INFO: Reading objects...\", flush=True)\n object_names = libpost.get_object_names()\n print(\"INFO: Done. Object names are:\", \" \".join(object_names), flush=True)\n print(\"INFO: Reading time...\", flush=True)\n time_dirs, time_list, time = libpost.get_time()\n average_time_steps = np.round(np.linspace(0, time.size-1, n_average)).astype(int)\n print(\"INFO: Done.\", flush=True)\n print(\"INFO: Processing init...\", flush=True)\n objects_pos_init = {}\n for name in object_names:\n obj = libpost.get_object(time_dirs[time_list.index(0.0)], name)\n pos_0 = libpost.get_object_properties(obj, [\"particle_.*__pos_0\"])[\"value\"]\n objects_pos_init[name] = np.empty((pos_0.size, 3))\n objects_pos_init[name][:, 0] = pos_0\n objects_pos_init[name][:, 1] = libpost.get_object_properties(obj, [\"particle_.*__pos_1\"])[\"value\"]\n objects_pos_init[name][:, 2] = libpost.get_object_properties(obj, [\"particle_.*__pos_2\"])[\"value\"]\n print(\"INFO: Done.\", flush=True)\n print(\"INFO: Processing effective velocity along axis...\", flush=True)\n objects_standard_deviation = {}\n for name in object_names:\n print(\"\\tINFO: Processing object {name}...\".format(name=name), flush=True)\n objects_standard_deviation[name] = np.empty((average_time_steps.shape[0], 3))\n for index in range(average_time_steps.size):\n t = time[average_time_steps[index]]\n print(\"\\t\\tINFO: Processing t={t}/{t_f}...\".format(t=t, t_f=time[-1]), flush=True)\n # read objects\n obj = libpost.get_object(time_dirs[time_list.index(t)], name)\n # effective velocity\n pos = np.empty(objects_pos_init[name].shape)\n pos[:, 0] = libpost.get_object_properties(obj, [\"particle_.*__pos_0\"])[\"value\"]\n pos[:, 1] = libpost.get_object_properties(obj, [\"particle_.*__pos_1\"])[\"value\"]\n pos[:, 2] = libpost.get_object_properties(obj, [\"particle_.*__pos_2\"])[\"value\"]\n objects_standard_deviation[name][index, :] = np.std(pos - objects_pos_init[name], axis=0)\n print(\"\\t\\tINFO: Done processing t={t}/{t_f}.\".format(t=t, t_f=time[-1]), flush=True)\n print(\"\\tDone processing object {name}.\".format(name=name), flush=True)\n print(\"INFO: Done.\", flush=True)\n print(\"INFO: Saving...\", flush=True)\n for name in object_names:\n np.savetxt(\"{name}__standard_deviation.csv\".format(name=name), np.column_stack((time[average_time_steps], objects_standard_deviation[name])), delimiter=\",\", header=\"time,std_x,std_y,std_z\")\n print(\"INFO: Done.\", flush=True)\n print(\"INFO: Computing diffusion coefficients...\", flush=True)\n merged_objects = {}\n for object_name in objects_standard_deviation:\n # compute diffusion coefficient by fitting\n diffusion_coefficient_x, cov = sp.optimize.curve_fit(fit_func, time[average_time_steps], objects_standard_deviation[object_name][:, 0])\n diffusion_coefficient_y, cov = sp.optimize.curve_fit(fit_func, time[average_time_steps], objects_standard_deviation[object_name][:, 1])\n diffusion_coefficient_z, cov = sp.optimize.curve_fit(fit_func, time[average_time_steps], objects_standard_deviation[object_name][:, 2])\n # merge\n reduced_object_name = object_name.split(\"__\")[0]\n if not reduced_object_name in merged_objects:\n merged_objects[reduced_object_name] = {}\n merged_objects[reduced_object_name][\"value\"] = [np.array(list(libpost.get_properties_from_string(object_name).values()) + list(diffusion_coefficient_x) + list(diffusion_coefficient_y) + list(diffusion_coefficient_z))]\n merged_objects[reduced_object_name][\"info\"] = list(libpost.get_properties_from_string(object_name).keys()) + [\"diffusion_coefficient_x,diffusion_coefficient_y,diffusion_coefficient_z\"]\n else:\n merged_objects[reduced_object_name][\"value\"].append(np.array(list(libpost.get_properties_from_string(object_name).values()) + list(diffusion_coefficient_x) + list(diffusion_coefficient_y) + list(diffusion_coefficient_z)))\n for reduced_object_name in merged_objects:\n merged_objects[reduced_object_name][\"value\"] = np.stack(merged_objects[reduced_object_name][\"value\"])\n for column in range(merged_objects[reduced_object_name][\"value\"].shape[1] - 3):\n merged_objects[reduced_object_name][\"value\"] = merged_objects[reduced_object_name][\"value\"][np.argsort(merged_objects[reduced_object_name][\"value\"][:, column])]\n print(\"INFO: Done.\", flush=True)\n print(\"INFO: Saving...\", flush=True)\n for name in merged_objects:\n np.savetxt(\"{name}__diffusion_coefficient.csv\".format(name=name), merged_objects[name][\"value\"], delimiter=\",\", header=\",\".join(merged_objects[name][\"info\"]))\n print(\"INFO: Done.\", flush=True)\n\nif __name__ == '__main__':\n args = parse()\n main(args.number_average)\n","sub_path":"modules/pyp0st/post_dispersion_plane.py","file_name":"post_dispersion_plane.py","file_ext":"py","file_size_in_byte":5616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288918947","text":"import numpy as np\r\nfrom sklearn import svm\r\nfrom sklearn import ensemble\r\nfrom json import load\r\nfrom pickle import dumps\r\nfrom time import time\r\n\r\ncenter = (1122, 984)\r\n\r\n#Makes radius feature from x,y coordinates\r\ndef rad_relation(obj_list):\r\n output = []\r\n for obj in obj_list:\r\n x = center[0] - obj[0]\r\n y = center[1] - obj[1]\r\n rad = int((x**2 + y**2)**(1/2))\r\n output.append([rad, obj[2], obj[3], obj[4]])\r\n return output\r\n\r\n#loading all json files into objects\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data\\\\background_data.json\", 'r') as ifile:\r\n background_obj = load(ifile)\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data\\\\black_data.json\", 'r') as ifile:\r\n black_obj = load(ifile)\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data\\\\brown_data.json\", 'r') as ifile:\r\n brown_obj = load(ifile)\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data1\\\\brown.json\", 'r') as ifile:\r\n brown_obj += load(ifile)\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data\\\\shadows_data.json\", 'r') as ifile:\r\n shadows_obj = load(ifile)\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data\\\\white_data.json\", 'r') as ifile:\r\n white_obj = load(ifile)\r\n\r\n#Taking about 2000 examples of each object class. \r\nX = rad_relation(background_obj)[::50]\r\nX += rad_relation(black_obj)[::3]\r\nX += rad_relation(brown_obj)[::8]\r\nX += rad_relation(shadows_obj)[::4]\r\nX += rad_relation(white_obj)[::2]\r\nX = np.array(X)\r\n\r\nX_test = rad_relation(background_obj)[1::50]\r\nX_test += rad_relation(black_obj)[1::3]\r\nX_test += rad_relation(brown_obj)[1::8]\r\nX_test += rad_relation(shadows_obj)[1::4]\r\nX_test += rad_relation(white_obj)[1::2]\r\nX_test = np.array(X_test)\r\n\r\n#Making target list (np.array)\r\ny = []\r\nfor _ in range(0, len(background_obj[::50])):\r\n y.append(1)\r\nfor _ in range(0, len(black_obj[::3])):\r\n y.append(2)\r\nfor _ in range(0, len(brown_obj[::8])):\r\n y.append(3)\r\nfor _ in range(0, len(shadows_obj[::4])):\r\n y.append(4)\r\nfor _ in range(0, len(white_obj[::2])):\r\n y.append(5)\r\ny = np.array(y)\r\n\r\ny_test = []\r\nfor _ in range(0, len(background_obj[1::50])):\r\n y_test.append(1)\r\nfor _ in range(0, len(black_obj[1::3])):\r\n y_test.append(2)\r\nfor _ in range(0, len(brown_obj[1::8])):\r\n y_test.append(3)\r\nfor _ in range(0, len(shadows_obj[1::4])):\r\n y_test.append(4)\r\nfor _ in range(0, len(white_obj[1::2])):\r\n y_test.append(5)\r\ny_test = np.array(y_test)\r\n\r\n#Create and train classifier. Dump classifier object into a file\r\nclf = svm.SVC(kernel='linear')\r\nstart = time()\r\nclf.fit(X, y)\r\nend = time()\r\nprint(clf.score(X_test, y_test))\r\ns = dumps(clf)\r\nwith open(\"C:\\\\Users\\\\JohnVR\\\\Desktop\\\\data1\\\\svm_linear4.pkl\", 'wb+') as ofile:\r\n ofile.write(s)\r\nprint(\"Time:\", end-start)","sub_path":"radius_trainer.py","file_name":"radius_trainer.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467684983","text":"\nimport os\nfrom flask import Flask, request\nimport base64\nimport pymongo\n\napp = Flask(__name__)\n\nuri = 'mongodb://'\n\n# Get report from `Buglife` and store to mongodb \n@app.route('/api/v1/reports', methods=['POST'])\ndef submit_report():\n data = request.json\n\n client = pymongo.MongoClient(uri, retryWrites=False)\n db = client.get_default_database()\n collection = db['reports']\n collection.insert_one(data)\n\n client.close()\n\n return '{\\\"success\\\": true}'\n\nif __name__ == '__main__':\n # Threaded option to enable multiple instances for multiple user access support\n app.run(threaded=True, port=5000)","sub_path":"Server/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"646091458","text":"from numpy import *\na=zeros((3,2))\nprint(a)\na1=zeros((3,2),dtype=int)\nprint(a1)\nprint(a[0][0])\nprint(a1[0][0])\nfor r in a1:\n for c in r:\n print(c)\n print()\nn=len(a)\nfor i in range(n):\n for j in range(len(a[i])):\n print('Index',i,j,\"=\",a[i])\n print()\nn1=len(a1)\ni=0\nwhile i 2:\n\t\tif year%4 == 0:\n\t\t\tif year%100 == 0:\n\t\t\t\tif year%400 == 0:\n\t\t\t\t\td = -1\n\t\t\t\telse: \n\t\t\t\t\td = -2\n\t\t\telse:\n\t\t\t\td = -1\n\t\telse:\n\t\t\td = -2\n\telse:\n\t\td = 0\n\te = day\n\trd = a+b+c+d+e\n\treturn rd\n","sub_path":"rd.py","file_name":"rd.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"215868717","text":"import asyncio\nimport hashlib\nimport os\nimport json\nfrom collections import defaultdict\nfrom subprocess import Popen\n\nimport websockets\n\n#modules that handle received messages\nimport core\nimport nwdb\nimport config\nimport mailqueue\nimport auth\nimport contacts\nimport inbox\nimport objects\nimport clan\nimport analytics\n\n\nclients = dict()\nrooms = defaultdict(set)\n\n\nclass AuthException(Exception):\n pass\n\n\nclass Client:\n def __init__(self, ws):\n self.session = {}\n self.ws = ws\n self.rooms = set()\n self.uid = hashlib.md5(os.urandom(8)).hexdigest()\n self.authenticated = False\n self.dead = False\n\n def require_auth(self):\n \"\"\"Raise exception if client is not authenticated\"\"\"\n if not self.authenticated:\n raise AuthException()\n\n @asyncio.coroutine\n def send(self, msg, *args):\n \"\"\"Send a msg to the client\"\"\"\n if self.dead: return\n payload = json.dumps(dict(name=msg, type=\"evt\", args=list(args)))\n print(\"> \" + payload)\n try:\n yield from self.ws.send(payload)\n except websockets.exceptions.InvalidState:\n print(\"InvalidState\", self.uid)\n yield from self.close()\n\n @asyncio.coroutine\n def whisper(self, uid, msg, *args):\n \"\"\"Send a msg directly to a connected user\"\"\"\n self.require_auth()\n c = clients[uid]\n yield from c.send(\"whispers\", msg, self.uid, *args)\n\n @asyncio.coroutine\n def say(self, room, msg, *args):\n \"\"\"Broadcast a msg to everyone in the room\"\"\"\n self.require_auth()\n for c in list(rooms[room]):\n yield from c.send(\"said\", msg, self.uid, room, *args)\n\n @asyncio.coroutine\n def join(self, name):\n \"\"\"Join a room\"\"\"\n self.require_auth()\n self.rooms.add(name)\n rooms[name].add(self)\n yield from self.send(\"dir\", name, list(i.uid for i in rooms[name]))\n yield from self.say(name, \"hello\")\n \n @asyncio.coroutine\n def leave(self, name):\n \"\"\"Leave a room\"\"\"\n self.require_auth()\n yield from self.say(name, \"bye\")\n self.rooms.remove(name)\n rooms[name].remove(self)\n\n @asyncio.coroutine\n def close(self):\n self.dead = True\n clients.pop(self.uid)\n for r in list(self.rooms):\n yield from self.leave(r)\n\n@asyncio.coroutine\ndef close():\n for c in list(clients.values()):\n yield from c.ws.close()\n\n@asyncio.coroutine\ndef server(ws, path):\n client = Client(ws)\n clients[client.uid] = client \n yield from client.send(\"welcome\", client.uid)\n while not client.dead:\n msg = yield from ws.recv()\n if msg is None: break\n try:\n obj = json.loads(msg)\n except ValueError:\n break\n print(\"< \" + str(obj))\n mType = obj[\"type\"]\n try:\n if mType == \"evt\":\n yield from handle_event(client, obj)\n if mType == \"fn\":\n yield from handle_function(client, obj)\n except AuthException:\n yield from client.send(\"unauthorized\")\n except Exception as e:\n print(type(e), str(e))\n yield from client.send(\"exception\", obj, str(type(e).__name__), str(e))\n\n yield from client.close()\n\n@asyncio.coroutine\ndef handle_function(client, msg):\n name = msg[\"name\"]\n args = msg[\"args\"]\n mID = msg[\"id\"]\n result = yield from core.function_handlers[name](client, *args)\n yield from client.send(\"return\", mID, result)\n\n@asyncio.coroutine\ndef handle_event(client, msg):\n name = msg[\"name\"]\n args = msg[\"args\"]\n if name == \"join\":\n yield from client.join(args[0])\n elif name == \"leave\":\n yield from client.leave(args[0])\n elif name == \"say\":\n yield from client.say(args[0], args[1], *args[2:])\n elif name == \"whisper\":\n yield from client.whisper(args[0], args[1], *args[2:])\n else: \n yield from core.event_handlers[name](client, *args)\n\n\n\n","sub_path":"netwrok/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"230280747","text":"\"\"\"\nImaginative Walk Scripts for ablation study\nCreated by Kai Yi on May, 23.\nContact email: williamyi96@gmail.com\nALL RIGHT RESERVED.\n\"\"\"\n\nimport os\nimport random\nimport argparse\n\n\ndef read_args() -> argparse.Namespace:\n parser = argparse.ArgumentParser('Running LLL trainer')\n parser.add_argument('-n', '--num_runs', default=3, type=int, help='Number of runs for each experimental setup')\n parser.add_argument('-d', '--dataset', type=str, help='Which dataset to run on?', default='PACS')\n parser.add_argument('-m', '--method', type=str, help='Which method to run?', default='CuMix')\n parser.add_argument('--trainer', type=str, default='/ibex/scratch/yik/rwzsl/train_extp.py')\n parser.add_argument('--root_dir', type=str, default='/ibex/scratch/yik/rwzsl')\n parser.add_argument('--gzsl', action='store_true', help='DZSL experiment or DGZSL experiment?')\n parser.add_argument('--text_dataset', '-td', action='store_true')\n return parser.parse_args()\n\n\ndef main(args):\n # Ablations on iddferent interpolation and extrapolations\n EXTPS = [0, 1, 2, 3, 4]\n CUB_EASY_BEST_CONFIG = './configs/CUB_easy_Best_HPs.yml'\n CUB_HARD_BEST_CONFIG = './configs/CUB_hard_Best_HPs.yml'\n CONFIGS = {'easy': CUB_EASY_BEST_CONFIG,\n 'hard': CUB_HARD_BEST_CONFIG}\n SPLITMODE = ['easy', 'hard']\n\n trainer = '/ibex/scratch/yik/rwzsl/train_extp.py'\n i = 0\n for r in range(1, args.num_runs+1):\n for extp in EXTPS:\n for splitmode in SPLITMODE:\n job_name = f'grawd_cub_{splitmode}_r{r}_extp{extp}_{i}'\n out_name = f'grawd_cub_{splitmode}_r{r}_extp{extp}_{i}.out'\n err_name = f'grawd_cub_{splitmode}_r{r}_extp{extp}_{i}.err'\n\n slurm_script = f'{args.root_dir}/scripts/slurm.sh'\n cli_args = f' --dataset CUB --splitmode {splitmode} --exp_name {job_name} --rw_config_path {CONFIGS[splitmode]} --extp {extp}'\n\n command = f'sbatch -J {job_name} -o {out_name} -e {err_name} ' \\\n f'--export=ALL,cli_args=\"{trainer} {cli_args}\" {slurm_script}'\n os.system(command)\n i += 1\n\n # Ablations on gamma, exponential decay\n CONFIG_NO = [1, 2, 3, 4]\n trainer = '/ibex/scratch/yik/rwzsl/train_gamma_abs.py'\n for r in range(1, args.num_runs+1):\n for config in CONFIG_NO:\n for splitmode in SPLITMODE:\n job_name = f'grawd_cub_{splitmode}_r{r}_exp_decay{config}_{i}'\n out_name = f'grawd_cub_{splitmode}_r{r}_exp_decay{config}_{i}.out'\n err_name = f'grawd_cub_{splitmode}_r{r}_exp_decay{config}_{i}.err'\n\n slurm_script = f'{args.root_dir}/scripts/slurm.sh'\n\n config_path = f'./configs/CUB_{splitmode}_Best_HPs_{config}.yml'\n\n cli_args = f' --dataset CUB --splitmode {splitmode} --exp_name {job_name} --rw_config_path {config_path}'\n\n command = f'sbatch -J {job_name} -o {out_name} -e {err_name} ' \\\n f'--export=ALL,cli_args=\"{trainer} {cli_args}\" {slurm_script}'\n os.system(command)\n i += 1\n\n\nif __name__ == \"__main__\":\n args = read_args()\n main(args=args)\n","sub_path":"scripts/batch_runs_bhps.py","file_name":"batch_runs_bhps.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578461651","text":"# Copyright 2018 Northern.tech AS\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport pytest\n\nfrom common import clean_db, mongo, management_api, clean_migrated_db, devices, device_api, cli, \\\ntenant_foobar, tenant_foobar_devices, tenant_foobar_clean_migrated_db\n\nfrom cryptutil import compare_keys\n\nimport json\nimport bravado\n\n\nclass TestManagementPreauthorizeBase:\n def _test_ok(self, management_api, devices, **kwargs):\n aid = '1'\n device_id = '2'\n key = '''-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzogVU7RGDilbsoUt/DdH\nVJvcepl0A5+xzGQ50cq1VE/Dyyy8Zp0jzRXCnnu9nu395mAFSZGotZVr+sWEpO3c\nyC3VmXdBZmXmQdZqbdD/GuixJOYfqta2ytbIUPRXFN7/I7sgzxnXWBYXYmObYvdP\nokP0mQanY+WKxp7Q16pt1RoqoAd0kmV39g13rFl35muSHbSBoAW3GBF3gO+mF5Ty\n1ddp/XcgLOsmvNNjY+2HOD5F/RX0fs07mWnbD7x+xz7KEKjF+H7ZpkqCwmwCXaf0\niyYyh1852rti3Afw4mDxuVSD7sd9ggvYMc0QHIpQNkD4YWOhNiE1AB0zH57VbUYG\nUwIDAQAB\n-----END PUBLIC KEY-----\n'''\n iddata = '{\"foo\":\"bar\"}'\n\n req = management_api.make_preauth_req(aid, device_id, iddata, key)\n _, rsp = management_api.preauthorize(req, **kwargs)\n assert rsp.status_code == 201\n\n devs = management_api.list_devices(**kwargs)\n assert len(devs) == 6\n\n found = [d for d in devs if d.id == device_id]\n assert len(found) == 1\n\n found = found[0]\n assert found.id == device_id\n assert found.id_data == iddata\n assert len(found.auth_sets) == 1\n\n auth_set = found.auth_sets[0]\n assert auth_set.id == aid\n assert auth_set.id_data == iddata\n assert compare_keys(auth_set.pubkey, key)\n assert auth_set.status == 'preauthorized'\n\n def _test_bad_key(self, management_api, devices, **kwargs):\n aid = '1'\n device_id = '2'\n key = '''-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzogVU7RGDilbsoUt/DdH\nVJvcepl0A5+xzGQ50cq1VE/Dyyy8Zp0jzRXCnnu9nu395mAFSZGotZVr+sWEpO3c\nyC3VmXdBZmXmQdZqbdD/GuixJOYfqta2ytbIUPRXFN7/I7sgzxnXWBYXYmObYvdP\nokP0mQanY+WKxp7Q16pt1RoqoAd0kmV39g13rFl35muSHbSBoAW3GBF3gO+mF5Ty\n1ddp/XcgLOsmvNNjY+2HOD5F/RX0fs07mWnbD7x+xz7KEKjF+H7ZpkqCwmwCXaf0\niyYyh1852rti3Afw4mDxuVSD7sd9ggvYMc0QHIpQNkD4YWOhNiE1AB0zH57VbUYG\nUwIDAQAB\n'''\n iddata = '{\"foo\":\"bar\"}'\n\n req = management_api.make_preauth_req(aid, device_id, iddata, key)\n\n try:\n _, rsp = management_api.preauthorize(req, **kwargs)\n except bravado.exception.HTTPError as e:\n assert e.status_code == 400\n assert e.swagger_result.error == 'failed to decode preauth request: cannot decode public key'\n\n def _test_conflict(self, management_api, devices, **kwargs):\n existing = devices[0][0]\n req = management_api.make_preauth_req('1', '2', existing.identity, existing.public_key)\n try:\n _, rsp = management_api.preauthorize(req, **kwargs)\n except bravado.exception.HTTPError as e:\n assert e.response.status_code == 409\n else:\n assert False, \"unexpected code \" + str(rsp.status_code)\n\n devs = management_api.list_devices(**kwargs)\n assert len(devs) == 5\n\nclass TestManagementPreauthorize(TestManagementPreauthorizeBase):\n @pytest.mark.parametrize('devices', ['5'], indirect=True)\n def test_ok(self, management_api, devices):\n self._test_ok(management_api, devices)\n\n @pytest.mark.parametrize('devices', ['5'], indirect=True)\n def test_conflict(self, management_api, devices):\n self._test_conflict(management_api, devices)\n\n @pytest.mark.parametrize('devices', ['5'], indirect=True)\n def test_bad_key(self, management_api, devices):\n self._test_bad_key(management_api, devices)\n\nclass TestManagementPreauthorizeMultiTenant(TestManagementPreauthorizeBase):\n @pytest.mark.parametrize('tenant_foobar_devices', ['5'], indirect=True)\n def test_ok(self, management_api, tenant_foobar_devices, tenant_foobar):\n auth = 'Bearer ' + tenant_foobar\n self._test_ok(management_api, tenant_foobar_devices, Authorization=auth)\n\n @pytest.mark.parametrize('tenant_foobar_devices', ['5'], indirect=True)\n def test_conflict(self, management_api, tenant_foobar_devices, tenant_foobar):\n auth = 'Bearer ' + tenant_foobar\n self._test_conflict(management_api, tenant_foobar_devices, Authorization=auth)\n\n @pytest.mark.parametrize('tenant_foobar_devices', ['5'], indirect=True)\n def test_bad_key(self, management_api, tenant_foobar_devices, tenant_foobar):\n auth = 'Bearer ' + tenant_foobar\n self._test_bad_key(management_api, tenant_foobar_devices, Authorization=auth)\n","sub_path":"tests/tests/test_preauth.py","file_name":"test_preauth.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"437364356","text":"'''\nprint text\ncalculation\nvariables\n'''\n\nname = \"christophe\"\nprint(name)\n\ngetal1 = 2\ngetal2 = 3\nsom = getal1 + getal2\nprint(\"{0} + {1} = {2}\".format(getal1, getal2, som))\n\n#ask for user input\nname = input(\"Your name: \")\nage = input(\"Your age: \")\nprint(\"You are {} and you are {} years old\".format(name, age))","sub_path":"src/001basics.py","file_name":"001basics.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191584113","text":"\"\"\"Script to convert the outputs of Redshift queries into different formats.\"\"\"\n\nimport argparse\nimport gzip\nimport json\nimport os\nimport shutil\nimport sys\nimport zipfile\n\nimport loompy\nimport pandas\nimport s3fs\n\nfrom matrix.common import constants\nfrom matrix.common import date\nfrom matrix.common.logging import Logging\nfrom matrix.common.constants import MatrixFormat\nfrom matrix.common.request.request_tracker import RequestTracker, Subtask\n\nLOGGER = Logging.get_logger(__file__)\nSUPPORTED_FORMATS = [item.value for item in MatrixFormat]\n\n\nclass MatrixConverter:\n\n def __init__(self, args):\n self.args = args\n self.format = args.format\n self.request_tracker = RequestTracker(args.request_id)\n self.expression_manifest = None\n self.cell_manifest = None\n self.gene_manifest = None\n\n self.local_output_filename = os.path.basename(os.path.normpath(args.target_path))\n self.target_path = args.target_path\n self.working_dir = args.working_dir\n self.FS = s3fs.S3FileSystem()\n\n Logging.set_correlation_id(LOGGER, value=args.request_id)\n\n def run(self):\n try:\n LOGGER.debug(f\"Beginning matrix conversion run for {self.args.request_id}\")\n self.expression_manifest = self._parse_manifest(self.args.expression_manifest_key)\n self.cell_manifest = self._parse_manifest(self.args.cell_metadata_manifest_key)\n self.gene_manifest = self._parse_manifest(self.args.gene_metadata_manifest_key)\n\n LOGGER.debug(f\"Beginning conversion to {self.format}\")\n local_converted_path = getattr(self, f\"_to_{self.format}\")()\n LOGGER.debug(f\"Conversion to {self.format} completed\")\n\n LOGGER.debug(f\"Beginning upload to S3\")\n self._upload_converted_matrix(local_converted_path, self.target_path)\n LOGGER.debug(\"Upload to S3 complete, job finished\")\n\n os.remove(local_converted_path)\n\n self.request_tracker.complete_subtask_execution(Subtask.CONVERTER)\n self.request_tracker.complete_request(duration=(date.get_datetime_now() -\n date.to_datetime(self.request_tracker.creation_date))\n .total_seconds())\n except Exception as e:\n LOGGER.info(f\"Matrix Conversion failed on {self.args.request_id} with error {str(e)}\")\n self.request_tracker.log_error(str(e))\n raise e\n\n def _parse_manifest(self, manifest_key):\n \"\"\"Parse a manifest file produced by a Redshift UNLOAD query.\n\n Args:\n manifest_key: S3 location of the manifest file.\n\n Returns:\n dict with three keys:\n \"columns\": the column headers for the tables\n \"part_urls\": full S3 urls for the files containing results from each\n Redshift slice\n \"record_count\": total number of records returned by the query\n \"\"\"\n manifest = json.load(self.FS.open(manifest_key))\n\n return {\n \"columns\": [e[\"name\"] for e in manifest[\"schema\"][\"elements\"]],\n \"part_urls\": [e[\"url\"] for e in manifest[\"entries\"] if e[\"meta\"][\"record_count\"]],\n \"record_count\": manifest[\"meta\"][\"record_count\"]\n }\n\n def _n_slices(self):\n \"\"\"Return the number of slices associated with this Redshift result.\n\n Redshift UNLOAD creates on object per \"slice\" of the cluster. We might want to\n iterate over that, so this get the count of them.\n \"\"\"\n return len(self.cell_manifest[\"part_urls\"])\n\n def _load_cell_table_slice(self, slice_idx):\n \"\"\"Load the cell metadata table from a particular result slice.\n\n Args:\n slice_idx: Index of the slice to get cell metadata for\n\n Returns:\n dataframe of cell metadata. Index is \"cellkey\" and other columns are metadata\n fields.\n \"\"\"\n\n cell_table_columns = self._map_columns(self.cell_manifest[\"columns\"])\n cell_table_dtype = {c: \"category\" for c in cell_table_columns}\n cell_table_dtype[\"genes_detected\"] = \"uint32\"\n cell_table_dtype[\"cellkey\"] = \"object\"\n\n part_url = self.cell_manifest[\"part_urls\"][slice_idx]\n df = pandas.read_csv(\n part_url, sep='|', header=None, names=cell_table_columns,\n dtype=cell_table_dtype, true_values=[\"t\"], false_values=[\"f\"],\n index_col=\"cellkey\")\n\n return df\n\n def _load_gene_table(self):\n \"\"\"Load the gene metadata table.\n\n Returns:\n dataframe of gene metadata. Index is \"featurekey\"\n \"\"\"\n\n gene_table_columns = self._map_columns(self.gene_manifest[\"columns\"])\n\n dfs = []\n for part_url in self.gene_manifest[\"part_urls\"]:\n df = pandas.read_csv(part_url, sep='|', header=None, names=gene_table_columns,\n true_values=[\"t\"], false_values=[\"f\"],\n index_col=\"featurekey\")\n\n dfs.append(df)\n return pandas.concat(dfs)\n\n def _load_expression_table_slice(self, slice_idx, chunksize=1000000):\n \"\"\"Load expression data from a slice, yielding the data by a fixed number\n of rows.\n\n Args:\n slice_idx: Index of the slice to get data for\n chunksize: Number of rows to yield at once\n\n Yields:\n dataframe of expression data\n \"\"\"\n\n part_url = self.expression_manifest[\"part_urls\"][slice_idx]\n expression_table_columns = [\"cellkey\", \"featurekey\", \"exprvalue\"]\n expression_dtype = {\"cellkey\": \"object\", \"featurekey\": \"object\", \"exprvalue\": \"float32\"}\n\n # Iterate over chunks of the remote file. We have to set a fixed set\n # number of rows to read, but we also want to make sure that all the\n # rows from a given cell are yielded with each chunk. So we are going\n # to keep track of the \"remainder\", rows from the end of a chunk for a\n # cell the spans a chunk boundary.\n remainder = None\n for chunk in pandas.read_csv(\n part_url, sep=\"|\", names=expression_table_columns,\n dtype=expression_dtype, header=None, chunksize=chunksize):\n\n # If we have some rows from the previous chunk, prepend them to\n # this one\n if remainder is not None:\n adjusted_chunk = pandas.concat([remainder, chunk], axis=0, copy=False)\n else:\n adjusted_chunk = chunk\n\n # Now get the rows for the cell at the end of this chunk that spans\n # the boundary. Remove them from the chunk we yield, but keep them\n # in the remainder.\n last_cellkey = adjusted_chunk.tail(1).cellkey.values[0]\n remainder = adjusted_chunk.loc[adjusted_chunk['cellkey'] == last_cellkey]\n adjusted_chunk = adjusted_chunk[adjusted_chunk.cellkey != last_cellkey]\n\n yield adjusted_chunk\n\n if remainder is not None:\n yield remainder\n\n def _map_columns(self, cols):\n return [constants.TABLE_COLUMN_TO_METADATA_FIELD[col]\n if col in constants.TABLE_COLUMN_TO_METADATA_FIELD else col\n for col in cols]\n\n def _to_mtx(self):\n \"\"\"Write a zip file with an mtx and two metadata tsvs from Redshift query\n manifests.\n\n Returns:\n output_path: Path to the zip file.\n \"\"\"\n # Add zip to the output filename and create the directory where we will\n # write output files.\n if not self.local_output_filename.endswith(\".zip\"):\n self.local_output_filename += \".zip\"\n results_dir = os.path.join(self.working_dir,\n os.path.splitext(self.local_output_filename)[0])\n os.makedirs(results_dir)\n\n # Load the gene metadata and write it out to a tsv\n gene_df = self._load_gene_table()\n gene_df.to_csv(os.path.join(results_dir, \"genes.tsv.gz\"), index_label=\"featurekey\",\n sep=\"\\t\", compression=\"gzip\")\n cell_df = pandas.concat([self._load_cell_table_slice(s) for s in range(self._n_slices())], copy=False)\n\n # To follow 10x conventions, features are rows and cells are columns\n n_rows = gene_df.shape[0]\n n_cols = cell_df.shape[0]\n n_nonzero = self.expression_manifest[\"record_count\"]\n\n cellkeys = []\n\n with gzip.open(os.path.join(results_dir, \"matrix.mtx.gz\"), \"w\", compresslevel=4) as exp_f:\n # Write the mtx header\n exp_f.write(\"%%MatrixMarket matrix coordinate real general\\n\".encode())\n exp_f.write(f\"{n_rows} {n_cols} {n_nonzero}\\n\".encode())\n\n cell_count = 0\n for slice_idx in range(self._n_slices()):\n for chunk in self._load_expression_table_slice(slice_idx):\n\n grouped = chunk.groupby(\"cellkey\")\n for cell_group in grouped:\n single_cell_df = cell_group[1]\n single_cell_coo = single_cell_df.pivot(\n index=\"featurekey\", columns=\"cellkey\", values=\"exprvalue\").reindex(\n index=gene_df.index).to_sparse().to_coo()\n\n for row, col, value in zip(single_cell_coo.row, single_cell_coo.col, single_cell_coo.data):\n exp_f.write(f\"{row+1} {col+cell_count+1} {value}\\n\".encode())\n cell_count += 1\n\n cellkeys.append(cell_group[0])\n\n cell_df = cell_df.reindex(index=cellkeys)\n cell_df.to_csv(os.path.join(results_dir, \"cells.tsv.gz\"), sep='\\t',\n index_label=\"cellkey\", compression=\"gzip\")\n\n # Create a zip file out of the three written files.\n zipf = zipfile.ZipFile(os.path.join(self.working_dir, self.local_output_filename), 'w')\n zipf.write(os.path.join(results_dir, \"genes.tsv.gz\"),\n arcname=os.path.join(os.path.basename(results_dir), \"genes.tsv.gz\"))\n zipf.write(os.path.join(results_dir, \"matrix.mtx.gz\"),\n arcname=os.path.join(os.path.basename(results_dir), \"matrix.mtx.gz\"))\n zipf.write(os.path.join(results_dir, \"cells.tsv.gz\"),\n arcname=os.path.join(os.path.basename(results_dir), \"cells.tsv.gz\"))\n zipf.write(\"mtx_readme.md\")\n zipf.close()\n\n shutil.rmtree(results_dir)\n\n return os.path.join(self.working_dir, self.local_output_filename)\n\n def _to_loom(self):\n \"\"\"Write a loom file from Redshift query manifests.\n\n Returns:\n output_path: Path to the new loom file.\n \"\"\"\n\n # Put loom on the output filename if it's not already there.\n if not self.local_output_filename.endswith(\".zip\"):\n self.local_output_filename += \".zip\"\n\n loom_filename = self.local_output_filename.rstrip(\".zip\")\n\n # Read the row (gene) attributes and then set some conventional names\n gene_df = self._load_gene_table()\n gene_df[\"featurekey\"] = gene_df.index\n row_attrs = gene_df.to_dict(\"series\")\n # Not expected to be unique\n row_attrs[\"Gene\"] = row_attrs.pop(\"featurename\")\n row_attrs[\"Accession\"] = row_attrs.pop(\"featurekey\")\n for key, val in row_attrs.items():\n row_attrs[key] = val.values\n\n loom_parts = []\n loom_part_dir = os.path.join(self.working_dir, \".loom_parts\")\n\n if os.path.exists(loom_part_dir):\n shutil.rmtree(loom_part_dir)\n\n os.makedirs(loom_part_dir)\n\n # Iterate over the \"slices\" produced by the redshift query\n for slice_idx in range(self._n_slices()):\n\n # Get the cell metadata for all the cells in this slice\n cell_df = self._load_cell_table_slice(slice_idx)\n\n # Iterate over fixed-size chunks of expression data from this\n # slice.\n chunk_idx = 0\n for chunk in self._load_expression_table_slice(slice_idx):\n print(f\"Loading chunk {chunk_idx} from slice {slice_idx}\")\n sparse_cell_dfs = []\n\n # Group the data by cellkey and iterate over each cell\n grouped = chunk.groupby(\"cellkey\")\n for cell_group in grouped:\n single_cell_df = cell_group[1]\n\n # Reshape the dataframe so cellkey is a column and features\n # are rows. Reindex so all dataframes have the same row\n # order, and then sparsify because this is a very empty\n # dataset usually.\n sparse_cell_dfs.append(\n single_cell_df.pivot(\n index=\"featurekey\", columns=\"cellkey\", values=\"exprvalue\")\n .reindex(index=row_attrs[\"Accession\"]).to_sparse())\n\n # Concatenate the cell dataframes together. This is what we'll\n # write to disk.\n if not sparse_cell_dfs:\n continue\n sparse_expression_matrix = pandas.concat(sparse_cell_dfs, axis=1, copy=True)\n\n # Get the cell metadata dataframe for just the cell in this\n # chunk\n chunk_cell_df = cell_df.reindex(index=sparse_expression_matrix.columns)\n chunk_cell_df[\"cellkey\"] = chunk_cell_df.index\n for col in chunk_cell_df.columns:\n if chunk_cell_df[col].dtype.name == \"category\":\n chunk_cell_df[col] = chunk_cell_df[col].astype(\"object\")\n col_attrs = chunk_cell_df.to_dict(\"series\")\n col_attrs[\"CellID\"] = col_attrs.pop(\"cellkey\")\n\n # Just a thing you have to do...\n for key, val in col_attrs.items():\n col_attrs[key] = val.values\n\n # Write the data from this chunk to its own file.\n loom_part_path = os.path.join(loom_part_dir,\n f\"matrix.{slice_idx}.{chunk_idx}.loom\")\n print(f\"Writing to {loom_part_path}\")\n loompy.create(\n loom_part_path, sparse_expression_matrix.to_coo(), row_attrs, col_attrs)\n loom_parts.append(loom_part_path)\n chunk_idx += 1\n\n # Using the loompy method, combine all the chunks together into a\n # single file.\n print(f\"Parts complete. Writing to {loom_filename}\")\n loompy.combine(loom_parts,\n key=\"Accession\",\n output_file=os.path.join(self.working_dir, loom_filename))\n shutil.rmtree(loom_part_dir)\n\n zipf = zipfile.ZipFile(os.path.join(self.working_dir, self.local_output_filename), 'w')\n zipf.write(os.path.join(self.working_dir, loom_filename),\n arcname=loom_filename)\n zipf.write(\"loom_readme.md\")\n zipf.close()\n\n return os.path.join(self.working_dir, self.local_output_filename)\n\n def _to_csv(self):\n \"\"\"Write a zip file with csvs from Redshift query manifests and readme.\n\n Returns:\n output_path: Path to the new zip file.\n \"\"\"\n\n if not self.local_output_filename.endswith(\".zip\"):\n self.local_output_filename += \".zip\"\n\n results_dir = os.path.join(self.working_dir,\n os.path.splitext(self.local_output_filename)[0])\n os.makedirs(results_dir)\n\n gene_df = self._load_gene_table()\n gene_df.to_csv(os.path.join(results_dir, \"genes.csv\"), index_label=\"featurekey\")\n\n cellkeys = []\n with open(os.path.join(results_dir, \"expression.csv\"), \"w\") as exp_f:\n # Write the CSV's header\n gene_index_string_list = [str(x) for x in gene_df.index.tolist()]\n exp_f.write(','.join([\"cellkey\"] + gene_index_string_list))\n exp_f.write('\\n')\n\n for slice_idx in range(self._n_slices()):\n for chunk in self._load_expression_table_slice(slice_idx):\n # Group the data by cellkey and iterate over each cell\n grouped = chunk.groupby(\"cellkey\")\n for cell_group in grouped:\n single_cell_df = cell_group[1]\n single_cell_df.pivot(\n index=\"cellkey\", columns=\"featurekey\", values=\"exprvalue\").reindex(\n columns=gene_df.index).to_csv(exp_f, header=False, na_rep='0')\n cellkeys.append(cell_group[0])\n\n cell_df = pandas.concat([self._load_cell_table_slice(s) for s in range(self._n_slices())], copy=False)\n cell_df = cell_df.reindex(index=cellkeys)\n cell_df.to_csv(os.path.join(results_dir, \"cells.csv\"), index_label=\"cellkey\")\n\n zipf = zipfile.ZipFile(os.path.join(self.working_dir, self.local_output_filename), 'w', zipfile.ZIP_DEFLATED)\n zipf.write(os.path.join(results_dir, \"genes.csv\"),\n arcname=os.path.join(os.path.basename(results_dir), \"genes.csv\"))\n zipf.write(os.path.join(results_dir, \"expression.csv\"),\n arcname=os.path.join(os.path.basename(results_dir), \"expression.csv\"))\n zipf.write(os.path.join(results_dir, \"cells.csv\"),\n arcname=os.path.join(os.path.basename(results_dir), \"cells.csv\"))\n zipf.write(\"csv_readme.md\")\n zipf.close()\n\n shutil.rmtree(results_dir)\n\n return os.path.join(self.working_dir, self.local_output_filename)\n\n def _upload_converted_matrix(self, local_path, remote_path):\n \"\"\"\n Upload the converted matrix to S3.\n Parameters\n ----------\n local_path : str\n Path to the new, converted matrix file\n remote_path : str\n S3 path where the converted matrix will be uploaded\n \"\"\"\n self.FS.put(local_path, remote_path)\n\n\ndef main(args):\n \"\"\"Entry point.\"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"request_id\",\n help=\"ID of the request associated with this conversion.\")\n parser.add_argument(\"expression_manifest_key\",\n help=\"S3 url to Redshift manifest for the expression table.\")\n parser.add_argument(\"cell_metadata_manifest_key\",\n help=\"S3 url to Redshift manifest for the cell table.\")\n parser.add_argument(\"gene_metadata_manifest_key\",\n help=\"S3 url to Redshift manifest for the gene table.\")\n parser.add_argument(\"target_path\",\n help=\"S3 prefix where the file should be written.\")\n parser.add_argument(\"format\",\n help=\"Target format for conversion\",\n choices=SUPPORTED_FORMATS)\n parser.add_argument(\"working_dir\",\n help=\"Directory to write local files.\")\n args = parser.parse_args(args)\n LOGGER.debug(\n f\"Starting matrix conversion job with parameters: \"\n f\"{args.expression_manifest_key}, {args.cell_metadata_manifest_key}, \"\n f\"{args.gene_metadata_manifest_key}, {args.target_path}, {args.format}\")\n\n matrix_converter = MatrixConverter(args)\n matrix_converter.run()\n\nif __name__ == \"__main__\":\n print(f\"STARTED with argv: {sys.argv}\")\n main(sys.argv[1:])\n","sub_path":"matrix/docker/matrix_converter.py","file_name":"matrix_converter.py","file_ext":"py","file_size_in_byte":19483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635584791","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom . import errors\n\n\n# Module API\n\nclass Iterator(object):\n \"\"\"Iterator representation.\n \"\"\"\n\n # Public\n\n def __init__(self, items, processors):\n self.__items = items\n self.__processors = processors\n self.__index = None\n self.__count = 0\n self.__keys = None\n self.__values = None\n self.__headers = None\n self.__is_stop = False\n self.__is_skip = False\n self.__lookahead = False\n self.__exception = None\n\n def __iter__(self):\n return self\n\n def __next__(self, lookahead=False): #noqa\n\n # Return if lookahead is set on prev iteration\n if self.__lookahead and not lookahead:\n self.__lookahead = False\n return self\n\n # Stop iteration\n if self.__is_stop:\n raise StopIteration()\n\n # Update index\n if self.__index is None:\n self.__index = 0\n else:\n self.__index += 1\n\n # Reset variables\n self.__keys = None\n self.__values = None\n self.__is_stop = False\n self.__is_skip = False\n\n # Get next keys, values from items\n try:\n self.__keys, self.__values = next(self.__items)\n except StopIteration:\n raise\n except Exception as exception:\n self.__exception = exception\n\n # Process iterator by processors\n for processor in self.__processors:\n if self.__exception is None:\n processor.process(self)\n else:\n processor.handle(self)\n if self.__is_skip:\n break\n\n # Raise if there is active exception\n if self.__exception is not None:\n raise self.__exception\n\n # Skip iteration\n if self.__is_skip:\n return self.__next__(lookahead)\n\n # Update count\n self.__count += 1\n\n # Set lookahead\n self.__lookahead = lookahead\n\n return self\n\n def __repr__(self):\n\n # Template and format\n template = (\n 'Iterator <{self.index}, {self.count}, '\n '{self.headers}, {self.values}>')\n result = template.format(self=self)\n\n return result\n\n def skip(self):\n \"\"\"Skip current iteration.\n \"\"\"\n self.__is_skip = True\n\n def stop(self):\n \"\"\"Stop iteration process.\n \"\"\"\n self.__is_stop = True\n\n @property\n def index(self):\n \"\"\"Item index from underlaying stream.\n\n Before iteration: None\n On first item: 0\n On second item: 1\n ...\n\n \"\"\"\n return self.__index\n\n @property\n def count(self):\n \"\"\"Count of non skipped items.\n\n Before iteration: 0\n After first non skipped item: 1\n After second non skipped item: 2\n ...\n\n \"\"\"\n return self.__count\n\n @property\n def keys(self):\n \"\"\"Item keys.\n \"\"\"\n return self.__keys\n\n @property\n def values(self):\n \"\"\"Item values.\n \"\"\"\n return self.__values\n\n @values.setter\n def values(self, values):\n \"\"\"Set item values.\n\n Parameters\n ----------\n values: tuple\n\n \"\"\"\n self.__values = values\n\n @property\n def headers(self):\n \"\"\"Item headers.\n \"\"\"\n return self.__headers\n\n @headers.setter\n def headers(self, headers):\n \"\"\"Set item headers.\n\n Parameters\n ----------\n headers: tuple\n\n \"\"\"\n if self.__count != 0:\n message = 'Headers could be set only before first item is emited.'\n raise errors.Error(message)\n self.__headers = headers\n\n @property\n def exception(self):\n \"\"\"Current exception.\n \"\"\"\n return self.__exception\n\n # Python2 support\n next = __next__\n","sub_path":"tabulator/iterator.py","file_name":"iterator.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"531202998","text":"# importing socket libraries\nimport socket\nimport sys\n\n# main function\ndef main():\n\thost = '127.0.0.1'\n\tport = 54321\n\n\t#creating socket object\n\ts = socket.socket()\n\n\t# connecting with Server\n\t# connect func takes only one argument\n\ts.connect((host, port))\n\n\t#taking input from console\n\tmessage = input(\"Enter message here -->: \")\n\n\t#Condition for terminating connection:\n\twhile(message != 'q'):\n\t\t# sending message for server\n\t\ts.send(message.encode())\n\n\t\t#recieving processed data from server\n\t\tdata = s.recv(1024)\n\n\t\t#printing the data recieved \n\t\tprint(\"Recieved data from Server: \" + str(data.decode()))\n\t\tprint(\"\")\n\n\t\t#taking input from console\n\t\tmessage = input(\"Enter message here -->: \")\n\n\t#print for session termination\n\tprint(\"---------session terminated------------\")\n\tprint(\"\")\n\t\n\t#closing connection from client\n\ts.close()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"m8/Assignment1/Socket_TCP_client.py","file_name":"Socket_TCP_client.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"119456081","text":"\"\"\"\nViews for help documentation\n\"\"\"\nfrom os import walk\nfrom os.path import sep, join, isfile, isdir\n\nimport time\nimport ujson\nimport urllib.request, urllib.parse, urllib.error\nimport redis\n\nfrom docutils.core import publish_parts\n\nfrom cornice import Service\nfrom pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest\n\nfrom webgnome_api.common.views import cors_exception, cors_policy\nfrom webgnome_api.common.indexing import iter_keywords\n\nhelp_svc = Service(name='help', path='/help*dir',\n description=\"Help Documentation and Feedback API\",\n cors_policy=cors_policy)\n\n\n@help_svc.get()\ndef get_help(request):\n '''Get the requested help file if it exists'''\n help_dir = get_help_dir_from_config(request)\n requested_dir = urllib.parse.unquote(sep.join(request.matchdict['dir']))\n requested_file = join(help_dir, requested_dir)\n\n if isfile(requested_file + '.rst'):\n # a single help file was requested\n html = ''\n with open(requested_file + '.rst', 'r') as f:\n html = publish_parts(f.read(), writer_name='html')['html_body']\n\n return {'path': requested_file, 'html': html}\n elif isdir(requested_file) and requested_dir != '':\n # a directory was requested\n # aggregate the files contained with in the given directory\n # and sub dirs.\n for path, _dirnames, filenames in walk(requested_file):\n filenames.sort()\n\n html = ''\n\n for fname in filenames:\n with open(join(path, fname), 'r') as f:\n html += publish_parts(f.read(),\n writer_name='html')['html_body']\n\n return {'path': requested_file, 'html': html}\n elif isdir(requested_file) and requested_dir != '':\n aggregate = []\n for path, _dirnames, filenames in walk(requested_file):\n filenames.sort()\n\n # exclude location file user guides\n if path.count(join('model', 'locations')) == 0:\n for fname in filenames:\n text = ''\n with open(join(path, fname), 'r') as f:\n text = f.read()\n\n parts_whole = publish_parts(text)\n parts = publish_parts(text, writer_name='html')\n\n html = parts['html_body']\n keywords = iter_keywords(parts_whole['whole'])\n\n aggregate.append({'path': join(path,\n fname.replace('.rst', '')),\n 'html': html,\n 'keywords': keywords})\n\n return aggregate\n else:\n raise cors_exception(request, HTTPNotFound)\n\n\n@help_svc.put()\n@help_svc.post()\ndef create_help_feedback(request):\n '''Creates a feedback entry for the given help section'''\n try:\n json_request = ujson.loads(request.body)\n except Exception:\n raise cors_exception(request, HTTPBadRequest)\n\n json_request['ts'] = int(time.time())\n\n # find redis using redis sessions config\n rhost = request.registry.settings.get('redis.sessions.host', 'localhost')\n rport = request.registry.settings.get('redis.sessions.port', 6379)\n\n client = redis.Redis(host=rhost, port=rport)\n\n if 'index' not in json_request:\n json_request['index'] = client.incr('index')\n\n client.set('feedback' + str(json_request['index']), str(json_request))\n\n return json_request\n\n\ndef get_help_dir_from_config(request):\n help_dir = request.registry.settings['help_dir']\n\n if help_dir[0] == sep:\n full_path = help_dir\n else:\n here = request.registry.settings['install_path']\n full_path = join(here, help_dir)\n\n return full_path\n","sub_path":"webgnome_api/views/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"241428119","text":"# for error handling use try/except\n\n\ndef divide(x, y):\n try:\n return x / y\n except ZeroDivisionError:\n print(\"Error: Invalid Argument\")\n\n\nprint(divide(9, 2))\nprint(divide(3, 8))\nprint(divide(100, 10))\nprint(divide(9, 0))\n\n\n# The Collatz Sequence\n\ndef collatz(x):\n out = 0\n if x % 2 == 0:\n out = x // 2\n elif x % 2 == 1:\n out = 3 * x + 1\n return out\n\n\nnum = int(input(\"Enter a number: \"))\nans = collatz(num)\n\nwhile True:\n ans = collatz(ans)\n print(ans)\n if ans == 1:\n break\n","sub_path":"AutomateBoring/errorHandling.py","file_name":"errorHandling.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"436917616","text":"__author__ = 'hle'\n\n\ndef to_log(log, df, match, msg):\n\tiloc = get_match_bool(df, match)\n\tfor pair in iloc:\n\t\tlog = log_cell(log, pair[0], pair[1], msg)\n\treturn log\n\ndef log_cell(log, row, col, msg):\n\tlog.iloc[row, col] = msg\n\treturn log\n\ndef get_match_bool(df, match_to):\n\t\"\"\"\n\t:param df: the dataframe that is used for searching\n\t:param series: the series\n\t:return: list of typle location\n\t\"\"\"\n\tsmall_df = df.loc[match_to.index]\n\tbool = df.isin(match_to)\n\tindex_list = get_index(-bool)\n\t# for item in index_list:\n\t# \tprint(df.iloc[item])\n\treturn index_list\n\ndef log_cellpair(log, style, col, row, msg, xformat='ERROR'):\n\t\"\"\"\n\titerate every single item in col and row to write message, take row col as pair\n\n\tex. log[row[1], loc[1]] = message\n\n\t:param log: log dataframe\n\t:param style: style dataframe\n\t:param col: col list\n\t:param row: row list\n\t:param msg: log message\n\t:param xformat: what kind of style\n\t:return:\n\t\"\"\"\n\n\tfor cur_col in col:\n\t\tfor cur_row in row:\n\t\t\tlog_block(log, style, [cur_col], [cur_row], msg, xformat=xformat)\n\n\treturn log, style\n\ndef log_block(log, style, col, row, msg, xformat='ERROR', ithrow=False):\n\t\"\"\"\n\tWrite log for a continuous block, all combination of col and row\n\n\tex. col = ['col1', 'col2']\n\t\trow = [1 2 3 ]\n\n\t\teverything in this range will be written\n\n\t:param log:\n\t:param style:\n\t:param col: expecting a LIST\n\t:param row: expecting a LIST\n\t:param msg:\n\t:param xformat:\n\t:return:\n\t\"\"\"\n\t# array_bool = df[col].isin(cond) # only works for string,\n\t# log[col].loc[row] = log[col].loc[row].applymap(lambda x: check_contain(x, msg))\n\t# style[col].loc[row] = style[col].loc[row].applymap(lambda x: xformat)\n\tif ithrow is False:\n\t\tlog.update(log[col].loc[row].applymap(lambda x: check_contain(x, msg)))\n\t\tstyle.update(style[col].loc[row].applymap(lambda x: xformat))\n\telse:\n\t\tlog.update(log[col].iloc[row].applymap(lambda x: check_contain(x, msg)))\n\t\tstyle.update(style[col].iloc[row].applymap(lambda x: xformat))\n\treturn log, style\n\ndef cell_log(log, style, col, row, msg, xformat='ERROR'):\n\ttry:\n\t\tlog.update(log[col].loc[row].map(lambda x: check_contain(x, msg)))\n\t\tstyle.update(style[col].loc[row].map(lambda x: xformat))\n\texcept:\n\t\tlog.update(log[col].loc[str(row)].map(lambda x: check_contain(x, msg)))\n\t\tstyle.update(style[col].loc[str(row)].map(lambda x: xformat))\n\treturn log, style\n\nclass LogIt():\n\tdef __init__(self):\n\t\tself.log = {}\n\n\tdef update(self, new_log):\n\t\tself.log.update(new_log)\n\n#\n\ndef check_contain(x, msg):\n\t# process.debug('1. input: {}|{}'.format(x, log))\n\t# process.debug('Type: {}'.format(type(x)))\n\tif type(x) == float or type(x) == int:\n\t\t# process.debug(\"2. float check: passed, used '{}'\".format(log))\n\t\tout = msg\n\telif type(x) == str:\n\t\t# process.debug('2. str check: passed')\n\t\tif msg not in x:\n\t\t\tout = msg + '\\n' + x\n\t\t# process.debug('3. concated log: {}'.format(out))\n\t\telse:\n\t\t\t# process.debug(\"3. no concate performed, '{}' was used\".format(x))\n\t\t\tout = x\n\t\t# process.debug(\"4. returning: {}\".format(out))\n\treturn out\n\nif __name__ == '__main__':\n\told_log = {}\n\told_log['A'] = {}\n\tcit_log = LogIt()\n\n\n\n\n\t# import pandas\n\t# import cnd_generator.preprocessing.load_config as c\n\n\t# findit = pandas.Series({1: 'test', 3: 'test1'})\n\t# bool = c.df2.isin(findit)\n\t# to_log()\n\n\t# mylist = get_index(-bool)\n\t#\n\t# print(mylist)\n\t#\n\t# for item in mylist:\n\t# \tprint(c.df2.iloc[item])","sub_path":"cnd_generator/utils/log_tool/logit.py","file_name":"logit.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"388537807","text":"import tensorflow as tf\nfrom util.ops import softmax_loss, accuracy\n\nimport estim.base\n\n\nclass Classification(estim.base.Estimator):\n def metrics(self, is_training=True):\n return ['loss', 'acc/top-1', 'acc/top-5']\n\n def build_train_ops(self, batch_size, total_steps, lr_decay):\n # get tensors from dataset and predict the output\n features, labels = (self.dataset\n .build(batch_size, is_training=True)\n .make_one_shot_iterator()\n .get_next())\n if self.use_fp16: features = tf.cast(features, tf.float16)\n\n logits = self.model.call(features, is_training=True)\n if self.use_fp16: logits = tf.cast(logits, tf.float32)\n\n # calculate loss and accuracy of prediction\n loss_op = softmax_loss(logits, labels)\n acc_1_op = accuracy(logits, labels, top_k=1)\n acc_5_op = accuracy(logits, labels, top_k=5)\n\n # train by optimizer with learning rate decay\n global_step = tf.train.get_or_create_global_step()\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n train_op = self.optimizer.minimize(\n loss_op,\n lr_decay.decay(global_step, total_steps),\n global_step,\n loss_scale=128 if self.use_fp16 else 1)\n\n return {'loss': loss_op, 'acc/top-1': acc_1_op, 'acc/top-5': acc_5_op, 'train': train_op}\n\n def build_test_ops(self, batch_size):\n # get tensors from dataset and predict the output\n features, labels = (self.dataset\n .build(batch_size, is_training=False)\n .make_one_shot_iterator()\n .get_next())\n logits = self.model.call(features, is_training=False)\n\n # calculate loss and accuracy of prediction\n loss_op = softmax_loss(logits, labels)\n acc_1_op = accuracy(logits, labels, top_k=1)\n acc_5_op = accuracy(logits, labels, top_k=5)\n\n return {'loss': loss_op, 'acc/top-1': acc_1_op, 'acc/top-5': acc_5_op}\n","sub_path":"src/estim/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76733154","text":"# %load q02_best_k_features/build.py\n# Default imports\n\nimport pandas as pd\nimport numpy as np\ndata = pd.read_csv('data/house_prices_multivariate.csv')\n\nfrom sklearn.feature_selection import SelectPercentile\nfrom sklearn.feature_selection import f_regression\nfrom sklearn.feature_selection import f_regression, mutual_info_regression\n#k=20\n# Write your solution here:\ndef percentile_k_features(df, k=20):\n X = df.iloc[:,:-1]\n y = df.iloc[:,-1]\n select_percentile = SelectPercentile(f_regression, k)\n select_percentile.fit(X,y)\n dataframe = pd.DataFrame()\n dataframe['cols'] = X.columns\n dataframe['selected'] = select_percentile.get_support()\n dataframe['score'] = select_percentile.scores_\n dataframe.sort_values('score', inplace=True, ascending=False)\n return list(dataframe[dataframe['selected'] == True]['cols'])\n\n\npercentile_k_features(data)\n\n\n\n\n","sub_path":"q02_best_k_features/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"325878092","text":"\"\"\"\r\nFor Hydrogen;\r\n%load_ext autoreload\r\n%autoreload 2\r\n\"\"\"\r\nfrom typing import List,Tuple,Union\r\nimport numpy as np\r\nimport torch\r\nimport torch.autograd as autograd\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom pytorch_pretrained_bert import BertTokenizer, BertModel\r\nfrom decoder import eisner_decode\r\nfrom data_processor import ConllDataSet\r\nfrom util import set_logger\r\n# set logger\r\nlogger = set_logger(__name__)\r\n# Fix seed\r\ntorch.manual_seed(1)\r\n\r\nclass BiLSTM_Parser(nn.Module):\r\n\r\n def __init__(self,\r\n vocab_size,\r\n pos_size,\r\n word_embed_dim,\r\n pos_embed_dim,\r\n lstm_hidden_dim,\r\n mlp_hidden_dim,\r\n num_layers):\r\n\r\n super(BiLSTM_Parser,self).__init__()\r\n\r\n # Hidden dimension must be an even number for now\r\n # This is the TOTAL dimension of the bidirectional hidden layer\r\n assert lstm_hidden_dim % 2 == 0\r\n\r\n # Hyperparam\r\n self.vocab_size = vocab_size\r\n self.word_embed_dim = word_embed_dim\r\n self.pos_embed_dim = pos_embed_dim\r\n self.lstm_hidden_dim = lstm_hidden_dim\r\n\r\n # Layers\r\n self.word_embeds = nn.Embedding(vocab_size, word_embed_dim)\r\n self.pos_embeds = nn.Embedding(pos_size, pos_embed_dim)\r\n self.lstm = nn.LSTM(input_size = word_embed_dim+pos_embed_dim,\r\n hidden_size = lstm_hidden_dim // 2,\r\n num_layers = num_layers,\r\n bidirectional= True,\r\n dropout=0.25)\r\n self.Linear_head = nn.Linear(lstm_hidden_dim,mlp_hidden_dim //2)\r\n self.Linear_modif = nn.Linear(lstm_hidden_dim,mlp_hidden_dim //2)\r\n self.output_layer = nn.Linear(mlp_hidden_dim,1) # output layer\r\n\r\n # Store intermediate score matrices here (values are float, not tensor)\r\n self.score_matrix_float = None\r\n\r\n # Is the model used in training or inference\r\n self.is_train_mode = True\r\n\r\n # For test : word_tensor = data[0]; pos_tensor = data[1]\r\n def compute_score_matrix(self,\r\n word_tensor:torch.LongTensor,\r\n pos_tensor :torch.LongTensor) \\\r\n -> List[List[torch.Tensor]]:\r\n \"\"\"\r\n Compute a score matrix where\r\n (i,j) element is the score of ith word being the head of jth word\r\n \"\"\"\r\n sentence_len = len(word_tensor[0])\r\n # Word/POS embedding\r\n word_embeds = self.word_embeds(word_tensor) # word_embeds.shape = (1,sentence_len,word_embed_dim)\r\n pos_embeds = self.pos_embeds(pos_tensor) # pos_embeds.shape = (1,sentence_len,pos_embed_dim)\r\n embeds = torch.cat((word_embeds,pos_embeds),2) # embeds.shape = (1,sentence_len,(word_embed_dim+pos_embed_dim))\r\n embeds = embeds.view(sentence_len,1,-1) # embeds.shape = (sentence_len,1,(word_embed_dim+pos_embed_dim))\r\n # Bidirectional LSTM\r\n lstm_out, _ = self.lstm(embeds) # lstm_out.shape = (sentence_len,1,lstm_hidden_dim)\r\n lstm_out = lstm_out.view(sentence_len, self.lstm_hidden_dim)\r\n # Compute score of h -> m (Hold values in float as well for decoding etc)\r\n ## Precompute the necessrary components\r\n head_features = self.Linear_head(lstm_out) # head_features.shape(sentence_len,mlp_hidden_dim//2)\r\n modif_features = self.Linear_modif(lstm_out) # head_features.shape(sentence_len,mlp_hidden_dim//2)\r\n ## Compute\r\n score_matrix = []\r\n score_matrix_float = []\r\n for h in range(sentence_len):\r\n score_matrix.append([])\r\n score_matrix_float.append([])\r\n for m in range(sentence_len):\r\n # Words cannot depend on itself\r\n if h == m:\r\n score_matrix[h].append(np.nan)\r\n score_matrix_float[h].append(np.nan)\r\n else:\r\n feature_func = torch.cat((head_features[h],modif_features[m]))\r\n neuron = torch.tanh(feature_func) # neuron.shape = [mlp_hidden_dim]\r\n score = self.output_layer(neuron)\r\n score_matrix[h].append(score)\r\n score_matrix_float[h].append(score.item())\r\n\r\n return score_matrix,score_matrix_float\r\n\r\n def compute_head_score(self,\r\n score_matrix:List[List[torch.Tensor]],\r\n head_list:List[int]) \\\r\n -> torch.Tensor:\r\n score = 0\r\n for m,h in enumerate(head_list):\r\n score += score_matrix[h][m]\r\n return score\r\n\r\n def compute_hamming_cost(self,head_hat:List[int],head_golden:List[int]) -> int:\r\n # Ignore ROOT\r\n head_hat = np.array(head_hat[1:])\r\n head_golden = np.array(head_golden[1:])\r\n # Number of head not matching\r\n return int(np.sum(head_hat != head_golden))\r\n\r\n def forward(self,\r\n word_tensor:torch.LongTensor,\r\n pos_tensor :torch.LongTensor,\r\n head_golden:List[int] = None) \\\r\n -> Tuple[List[int],torch.Tensor,Union[torch.Tensor,None]]:\r\n\r\n # Check inconsistent argument and mode\r\n if self.is_train_mode and head_golden is None:\r\n raise ValueError(\"Pass golden for training mode\")\r\n elif not self.is_train_mode and head_golden is not None:\r\n raise ValueError(\"Golden is not needed for inference\")\r\n\r\n # Calculate score matrix (Hold values for convenience)\r\n score_matrix,score_matrix_float = self.compute_score_matrix(word_tensor,pos_tensor)\r\n self.score_matrix_float = score_matrix_float\r\n # Find the best path, given the score_matrix\r\n head_hat = eisner_decode(score_matrix_float,head_golden)\r\n # Compute the score\r\n score_hat = self.compute_head_score(score_matrix,head_hat)\r\n if head_golden is not None:\r\n score_golden = self.compute_head_score(score_matrix,head_golden)\r\n score_hat += self.compute_hamming_cost(head_hat,head_golden)\r\n else:\r\n score_golden = None\r\n return head_hat,score_hat,score_golden\r\n\r\n# Loss function\r\ndef margin_based_loss(score_hat:torch.Tensor,\r\n score_golden:torch.Tensor) -> torch.Tensor:\r\n margin = score_golden - score_hat\r\n return max(0,1 - margin)\r\n\r\nif __name__ == '__main__':\r\n\r\n ### Script for test\r\n\r\n # Load test\r\n from pathlib import Path\r\n train_path = Path(\"data\",\"en-universal-train.conll\")\r\n train_data = ConllDataSet(train_path)\r\n\r\n # Init model (self = model)\r\n model = BiLSTM_Parser(vocab_size = train_data.vocab_size,\r\n pos_size = train_data.pos_size,\r\n word_embed_dim = 100,\r\n pos_embed_dim = 25,\r\n lstm_hidden_dim = 250,\r\n mlp_hidden_dim = 100,\r\n num_layers = 2)\r\n # Check forward() and loss funtion\r\n data = train_data[1]\r\n head_hat,score_hat,score_golden = model(data[0],data[1],data[2])\r\n loss = margin_based_loss(score_hat,score_golden)\r\n logger.debug(\"Data flowed through the network!\")\r\n # Check computational graph\r\n component = loss.grad_fn\r\n while len(component.next_functions) != 0:\r\n logger.debug(component)\r\n component = component.next_functions[0][0]\r\n","sub_path":"mst_bert.py","file_name":"mst_bert.py","file_ext":"py","file_size_in_byte":7567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"395385474","text":"from django.http import HttpResponseNotFound\nfrom django.shortcuts import render, HttpResponse, redirect, get_object_or_404\nfrom database.models import Products, Order, Customer, Area, OrderDetail, Schedule, Asset\nfrom ast import literal_eval\nfrom .forms import OrderForm, OrderQuantityForm\nfrom Admin.views import string_to_list, form_to_string\n\n\ndef home(request):\n if request.user.is_authenticated and request.user.is_customer:\n user = Customer.objects.get(username=request.user.username)\n\n context = {\n 'user': user,\n 'assets': user.assets.all(),\n 'orders': Order.objects.filter(customer=request.user, delivered=False)\n }\n\n return render(request, 'customer/home.html', context)\n\n return render(request, 'home.html')\n\n\ndef view_order(request, order_id):\n if request.user.is_authenticated and not request.user.is_superuser:\n order = Order.objects.get(id=order_id)\n customer = order.customer\n data = {'order': order, 'quantity': product_quantity_list(order.desc.all()), 'customer': customer}\n return render(request, 'customer/ordered.html', data)\n\n return HttpResponseNotFound()\n\n\ndef my_orders(request):\n if request.user.is_authenticated and not request.user.is_superuser:\n orders = Order.objects.filter(customer=request.user).order_by('-ordered_at')\n context = {\n 'orders': orders,\n 'user': Customer.objects.get(username=request.user.username)\n }\n return render(request, 'customer/view_orders.html', context=context)\n\n\ndef order_confirmed(request):\n if request.POST and request.user.is_authenticated:\n data = request.session['data']\n order_ = Order(customer=Customer.objects.get(username=data['username']),\n frequency=data['frequency'],\n address=data['address'],\n area=Area.objects.get(name=data['area_name'], city__city=data['city__city']),\n price=data['price'])\n order_.save()\n set_order_description(order_, data['quantity'])\n request.session['data'] = None\n return redirect('customer_home')\n return HttpResponseNotFound()\n\n\ndef order(request):\n if request.user.is_authenticated and not request.user.is_superuser and not request.user.is_employee:\n if request.POST:\n orderForm = OrderForm(request.POST, username=request.user.username)\n customer = Customer.objects.get(username=request.user.username)\n quantityForm = OrderQuantityForm(request.POST)\n if orderForm.is_valid() and quantityForm.is_valid():\n quantity = form_to_string(quantityForm)\n if not has_quantity(quantity):\n return render(request, 'customer/order_form.html',\n {'message': 'Invalid Data or Empty order!',\n 'order_form': OrderForm(username=request.user.username),\n 'quantity_form': OrderQuantityForm()})\n area = orderForm.cleaned_data['area'].split(',')\n if not can_place_order(string_to_list(quantity),\n Area.objects.get(name=area[0].strip(), city__city=area[1].strip())):\n return render(request, 'customer/order_form.html',\n {'message': 'Order too large for selected area. Please reduce order!',\n 'order_form': OrderForm(username=request.user.username),\n 'quantity_form': OrderQuantityForm()})\n price = get_price(quantity, customer)\n if orderForm.cleaned_data['area'] != \"%s\" % customer.area and not orderForm.cleaned_data['address']:\n return render(request, 'customer/order_form.html',\n {'message': 'Must Enter Address if area other than default is selected!',\n 'order_form': OrderForm(username=request.user.username),\n 'quantity_form': OrderQuantityForm()})\n\n if orderForm.cleaned_data['address'] and orderForm.cleaned_data['area']:\n address = orderForm.cleaned_data.get('address')\n selected_area = Area.objects.get(name=area[0].strip(), city__city=area[1].strip())\n else:\n address = customer.address\n selected_area = customer.area\n\n order_ = Order(customer=customer, frequency=orderForm.cleaned_data['order_type'],\n address=address, area=selected_area, price=price)\n request.session['data'] = {\n \"username\": request.user.username,\n 'frequency': orderForm.cleaned_data['order_type'],\n \"address\": address,\n 'area_name': area[0].strip(),\n 'city__city': area[1].strip(),\n 'price': price,\n \"quantity\": quantity\n }\n\n data = {'order': order_, 'quantity': get_product_quantity_map(quantity), 'customer': customer,\n 'price': price}\n return render(request, 'customer/confirm_order.html', data)\n return render(request, 'customer/order_form.html',\n {'message': 'Please retry!', 'order_form': OrderForm(username=request.user.username),\n 'quantity_form': OrderQuantityForm()})\n return render(request, 'customer/order_form.html',\n {\n 'order_form': OrderForm(username=request.user.username),\n 'quantity_form': OrderQuantityForm(),\n 'areas': Area.objects.all(),\n\n })\n return HttpResponse(status=404)\n\n\ndef get_price(description, customer):\n prices = customer.discounted_price.all()\n products = string_to_list(description)\n net_price = 0\n for product in products:\n for product_price in prices:\n if product[0] == str(product_price.product.id):\n net_price += product_price.price * int(product[1])\n break\n return net_price\n\n\ndef get_product_quantity_map(description):\n product_list = string_to_list(description)\n print(description)\n products = Products.objects.all()\n for product_in_order in product_list:\n for product in products:\n if int(product_in_order[0]) == product.id:\n product_in_order[0] = product.name\n break\n return product_list\n\n\ndef has_quantity(description):\n products = string_to_list(description)\n valid = False\n for product in products:\n if int(product[1]) < 0:\n return False\n if int(product[1]) > 0:\n valid = True\n return valid\n\n\ndef profile(request):\n if request.user.is_authenticated:\n customer = Customer.objects.get(username=request.user.username)\n if customer:\n data = {'user': customer}\n return render(request, 'customer/profile.html', data)\n return HttpResponseNotFound()\n\n\ndef set_order_description(order, description):\n desc = string_to_list(description)\n products_ordered = []\n for pairs in desc:\n if int(pairs[1]) > 0:\n product = OrderDetail(product=Products.objects.get(id=pairs[0]), quantity=int(pairs[1]))\n product.save()\n products_ordered.append(product)\n order.desc.set(products_ordered)\n order.save()\n\n\ndef can_place_order(description, area):\n products = Products.objects.all()\n total_weight = 0\n for pairs in description:\n for product in products:\n if product.id == pairs[0]:\n total_weight += product.weight * int(pairs[1])\n break\n available_days = Schedule.objects.filter(areas=area).distinct().order_by(\n 'vehicle__vehicleModel__weightCapacity').order_by('order')\n for day in available_days:\n if total_weight <= day.day_capacity:\n return True\n return False\n\n\ndef product_quantity_list(desc):\n product_list = []\n for products in desc:\n product_list.append([products.product.name, products.quantity])\n return product_list\n","sub_path":"Water_management/customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259365215","text":"#use quick sort with recusion, help from - https://stackoverflow.com/questions/18262306/quicksort-with-python\ndef sort(array):\n lesser = []\n equal = []\n greater = []\n\n if len(array) > 1:\n pivot = array[0]\n for x in array:\n if x < pivot:\n lesser.append(x)\n elif x == pivot:\n equal.append(x)\n elif x > pivot:\n greater.append(x)\n return sort(lesser)+equal+sort(greater) \n else: \n return array\n\n# Complete the findMedian function below.\ndef findMedian(arr):\n sortedarray = sort(arr)\n med = len(arr) - len(arr)//2\n print(str(len(arr)))\n print(str(med))\n return sortedarray[med-1]\n","sub_path":"Problem Solving - Algorithms/Find_the_Median.py","file_name":"Find_the_Median.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351788693","text":"from kivy.app import App\nfrom kivy.lang import Builder\n\nfrom kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition\n\n\nclass StartScreen(GridLayout):\n\n\n\n def __init__(self, **kwargs):\n super(StartScreen, self).__init__(**kwargs)\n\n self.counterVar = NumericProperty(1)\n\n self.counter = Label(text=self.counterVar)\n self.minusButton = Button(text=\"-\")\n self.plusButton = Button(text=\"+\")\n\n\n\n self.plusButton.bind(on_press=self.updatePlus)\n self.minusButton.bind(on_press=self.updateMinus)\n\n self.cols = 3\n self.add_widget(self.minusButton)\n self.add_widget(self.counter)\n self.add_widget(self.plusButton)\n\n def updatePlus(self, event):\n self.counterVar += 1\n self.counter.text = str(self.counterVar)\n\n def updateMinus(self, event):\n self.counterVar -= 1\n self.counter.text = str(self.counterVar)\n\nclass MainApp(App):\n def build(self):\n return StartScreen()\n\nif __name__ == '__main__':\n MainApp().run()\n","sub_path":"v1_counter_numericproperty/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"131206708","text":"#coding:iso-8859-9 Türkçe\r\n# p_32601.py: Pandas serisinde çoklu endeks ve sıralama örneği.\r\n\r\nimport pandas as pd\r\n\r\nşehirler = [\"Viyana\", \"Hamburg\", \"Berlin\", \"Zürih\"]\r\nözellikleri = [(\"ülke\", \"yüzölçümü\", \"nüfus\", \"yoğunluk\")] * 4\r\nendeks = [şehirler, özellikleri]\r\nveriler = [\r\n (\"Avusturya\", 414.60, 1805681, int (1805681 / 414.6 * 100) / 100),\r\n (\"Almanya\", 755.00, 1760433, int (1760433 / 755 * 100) / 100),\r\n (\"Almanya\", 891.85, 3562166, int (3562166 / 891.85 * 100) / 100),\r\n (\"İsviçre\", 87.88, 378884, int (378884 / 87.88* 100) / 100) ]\r\nşehirlerSerisi = pd.Series (veriler, index=endeks)\r\n\r\nprint (\"Şehirler ve özellikleri'ne endeksli veriler serisi:\\n\", şehirlerSerisi, sep=\"\")\r\nprint (\"-\"*79)\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nşehirler = [\r\n \"Viyana\", \"Viyana\", \"Viyana\", \"Viyana\",\r\n \"Hamburg\",\"Hamburg\", \"Hamburg\", \"Hamburg\",\r\n \"Berlin\", \"Berlin\", \"Berlin\", \"Berlin\",\r\n \"Zürih\", \"Zürih\", \"Zürih\", \"Zürih\"]\r\nözellikleri = [\r\n \"ülke\", \"yüzölçümü\", \"nüfus\", \"yoğunluk\",\r\n \"ülke\", \"yüzölçümü\", \"nüfus\", \"yoğunluk\",\r\n \"ülke\", \"yüzölçümü\", \"nüfus\", \"yoğunluk\",\r\n \"ülke\", \"yüzölçümü\", \"nüfus\", \"yoğunluk\" ]\r\nveriler = [\r\n \"Avusturya\", 414.60, 1805681, int (1805681 / 414.6 * 100) / 100,\r\n \"Almanya\", 755.00, 1760433, int (1760433 / 755 * 100) / 100,\r\n \"Almanya\", 891.85, 3562166, int (3562166 / 891.85 * 100) / 100,\r\n \"İsviçre\", 87.88, 378884, int (378884 / 87.88* 100) / 100 ]\r\nendeks = [şehirler, özellikleri]\r\nşehirlerSerisi = pd.Series (veriler, index=endeks)\r\n\r\nprint (\"\\n4 faklı şehir ve özellikleri'ne endeksli veriler serisi:\\n\", şehirlerSerisi, sep=\"\")\r\nprint (\"-\"*50)\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nşS= şehirlerSerisi\r\nprint (\"\\nSadece Viyana'nın özellikli verileri:\\n\", şS [\"Viyana\"], sep=\"\")\r\n\r\nprint (\"\\nViyana'nın yoğunluk özellikli verisi: \", şS [\"Viyana\"] [\"yoğunluk\"],\r\n \"\\nVeya: \", şS [\"Viyana\", \"yoğunluk\"], sep=\"\")\r\n\r\nprint (\"\\nSadece Hamburg ve Zürih'in özellikli verileri:\\n\", şS [[\"Hamburg\", \"Zürih\"]], sep=\"\")\r\nprint (\"-\"*50)\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nşS2 = şS.sort_index()\r\nprint (\"\\nTüm verileri artan sıralı şehirler serisi:\\n\", şS2, sep=\"\")\r\n\r\nprint (\"\\nŞehirler arasından dilim verileri:\\n\", şS2 [\"Hamburg\" : \"Viyana\"], sep=\"\" )\r\nprint (\"-\"*40)\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nprint (\"\\nTüm şehirlerin sadece yoğunluk verileri:\\n\", şS [:, \"yoğunluk\"], sep=\"\")\r\nprint (\"-\"*52)\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nşS3 = şS.swaplevel()\r\nprint (\"\\nŞehirler değil ÖZELLİKLER öncelikli endeks verileri:\\n\", şS3, sep=\"\")\r\n\r\nşS3.sort_index (inplace=True)\r\nprint (\"\\nÖzelliklere göre artan sıralı gruplanan veriler:\\n\", şS3, sep=\"\")\r\n\r\n\r\n\r\n\"\"\"Çıktı:\r\n>python p_32601.py\r\nŞehirler ve özellikleri'ne endeksli veriler serisi:\r\nViyana (ülke, yüzölçümü, nüfus, yoğunluk) (Avusturya, 414.6, 1805681, 4355.23)\r\nHamburg (ülke, yüzölçümü, nüfus, yoğunluk) (Almanya, 755.0, 1760433, 2331.69)\r\nBerlin (ülke, yüzölçümü, nüfus, yoğunluk) (Almanya, 891.85, 3562166, 3994.13)\r\nZürih (ülke, yüzölçümü, nüfus, yoğunluk) (İsviçre, 87.88, 378884, 4311.37)\r\ndtype: object\r\n-------------------------------------------------------------------------------\r\n\r\n4 faklı şehir ve özellikleri'ne endeksli veriler serisi:\r\nViyana ülke Avusturya\r\n yüzölçümü 414.6\r\n nüfus 1805681\r\n yoğunluk 4355.23\r\nHamburg ülke Almanya\r\n yüzölçümü 755\r\n nüfus 1760433\r\n yoğunluk 2331.69\r\nBerlin ülke Almanya\r\n yüzölçümü 891.85\r\n nüfus 3562166\r\n yoğunluk 3994.13\r\nZürih ülke İsviçre\r\n yüzölçümü 87.88\r\n nüfus 378884\r\n yoğunluk 4311.37\r\ndtype: object\r\n--------------------------------------------------\r\n\r\nSadece Viyana'nın özellikli verileri:\r\nülke Avusturya\r\nyüzölçümü 414.6\r\nnüfus 1805681\r\nyoğunluk 4355.23\r\ndtype: object\r\n\r\nViyana'nın yoğunluk özellikli verisi: 4355.23\r\nVeya: 4355.23\r\n\r\nSadece Hamburg ve Zürih'in özellikli verileri:\r\nHamburg ülke Almanya\r\n yüzölçümü 755\r\n nüfus 1760433\r\n yoğunluk 2331.69\r\nZürih ülke İsviçre\r\n yüzölçümü 87.88\r\n nüfus 378884\r\n yoğunluk 4311.37\r\ndtype: object\r\n--------------------------------------------------\r\n\r\nTüm verileri artan sıralı şehirler serisi:\r\nBerlin nüfus 3562166\r\n yoğunluk 3994.13\r\n yüzölçümü 891.85\r\n ülke Almanya\r\nHamburg nüfus 1760433\r\n yoğunluk 2331.69\r\n yüzölçümü 755\r\n ülke Almanya\r\nViyana nüfus 1805681\r\n yoğunluk 4355.23\r\n yüzölçümü 414.6\r\n ülke Avusturya\r\nZürih nüfus 378884\r\n yoğunluk 4311.37\r\n yüzölçümü 87.88\r\n ülke İsviçre\r\ndtype: object\r\n\r\nŞehirler arasından dilim verileri:\r\nHamburg nüfus 1760433\r\n yoğunluk 2331.69\r\n yüzölçümü 755\r\n ülke Almanya\r\nViyana nüfus 1805681\r\n yoğunluk 4355.23\r\n yüzölçümü 414.6\r\n ülke Avusturya\r\ndtype: object\r\n----------------------------------------\r\n\r\nTüm şehirlerin sadece yoğunluk verileri:\r\nViyana 4355.23\r\nHamburg 2331.69\r\nBerlin 3994.13\r\nZürih 4311.37\r\ndtype: object\r\n----------------------------------------------------\r\n\r\nŞehirler değil ÖZELLİKLER öncelikli endeks verileri:\r\nülke Viyana Avusturya\r\nyüzölçümü Viyana 414.6\r\nnüfus Viyana 1805681\r\nyoğunluk Viyana 4355.23\r\nülke Hamburg Almanya\r\nyüzölçümü Hamburg 755\r\nnüfus Hamburg 1760433\r\nyoğunluk Hamburg 2331.69\r\nülke Berlin Almanya\r\nyüzölçümü Berlin 891.85\r\nnüfus Berlin 3562166\r\nyoğunluk Berlin 3994.13\r\nülke Zürih İsviçre\r\nyüzölçümü Zürih 87.88\r\nnüfus Zürih 378884\r\nyoğunluk Zürih 4311.37\r\ndtype: object\r\n\r\nÖzelliklere göre artan sıralı gruplanan veriler:\r\nnüfus Berlin 3562166\r\n Hamburg 1760433\r\n Viyana 1805681\r\n Zürih 378884\r\nyoğunluk Berlin 3994.13\r\n Hamburg 2331.69\r\n Viyana 4355.23\r\n Zürih 4311.37\r\nyüzölçümü Berlin 891.85\r\n Hamburg 755\r\n Viyana 414.6\r\n Zürih 87.88\r\nülke Berlin Almanya\r\n Hamburg Almanya\r\n Viyana Avusturya\r\n Zürih İsviçre\r\ndtype: object\r\n\"\"\"","sub_path":"Bernd Klein (520) ile Python/p_32601.py","file_name":"p_32601.py","file_ext":"py","file_size_in_byte":7448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"211589453","text":"# Author: Trevor Strobel\n# Date: 5/19/2021\n\nimport csv\nfrom salarStrings import country_names, city_names, male_names, female_names\n \n# All Data\nwith open('1.csv', mode='w') as csvFile:\n data = country_names + city_names + male_names + female_names\n for x in data:\n csvFile.write(x + \"\\n\")\n\n# Countries\nwith open('2.csv', mode='w') as csvFile:\n for x in country_names:\n csvFile.write(x +\"\\n\")\n\n# Cities\nwith open('3.csv', mode='w') as csvFile:\n for x in city_names:\n csvFile.write(x +\"\\n\") \n\n# Male Names\nwith open('4.csv', mode='w') as csvFile:\n for x in male_names:\n csvFile.write(x +\"\\n\")\n\n# Female Names\nwith open('5.csv', mode='w') as csvFile:\n for x in female_names:\n csvFile.write(x +\"\\n\")\n\n# All Names\nwith open('6.csv', mode='w') as csvFile:\n names = male_names + female_names\n for x in names:\n csvFile.write(x + \"\\n\")\n ","sub_path":"utils/StringData/csvGen.py","file_name":"csvGen.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"237528442","text":"from django.contrib.auth import login, authenticate\r\nfrom django.shortcuts import render, redirect\r\nfrom .forms import RegistrationForm, CreateCardPackage, CreateCardGroup, CreateCards, CreateComments\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.contrib.auth.forms import UserCreationForm\r\nfrom .models import Card_Packages, Card_Groups, Cards, Comments\r\nfrom django.template.response import TemplateResponse\r\nfrom django.contrib import messages \r\n\r\n\r\ndef index(request):\r\n \"\"\"\r\n View function for home page of site.\r\n \"\"\"\r\n # Number of visits to this view, as counted in the session variable.\r\n num_visits=request.session.get('num_visits', 0)\r\n request.session['num_visits'] = num_visits+1\r\n # Render the HTML template index.html with the data in the context variable\r\n return render(\r\n request,\r\n 'index.html',\r\n context={'num_visits': num_visits}, # num_visits appended\r\n )\r\n\r\n\r\ndef create(request):\r\n return render(\r\n request,\r\n 'project.html',\r\n )\r\n\r\n\r\ndef cards(request):\r\n if request.method == 'POST':\r\n form = CreateCardPackage(request.POST, instance=Card_Packages())\r\n if form.is_valid():\r\n titles = request.POST.getlist('title')\r\n texts = request.POST.getlist('text')\r\n groups = request.POST.getlist('group')\r\n names = request.POST.getlist('name')\r\n user = request.user\r\n for name in names:\r\n cardPackage = Card_Packages(name=name, user=user)\r\n cardPackage.save()\r\n for title in titles:\r\n group = Card_Groups(card_package=cardPackage, title=title)\r\n group.save()\r\n for text in texts:\r\n card = Cards(card_package=cardPackage, card_group=group, text=text)\r\n card.save()\r\n return render(\r\n request,\r\n 'index.html',\r\n )\r\n else:\r\n form = CreateCardPackage(instance=Card_Packages())\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'project.html',\r\n {'form': form}\r\n )\r\n else:\r\n form = CreateCardPackage(instance=Card_Packages())\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'project.html',\r\n {'form': form}\r\n )\r\n\r\n\r\ndef register(request):\r\n if request.method == 'POST':\r\n form = RegistrationForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n username = form.cleaned_data.get('username')\r\n password = form.cleaned_data.get('password1')\r\n user = authenticate(username=username, password=password)\r\n login(request, user)\r\n return render(\r\n request,\r\n 'index.html',\r\n )\r\n else:\r\n form = RegistrationForm()\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'register.html',\r\n {'form': form}\r\n )\r\n else:\r\n form = RegistrationForm()\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'register.html',\r\n {'form': form}\r\n )\r\n\r\n\r\ndef view(request):\r\n cardPackages = Card_Packages.objects.all()\r\n return render(\r\n request,\r\n 'view.html',\r\n )\r\n\r\n\r\ndef package(request):\r\n cardPackages = Card_Packages.objects.all()\r\n context = {'cardPackages': cardPackages}\r\n return render(\r\n request,\r\n 'package.html',\r\n context\r\n )\r\n\r\n\r\ndef packageList(request, package):\r\n package = Card_Packages.objects.get(id__exact=package)\r\n context = {'package': package}\r\n return render(\r\n request,\r\n 'packageList.html',\r\n context\r\n )\r\n\r\n\r\ndef admin(request):\r\n cardPackages = Card_Packages.objects.all()\r\n context = {'cardPackages': cardPackages}\r\n return render(\r\n request,\r\n 'admin.html',\r\n context\r\n )\r\n\r\n\r\ndef edit(request, package):\r\n package = Card_Packages.objects.get(id__exact=package)\r\n context = {'package': package}\r\n return render(\r\n request,\r\n 'edit.html',\r\n context\r\n )\r\n\r\n\r\ndef comments(request):\r\n if request.method =='POST':\r\n form = CreateComments(request.POST, instance=Comments())\r\n name = request.POST.get('name')\r\n cardPackage = Card_Packages.objects.get(name = name)\r\n user = request.user\r\n comment = request.POST.get('comment')\r\n comments = Comments(card_package = cardPackage, user = user, comment = comment)\r\n comments.save()\r\n return render(\r\n request,\r\n 'index.html',\r\n )\r\n else:\r\n form = CreateCardPackage(instance=Comments())\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'packageList.html',\r\n {'form': form}\r\n )\r\n\r\n\r\ndef editPackage(request, package):\r\n if request.method == 'POST':\r\n form = CreateCardPackage(request.POST, instance=Card_Packages())\r\n if form.is_valid():\r\n cardPackage = Card_Packages.objects.get(id__exact=package)\r\n titles = request.POST.getlist('title')\r\n texts = request.POST.getlist('text')\r\n cardGroupIDs = request.POST.getlist('cardGroupID')\r\n cardListIDs = request.POST.getlist('cardListID')\r\n name = request.POST.get('name')\r\n user = request.user\r\n cardPackage.name = name\r\n cardPackage.save()\r\n group = Card_Groups()\r\n card = Cards()\r\n for cardGroupID, title in zip(cardGroupIDs, titles):\r\n group.id = cardGroupID\r\n group.card_package = cardPackage\r\n group.title = title\r\n group.save()\r\n for cardListID, text in zip(cardListIDs, texts):\r\n card.id = cardListID\r\n card.card_package = cardPackage\r\n card.card_group = group\r\n card.text = text\r\n card.save()\r\n return render(\r\n request,\r\n 'admin.html',\r\n )\r\n else:\r\n form = CreateCardPackage(instance=Card_Packages())\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'admin.html',\r\n {'form': form}\r\n )\r\n else:\r\n form = CreateCardPackage(instance=Card_Packages())\r\n args = {'form': form}\r\n return render(\r\n request,\r\n 'admin.html',\r\n {'form': form}\r\n )\r\n\r\n\r\ndef cardPackages(request):\r\n cardPackages = Card_Packages.objects.all() \r\n return TemplateResponse(request, views.index, {'cardPackages': cardPackages})\r\n\r\n\r\ndef cardGroups(request):\r\n cardGroups = Card_Groups.objects.all() \r\n return TemplateResponse(request, views.index, {'cardGroups': cardGroups})\r\n\r\n\r\ndef cardList(request):\r\n cardList = Cards.objects.all() \r\n return TemplateResponse(request, views.index, {'cardList': cardList})\r\n","sub_path":"MyDigitalHealth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484013828","text":"def gen_next(x):\n x = list(str(x))\n oplist = []\n tmp = []\n\n tmp.append(x[0])\n for i in range(1, len(x)):\n if x[i] == x[i-1]:\n tmp.append(x[i])\n else:\n oplist.append(tmp)\n tmp = []\n tmp.append(x[i])\n \n oplist.append(tmp)\n\n ret = ''\n for el in oplist:\n ret += str(len(el))\n ret += str(el[0])\n\n return ret\n\n\na=[1]\nfor i in range(30):\n a.append(gen_next(a[-1]))\n\nprint(len(a[30]))\n","sub_path":"pythonchallenge/t_10.py","file_name":"t_10.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"412493736","text":"#!/usr/bin/python3\nimport math\n\"\"\"\nProblem 3\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\n What is the largest prime factor of the number 600851475143 ?\n\"\"\"\ndef isPrime(n):\n \"\"\" Check whether or not a number is even \"\"\"\n if n == 2 or n == 3:\n return True\n elif n % 2 == 0 or n % 3== 0:\n return False \n else:\n return all ( n % i for i in range(3,int(n**0.5)+1))\n\ndef maxFactor(n):\n \"\"\" Get the maximum prime Factor to reduce operations \"\"\"\n maxFac = -1\n while n % 2 == 0:\n maxFac = 2\n n /= 2\n for i in range(3, int(math.sqrt(n))+1, 2):\n while n % i == 0:\n maxFac = i\n n = n / i\n if n > 2 :\n maxFac = n\n return int(maxFac)\n\ndef Problem(number = 600851475143):\n maxPrime = maxFactor(number) \n smallPrimes = (2,) + tuple( n for n in range(3, maxPrime+1, 2) if isPrime(n)) \n factors = [] \n for checker in smallPrimes: \n while number % checker == 0:\n factors.append(checker)\n number //= checker \n print(factors)\n\nif __name__ == \"__main__\":\n Problem()","sub_path":"01.python/problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"547390769","text":"#! /usr/bin/python\n\n__author__ = \"imrul\"\n__date__ = \"$Dec 21, 2015 10:59:54 PM$\"\n\nimport sys\nimport csv\nimport math\n\nuniqVillage = sys.argv[1];\ndist = sys.argv[2];\nradius = sys.argv[3];\n\ndef getDistance(x1, y1, x2, y2):\n distance = math.sqrt(((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)));\n return float(distance);\n\ndef printNearest(village_id, nList):\n line = village_id;\n count = 0;\n for vid in nList:\n if(count == 0):\n line = line+\",\"+vid;\n \n \nwith open(uniqVillage, 'rb') as csvfile2:\n reader2 = csv.reader(csvfile2, delimiter=',')\n with open(dist, 'rb') as csvfile1:\n reader1 = csv.reader(csvfile1, delimiter=',')\n for row in reader2:\n village_id = row[0];\n x1_cor = float(row[1]);\n y1_cor = float(row[2]);\n csvfile1.seek(0);\n count = 0;\n sys.stdout.write(village_id)\n for r in reader1:\n if(count > 0):\n if(village_id != r[1]):\n x2_cor = float(r[4]);\n y2_cor = float(r[5]);\n distance = getDistance(x1_cor, y1_cor, x2_cor, y2_cor);\n if(distance < float(radius)):\n sys.stdout.write(\",\"+str(r[1]));\n count = count + 1;\n sys.stdout.write(\"\\n\"); \n \n\n","sub_path":"src/dataPreparation/getNearestVillage.py","file_name":"getNearestVillage.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605076370","text":"import torchvision.models as models\nimport torch\nimport argparse\n\nif __name__ == '__main__':\n \"\"\"\n Downloading and saving the requested ResNet backbone to the 'models' folder\n The resnet_type argument Supports: resnet34, resnet50, resnet152\n \"\"\"\n arg_parser = argparse.ArgumentParser()\n arg_parser.add_argument(\"model_name\", help=\"The requested ResNet model (e.g. resnet34, resnet50, resnet152\")\n args = arg_parser.parse_args()\n\n if args.model_name == 'resnet34':\n model = models.resnet34(pretrained=True)\n elif args.model_name == 'resnet50':\n model = models.resnet50(pretrained=True)\n elif args.model_name == 'resnet152':\n model = models.resnet152(pretrained=True)\n else:\n raise ValueError('Unsupported model name - {}'.format(args.model_name))\n\n # Removing the last two layer\n backbone_model = torch.nn.Sequential(*(list(model.children())[:-2]))\n\n # Saving the model\n torch.save(backbone_model, '../models/backbones/{}.pth'.format(args.model_name))\n","sub_path":"util/get_resnet_backbone.py","file_name":"get_resnet_backbone.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344473531","text":"import turtle\nturtle.shape(\"turtle\")\nfun=turtle.Turtle()\nfun.shape('square')\nfun.goto(100,-100)\nfun.pensize(18)\nfun.goto(100,0)\nfun.goto(0,0)\nfun.goto(0,-100)\nfun.goto(100,-100)\ncharlie=turtle.clone()\ncharlie.shape('triangle')\ncharlie.penup()\ncharlie.goto(-50,0)\ncharlie.pendown()\ncharlie.goto(-50,100)\ncharlie.goto(-100,0)\ncharlie.goto(-50,0)\nfun.goto(200,-90)\nfun.stamp()\nfun.goto(300,-300)\nfun.stamp()\nfun.pensize(5)\nfun.goto(10,100)\nturtle.goto(22,200)\nturtle.stamp()\nturtle.goto(100,100)\nfun.clearstamp()\n","sub_path":"lab_4.py","file_name":"lab_4.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618762629","text":"import os\r\nfrom os import sys\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import Qt\r\n\r\n\r\nclass PhotosApp(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n # utawianie rozmaru\r\n self.setMinimumSize(800, 600)\r\n\r\n # znaczace zmienne\r\n self.SCALE_FACTOR = 1.5\r\n self.iterator = 0\r\n self.buttons = {}\r\n self.fileNameList = []\r\n\r\n self.photo = QLabel()\r\n self.photo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\r\n self.photo.setScaledContents(True)\r\n self.photo.setAlignment(Qt.AlignCenter)\r\n\r\n self.scrollArea = QScrollArea()\r\n # self.scrollArea.\r\n self.scrollArea.setAlignment(Qt.AlignCenter)\r\n self.scrollArea.setWidget(self.photo)\r\n self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)\r\n self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)\r\n\r\n # ustawianie głównego layoutu i widgetu\r\n self.mainLayout = QVBoxLayout()\r\n self.bottomLayout = QHBoxLayout()\r\n self.mainWidget = QWidget()\r\n self.mainWidget.setLayout(self.mainLayout)\r\n self.setCentralWidget(self.mainWidget)\r\n self.mainLayout.addWidget(self.scrollArea)\r\n self.mainLayout.addLayout(self.bottomLayout)\r\n self._initializeControlButtons()\r\n\r\n # ustawienia paska aplikacji\r\n self.setWindowTitle(\"Przeglądarka zdjęć\")\r\n self.setWindowIcon(QIcon(\"icon.png\"))\r\n self.setStyleSheet(\r\n \"QMenuBar, QMenu, QPushButton\"\r\n \"{background: black;\"\r\n \"color: red;}\"\r\n \"QScrollArea, QLabel{\"\r\n \"background: #303030;\"\r\n \"color:white;}\"\r\n \"PhotosApp, QScrollArea{\"\r\n \"background: #303030;}\")\r\n\r\n # stworzenie menu\r\n self._initializeMenuBar()\r\n self.show()\r\n\r\n # __init__()\r\n def _resizeImage(self, name):\r\n if name == \"zoom+\":\r\n # self.scrollArea.resize(self.photo.size() * self.SCALE_FACTOR)\r\n self.photo.resize(self.photo.size() * self.SCALE_FACTOR)\r\n else:\r\n self.photo.resize(self.photo.size() / self.SCALE_FACTOR)\r\n\r\n def handleButtonClick(self, event):\r\n name = self.sender().text()\r\n if name in [\"<\", \">\"]:\r\n self._changeImage(name)\r\n elif name in [\"zoom+\", \"zoom-\"]:\r\n self._resizeImage(name)\r\n\r\n def _changeImage(self, option):\r\n length = self.fileNameList.__len__()\r\n if length != 0:\r\n if option == \"<\" and length != 0:\r\n if self.iterator == 0:\r\n self.iterator = length - 1\r\n else:\r\n self.iterator -= 1\r\n self._initializeImageScreen(self.fileNameList[self.iterator])\r\n elif option == \">\":\r\n if self.iterator == length - 1:\r\n self.iterator = 0\r\n else:\r\n self.iterator += 1\r\n self._initializeImageScreen(self.fileNameList[self.iterator])\r\n else:\r\n self._displayMessage(\"Zły przycisk\")\r\n else:\r\n self._displayMessage(\"Brak załadowanych zdjęć\")\r\n\r\n def _initializeControlButtons(self):\r\n buttonNames = [\"<\", \"zoom+\", \"zoom-\", \">\"]\r\n for name in buttonNames:\r\n self.buttons[name] = QPushButton(\r\n name, clicked=self.handleButtonClick)\r\n self.bottomLayout.addWidget(self.buttons[name])\r\n\r\n def _initializeImageScreen(self, imageName: str):\r\n pix = QPixmap(f\"{self.choosenDirectory}/{imageName}\")\r\n self.photo.resize(pix.width(), pix.height())\r\n self.photo.setPixmap(pix)\r\n\r\n def _initializeMenuBar(self):\r\n self.menu = QMenuBar(self)\r\n self.setMenuBar(self.menu)\r\n self.file = QMenu(\"Plik\", self)\r\n self.menu.addMenu(self.file)\r\n self.menu.addMenu(QMenu(\"Widok\", self))\r\n self.menu.addMenu(QMenu(\"Pomoc\", self))\r\n self._addActionsToFileView()\r\n\r\n def _openFolder(self, event):\r\n self.fileNameList.clear()\r\n self.choosenDirectory = str(\r\n QFileDialog.getExistingDirectory(self, \"Wybierz folder\"))\r\n if self.choosenDirectory == \"\":\r\n self._displayMessage(\"Brak określonej ścieżki\")\r\n else:\r\n self._getImagesNames()\r\n\r\n def _addActionsToFileView(self):\r\n self.openFolderAction = QAction(\"Wybierz folder\")\r\n self.openFolderAction.triggered.connect(self._openFolder)\r\n self.file.addAction(self.openFolderAction)\r\n\r\n def _getImagesNames(self):\r\n fileNames = os.listdir(self.choosenDirectory)\r\n for name in fileNames:\r\n if name.endswith(\".jpg\") or name.endswith(\".png\"):\r\n self.fileNameList.append(name)\r\n if self.fileNameList.__len__() == 0:\r\n self._displayMessage(\"Brak zdjęć w podanej lokalizacji\")\r\n else:\r\n self._initializeImageScreen(self.fileNameList[0])\r\n\r\n def _displayMessage(self, message: str):\r\n self.photo.resize(200, 200)\r\n self.photo.setText(message)\r\n\r\n\r\nif __name__ == '__main__':\r\n appHandler = QApplication([])\r\n photoApp = PhotosApp()\r\n sys.exit(appHandler.exec_())\r\n","sub_path":"PhotosApp.py","file_name":"PhotosApp.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"227619933","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 19 18:59:40 2018\n\n@author: Stefan Draghici\n\"\"\"\n\n# write to a file\nfile_handle=open('userdata.txt', 'w')\nname=input('enter your name: ')\nage=input('enter your age: ')\nfile_handle.write('Username is: %s\\n'%name)\nfile_handle.write('Age is: %s\\n'%str(age))","sub_path":"Python Pros/save user input.py","file_name":"save user input.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"574333300","text":"'''\nFITS handling functions\n'''\nimport logging\nimport numpy as np\nfrom ..config import *\n\ndef fits_header_check(header):\n\t'''Function that checks input FITS datacube header for\n\trequired header keywords.\n\tRequired headers = ['CDELT1/2/3'], ['CDELT3'] > 0, ['CRVAL3'], ['NAXIS1/2/3'], ['FUNITS']/['BUNIT'], ['CRPIX3'],\n\t['CTYPE1/2/3'] = 'RA, DEC, WAVELENGTH, ['CUNIT1/2/3'] = MAS, MAS, microns/angstroms/etc,\n\t['SPECRES'].\n\n\t\tInput:\n\n\t\theader: FITS file header\n\n\t'''\n\n\trequired_headers = ['NAXIS1', 'NAXIS2', 'NAXIS3', 'CDELT1',\n\t\t\t\t'CDELT2', 'CDELT3', 'CRVAL3', 'FUNITS',\n\t\t\t\t'CRPIX3', 'CUNIT1', 'CUNIT2', 'CUNIT3',\n\t\t\t\t'CTYPE1', 'CTYPE2', 'CTYPE3', 'SPECRES']\n\tmissing_headers = []\n\n\tctype1 = ['ra', 'x']\n\tctype2 = ['dec', 'y']\n\tctype3 = ['wavelength']\n\tcunit1 = ['mas', 'arcsec']\n\tcunit2 = cunit1\n\tcunit3 = ['micron', 'angstrom', 'meter', 'nanometers',\n\t\t'microns', 'angstroms', 'meters', 'nm']\n\tfunits = ['J/s/m2/um/arcsec2', 'erg/s/cm2/A/arcsec2',\n\t\t'J/s/m2/A/arcsec2', 'erg/s/cm2/um/arcsec2']\n\n\t#Check for use of BUNIT key\n\tif 'BUNIT' in header:\n\t\theader['FUNITS'] = header['BUNIT']\n\t\t\n\tfor i in required_headers:\n\t\tif i not in header:\n\t\t\tlogging.error('Missing header: ' + i)\n\t\t\tmissing_headers.append(i)\n\t\n\tif len(missing_headers) != 0:\n\t\traise HSIMError('Missing headers. Please correct datacube header.')\n\telse:\n\t\tif header['CUNIT1'].lower() == 'arcsec':\n\t\t\theader['CUNIT1'] = 'mas'\n\t\t\theader['CDELT1'] = header['CDELT1']*1000.\n\t\tif header['CUNIT2'].lower() == 'arcsec':\n\t\t\theader['CUNIT2'] = 'mas'\n\t\t\theader['CDELT2'] = header['CDELT2']*1000.\n\t\t\n\t\tlogging.info('All required headers present')\n\n\tif header['CTYPE3'].lower() not in ctype3:\n\t\traise HSIMError(\"CTYPE3 must be set to: \", ctype3)\n\tif header['CTYPE2'].lower() not in ctype2:\n\t\traise HSIMError(\"CTYPE2 must be set to: \", ctype2)\n\tif header['CTYPE1'].lower() not in ctype1:\n\t\traise HSIMError(\"CTYPE1 must be set to: \", ctype1)\n\tif header['CUNIT3'].lower() not in cunit3:\n\t\traise HSIMError(\"CUNIT3 must be set to one of: \", cunit3)\n\tif header['CUNIT2'].lower() not in cunit2:\n\t\traise HSIMError(\"CUNIT2 must be set to one of: \", cunit2)\n\tif header['CUNIT1'].lower() not in cunit1:\n\t\traise HSIMError(\"CUNIT1 must be set to one of: \", cunit1)\n\tif header['FUNITS'] not in funits:\n\t\traise HSIMError(\"FUNITS must be set to one of: \", funits)\n\tif header['CDELT3'] <= 0:\n\t\traise HSIMError(\"CDELT3 must be positive\")\n\t\n\tif \"CRVAL1\" not in header:\n\t\theader[\"CRVAL1\"] = 0\n\tif \"CRPIX1\" not in header:\n\t\theader[\"CRPIX1\"] = 1\n\t\t\n\tif \"CRVAL2\" not in header:\n\t\theader[\"CRVAL2\"] = 0\n\tif \"CRPIX2\" not in header:\n\t\theader[\"CRPIX2\"] = 1\n\t\n\tlogging.info('All header values acceptable')\n\n\ndef wavelength_array(header):\n\t'''Function that creates wavelength array in microns\n\tusing FITS file header.\n\n\t\tInputs:\n\n\t\theader: FITS file header\n\n\t\tOutputs:\n\n\t\tlambs: wavelength array in microns\n\t\thead: updated FITS file header\n\n\t'''\n\n\t#Create wavelength array using FITS headers\n\tlambs = header['CRVAL3'] + header['CDELT3']*(np.linspace(1, header['NAXIS3'], header['NAXIS3']) - header['CRPIX3'])\n\t\n\t#Check wavelength value of headers ['CDELT3'], ['CRVAL3'], ['SPECRES'] using header ['CUNITS3']\n\t#Working units of simulator = MICRONS\n\tw_units = header['CUNIT3'].lower()\n\n\tif w_units == 'microns' or w_units == 'micron':\n\t\tfactor = 1.\n\telif w_units == 'angstroms' or w_units == 'angstrom':\n\t\tfactor = 1.E-4\n\telif w_units == 'meters' or w_units == 'meter':\n\t\tfactor = 1.E6\n\telif w_units == 'nm' or w_units == 'nanometers':\n\t\tfactor = 1.E-3\n\telse:\n\t\traise HSIMError('Choose correct units please: microns, angstroms, metres or nm')\n\t\n\tlambs *= factor\n\theader['SPECRES'] *= factor\n\theader['CDELT3'] *= factor\n\t\n\t#Update header with new wavelength units\n\theader['CRVAL3'] = lambs[0]\n\theader['CUNIT3'] = 'microns'\n\n\treturn lambs, header\n\n\n","sub_path":"hsim/src/modules/fits_utils.py","file_name":"fits_utils.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"395416319","text":"from .core import CoreBot\nfrom .utils import getname, Database, load_db, save_db, get_attr\nfrom .args import Arg, UserType\nimport discord\nimport asyncio\nimport os\n# import subprocess\n# import queue\n# import threading\n# from string import printable\nimport time\n# import re\nfrom math import ceil, floor\n\nfrom .game_systems.base import GameSystem, GameError, GameEndException, JoinLeaveProhibited\nfrom .game_systems.story import StorySystem\nfrom .game_systems.poker import PokerSystem\n\nfrom functools import lru_cache\n\n# def avg(n):\n# return sum(n)/len(n)\n\n# Games overhaul / notes:\n\nSYSTEMS = [StorySystem, PokerSystem]\n\n\n# New commands:\n# !invite @user : bidder invites user to game\n# !join : Invitee accepts invitation to join game (dispatch on_join)\n# !leave : Player leaves game (dispatch on_leave). If bidder leaves, dispatch on_end instead\n\n# Enable games adds the following commands, events, and tasks\n# !games :\n\ndef EnableGames(bot):\n if not isinstance(bot, CoreBot):\n raise TypeError(\"This function must take a CoreBot\")\n\n bot.reserve_channel('games')\n bot._pending_activity = set()\n bot._game_system = None\n\n def listgames():\n for system in SYSTEMS:\n for game in system.games():\n yield game, system.name, system\n\n async def restore_game(self):\n state = load_db('game.json', {'user':'~'})\n if state['user'] != '~' and self._game_system is None:\n await self.send_message(\n self.fetch_channel('games'),\n \"The game has been interrupted. \"\n \"Please wait while I resume the previous game\"\n )\n try:\n self._game_system = await {\n game:system\n for game, sysname, system in listgames()\n }[state['game']].restore(self, state['game'])\n await self._game_system.on_init()\n await self._game_system.on_restore(\n self.get_user(state['user'])\n )\n await self._game_system.on_ready()\n except GameError:\n await self.send_message(\n self.fetch_channel('games'),\n \"I was unable to restore the previous state. \"\n \"The current game will be refunded\"\n )\n await self.trace()\n self.dispatch('endgame', 'hard')\n raise\n except:\n await self.send_message(\n self.fetch_channel('games'),\n \"I was unable to restore the previous state. \"\n \"The current game will be refunded\"\n )\n await self.trace()\n self.dispatch('endgame', 'critical')\n raise\n\n @bot.add_command('invite', Arg('user', type=UserType(bot), help=\"Username, nickname, or ID of user\"))\n async def cmd_invite(self, message, args):\n \"\"\"\n `$!invite ` : Invites the given user to join your game.\n Can only be used if you are the host of the current game\n Example: `$!invite $NAME` : Invites me to join your game\n \"\"\"\n async with Database('game.json', {'user':'~'}) as state:\n if state['user'] == '~':\n await self.send_message(\n message.channel,\n \"There are no games in progress. You can start one with `$!bid`\"\n )\n elif state['user'] != message.author.id:\n await self.send_message(\n message.channel,\n \"You are not the host of the current game. Only the host \"\n \"(who had the winning `$!bid` can invite players)\"\n )\n else:\n if self._game_system is None:\n await restore_game(self)\n if self._game_system.is_playing(args.user):\n return await self.send_message(\n message.channel,\n \"%d is already playing this game\" % getname(args.user)\n )\n if 'invites' not in state:\n state['invites'] = [args.user.id]\n elif args.user.id not in state['invites']:\n state['invites'].append(args.user.id)\n await self.send_message(\n args.user,\n '%s has invited you to play %s. Use `$!join` to accept the '\n 'invite and join the game.' % (\n message.author.mention,\n state['game']\n )\n )\n state.save()\n await self.send_message(\n message.channel,\n \"Invite sent to %s\" % args.user.mention\n )\n\n @bot.add_command('join', empty=True)\n async def cmd_join(self, message, content):\n \"\"\"\n `$!join` : Joins the current game, if you've been invited\n \"\"\"\n print(\"joining\")\n async with Database('game.json', {'user':'~'}) as state:\n print(\"Acquired state\")\n if state['user'] == '~':\n await self.send_message(\n message.channel,\n \"There are no games in progress. You can start one with `$!bid`\"\n )\n elif 'invites' not in state or message.author.id not in state['invites']:\n await self.send_message(\n message.channel,\n \"You have not been invited to play this game\"\n )\n else:\n print(\"State is joinable\")\n state['invites'].remove(message.author.id)\n state.save()\n await self.send_message(\n message.channel,\n \"Attempting to join the game...\"\n )\n if self._game_system is None:\n await restore_game(self)\n try:\n print(\"Joining\")\n await self._game_system.on_join(message.author)\n except JoinLeaveProhibited:\n await self.send_message(\n message.channel,\n \"The current game prohibits new players from joining the game\"\n )\n except GameEndException:\n await self.trace()\n await self.send_message(\n self.fetch_channel('games'),\n \"Encountered a critical error while adding a new player.\"\n \" The current game will be refunded\"\n )\n self.dispatch('endgame', 'hard')\n except:\n await self.trace()\n await self.send_message(\n self.fetch_channel('games'),\n \"Encountered an error while adding a new player\"\n )\n else:\n await self.send_message(\n message.channel,\n \"The game has processed your request to join. \"\n \"Use `$!leave` to leave the game\"\n )\n\n\n @bot.add_command('leave', empty=True)\n async def cmd_leave(self, message, content):\n \"\"\"\n `$!leave` : Leaves the current game, if you're playing.\n If you are the host of the game, leaving will end the game\n \"\"\"\n async with Database('game.json', {'user':'~'}) as state:\n print(\"LEAVING GAME\")\n if state['user'] == '~':\n await self.send_message(\n message.channel,\n \"There are no games in progress. You can start one with `$!bid`\"\n )\n else:\n if self._game_system is None:\n await restore_game(self)\n if not self._game_system.is_playing(message.author):\n await self.send_message(\n message.channel,\n \"You are not playing this game\"\n )\n else:\n if message.author.id == state['user']:\n await self.send_message(\n message.channel,\n \"You are the host of the current game. If you leave,\"\n \" the game will end. Do you still want to leave the\"\n \" game? (Yes/No)\"\n )\n while True:\n try:\n response = await self.wait_for(\n 'message',\n check=lambda m: m.author==message.author and m.channel == message.channel,\n timeout=60,\n )\n except asyncio.TimeoutError:\n await self.send_message(\n message.channel,\n \"%s, if you still want to leave the game, \"\n \"you'll have to use `$!leave` again\" % getname(message.author)\n )\n return\n if response.content.lower().strip() == 'no':\n await self.send_message(\n message.channel,\n \"Okay, %s. You will still remain in the game\" % getname(message.author)\n )\n return\n elif response.content.lower().strip() == 'yes':\n await self.send_message(\n self.fetch_channel('games'),\n \"Ending the game. The host, %s, has left\" % message.author.mention\n )\n return self.dispatch('endgame')\n await self.send_message(\n message.channel,\n \"I didn't understand your response. %s, would you\"\n \" like to quit your game? (Yes/No)\" % message.author.mention\n )\n else:\n try:\n await self._game_system.on_leave(message.author)\n except JoinLeaveProhibited:\n await self.send_message(\n message.channel,\n \"The current game prohibits players from leaving the game\"\n )\n except GameEndException:\n await self.trace()\n await self.send_message(\n self.fetch_channel('games'),\n \"Encountered a critical error while removing a player.\"\n \" The current game will be refunded\"\n )\n self.dispatch('endgame', 'hard')\n except:\n await self.trace()\n await self.send_message(\n self.fetch_channel('games'),\n \"Encountered an error while removing a player\"\n )\n\n\n @bot.add_command('games', empty=True)\n async def cmd_games(self, message, content):\n \"\"\"\n `$!games` : Lists the available games\n \"\"\"\n await self.send_message(\n message.channel,\n \"\\n\\n===========\\n\\n\".join(\n \"**%s**\\n%s\" % (\n system.name,\n ', '.join(sorted(\n '`%s`' % game for game in system.games()\n ))\n )\n for system in SYSTEMS\n )\n )\n\n def checker(self, message):\n state = load_db('game.json', {'user':'~'})\n return (\n message.channel == self.fetch_channel('games') and\n (not message.content.startswith(self.command_prefix)) and\n state['user'] != '~'\n )\n\n @bot.add_special(checker)\n async def state_router(self, message, content):\n # Routes messages depending on the game state\n # if not allowed:\n state = load_db('game.json', {'user':'~'})\n if state['user'] != '~' and self._game_system is None:\n await restore_game(self)\n if self._game_system.is_playing(message.author):\n try:\n await self._game_system.on_input(\n message.author,\n message.channel,\n message\n )\n except GameEndException:\n await self.send_message(\n self.fetch_channel('games'),\n \"The game encountered an irrecoverable error.\"\n \" I will refund you for the current game\"\n )\n await self.trace()\n self.dispatch('endgame', 'hard')\n except:\n await self.trace(False)\n elif 'restrict' in state and state['restrict']:\n await self.send_message(\n message.author,\n \"The current player has disabled comments in the story channel\"\n )\n await asyncio.sleep(0.5)\n await message.delete()\n\n\n @bot.add_command('toggle-comments', empty=True)\n async def cmd_toggle_comments(self, message, content):\n \"\"\"\n `$!toggle-comments` : Toggles allowing spectator comments in the story_channel\n \"\"\"\n async with Database('game.json', {'user':'~'}) as state:\n if state['user'] != message.author.id:\n await self.send_message(\n message.channel,\n \"You can't toggle comments if you aren't the game host\"\n )\n else:\n if 'restrict' not in state:\n state['restrict'] = True\n else:\n state['restrict'] = not state['restrict']\n await self.send_message(\n self.fetch_channel('games'),\n \"Comments from spectators are now %s\" % (\n 'forbidden' if state['restrict'] else 'allowed'\n )\n )\n state.save()\n\n @bot.add_command('_start', Arg('game', help=\"The game to play\"))\n async def cmd_start(self, message, args):\n \"\"\"\n `$!_start ` : Starts one of the allowed games\n Example: `$!_start zork1`\n \"\"\"\n async with Database('game.json', {'user':'~'}) as state:\n if state['user'] == '~':\n games = {\n game:system\n for game, sysname, system in listgames()\n }\n if args.game in games:\n state['bids'] = [{\n 'user':message.author.id,\n 'game':args.game,\n 'amount':0\n }]\n state.save()\n self.dispatch('startgame')\n else:\n await self.send_message(\n message.channel,\n \"That is not a valid game\"\n )\n else:\n await self.send_message(\n message.channel,\n \"Please wait until the current player finishes their game\"\n )\n\n @lru_cache(4096)\n def xp_for(level):\n if level <= 2:\n return 10\n else:\n return (2*xp_for(level-1)-xp_for(level-2))+5\n\n @bot.subscribe('grant_xp')\n async def grant_some_xp(self, evt, user, xp):\n # print(\n # \": %d xp has been granted to %s\" % (\n # xp, str(user)\n # )\n # )\n async with Database('players.json') as players:\n if user.id not in players:\n players[user.id] = {\n 'level':1,\n 'xp':0,\n 'balance':10\n }\n player = players[user.id]\n player['xp'] += xp\n current_level = player['level']\n while player['xp'] >= xp_for(player['level']+1):\n player['xp'] -= xp_for(player['level']+1)\n player['level'] += 1\n if player['level'] > current_level:\n await self.send_message(\n user,\n \"Congratulations on reaching level %d! Your weekly token payout\"\n \" and maximum token balance have both been increased. To check\"\n \" your balance, type `$!balance`\" % player['level']\n )\n players[user.id] = player\n players.save()\n\n @bot.add_command('balance', empty=True)\n async def cmd_balance(self, message, content):\n \"\"\"\n `$!balance` : Displays your current token balance\n \"\"\"\n async with Database('players.json') as players:\n if message.author.id not in players:\n players[message.author.id] = {\n 'level':1,\n 'xp':0,\n 'balance':10\n }\n player = players[message.author.id]\n await self.send_message(\n message.author,\n \"You are currently level %d and have a balance of %d tokens\\n\"\n \"You have %d xp to go to reach the next level\" % (\n player['level'],\n player['balance'],\n xp_for(player['level']+1)-player['xp']\n )\n )\n\n @bot.add_command(\n 'bid',\n Arg('amount', type=int, help='Amount of tokens to bid'),\n Arg('game', help=\"The game to play\")\n )\n async def cmd_bid(self, message, args):\n \"\"\"\n `$!bid ` : Place a bid to play the next game\n Example: `$!bid 1 zork1`\n \"\"\"\n async with Database('game.json', {'user':'~'}) as state:\n if message.author.id == state['user']:\n await self.send_message(\n message.channel,\n \"You can't bid on a game while you're currently hosting one.\"\n \" Why not give someone else a turn?\"\n )\n return\n async with Database('players.json') as players:\n bid = args.amount\n game = args.game\n games = {\n game:system\n for game, sysname, system in listgames()\n }\n if 'bids' not in state:\n state['bids'] = [{'user':'', 'amount':0, 'game':''}]\n # print(state)\n # print(players)\n # print(bid)\n # print(game)\n if bid <= state['bids'][-1]['amount']:\n if len(state['bids'][-1]['user']):\n await self.send_message(\n message.channel,\n \"The current highest bid is %d tokens. Your bid must\"\n \" be at least %d tokens.\" % (\n state['bids'][-1]['amount'],\n state['bids'][-1]['amount'] + 1\n )\n )\n return\n else:\n await self.send_message(\n message.channel,\n \"The minimum bid is 1 token\"\n )\n return\n if message.author.id not in players:\n players[message.author.id] = {\n 'level':1,\n 'xp':0,\n 'balance':10\n }\n if bid > players[message.author.id]['balance']:\n await self.send_message(\n message.channel,\n \"You do not have enough tokens to make that bid.\"\n \"To check your token balance, use `!balance`\"\n )\n return\n if game not in games:\n await self.send_message(\n message.channel,\n \"That is not a valid game. To see the list of games that\"\n \" are available, use `$!games`\"\n )\n return\n user = self.get_user(state['bids'][-1]['user'])\n if user:\n await self.send_message(\n user,\n \"You have been outbid by %s with a bid of %d tokens.\"\n \" If you would like to place another bid, use \"\n \"`$!bid %d %s`\" % (\n getname(message.author),\n bid,\n bid+1,\n state['bids'][-1]['game']\n )\n )\n state['bids'].append({\n 'user':message.author.id,\n 'amount':bid,\n 'game':game\n })\n state.save()\n if state['user'] == '~':\n self.dispatch('startgame')\n else:\n await self.send_message(\n message.channel,\n \"Your bid has been placed. If you are not outbid, your\"\n \" game will begin after the current game has ended\"\n )\n\n @bot.add_command(\n '_payout',\n Arg('user', type=UserType(bot), help=\"Username or ID\"),\n Arg('amount', type=int, help=\"Amount to pay\"),\n Arg('type', choices=['xp', 'tokens'], help=\"Type of payout (xp or tokens)\")\n )\n async def cmd_payout(self, message, args):\n \"\"\"\n `$!_payout ` : Pays xp/tokens to the provided user\n Example: `$!_payout some_user_id 12 xp`\n \"\"\"\n async with Database('players.json') as players:\n if args.user.id not in players:\n players[args.user.id] = {\n 'level':1,\n 'xp':0,\n 'balance':10\n }\n if args.type == 'tokens':\n players[args.user.id]['balance'] += args.amount\n else:\n self.dispatch(\n 'grant_xp',\n args.user,\n args.amount\n )\n players.save()\n\n @bot.add_command('reup', empty=True)\n async def cmd_reup(self, message, content):\n \"\"\"\n `$!reup` : Extends your current game session by 1 day\n \"\"\"\n async with Database('game.json', {'user':'~', 'bids':[]}) as state:\n async with Database('players.json') as players:\n if 'reup' not in state:\n state['reup'] = 1\n if state['user'] != message.author.id:\n await self.send_message(\n message.channel,\n \"You are not currently hosting a game\"\n )\n elif not (self._game_system is None or self._game_system.played):\n await self.send_message(\n message.channel,\n \"You should play your game first\"\n )\n elif players[state['user']]['balance'] < state['reup']:\n await self.send_message(\n message.channel,\n \"You do not have enough tokens to extend this session \"\n \"(%d tokens).\" % state['reup']\n )\n else:\n state['time'] += 86400\n # 1 day + the remaining time\n players[state['user']]['balance'] -= state['reup']\n state['reup'] += 1\n if 'notified' in state:\n del state['notified']\n await self.send_message(\n self.fetch_channel('games'),\n \"The current game session has been extended\"\n )\n state.save()\n\n @bot.subscribe('endgame')\n async def end_game(self, evt, hardness='soft'):\n async with Database('game.json', {'user':'~'}) as state:\n user = self.get_user(state['user'])\n async with Database('players.json') as players:\n if self._game_system is None or not self._game_system.played:\n await self.send_message(\n self.fetch_channel('games'),\n \"You quit your game without playing. \"\n \"You are being refunded %d tokens\" % (\n state['refund']\n )\n )\n players[user.id]['balance'] += state['refund']\n elif hardness != 'soft':\n await self.send_message(\n self.fetch_channel('games'),\n \"You are being refunded %d tokens.\"\n \" I apologize for the inconvenience\" % (\n state['refund']\n )\n )\n players[user.id]['balance'] += state['refund']\n state.save()\n players.save()\n if hardness != 'critical' and self._game_system is not None:\n try:\n await self._game_system.on_end(user)\n except:\n await self.trace()\n await self.send_message(\n self.fetch_channel('games'),\n \"I encountered an error while ending the game. \"\n \"Scores and payouts may not have been processed. \"\n \"If you belive this to be the case, please make a `!bug` report\"\n )\n async with Database('game.json', {'user':'~'}) as state:\n state['bids'] = state['bids'] if 'bids' in state else []\n state['user'] = '~'\n for k in set(state) - {'user', 'bids'}:\n del state[k]\n if self._game_system is not None:\n try:\n await self._game_system.on_cleanup()\n except:\n await self.trace()\n self._game_system = None\n state.save()\n if 'bids' not in state or len(state['bids']) == 1:\n await self.send_message(\n self.fetch_channel('games'),\n \"The game is now idle and will be awarded to the first bidder\"\n )\n else:\n self.dispatch('startgame')\n\n @bot.subscribe('startgame')\n async def start_game(self, evt):\n print(\"Starting game\")\n async with Database('game.json', {'user':'~', 'bids':[]}) as state:\n async with Database('players.json') as players:\n if state['user'] == '~':\n for bid in reversed(state['bids']):\n if bid['user'] != '':\n if bid['user'] not in players:\n players[bid['user']] = {\n 'level':1,\n 'xp':0,\n 'balance':10\n }\n user = self.get_user(bid['user'])\n if bid['amount'] > players[bid['user']]['balance']:\n await self.send_message(\n user,\n \"You do not have enough tokens to cover your\"\n \" bid of %d. Your bid is forfeit and the game\"\n \" shall pass to the next highest bidder\" % (\n bid['amount']\n )\n )\n continue\n players[bid['user']]['balance'] -= bid['amount']\n players.save()\n state['user'] = bid['user']\n state['restrict'] = False\n state['game'] = bid['game']\n state['refund'] = max(0, bid['amount'] - 1)\n state['time'] = time.time()\n state['bids'] = [{'user':'', 'amount':0, 'game':''}]\n state.save()\n await self.send_message(\n user,\n 'You have up to 2 days to finish your game, after'\n ' which, your game will automatically end\\n'\n 'Here are the global game-system controls:\\n'\n 'Any message you type in the games channel will be interpreted'\n ' as input to the game **unless** your message starts with `$!`'\n ' (my commands)\\n'\n '`$!reup` : Use this command to add a day to your game session\\n'\n 'This costs 1 token, and the cost will increase each time\\n'\n '`$!invite ` : Use this command to invite users to the game.'\n ' Note that not all games will allow players to join'\n ' or may only allow players to join at specific times\\n'\n '`$!leave` : Use this command to leave the game.'\n ' As the host, this will force the game to end\\n'\n '`$!toggle-comments` : Use this command to toggle permissions in the games channel\\n'\n 'Right now, anyone can send messages in the channel'\n ' while you\\'re playing. If you use `$!toggle-comments`,'\n ' nobody but you will be allowed to send messages.'\n ' Note: even when other users are allowed to send'\n ' messages, the game will only process messages'\n ' from users who are actually playing'\n )\n await self.send_message(\n self.fetch_channel('games'),\n '%s is now playing %s\\n'\n 'The game will begin shortly' % (\n user.mention,\n bid['game']\n )\n )\n break\n if state['user'] != '~':\n try:\n print(bid)\n self._game_system = {\n game:system\n for game, sysname, system in listgames()\n }[bid['game']](self, bid['game'])\n await self._game_system.on_init()\n await self._game_system.on_start(user)\n await self._game_system.on_ready()\n except GameError:\n await self.send_message(\n self.fetch_channel('games'),\n \"I was unable to initialize the game. \"\n \"The current game will be refunded\"\n )\n await self.trace()\n self.dispatch('endgame', 'hard')\n except:\n await self.send_message(\n self.fetch_channel('games'),\n \"I was unable to initialize the game. \"\n \"The current game will be refunded\"\n )\n await self.trace()\n self.dispatch('endgame', 'critical')\n return\n async with Database('game.json', {'user':'~', 'bids':[]}) as state:\n state['user'] = '~'\n state['transcript'] = []\n state['game'] = ''\n state['reup'] = 1\n state['bids'] = [{'user':'', 'amount':0, 'game':''}]\n state.save()\n await self.send_message(\n self.fetch_channel('games'),\n \"None of the bidders for the current game session could\"\n \" honor their bids. The game is now idle and will be\"\n \" awarded to the first bidder\"\n )\n\n\n @bot.subscribe('command')\n async def record_command(self, evt, command, user):\n async with Database('weekly.json') as week:\n if user.id not in week:\n week[user.id] = {}\n # print(week)\n if 'commands' not in week[user.id]:\n week[user.id]['commands'] = [command]\n # print(\"granting xp for first command\", command)\n self.dispatch(\n 'grant_xp',\n user,\n 5\n )\n elif command not in week[user.id]['commands']:\n week[user.id]['commands'].append(command)\n # print(\"granting xp for new command\", command)\n self.dispatch(\n 'grant_xp',\n user,\n 5\n )\n week[user.id]['active'] = True\n week.save()\n\n @bot.subscribe('after:message')\n async def record_activity(self, evt, message):\n if message.author.id != self.user.id:\n self._pending_activity.add(message.author.id)\n\n @bot.subscribe('cleanup')\n async def save_activity(self, evt):\n async with Database('weekly.json') as week:\n # print(week, self._pending_activity)\n for uid in self._pending_activity:\n if uid not in week:\n week[uid]={'active':True}\n else:\n week[uid]['active']=True\n self._pending_activity = set()\n # print(week)\n week.save()\n\n @bot.add_command('timeleft', empty=True)\n async def cmd_timeleft(self, message, content):\n \"\"\"\n `$!timeleft` : Gets the remaining time for the current game\n \"\"\"\n async with Database('game.json', {'user':'~', 'bids':[]}) as state:\n if state['user'] == '~':\n await self.send_message(\n message.channel,\n \"Currently, nobody is playing a game\"\n )\n else:\n delta = (state['time'] + 172800) - time.time()\n d_days = delta // 86400\n delta = delta % 86400\n d_hours = delta // 3600\n delta = delta % 3600\n d_minutes = delta // 60\n d_seconds = delta % 60\n await self.send_message(\n message.channel,\n \"%s's game of %s will end in %d days, %d hours, %d minutes, \"\n \"and %d seconds\" % (\n str(self.get_user(state['user'])),\n state['game'],\n d_days,\n d_hours,\n d_minutes,\n d_seconds\n )\n )\n\n @bot.add_command('highscore', Arg('game', help=\"The game to get the highscore of\"))\n async def cmd_highscore(self, message, args):\n \"\"\"\n `$!highscore ` : Gets the current highscore for that game\n Example: `$!highscore zork1`\n \"\"\"\n async with Database('scores.json') as scores:\n if args.game in scores:\n score, uid = sorted(\n scores[args.game],\n key=lambda x:x[0],\n reverse=True\n )[0]\n await self.send_message(\n message.channel,\n \"High score for %s: %d set by %s\" % (\n args.game,\n score,\n get_attr(self.get_user(uid), 'mention', '')\n )\n )\n else:\n await self.send_message(\n message.channel,\n \"No scores for this game yet\"\n )\n\n\n @bot.add_task(604800) # 1 week\n async def reset_week(self):\n #{uid: {}}\n async with Database('players.json') as players:\n async with Database('weekly.json') as week:\n print(\"Resetting the week\")\n xp = []\n for uid in week:\n user = self.get_user(uid)\n if uid not in players:\n players[uid] = {\n 'level':1,\n 'xp':0,\n 'balance':10\n }\n payout = players[user.id]['level']\n if players[user.id]['balance'] < 20*players[user.id]['level']:\n payout *= 2\n elif players[user.id]['balance'] > 100*players[user.id]['level']:\n payout //= 10\n players[uid]['balance'] += payout\n if 'active' in week[uid] or uid in self._pending_activity:\n xp.append([user, 5])\n #only notify if they were active. Otherwise don't bother them\n await self.send_message(\n self.get_user(uid),\n \"Your allowance was %d tokens this week. Your balance is now %d \"\n \"tokens\" % (\n payout,\n players[uid]['balance']\n )\n )\n self._pending_activity = set()\n players.save()\n os.remove('weekly.json')\n for user, payout in xp:\n # print(\"granting xp for activity payout\")\n self.dispatch(\n 'grant_xp',\n user,\n payout\n )\n\n @bot.add_task(1800) # 30 minutes\n async def check_game(self):\n async with Database('game.json', {'user':'~', 'bids':[]}) as state:\n now = time.time()\n if state['user'] != '~' and now - state['time'] >= 172800: # 2 days\n user = self.get_user(state['user'])\n self.dispatch('endgame', user)\n return\n elif state['user'] != '~' and now - state['time'] >= 151200: # 6 hours left\n if 'notified' not in state or state['notified'] == 'first':\n await self.send_message(\n self.get_user(state['user']),\n \"Your current game of %s is about to expire. If you wish to extend\"\n \" your game session, you can `$!reup` at a cost of %d tokens,\"\n \" which will grant you an additional day\" % (\n state['game'],\n state['reup'] if 'reup' in state else 1\n )\n )\n state['notified'] = 'second'\n state.save()\n elif (self._game_system is not None and self._game_system.played) and state['user'] != '~' and now - state['time'] >= 86400: # 1 day left\n if 'notified' not in state:\n await self.send_message(\n self.get_user(state['user']),\n \"Your current game of %s will expire in less than 1 day. If you\"\n \" wish to extend your game session, you can `$!reup` at a cost of\"\n \" %d tokens, which will grant you an additional day\" % (\n state['game'],\n state['reup'] if 'reup' in state else 1\n )\n )\n state['notified'] = 'first'\n state.save()\n if self._game_system is not None:\n try:\n await self._game_system.on_check()\n except:\n await self.trace()\n return bot\n","sub_path":"bots/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":41185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30189201","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\n\nfrom setuptools import setup, find_packages\n\nPACKAGE_NAME = \"hashcode20\"\n\nhere = os.path.abspath(os.path.dirname(__file__))\nabout = {}\nwith open(os.path.join(here, PACKAGE_NAME, '__version__.py'), 'r') as f:\n exec(f.read(), about)\n\nwith open('README.md', 'r') as f:\n readme = f.read()\n\n\nsetup(\n name=about[\"__title__\"],\n description=about['__description__'],\n version=about['__version__'],\n author=about['__author__'],\n author_email=about[\"__email__\"],\n long_description=readme,\n packages=find_packages(),\n install_requires=[],\n tests_require=[],\n entry_points={\n 'console_scripts': [\"hashcode20=hashcode20.__main__:main\"],\n },\n classifiers=[\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'License :: OSI Approved :: MIT Software License',\n 'Programming Language :: Python :: 3.7',\n ],\n license=about['__license__']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"401271021","text":"import click\nfrom tabulate import tabulate\nfrom two1.lib.server import rest_client\nfrom two1.commands.config import TWO1_HOST\nfrom two1.lib.server.analytics import capture_usage\nfrom two1.lib.util.decorators import json_output\nfrom two1.lib.util.uxstring import UxString\n\ndef has_bitcoinkit():\n \"\"\"Quick check for presence of mining chip via file presence.\n\n The full test is to actually try to boot the chip, but we\n only try that if this file exists.\n\n We keep this file in two1/commands/status to avoid a circular\n import.\n \"\"\"\n try:\n with open(\"/proc/device-tree/hat/product\", \"r\") as f:\n bitcoinkit_present = f.read().startswith('21 Bitcoin')\n except FileNotFoundError:\n bitcoinkit_present = False\n return bitcoinkit_present\n\n\ndef get_hashrate():\n \"\"\"Return hashrate of mining chip on current system.\n \"\"\"\n hashrate = None\n\n try:\n import socket\n import json\n\n s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n s.connect(\"/tmp/minerd.sock\")\n\n buf = b\"\"\n\n while True:\n chunk = s.recv(4096)\n\n # If server disconnected\n if not chunk:\n s.close()\n break\n\n buf += chunk\n while b\"\\n\" in buf:\n pos = buf.find(b\"\\n\")\n data = buf[0:pos].decode('utf-8')\n buf = buf[pos+1:]\n\n event = json.loads(data)\n\n if event['type'] == \"StatisticsEvent\":\n # Use 15min hashrate, if uptime is past 15min\n if event['payload']['statistics']['uptime'] > 15*60:\n hashrate = \"{:.1f} GH/s\".format(event['payload']['statistics']['hashrate']['15min']/1e9)\n else:\n hashrate = \"~50 GH/s (warming up)\"\n\n break\n\n if hashrate:\n break\n except:\n pass\n\n return hashrate or UxString.Error.data_unavailable\n\n\ndef status_mining(config, client):\n has_chip = has_bitcoinkit()\n if has_chip:\n bk = \"21 mining chip running (/run/minerd.pid)\"\n mined = client.get_mined_satoshis()\n hashrate = get_hashrate()\n if hashrate == UxString.Error.data_unavailable:\n bk = \"Run {} to start mining\".format(click.style(\"21 mine\", bold=True))\n else:\n bk, mined, hashrate = None, None, None\n data = dict(is_mining=bk,\n hashrate=hashrate,\n mined=mined)\n if has_chip:\n out = UxString.status_mining.format(**data)\n config.log(out)\n\n return data\n\n\n@click.command(\"status\")\n@click.option(\"--detail\",\n is_flag=True,\n default=False,\n help=\"List non-zero balances for each address\")\n@json_output\ndef status(config, detail):\n \"\"\"View your bitcoin balance and address.\n \"\"\"\n return _status(config, detail)\n\n\n@capture_usage\ndef _status(config, detail):\n client = rest_client.TwentyOneRestClient(TWO1_HOST,\n config.machine_auth,\n config.username)\n\n\n status = {\n \"account\": status_account(config),\n \"mining\": status_mining(config, client),\n \"wallet\": status_wallet(config, client, detail)\n }\n\n config.log(\"\")\n # status_endpoints(config)\n # status_bought_endpoints(config)\n\n return status\n\ndef status_account(config):\n status_account = {\n \"username\": config.username,\n \"address\": config.wallet.current_address\n }\n config.log(UxString.status_account.format(**status_account))\n return status_account\n\nSEARCH_UNIT_PRICE = 800\nSMS_UNIT_PRICE = 1000\n\n\ndef status_wallet(config, client, detail=False):\n \"\"\"Print wallet status to the command line.\n \"\"\"\n twentyone_balance, onchain, pending_transactions, flushed_earnings = \\\n _get_balances(config, client)\n\n if detail:\n # show balances by address for default wallet\n address_balances = config.wallet.balances_by_address(0)\n byaddress = [\"Addresses:\"]\n for addr, balances in address_balances.items():\n if balances['confirmed'] > 0 or balances['total'] > 0:\n byaddress.append(\"{}: {} (confirmed), {} (total)\".format(\n addr, balances['confirmed'], balances['total']))\n byaddress = '\\n '.join(byaddress)\n else:\n byaddress = \"To see all wallet addresses, do 21 status --detail\"\n\n status_wallet = {\n \"twentyone_balance\": twentyone_balance,\n \"onchain\": onchain,\n \"flushing\": flushed_earnings,\n \"byaddress\": byaddress\n }\n config.log(UxString.status_wallet.format(**status_wallet))\n\n total_balance = twentyone_balance + onchain\n buyable_searches = int(total_balance / SEARCH_UNIT_PRICE)\n buyable_sms = int(total_balance / SMS_UNIT_PRICE)\n status_buyable = {\n \"buyable_searches\": buyable_searches,\n \"search_unit_price\": SEARCH_UNIT_PRICE,\n \"buyable_sms\": buyable_sms,\n \"sms_unit_price\": SMS_UNIT_PRICE\n }\n config.log(UxString.status_buyable.format(**status_buyable), nl=False)\n\n if total_balance == 0:\n config.log(UxString.status_empty_wallet.format(click.style(\"21 mine\",\n bold=True)))\n else:\n buy21 = click.style(\"21 buy\", bold=True)\n buy21help = click.style(\"21 buy --help\", bold=True)\n config.log(UxString.status_exit_message.format(buy21, buy21help),\n nl=False)\n\n return {\n \"wallet\" : status_wallet,\n \"buyable\": status_buyable\n }\n\n\ndef _get_balances(config, client):\n balance_c = config.wallet.confirmed_balance()\n balance_u = config.wallet.unconfirmed_balance()\n pending_transactions = balance_u - balance_c\n\n spendable_balance = min(balance_c, balance_u)\n\n data = client.get_earnings()\n twentyone_balance = data[\"total_earnings\"]\n flushed_earnings = data[\"flushed_amount\"]\n\n return twentyone_balance, spendable_balance, pending_transactions, flushed_earnings\n\n\ndef status_earnings(config, client):\n data = client.get_earnings()\n total_earnings = data[\"total_earnings\"]\n total_payouts = data[\"total_payouts\"]\n config.log('\\nMining Proceeds', fg='magenta')\n config.log('''\\\n Total Earnings : {}\n Total Payouts : {}'''\n .format(none2zero(total_earnings),\n none2zero(total_payouts))\n )\n\n if \"flush_amount\" in data and data[\"flush_amount\"] > 0:\n flush_amount = data[\"flush_amount\"]\n config.log('''\\\n Flushed Earnings : {}'''\n .format(none2zero(flush_amount)),\n )\n config.log(\"\\n\" + UxString.flush_status % flush_amount, fg='green')\n\n\ndef status_shares(config, client):\n try:\n share_data = client.get_shares()\n except:\n share_data = None\n headers = (\"\", \"Total\", \"Today\", \"Past Hour\")\n data = []\n\n if share_data:\n try:\n for n in [\"good\", \"bad\"]:\n data.append(map(none2zero, [n, share_data[\"total\"][n],\n share_data[\"today\"][n],\n share_data[\"hour\"][n]]))\n except KeyError:\n data = [] # config.log(UxString.Error.data_unavailable)\n\n if len(data):\n config.log(\"\\nShare statistics:\", fg=\"magenta\")\n config.log(tabulate(data, headers=headers, tablefmt='psql'))\n # else:\n # config.log(UxString.Error.data_unavailable)\n\n\ndef none2zero(x):\n # function to map None values of shares to 0\n return 0 if x is None else x\n","sub_path":"two1/commands/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191694624","text":"#\n# This is a one-off fixer for the DXFs provided by a lady, Paula, who\n# digitized MKors patterns. It's ugly, but gets the job done\n#\n\n\nimport os\nimport tkinter as tk\nfrom tkinter import filedialog\n\n\n''' file dialogue pop up to get DXF '''\nroot = tk.Tk()\nroot.withdraw()\ndxf = filedialog.askopenfilename()\n\n# sizes = [\"XXXS\", \"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"2X\", \"XXXL\", \"3X\"]\n# dxf = os.path.expanduser('~/Desktop/dxf/test.dxf')\ndxf_name = os.path.splitext(os.path.basename(dxf))[0]\ndxf_out = os.path.expanduser('~/Desktop/' + dxf_name + '-FIXED.dxf')\n\n\ndef prep_list(list):\n ''' join a list into a string '''\n list.append(\"\\n\")\n for i in list:\n new = \" \".join(list)\n return new\n\n\nwith open(dxf, 'r') as file, open(dxf_out, 'w') as output:\n ''' walk through the dxf line by line '''\n for line in file:\n new_line = \"\"\n if \"Sample Size:\" in line:\n new_line = \"Sample Size: M\" + \"\\n\"\n output.write(new_line)\n elif \"_0\" in line and \"size\" not in line.lower():\n ls = line.split()\n size = ls[0].split(\"-\")[0]\n ls[0] = ls[0].strip(size + \"-\")\n ls[-1] = ls[-1].strip(\"_0\") + \"_\" + str(size)\n if len(ls) > 1:\n del ls[0]\n output.write(prep_list(ls))\n elif \"size:\" in line.lower() and \"0_\" in line:\n ls = line.split()\n new_line = \"Size: \" + str(size) + \"\\n\"\n output.write(new_line)\n elif \"All Sizes\" in line and \"Piece Name\" not in line:\n ls = line.split()\n ls[-1] = ls[-1].strip(\"_0\") + \"_\" + \"M\"\n del ls[0:2]\n output.write(prep_list(ls))\n elif \"Piece Name\" in line:\n ls = line.split()\n size = ls[3].split(\"-\")[0]\n if \"All Sizes\" in line:\n del ls[3:5]\n output.write(prep_list(ls))\n else:\n ls = line.split()\n if len(ls) > 3:\n ls[3] = ls[3].strip(size + \"-\")\n if ls[3] == \"\":\n del ls[3]\n else:\n ls[3] = ls[3].strip(size + \"-\")\n new_line = prep_list(ls)\n output.write(new_line)\n else:\n output.write(line)\n\n\nprint (\"\\nINFO: DONE\")","sub_path":"scripts/dxf_fixer.py","file_name":"dxf_fixer.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"92423731","text":"\"\"\"\nDjango settings for persona2 project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nTEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')\nSTATIC_PATH = os.path.join(BASE_DIR, 'static')\nSTATICFILES_DIRS = (STATIC_PATH,)\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ['SECRET_KEY']\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nALLOWED_HOSTS = []\n\nTEMPLATE_DIRS = [TEMPLATE_PATH,]\nCRISPY_TEMPLATE_PACK = 'bootstrap3'\n\nSTATIC_ROOT = \"/users/christopherallison/.virtualenvs/persona2/persona2/static/\"\n\n'''TREASURE_MAP = {\n 'BACKEND': 'treasuremap.backends.google.GoogleMapBackend',\n 'API_KEY': 'AIzaSyCt_OIk6L_5Ai7K19G6bsZMA9L7lw6yTjY',\n 'SIZE': (400, 600),\n 'MAP_OPTIONS': {\n 'zoom': 5\n }\n}'''\n\nLEAFLET_CONFIG = {\n #'SPACIAL_EXTENT': (5.0, 44.0, 7.5, 46),\n 'DEFAULT_CENTER': (50.91, -1.37),\n 'DEFAULT_ZOOM': 6,\n 'MIN_ZOOM': 1,\n 'MAX_ZOOM': 18,\n 'TILES': \"http://pelagios.dme.ait.ac.at/tilesets/imperium/{z}/{x}/{y}.png\"\n}\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n # Required by allauth template tags\n \"django.core.context_processors.request\",\n 'django.contrib.auth.context_processors.auth',\n # allauth specific context processors\n \"allauth.account.context_processors.account\",\n \"allauth.socialaccount.context_processors.socialaccount\",\n)\n\nAUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n \"django.contrib.auth.backends.ModelBackend\",\n # `allauth` specific authentication methods, such as login by e-mail\n \"allauth.account.auth_backends.AuthenticationBackend\",\n)\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n 'personas',\n 'crispy_forms',\n 'allauth',\n 'allauth.account',\n 'leaflet',\n 'djgeojson',\n 'sorl.thumbnail',\n 'django_markdown',\n #'treasuremap',\n #'allauth.socialaccount',\n # ... include the providers you want to enable:\n #'allauth.socialaccount.providers.amazon',\n #'allauth.socialaccount.providers.facebook',\n #'allauth.socialaccount.providers.github',\n #'allauth.socialaccount.providers.google',\n #'allauth.socialaccount.providers.twitter',\n)\n\nSITE_ID = 1\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'persona2.urls'\n\nWSGI_APPLICATION = 'persona2.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'chronicles',\n 'USER': 'christopher_allison',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\n# Security\n\n#CSRF_COOKIE_SECURE = True\n#ESSION_COOKIE_SECURE = True\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n# Heroku Settings\n\nimport dj_database_url\nDATABASES['default'] = dj_database_url.config()\nDATABASES['default']['ENGINE'] = 'django_postgrespool'\n\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nALLOWED_HOSTS = ['story-chronicles.herokuapp.com']\n\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nSTATIC_ROOT = 'staticfiles'\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n )\n\nACCOUNT_SIGNUP_FORM_CLASS = 'personas.forms.SignupForm'\n","sub_path":"persona2/settings_prod.py","file_name":"settings_prod.py","file_ext":"py","file_size_in_byte":4626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546432892","text":"#!/usr/bin/env python\n\n# __ __) ______ \n# (, /| /| , /) (, / ) /) \n# / | / | (/_ _ /---( _ _ _(/ _ ___\n# ) / |/ |__(_/(___(/_ ) / ____)(_(_/_)_(_(__(/_(_) \n# (_/ ' (_/ ( \n \n# ,dPYb, I8 \n# IP'`Yb I8 \n# I8 8I gg 88888888 \n# I8 8' \"\" I8 \n# ,gggg, I8 dP gg ,ggg, ,ggg,,ggg, I8 ,ggggg, ,ggg,,ggg, ,ggg, \n# dP\" \"Yb I8dP 88 i8\" \"8i ,8\" \"8P\" \"8, I8 dP\" \"Y8ggg ,8\" \"8P\" \"8, i8\" \"8i \n# i8' I8P 88 I8, ,8I I8 8I 8I ,I8, i8' ,8I I8 8I 8I I8, ,8I \n# ,d8,_ _,d8b,_ _,88,_ `YbadP' ,dP 8I Yb, ,d88b, ,d8, ,d8' ,dP 8I Yb, `YbadP' \n# P\"\"Y8888PP8P'\"Y888P\"\"Y8888P\"Y8888P' 8I `Y888P\"\"Y88 P\"Y8888P\" 8P' 8I `Y8888P\"Y888\n \nimport socket\nimport argparse\nimport re\nimport sys\nfrom argparse import RawTextHelpFormatter\nfrom packet import Packet\nimport ipaddress\nfrom thread import myThread\n\nurl_regex = r\"^((http?):\\/)?\\/?([^:\\/\\s\\?]+)\\/?([^:\\/\\s\\?]+)?\"\n\n\ndef syn(router_addr, router_port, server_addr, server_port):\n while True:\n peer_ip = ipaddress.ip_address(socket.gethostbyname(server_addr))\n conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n timeout = 5\n try:\n p = Packet(packet_type=1,\n seq_num=1,\n peer_ip_addr=peer_ip,\n peer_port=server_port,\n payload=message.encode(\"utf-8\"))\n \n conn.sendto(p.to_bytes(), (router_addr, router_port))\n print(\" \\n \")\n print(\"-------------------BEGINNING HANDSHAKE-----------------\")\n print(\"[CLIENT] - Sending SYN - (PacketType = 1)\")\n conn.settimeout(timeout)\n print('[CLIENT] - Waiting For A Response - Should be an SYN-ACK')\n response, sender = conn.recvfrom(1024)\n p = Packet.from_bytes(response)\n print(\"[CLIENT] - Response Recieved. Is it a SYN-ACK? (Packet Type of 2)\")\n print('[CLIENT] - PacketType = ' , p.packet_type)\n\n if(p.packet_type == 2):\n print(\"[CLIENT] - Yes, Got a SYN-ACK back, send back ACK (Packet Type of 3)\")\n # just fucking send packet of type 3 send here and don't get anything back.\n return True\n\n except socket.timeout:\n print('[CLIENT] - No response after %d for Packet %d ' %(timeout, p.seq_num))\n finally:\n conn.close()\n\ndef ack(router_addr, router_port, server_addr, server_port):\n while True:\n peer_ip = ipaddress.ip_address(socket.gethostbyname(server_addr))\n conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n timeout = 5\n try:\n # Packet type to 1 (SYN). Then have the server recognize the packet_type and return a 2 (SYN-ACK)\n p = Packet(packet_type=3,\n seq_num=1,\n peer_ip_addr=peer_ip,\n peer_port=server_port,\n payload=message.encode(\"utf-8\"))\n print(\"[CLIENT] - Sending ACK\")\n conn.sendto(p.to_bytes(), (router_addr, router_port))\n \n\n # Receive a response within timeout\n conn.settimeout(timeout)\n print(\"[CLIENT] - Waiting For A Response - (Should be an ACK)\")\n response, sender = conn.recvfrom(1024)\n p = Packet.from_bytes(response)\n\n print(\"[CLIENT] - Response Recieved. Is it a SYN-ACK? (Packet of Type 3)\")\n print('[CLIENT] - PacketType = ' , p.packet_type)\n print(\"[CLIENT] - Yes, Got an ACK back. Proceed with request.\")\n return True\n\n except socket.timeout:\n print('[CLIENT] - No response after %ds for Packet %d ' %(timeout, p.seq_num))\n finally:\n conn.close()\n \n\n# create parser to pull out url from the command line\nparser = argparse.ArgumentParser(description='Mike Basdeo - 26788815 \\r\\nhttpc is a curl-like application but supports HTTP protocol only', add_help=False, formatter_class=RawTextHelpFormatter)\nparser.add_argument('--help', action='help', help='show this help message and exit')\n\n# get/post commands are optional(either/or) and don't have dashes\nparser.add_argument('mode', choices=['get','post'], help=\"Executes a HTTP GET or POST request for a given URL with inline data\")\n\n# positional requirement (mandatory no dash)\nparser.add_argument('url', action=\"store\", help=\"mandatory uniform resource locator to perform requet on\")\n\n# data command (optional)\nparser.add_argument('-d', dest=\"data\", action=\"store\", metavar=\"inline-data\", help=\"associates inline data to the body HTTP POST\")\n# header command (optional)\nparser.add_argument('-h', dest=\"header\", action=\"store\", metavar=\"inline-data\", help=\"associates headers to HTTP Request with the format\")\n\n# read from file command (optional)\nparser.add_argument('-f', dest=\"file\", action=\"store\", metavar=\"inline-data\", help=\"associates the content of a file to the body HTTP POST\")\n\n# output to file(optional)\nparser.add_argument('-o', dest=\"output\", action=\"store\", metavar=\"inline-data\", help=\"stores terminal output in a file\")\n\n# verbose command (optional)\nparser.add_argument('-v','--verbose', action=\"store_true\")\n\n# port command (optional)\nparser.add_argument('-p','--port', help=\"server port\", type=int, default=8007)\n\n\nparser.add_argument(\"--routerhost\", help=\"router host\", default=\"localhost\")\nparser.add_argument(\"--routerport\", help=\"router port\", type=int, default=3000)\nparser.add_argument(\"--serverhost\", help=\"server host\", default=\"localhost\")\nparser.add_argument(\"--serverport\", help=\"server port\", type=int, default=8007)\n\n\n\nargs = parser.parse_args()\n\n# chop up the found url using regex\nmatcher = re.search(url_regex, args.url)\n\nserver = matcher.group(3)\n\nquery_param = ''\nif(matcher.group(4)):\n query_param = matcher.group(4)\n\nif(args.port):\n port = args.port\n\ndef handshake():\n handShake = False\n # Always perform a handshake before initial request.\n while handShake == False:\n sendSyn = False\n sendSyn = syn(args.routerhost, args.routerport, args.serverhost, args.serverport)\n\n # Only return true when the whole thing comes back. check at each step. \n if sendSyn == True:\n sendAck = ack(args.routerhost, args.routerport, args.serverhost, args.serverport)\n if sendAck == True:\n print(\"--------------------HANDSHAKE COMPLETE-----------------\")\n handShake = True\n return True\n\n\n\n# GET REQUEST\nif(args.mode == 'get'):\n message = 'GET /'+query_param+' HTTP/1.1\\r\\n'\n message += 'Host:' +server+':'+str(port)+'\\r\\n'\n message += 'Connection: close\\r\\n'\n message += '\\r\\n'\n\n handShakeComplete = handshake()\n if handShakeComplete == True:\n\n objs = [myThread(i, \"Thread\", i, message, args.routerhost, args.routerport, args.serverhost, args.serverport) for i in range(10)]\n for obj in objs:\n obj.start()\n for ojb in objs:\n obj.join()\n\n\n# POST REQUEST\nif(args.mode == 'post'):\n if(args.data):\n data = args.data\n if (args.file):\n with open (args.file, \"r\") as myfile:\n data=myfile.read()\n \n print(data)\n data_bytes = data.encode()\n \n message = 'POST /'+query_param+' HTTP/1.1\\r\\n'\n message += 'Content-length:'+str(len(data_bytes))+'\\r\\n'\n message += 'Host:' +server+':'+str(port)+'\\r\\n'\n message += 'Connection: close\\r\\n\\r\\n'\n message += data+'\\r\\n'\n handShakeComplete = handshake()\n if handShakeComplete == True:\n objs = [myThread(i, \"Thread\", i, message, args.routerhost, args.routerport, args.serverhost, args.serverport) for i in range(10)]\n for obj in objs:\n obj.start()\n for ojb in objs:\n obj.join()\n\n\n# TODO Check that this still works.\n# if(args.output):\n# f = open(args.output, 'w')\n# sys.stdout = f\n# connect()\n# f.close()\n\n\n\n","sub_path":"httpc.py","file_name":"httpc.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"526899759","text":"#!/bin/python3\n# author: Jan Hybs\n\nimport os\nimport sys\nimport shutil\nimport subprocess\nfrom proc.execution import create_execute_command\nfrom utils.logging import logger\n\n\nclass Git(object):\n \"\"\"\n :type git: structures.project_step_git.ProjectStepGit\n \"\"\"\n def __init__(self, git):\n self.git = git\n self.dir = os.path.abspath(os.path.join(os.getcwd(), self.git.repo))\n self.execute = create_execute_command(\n logger_method=logger.debug,\n stdout=subprocess.DEVNULL,\n )\n\n def clone(self):\n if self.git.remove_before_checkout:\n shutil.rmtree(self.dir, ignore_errors=True)\n\n if os.path.exists(self.dir):\n # print('Directory not empty', self.dir, '(git clone skipped)')\n return\n\n self.execute('git clone', self.git.url, self.dir).wait()\n\n def checkout(self):\n branch = self.git.branch\n commit = self.git.commit\n\n if branch:\n branch = branch.replace('origin/', '')\n\n logger.info('Git checkout repo={self.git.repo} to branch={self.git.branch}, commit={self.git.commit}'.format(self=self))\n self.execute(\"git config core.pager\", \"\", dir=self.dir) # turn of less pager\n self.execute('pwd', dir=self.dir).wait()\n self.execute('git branch -vv', dir=self.dir).wait()\n self.execute('git fetch', dir=self.dir).wait()\n\n if branch:\n # just in case set remote upstream branch\n # then forcefully checkout to branch\n # and pull the latest changes\n self.execute('git branch --set-upstream-to=origin/%s %s' % (branch, branch), dir=self.dir).wait()\n self.execute('git checkout -f', branch, dir=self.dir).wait()\n self.execute('git pull', dir=self.dir).wait()\n\n if commit:\n # if there is a commit specified, we forcefully checkout it out\n head = subprocess.check_output('git rev-parse HEAD'.split(), cwd=self.dir).decode()\n if head != commit:\n self.execute('git checkout -f', commit, dir=self.dir).wait()\n # create new local branch with given name (if branch is specified)\n # so if someone asks on which branch we are, answer won't be 'detached HEAD'\n if branch:\n self.execute('git branch -d', branch, dir=self.dir).wait()\n self.execute('git checkout -b', branch, dir=self.dir).wait()\n\n def info(self):\n logger.debug('Repository currently at:')\n self.execute('git branch -vv', dir=self.dir).wait()\n self.execute('git log -n 10 --graph', '--pretty=format:%h %ar %aN%d %s', dir=self.dir).wait()\n","sub_path":"ci-hpc/vcs/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191128207","text":"import csv\n\ndata = []\n\nwith open('dump.csv', 'r') as csvfile:\n # get the data from the csv dump\n reader = csv.reader(csvfile)\n data = [int(point) for point in reader.next()]\n\n # make sure that there are no blips from the readings\n data = [a for a in data if (a > 20 and a < 500)]\n\nwith open('processed.csv', 'w') as csvfile:\n # write out modified data back out, overwriting the original data\n writer = csv.writer(csvfile)\n writer.writerow(data)","sub_path":"dataprocess/dataprocess.py","file_name":"dataprocess.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197432172","text":"import re\nimport config\nfrom models.db_tables import *\n\n\ndef get_nodeName(cmd_printout):\n return re.compile(r'[\\d\\w]+$').findall(cmd_printout)[0]\n\n\ndef get_alist(cmd_printout):\n result = {}\n line = ''\n entry = ''\n\n file_iterator = iter(cmd_printout.splitlines())\n\n alarm_entries = {\n 'Alarm Identifier': APalarms.alarmId.db_column,\n 'Object of Reference': APalarms.objectOfRef.db_column,\n 'Alarm Text': APalarms.alarmText.db_column,\n 'Problem Data': APalarms.problemData.db_column\n }\n\n re_alist = re.compile(r'(?:{0}).*'.format('|'.join(i for i in alarm_entries.keys())), re.MULTILINE)\n\n for i in range(len(alarm_entries)):\n while line not in re_alist.findall(line):\n if entry:\n result.get(alarm_entries.get(entry)).append(line)\n line = next(file_iterator)\n for entry in alarm_entries.keys():\n if entry in line:\n result.update({alarm_entries.get(entry): [line]})\n break\n line = next(file_iterator)\n\n return result\n\n\ndef get_prcstate(cmd_printout):\n result = {}\n re_prcstate = re.compile(r'^[^<>]+', re.MULTILINE).findall(cmd_printout)\n try:\n (currentNode, otherNode, swBRinfo) = re_prcstate[1].splitlines()\n except ValueError:\n (currentNode, otherNode) = re_prcstate[1].splitlines()\n swBRinfo = None\n\n result.update(dict(zip([ProcessControl.currentNodeState.db_column, ProcessControl.currentNodeInfo.db_column],\n currentNode.split(' ', 1))))\n result.update(dict(zip([ProcessControl.otherNodeState.db_column, ProcessControl.otherNodeInfo.db_column],\n otherNode.split(' ', 1))))\n result.update({ProcessControl.swBRinfo.db_column: swBRinfo})\n\n return result\n\n\ndef get_netls(cmd_printout):\n def set_network(l):\n config.network = l.split()[0]\n\n def set_node(l):\n config.node = l[-1]\n\n def set_ipAddress(l):\n config.ipAddress = l.split()[-1]\n\n def set_macAddress(l):\n config.macAddress = l.split()[-1]\n\n def set_subnetMask(l):\n config.subnetMask = l.split()[-1]\n\n def set_gwIpAddress(l):\n config.gw_ipAddress = l.split(':')[-1].strip()\n\n def set_clusterIpAddress(l):\n config.cluster_ipAddress = l.split()[-1]\n\n result = {}\n\n templates = {\n re.compile(r'^NODE-(.)'): set_node,\n re.compile(r'^IP Address'): set_ipAddress,\n re.compile(r'^MAC Address'): set_macAddress,\n re.compile(r'^Subnet Mask'): set_subnetMask,\n re.compile(r'^Gateway IP'): set_gwIpAddress,\n re.compile(r'^Cluster IP'): set_clusterIpAddress\n }\n\n networks = {\n 'Public': [{'A': [APNetworkList.PN_A_ipAddress.db_column,\n APNetworkList.PN_A_macAddress.db_column,\n APNetworkList.PN_A_subnetMask.db_column],\n 'B': [APNetworkList.PN_B_ipAddress.db_column,\n APNetworkList.PN_B_macAddress.db_column,\n APNetworkList.PN_B_subnetMask.db_column]},\n [APNetworkList.PN_GW_ipAddress.db_column,\n APNetworkList.PN_Cluster_ipAddress.db_column]],\n 'Separated': [{'A': [APNetworkList.SPN_A_ipAddress.db_column,\n APNetworkList.SPN_A_macAddress.db_column,\n APNetworkList.SPN_A_subnetMask.db_column],\n 'B': [APNetworkList.SPN_B_ipAddress.db_column,\n APNetworkList.SPN_B_macAddress.db_column,\n APNetworkList.SPN_B_subnetMask.db_column]},\n [APNetworkList.SPN_GW_ipAddress.db_column,\n APNetworkList.SPN_Cluster_ipAddress.db_column]],\n 'VLAN': [{'A': [APNetworkList.VN_A_ipAddress.db_column,\n APNetworkList.VN_A_macAddress.db_column,\n APNetworkList.VN_A_subnetMask.db_column],\n 'B': [APNetworkList.VN_B_ipAddress.db_column,\n APNetworkList.VN_B_macAddress.db_column,\n APNetworkList.VN_B_subnetMask.db_column]},\n [APNetworkList.VN_GW_ipAddress.db_column,\n APNetworkList.VN_Cluster_ipAddress.db_column]]\n }\n\n re_network = re.compile(r'^(?:{0}).+'.format('|'.join(n for n in networks.keys())))\n line_iterator = iter(cmd_printout.splitlines())\n line = next(line_iterator)\n\n for i in range(len(cmd_printout.splitlines())):\n\n while line and not re_network.findall(line):\n for t in templates:\n if t.findall(line):\n templates.get(t)(line)\n break\n try:\n line = next(line_iterator)\n except StopIteration:\n break\n\n if config.network and config.node and config.ipAddress and config.macAddress and config.subnetMask:\n # noinspection PyTypeChecker\n result.update(dict(zip(networks.get(config.network)[0].get(config.node),\n [config.ipAddress, config.macAddress, config.subnetMask])))\n config.node = config.ipAddress = config.macAddress = config.subnetMask = None\n\n if config.gw_ipAddress and config.cluster_ipAddress:\n # noinspection PyTypeChecker\n result.update(dict(zip(networks.get(config.network)[1],\n [config.gw_ipAddress, config.cluster_ipAddress])))\n config.gw_ipAddress = config.cluster_ipAddress = None\n\n if 'Network' in line:\n set_network(line)\n\n try:\n line = next(line_iterator)\n except StopIteration:\n break\n\n return result\n\n\ndef get_rifls(cmd_printout):\n entries = cmd_printout.splitlines()[-2:]\n result = {}\n interfaces = [\n [APrpiList.ActiveNode.db_column, APrpiList.ActiveNodeIp.db_column, APrpiList.ActiveNodeState.db_column],\n [APrpiList.PassiveNode.db_column, APrpiList.PassiveNodeIp.db_column, APrpiList.PassiveNodeState.db_column]\n ]\n for i in range(len(entries)):\n result.update(dict(zip(interfaces[i], entries[i].split())))\n return result\n\n\ndef get_swrprint(cmd_printout):\n result = {}\n entry = ''\n entries = {\n 'AP SOFTWARE': [True, [SoftwareRecord.System.db_column, SoftwareRecord.Node.db_column,\n SoftwareRecord.AposPackage.db_column, SoftwareRecord.AposSecurity.db_column,\n SoftwareRecord.ProductName.db_column, SoftwareRecord.Identity.db_column,\n SoftwareRecord.Revision.db_column], []],\n 'PACKAGE': [False, [SoftwareRecord.Packages.db_column], []],\n 'Category': [False, [SoftwareRecord.Categories.db_column], []]\n }\n\n re_swrprint = re.compile(r'^(?:{0}).+'.format('|'.join(e for e in entries.keys())))\n re_headers = [re.compile(r'PRODUCTNAME\\s+')]\n\n for line in cmd_printout.splitlines():\n if line and not re_swrprint.findall(line):\n if entry and entries.get(entry)[0]:\n for h in re_headers:\n if not h.findall(line):\n entries.get(entry)[2].append(line)\n elif entry and line:\n entries.get(entry)[2][0] += '\\n' + line\n continue\n\n if line:\n for k in entries.keys():\n if k in line:\n entry = k\n entries.get(entry)[2].append(line)\n break\n\n valuesOnly = []\n for k, v in entries.items():\n if v[0]:\n for e in v[2][1:-1]:\n valuesOnly.append(e.rsplit(' ', 1)[-1])\n valuesOnly.extend(v[2][-1].split())\n entries[k][2] = valuesOnly\n result.update(dict(zip(v[1], v[2])))\n\n return result\n\n\ndef get_hwcls(cmd_printout):\n re_hwcls = re.compile(r'^(?:>hw|HARDWARE CONFIGURATION)')\n result = [[Slot.MAGADDR.db_column,\n Slot.SLOT.db_column,\n Slot.SYSTYPE.db_column,\n Slot.SYSNUM.db_column,\n Slot.FBN.db_column,\n Slot.IPA.db_column,\n Slot.IPB.db_column],\n []]\n for line in cmd_printout.splitlines():\n if line and not re_hwcls.findall(line):\n result[1].append(line.split())\n return result\n\n\ndef get_hwiprint(cmd_printout):\n\n def parse_magazine(s):\n return list(re_magazine.findall(s)[0])\n\n def parse_backplane(s):\n return list(re_backplane.findall(s)[0])\n\n def parse_pfm(s):\n return list(re_pfm.findall(s)[0])\n\n def parse_board(s):\n return list(re_board.findall(s)[0])\n\n entry = ''\n result = {\n 'MAGAZINE': [False, [Magazine.MAGADDR.db_column,\n Magazine.CABROW.db_column,\n Magazine.CABNO.db_column,\n Magazine.XPOS.db_column,\n Magazine.YPOS.db_column],\n [], parse_magazine],\n 'BACKPANE': [False, [Backplane.MAGADDR.db_column,\n Backplane.PRODUCTNAME.db_column,\n Backplane.PRODUCTNO.db_column,\n Backplane.REV.db_column,\n Backplane.SERIALNO.db_column,\n Backplane.SUPPLIER.db_column,\n Backplane.MANDATE.db_column],\n [], parse_backplane],\n 'POWER': [True, [PowerAndFanModule.MAGADDR.db_column,\n PowerAndFanModule.INSTANCE.db_column,\n PowerAndFanModule.PRODUCTNAME.db_column,\n PowerAndFanModule.PRODUCTNO.db_column,\n PowerAndFanModule.REV.db_column,\n PowerAndFanModule.SERIALNO.db_column,\n PowerAndFanModule.DEVTYPE.db_column,\n PowerAndFanModule.HWVER.db_column,\n PowerAndFanModule.MANDATE.db_column],\n [], parse_pfm],\n 'BOARDS': [True, [Slot.XPOS.db_column,\n Slot.YPOS.db_column,\n Slot.PRODUCTNAME.db_column,\n Slot.PRODUCTNO.db_column,\n Slot.REV.db_column,\n Slot.SERIALNO.db_column,\n Slot.SUPPLIER.db_column,\n Slot.BUSTYPE.db_column,\n Slot.MANDATE.db_column],\n [], parse_board]\n }\n\n re_hwiprint = re.compile(r'^(?:{0}|{1}).+'.format(('|'.join(e for e in result.keys())), 'BACKPLANE'))\n re_headers = re.compile(r'^\\s*(?:MAGADDR|SERIALNO).+')\n\n re_magaddr = '^([\\d.]+)'\n re_pos = '(?:\\s+(\\d+|-))'\n re_slot = '(\\d{,2})'\n re_pname = '(\\S+(?:\\s?\\S+)*)'\n re_pnumber = '(\\S+(?:\\s?\\S+){,2}/\\S+)'\n re_revision = '(R\\S+)'\n re_snumber = '(\\S+)'\n re_hwver = '(\\S+)'\n re_supplier = '(\\S+(?:\\s*\\S+)*)?'\n re_mandate = '(\\d+)'\n re_instance = '(upper|lower)'\n re_devtype = '(hod|lod)'\n re_bustype = '(ipmi|mbus)'\n\n re_magazine = re.compile(r'{0}'.format(re_magaddr + re_pos * 4))\n re_backplane = re.compile(r'{0}\\s+{1}\\s+{2}\\s*{3}\\s+{4}\\s+{5}\\s+{6}'.format(\n re_magaddr, re_pname, re_pnumber, re_revision, re_snumber, re_supplier, re_mandate))\n re_pfm = re.compile(r'{0}\\s+{1}\\s+{2}\\s+{3}\\s*{4}\\s+{5}\\s+{6}\\s+{7}\\s+{8}'.format(\n re_magaddr, re_instance, re_pname, re_pnumber, re_revision, re_snumber, re_devtype, re_hwver, re_mandate),\n re.IGNORECASE)\n re_board = re.compile(r'{0}\\s+{1}\\s+{2}\\s+{3}\\s+{4}\\s+{5}\\s*{6}\\s+{7}\\s*{8}\\s+{9}\\s+{10}'.format(\n re_magaddr, re_slot, re_pos, re_pos, re_pname, re_pnumber, re_revision,\n re_snumber, re_supplier, re_bustype, re_mandate), re.IGNORECASE)\n\n # Parse command printout\n for line in cmd_printout.splitlines()[1:]:\n if line and not re_hwiprint.findall(line):\n if entry and result.get(entry) and not re_headers.findall(line):\n result.get(entry)[2].append(line)\n continue\n\n if line:\n for k in result.keys():\n if k in line:\n entry = k\n result.get(entry)[2].append(line)\n break\n\n # Keep values only\n for k in result.keys():\n if result.get(k)[0]:\n board = result.get(k)[2][1:]\n result[k][2] = [board[i] + ' ' + board[i + 1] for i in range(0, len(board), 2)]\n else:\n result[k][2] = result.get(k)[2][1:]\n\n # Parse values\n for k, v in result.items():\n for i in range(len(v[2])):\n v[2][i] = result.get(k)[-1](v[2][i])\n\n return result\n","sub_path":"modules/command_parsers.py","file_name":"command_parsers.py","file_ext":"py","file_size_in_byte":12796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394173076","text":"## Copyright (c) 2012-2014 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\"\"\"Create a new project \"\"\"\n\nimport os\n\nimport qisrc # for QISRC_ROOT_DIR\nfrom qisys import ui\nimport qisys.parsers\n\ndef copy_helper(project_name, directory):\n \"\"\"Create a new project in the specified directory.\n\n \"\"\"\n # Read the templates for projects\n template_dir = os.path.join(qisrc.QISRC_ROOT_DIR, \"templates\", \"project\")\n template_dir = os.path.abspath(template_dir)\n\n for file_name in os.listdir(template_dir):\n with open(os.path.join(template_dir, file_name), \"r\") as old_file:\n old_contents = old_file.read()\n new_contents = old_contents.replace(\"@project_name@\", project_name)\n with open(os.path.join(directory, file_name), \"w\") as new_file:\n new_file.write(new_contents)\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action \"\"\"\n qisys.parsers.worktree_parser(parser)\n parser.add_argument(\"project_name\",\n help=\"The name of the project. \"\n \"The project will be created in QI_WORK_TREE/ \")\n parser.add_argument(\"--git\", action=\"store_true\",\n help=\"Create a git repository\")\n\n\ndef do(args):\n \"\"\"\"Create a new project \"\"\"\n worktree = qisys.parsers.get_worktree(args)\n\n project_name = args.project_name\n project_path = os.path.join(os.getcwd(), project_name)\n\n if os.path.exists(project_path):\n raise Exception(\"%s already exists\" % project_path)\n os.mkdir(project_path)\n copy_helper(project_name, project_path)\n\n if args.git:\n qisys.command.call([\"git\", \"init\"], cwd=project_path)\n with open(os.path.join(project_path, \".gitignore\"), \"w\") as fp:\n fp.write(\"build-*\\n\")\n qisys.command.call([\"git\" , \"add\" , \".\"], cwd=project_path)\n qisys.command.call([\"git\" , \"commit\" , \"-m\" , \"initial commit\"], cwd=project_path)\n\n ui.info(ui.green, \"New project initialized in\", ui.bold, project_path)\n worktree.add_project(project_path)\n return worktree.get_project(project_path)\n","sub_path":"python/qisrc/actions/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373739438","text":"'''\n\n Python Script for Source to Source Translator\n Created by Yijie Zhuang, May 2015\n\n\n'''\n\n\n#!/usr/bin/python\nfrom pyparsing import *\nimport sys,string\n\n'''\n\n File initilization : \n\n Processing input file: param.cfg, Csrc/XXX.c Csrc/XXX_init.c\n a. param.cfg : used to config translator parameters;\n b. XXX.c : function to be translated into kernel, and related helper functions\n c. XXX_init.c: functions used to initilize kernel parameter,\n also contain functions for I/O operations\n Create output file: output_XXX.c, Makefile, kernel_XXX.cl, clhead.h\n\n'''\n\n\n#Read Config File to get the SourceFileName and SourceFunc\nconfig = open('param.cfg','r')\ncfglines = config.readlines()\ncsourcename = cfglines[0].split()[0]\ncsourcefunc = cfglines[0].split()[1]\nsubdir = csourcename.split('.')[0]\ncsource = open('Csrc/'+subdir+'/'+csourcename,'r')\ncsource_init = open('Csrc/'+subdir+'/'+csourcename.split('.')[0]+'_init.c','r')\n\n#Generate corresponding outputfile and Makefile\noutputname = 'output_' + csourcename\nfileout = open(outputname,'w')\nmakefile = open('Makefile','w')\n\n#Open .CL file\nCLfilename = 'kernel_'+csourcename.split('.')[0] + '.cl'\nCLfile = open(CLfilename,'w')\n\n#Read Source File\ncslines = csource.readlines()\n#Read Source_init file\ncsinitlines = csource_init.readlines()\n\n'''\n\n Grammer Rules for parsing each single line in the source file:\n Classify code line as function declaration and non-function declaration\n For kernel function declaration, record kernel arguments and types\n\n'''\n\nInputVar = []\nOutputVar = []\nKernelParaType = []\nKernelParaName = []\n\ndef ParseKernelFun (toks):\n '''\n Function when matching with a function declaration.\n Translate all the sublist into string and concatenate in the end\n toks[0] : ReturnType\n toks[1] : FuncName\n toks[2] : '('\n toks[3] : (FunParams)\n toks[4] : ')'\n toks[5] : ('{')\n ''' \n if toks[1] == csourcefunc:\n ''' \n Translate a kernel function\n '''\n toks[0] = ' '.join(toks[0])\n toks[0] = '__kernel ' + toks[0]\n if toks[3] != ')':\n for idx,item in enumerate(toks[3]):\n '''\n FuncParams: ArgDel0, ArgDel1, ...\n ArgDel: DataType ArgName\n '''\n if item != ',':\n KernelParaType.append(item[0])\n KernelParaName.append(item[1])\n if item[1] in InputVar:\n '''\n Input non-scalar Type\n '''\n if len(item[0]) != 1:\n item[0] = ' '.join(item[0])\n item.insert(0,'__global')\n else:\n item[0] = ' '.join(item[0]) \n toks[3][idx] = ' '.join(item)\n else: \n if len(item[0]) != 1:\n '''\n Output non-scalar Type\n '''\n item[0] = ' '.join(item[0])\n item.insert(0,'__global')\n else: \n '''\n Output scalar Type\n '''\n item[0] = ' '.join(item[0])\n item.insert(0,'__global')\n item.insert(2,' *')\n toks[3][idx] = ' '.join(item)\n toks[3] = ' '.join(toks[3])\n\n \n\nidentifier = Word(alphas+'_',alphanums+'_.')\nnumber = Word(nums+'-',nums+'.')\noperator = Word('!:=|&> 2:\n array_dict[item.split(' ')[1]] = item.split(' ')[2].strip()\n InputVar.append(item.split(' ')[1])\n else:\n InputVar.append(item.strip(' \\r\\n'))\n elif '#output' in item:\n rightside = item.split(':')[1]\n varlist = rightside.split(',')\n for item in varlist:\n if len(item.split(' ')) > 2: \n array_dict[item.split(' ')[1]] = item.split(' ')[2].strip()\n OutputVar.append(item.split(' ')[1])\n else:\n OutputVar.append(item.strip(' \\r\\n'))\n elif all(char in item for char in [csourcefunc,'void','(',')']): \n toks = programline.parseString(item)\n tmpLine = ' '.join(toks)+'\\n'\n lineBuffer.append(tmpLine)\n # Used '{' as indicator to add configure lines.\n if toks[-1] == '{':\n lineBuffer.extend(['int idx = get_global_id(0);\\n',\n 'int counter = idx;\\n',\n 'float seed = idx + 19;\\nfloat rand;\\n',\n 'float z0 =0;\\nfloat z1 = 0;\\nbool generate = false;\\n']) \n config_flag = True\n break\n\n'''\n Parsing body of the kernel function\n'''\n\nperturb_scalar = False\nperturb_nonscalar = False\nOriArrayName = []\nCopiedArrayName = []\n\n\nfor item in cslines[linum+1:]:\n line = item.strip() \n if line:\n if line == '{' and config_flag == False: \n lineBuffer.extend([ line+'\\n',\n 'int idx = get_global_id(0);\\n',\n 'int counter = idx;\\n',\n 'float seed = idx + 19;\\nfloat rand;\\n',\n 'float z0 =0;\\nfloat z1 = 0;\\nbool generate = false;\\n'])\n config_flag = True\n else:\n '''\n Notation Rules: #perturb_scalar var_name perturb_range\n #Perturb-nonscalar arrayname membername membersize noisetype param1 param2\n '''\n if '#perturb_scalar' in line:\n perturb_scalar = True\n toks = programline.parseString(line)\n percent = toks[-1]\n elif '#perturb_nonscalar' in line:\n perturb_nonscalar = True\n toks = programline.parseString(line)\n array_name = toks[2]\n array_copy = array_name + '_copy'\n ele_type = KernelParaType[KernelParaName.index(array_name)][0]\n\n if ele_type == 'float':\n noise_type = toks[-3]\n param_1 = toks[-2]\n param_2 = toks[-1]\n #Find Array size from dict\n array_size = array_dict[array_name]\n if array_name not in OriArrayName:\n del_line = ele_type+' '+array_copy+'['+array_size+']'\n lineBuffer.append(del_line+';\\n')\n\n if noise_type == 'Gaussian':\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n \"rand = generateGaussianNoise(\"+param_1+\",\"+param_2+\",&z0,&z1,&generate,&seed);\\n\",\n array_copy+\"[i] = \"+array_name+\"[i]+rand;\\n}\\n\"]\n else:\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n \"rand = generateUniformNoise(\"+param_1+\",\"+param_2+\",&seed);\\n\",\n array_copy+\"[i] = \"+array_name+\"[i]+rand;\\n}\\n\"]\n else:\n '''\n Perturb Self-defined Structures.\n #Perturb-nonscalar arrayname membername membersize noisetype param1 param2\n Currently Only support perturb sub-member of the structure\n '''\n member_name = toks[3]\n member_size = toks[4]\n noise_type = toks[-3]\n param_1 = toks[-2]\n param_2 = toks[-1]\n array_size = array_dict[array_name]\n \n if array_name not in OriArrayName:\n '''\n if array hasn't been perturbed before, add private copy declaration and copy from __global variable\n '''\n del_line = ele_type+' '+array_copy+'['+array_size+']'\n lineBuffer.append(del_line+';\\n')\n\n if noise_type == 'Gaussian':\n if member_size == '1':\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n array_copy+\"[i] = \"+array_name+\"[i];\\n\",\n \"rand = generateGaussianNoise(\"+param_1+\",\"+param_2+\",&z0,&z1,&generate,&seed);\\n\",\n array_copy+\"[i].\"+member_name+' = '+ array_name +\"[i].\"+member_name + \"+rand;\\n}\\n\"]\n else:\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n array_copy+\"[i] = \"+array_name+\"[i];\\n\",\n \"for(int j=0;j<\"+member_size+\";j++){\\n\",\n \"rand = generateGaussianNoise(\"+param_1+\",\"+param_2+\",&z0,&z1,&generate,&seed);\\n\",\n array_copy+\"[i].\"+member_name+\"[j] = \"+array_name+\"[i].\"+member_name+\"[j]+rand;\\n}\\n}\\n\"]\n else:\n if member_size == '1':\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n array_copy+\"[i] = \"+array_name+\"[i];\\n\",\n \"rand = generateUniformNoise(\"+param_1+\",\"+param_2+\",&seed);\\n\",\n array_copy+\"[i].\"+member_name+' = '+ array_name +\"[i].\"+member_name + \"+rand;\\n}\\n\"]\n else:\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n array_copy+\"[i] = \"+array_name+\"[i];\\n\",\n \"for(int j=0;j<\"+member_size+\";j++){\\n\",\n \"rand = generateUniformNoise(\"+param_1+\",\"+param_2+\",&seed);\\n\",\n array_copy+\"[i].\"+member_name+\"[j] = \"+array_name+\"[i].\"+member_name+\"[j]+rand;\\n}\\n}\\n\"]\n else:\n '''\n if array has been pertrubed before, no private copy and no coping from __global\n '''\n if noise_type == 'Gaussian':\n if member_size == '1':\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n \"rand = generateGaussianNoise(\"+param_1+\",\"+param_2+\",&z0,&z1,&generate,&seed);\\n\",\n array_copy+\"[i].\"+member_name+' = '+ array_name +\"[i].\"+member_name + \"+rand;\\n}\\n\"]\n else:\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n \"for(int j=0;j<\"+member_size+\";j++){\\n\",\n \"rand = generateGaussianNoise(\"+param_1+\",\"+param_2+\",&z0,&z1,&generate,&seed);\\n\",\n array_copy+\"[i].\"+member_name+\"[j] = \"+array_name+\"[i].\"+member_name+\"[j]+rand;\\n}\\n}\\n\"]\n else:\n if member_size == '1':\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n \"rand = generateUniformNoise(\"+param_1+\",\"+param_2+\",&seed);\\n\",\n array_copy+\"[i].\"+member_name+' = '+ array_name +\"[i].\"+member_name + \"+rand;\\n}\\n\"]\n else:\n perturblines = [\"for(int i=0;i<\"+array_size+\";i++){\\n\",\n \"for(int j=0;j<\"+member_size+\";j++){\\n\",\n \"rand = generateUniformNoise(\"+param_1+\",\"+param_2+\",&seed);\\n\",\n array_copy+\"[i].\"+member_name+\"[j] = \"+array_name+\"[i].\"+member_name+\"[j]+rand;\\n}\\n}\\n\"]\n\n \n lineBuffer.extend(perturblines) \n OriArrayName.append(array_name)\n CopiedArrayName.append(array_copy)\n \n else:\n toks = programline.parseString(line)\n '''\n a. Replace output var with multiple versions,output size become #Threads times larger\n For scalar value, add '[idx]'\n For non-scalar value, replace A[X] with A[idx*size+X]\n '''\n for idx,tok in enumerate(toks):\n if tok in OutputVar:\n #See if output var is a scalar type\n output_type = KernelParaType[KernelParaName.index(tok)]\n if len(output_type) != 1: \n array_size = array_dict[tok]\n if toks[idx+1] == '[':\n toks[idx+1] = toks[idx+1]+'idx*'+array_size+'+'\n else:\n toks[idx] = toks[idx] + '+idx*'+array_size \n else:\n toks[idx] = toks + '[idx]' \n else:\n toks[idx] = tok\n '''\n b. When perturbing arrays, replace OriArrayNames with CopiedArrayNames\n '''\n if perturb_nonscalar == True:\n for idx,tok in enumerate(toks):\n if tok in OriArrayName:\n toks[idx] = CopiedArrayName[OriArrayName.index(tok)]\n else:\n toks[idx] = tok\n newline = ' '.join(toks)+'\\n'\n '''\n c. When perturbing scalars, replace RHS with Noise function call\n '''\n if perturb_scalar == True:\n leftside = newline.split('=')[0]\n rightside = newline.split('=')[1].strip(';\\n') \n newrightside = 'inject_noise(idx,'+rightside+','+percent+',&counter);'\n newline = leftside+'='+newrightside+'\\n'\n perturb_scalar = False\n lineBuffer.append(newline)\n\nCLfile.writelines(lineBuffer)\n\n\n\n'''\n\n Generate Content for host file\n Copy XXX_init.c into host file\n Initilized all the input variables and setup memory buffers\n\n'''\n\n'''\n Pre-processing header of init files\n'''\n\nfor item in csinitlines:\n if any(word in item for word in ['#include','#define','namespace']):\n fileout.write(item.strip()+'\\n')\n \nfileout.write('#include \"init.h\"\\n')\nfileout.write('\\n')\n\n\n'''\n Copied rest of the init file into host file\n'''\n\nfor item in csinitlines:\n if any(word in item for word in ['#include','#define','namespace']):\n continue\n else:\n fileout.write(item.strip()+'\\n')\n \n\nfileout.write('\\nint main(){ \\n')\ninitFunCall = 'initializeCL(\\\"'+ 'kernel_'+csourcename.split('.')[0] + '.cl\\\",\\\"' + csourcefunc + '\\\");'\nfileout.write('status = '+initFunCall + '\\n')\nthreads = cfglines[1].split()[0]\nfileout.write('const int threads = '+ threads + '; \\n')\n\n'''\n\n Declare and init all input variables\n\n'''\n\ninitparam = ''\nfor idx,item in enumerate(KernelParaName):\n if item in InputVar:\n varline = ' '.join(KernelParaType[idx])+' '+item+';\\n'\n fileout.write(varline)\n if initparam == '': \n initparam = item\n else:\n initparam = initparam + ','+item\n \nfileout.write('init('+ initparam +');\\n')\n\n'''\n\n Setup mem_buffer and passing arguments\n Assuming all the output vars required for mem_buffer\n\n'''\n\n\nfor idx,item in enumerate(KernelParaName):\n if item in InputVar:\n if len(KernelParaType[KernelParaName.index(item)]) != 1:\n data_type = KernelParaType[KernelParaName.index(item)]\n buffname = 'buffer_'+item;\n fileout.write('cl_mem '+buffname+';\\n')\n array_size = array_dict[item]\n bufferline = buffname+' = '+ 'clCreateBuffer(context,CL_MEM_READ_ONLY,sizeof('+data_type[0] +')*'+array_size+',NULL,&status);\\n'\n fileout.write(bufferline)\n checkingline = 'if (status!=CL_SUCCESS){\\n std::cout<< \"ERROR in create buffer\\\\n\";\\n return 0;\\n}\\n'\n fileout.write(checkingline)\n enqueueline = 'clEnqueueWriteBuffer(cmdQueue,'+buffname+',CL_TRUE,0,sizeof('+data_type[0]+')*'+array_size+','+item+',0,NULL,NULL);\\n'\n fileout.write(enqueueline)\n argline = 'status = clSetKernelArg(kernel,'+str(idx)+',sizeof(cl_mem),(void *)&'+buffname+');\\n'\n fileout.write(argline)\n else:\n argline = 'status = clSetKernelArg(kernel,'+str(idx)+',sizeof(cl_'+' '.join(KernelParaType[idx])+'),(void *)&'+item+');\\n'\n fileout.write(argline)\n else:\n buffname = 'buffer_' + item\n fileout.write('cl_mem ' + buffname + ';\\n')\n data_type = KernelParaType[KernelParaName.index(item)]\n if len(data_type) != 1:\n item_size = array_dict[item]\n else:\n item_size = 1\n\n bufferline = buffname+' = '+ 'clCreateBuffer(context,CL_MEM_READ_WRITE,sizeof('+data_type[0]+')*'+str(item_size)+'*threads,NULL,&status);\\n'\n fileout.write(bufferline)\n checkingline = 'if (status!=CL_SUCCESS){\\n std::cout<< \"ERROR in create buffer\\\\n\";\\n return 0;\\n}\\n'\n fileout.write(checkingline)\n argline = 'status = clSetKernelArg(kernel,'+str(idx)+',sizeof(cl_mem),(void *)&'+buffname+');\\n'\n fileout.write(argline)\n \nfileout.write('launchKernel(threads); \\n')\n\n'''\n\n Read data from mem_buffer\n\n'''\n\n\nfor idx,item in enumerate(OutputVar):\n hostname = 'host_'+OutputVar[idx]\n datasize = hostname + '_size'\n item_type = KernelParaType[KernelParaName.index(item)]\n fileout.write(item_type[0] +'* ' + hostname+';\\n')\n if len(item_type) != 1:\n item_size = array_dict[item]\n else:\n item_size = 1\n fileout.write('size_t '+ datasize+' = sizeof('+item_type[0]+')*threads*'+str(item_size)+';\\n')\n allocline = hostname+' = ('+item_type[0]+'*)malloc('+datasize+');\\n'\n fileout.write(allocline)\n buffname = 'buffer_'+OutputVar[idx]\n dataFile = cfglines[idx+2].split()[0]\n enqueueline = 'clEnqueueReadBuffer(cmdQueue,'+buffname+',CL_TRUE,0,'+datasize+','+hostname+',0,NULL,NULL);\\n'\n fileout.write(enqueueline)\n writefileline = 'WriteToFile('+dataFile+','+hostname+',threads,'+str(item_size)+');\\n'\n fileout.write(writefileline)\n fileout.write('free('+hostname+');\\n')\n\n'''\n\n Release resources\n\n'''\n\nfileout.write('releaseResource();\\n')\nfor item in InputVar:\n if len(KernelParaType[KernelParaName.index(item)]) != 1:\n buffname = 'buffer_'+item\n fileout.write('clReleaseMemObject('+buffname+');\\n')\nfor item in OutputVar:\n buffname = 'buffer_'+item\n fileout.write('clReleaseMemObject('+buffname+');\\n')\n \n\nfileout.write('}')\n\n\n\n\n\n\n\n'''\n\n Generate Content in Makefile\n\n'''\n\nmakefile.writelines(['CC = g++\\n',\n 'LIBS = -lOpenCL\\n',\n 'AMDAPPSDKROOT = /opt/AMDAPPSDK-2.9-1\\n'])\ntargetline = 'output: ' + outputname + ' init.c init.h'\ncommandline = '\\t$(CC) -o output -I$(AMDAPPSDKROOT)/include -L$(AMDAPPSDKROOT)/lib/x86_64 '+ outputname + ' init.c init.h $(LIBS) -lrt' \n\nmakefile.write(targetline + '\\n')\nmakefile.write(commandline + '\\n')\n\nmakefile.write('clean: \\n')\nmakefile.write('\\trm output' + '\\n')\n\nfor idx,item in enumerate(OutputVar):\n dataFile = cfglines[idx+2].split()[0]\n makefile.write('\\trm '+dataFile+'\\n')\n\n\n\n\n\n","sub_path":"PyTrans/tran_phase_1.py","file_name":"tran_phase_1.py","file_ext":"py","file_size_in_byte":21404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"439617640","text":"import sys\nsys.stdin = open('boj_14502.txt', 'r')\n\nimport sys\nfrom collections import deque\nreadline = sys.stdin.readline\n\nN, M = map(int, readline().split())\nfields = [list(map(int, readline().split())) for _ in range(N)]\n\ndy = [-1, 1, 0, 0]\ndx = [0, 0, -1, 1]\n\nblanks = []\nviruses = []\nfor y in range(N):\n for x in range(M):\n if not fields[y][x]:\n blanks.append((y, x))\n elif fields[y][x] == 2:\n viruses.append((y, x))\n\n\nblank_num = len(blanks)\nmin_virus = 0xffffff\n\nfor a in range(blank_num - 2):\n for b in range(1, blank_num - 1):\n for c in range(2, blank_num):\n visited = [field[:] for field in fields]\n Q = deque()\n new_virus = 0\n\n visited[blanks[a][0]][blanks[a][1]], visited[blanks[b][0]][blanks[b][1]], visited[blanks[c][0]][blanks[c][1]] = 1, 1, 1\n\n for v_y, v_x in viruses:\n Q.append((v_y, v_x))\n\n while Q:\n c_y, c_x = Q.popleft()\n\n for d in range(4):\n n_y, n_x = c_y + dy[d], c_x + dx[d]\n if -1 < n_y < N and -1 < n_x < M and not visited[n_y][n_x]:\n visited[n_y][n_x] = 2\n new_virus += 1\n if new_virus > min_virus:\n Q.clear()\n break\n Q.append((n_y, n_x))\n\n if min_virus > new_virus:\n min_virus = new_virus\n\nprint(blank_num - min_virus - 3)\n","sub_path":"정준현/11_BFSDFS_03/boj_14502_연구소.py","file_name":"boj_14502_연구소.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"434568103","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport tensorflow as tf\nimport numpy as np\n\nclass NetworkModel(object):\n \"\"\"\n 这里的模型只是对item的输入用lstm建模,最后将lstm的输出与user的onehot编码变换进行结合 \"\"\" \n #搭建神经网络结构,部分为lstm\n def __init__(self,n_step,hidden_size,item_code_size,u_code_size,r_code_size,beta):\n \"\"\"\n 参数\n n_step: rnn循环的步数\n hidden_size: rnn部分隐藏单元大小\n item_code_size: item编码向量的大小 \n u_code_size: 用户编码向量的大小\n beta: 正则化系数\n \"\"\"\n \n self.n_step = n_step\n self.hidden_size = hidden_size\n self.item_code_size = item_code_size\n self.u_code_size = u_code_size\n self.r_code_size = r_code_size\n #这里的输入为电影onehot编码,电影隐向量\n self.item = tf.placeholder(tf.float32,[None,n_step,item_code_size],name=\"item\")\n self.rating = tf.placeholder(tf.float32,[None,n_step,r_code_size],name=\"rating\")\n\n batch_size = tf.shape(self.item)[0]\n\n #shape:[batch_size*n_step,item_code_size]\n _item = tf.reshape(self.item,[-1,item_code_size])\n _rating = tf.reshape(self.rating,[-1,r_code_size])\n\n\n #定义变换矩阵V[item_code_size,hidden_size],W[latent_vec_size,hidden_size]\n W = tf.Variable(tf.random_uniform(\n [item_code_size,hidden_size],\n -1.0/hidden_size,\n 1.0/hidden_size,\n dtype=tf.float32,\n name=\"W\"\n ))\n\n V = tf.Variable(tf.random_uniform(\n [r_code_size,hidden_size],\n -1.0/hidden_size,\n 1.0/hidden_size,\n dtype=tf.float32\n ))\n\n #产生lstm的输入[n_step*batch_size,hidden_size]\n\n item_bias = tf.Variable(tf.zeros([n_step,hidden_size]))\n\n tmp = tf.add(tf.matmul(_item,W),tf.matmul(_rating,V))\n tmp = tf.reshape(tmp,[batch_size,n_step,hidden_size])\n #shape:[batch_size,n_step,hidden_size]\n tmp = tf.add(tmp,item_bias)\n inputs = tf.sigmoid(tmp)\n\n #shape[n_step,batch_size,item_code_size]\n inputs = tf.transpose(inputs,[1,0,2])\n inputs = tf.reshape(inputs,[-1,hidden_size])\n\n inputs = tf.split(0,n_step,inputs) #分step批同时处理\n\n\n #batch_size = tf.shape(self.x_input)[0]\n ##将输入数据变换为rnn网络接受的形式\n #inputs = tf.transpose(self.x_input,[1,0,2])\n #inputs = tf.reshape(inputs,[-1,hidden_size])\n #inputs = tf.split(0,n_step,inputs)\n #这里rnn的hidden_size与输入数据的大小相同 \n lstm = tf.nn.rnn_cell.BasicLSTMCell(hidden_size,forget_bias=1.0,state_is_tuple=True)\n self.rnn_outputs,_states = tf.nn.rnn(lstm,inputs,dtype=tf.float32)\n \n #now shape is [n_step,batch_size,hidden_size]\n inner_outputs = tf.pack(self.rnn_outputs) \n inner_outputs = tf.reshape(inner_outputs,[-1,hidden_size])\n ##转换成[batch_size,n_step,hidden_size]的数据形式\n #inner_outputs = tf.transpose(inner_outputs,[1,0,2])\n\n #与lstm输出相乘的权值Y\n Y = tf.Variable(tf.random_uniform(\n [hidden_size,item_code_size],\n -1.0/hidden_size,\n 1.0/hidden_size,\n dtype=tf.float32,\n name=\"Y\"\n ))\n #shape:[n_step*batch_size,item_code_size]\n rnn_outs = tf.matmul(inner_outputs,Y)\n \n\n \"\"\"\n 定义用户部分的模型\n \"\"\"\n #需要输入的数据\n self.user = tf.placeholder(tf.float32,[None,self.n_step,u_code_size],name=\"usercode\")\n \n\n _user = tf.transpose(self.user,[1,0,2])\n _user = tf.reshape(_user,[-1,u_code_size])\n #定义用户模型部分参数P,Q\n #用户模型部分隐单元大小默认与rnn部分相同\n u_model_hidden_size = hidden_size \n\n P = tf.Variable(tf.random_uniform(\n [u_code_size,u_model_hidden_size],\n -1.0/u_code_size,\n 1.0/u_code_size\n ))\n\n user_bias = tf.Variable(tf.zeros([n_step,u_model_hidden_size]))\n\n #用户模型部分的输出为user*P+ulaten_vec*Q,shape:[batch_size*n_step,u_model_hidden_size]\n u_inner_outs = tf.matmul(_user,P)\n u_inner_outs = tf.reshape(u_inner_outs,[batch_size,n_step,u_model_hidden_size])\n u_inner_outs = tf.add(u_inner_outs,user_bias)\n #加一个激活函数,并将输出复制n_step份\n u_inner_outs = tf.nn.sigmoid(u_inner_outs)\n u_inner_outs = tf.transpose(u_inner_outs,[1,0,2])\n u_inner_outs = tf.reshape(u_inner_outs,[-1,u_model_hidden_size])\n \n\n #与用户模型输出相乘的矩阵Z\n Z = tf.Variable(tf.random_uniform(\n [u_model_hidden_size,item_code_size],\n -1.0/u_model_hidden_size,\n 1.0/u_model_hidden_size\n ))\n #用户模型的最终输出,变换到[n_step*batch_size,item_code_size]\n u_model_outs = tf.matmul(u_inner_outs,Z)\n u_model_outs = tf.reshape(u_model_outs,[n_step,batch_size,item_code_size])\n\n #得到最终输出O,使用softmax多分类\n rnn_outs = tf.reshape(rnn_outs,[n_step,batch_size,item_code_size])\n\n logits = tf.add(u_model_outs,rnn_outs)\n #恢复与输入,目标向量相同的形式\n logits = tf.transpose(logits,[1,0,2])#shape:[batch_size,n_step,item_code_size]\n #softmax:dim指做softmax计算的维度,默认为-1,即最后一个维度\n #self.Outs = tf.nn.log_softmax(logits,dim=-1,name=\"softmax_outs\")\n self.Outs = tf.nn.softmax(logits,dim=-1,name=\"softmax_outs\")\n\n #目标向量\n self.y_target = tf.placeholder(tf.float32,[None,n_step,item_code_size],name=\"y_target\")\n\n \n ##损失使用交叉熵,并使用正则抑制过拟合\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.Outs,labels=self.y_target)\n +beta*tf.nn.l2_loss(Y)\n +beta*tf.nn.l2_loss(Z)\n +beta*tf.nn.l2_loss(W)\n +beta*tf.nn.l2_loss(V)\n +beta*tf.nn.l2_loss(P))\n\n\n def train(self,sess,optimizer,train_data,item_code_size,u_code_size,r_code_size):\n \"\"\"\n 将一个batch的数据准备为onehot形式,并进行一个batch的训练\n 每个batch的一行形式为:\n 行首为用户编号,之后为电影及评分对\n \"\"\"\n batch_size = train_data.shape[0]\n\n batch_u_code = np.zeros([batch_size,self.n_step,u_code_size])\n batch_item_code = np.zeros([batch_size,self.n_step,item_code_size])\n batch_r_code = np.zeros([batch_size,self.n_step,r_code_size])\n batch_target = np.zeros([batch_size,self.n_step,item_code_size])\n\n for i in range(batch_size):\n user = train_data[i][0]\n for j in range(self.n_step):\n item = train_data[i][2*j+1]\n nextitem = train_data[i][2*(j+1)+1]\n rating = train_data[i][1+2*j+1]\n batch_u_code[i][j][user] = 1\n batch_item_code[i][j][item] = 1\n batch_r_code[i][j][rating-1] = 1 #rating值比其onehot编码1位置大1\n batch_target[i][j][nextitem] = 1\n _,cost = sess.run([optimizer,self.cost],feed_dict={\n self.item:batch_item_code,\n self.user:batch_u_code,\n self.rating:batch_r_code,\n self.y_target:batch_target})\n return cost \n\n\n def pred(self,sess,te_data,item_code_size,u_code_size,r_code_size):\n \"\"\"\n 预测返回的是一个列表,每一项为一个用户的预测,预测结果为一个大小为max_item_index+1的向量 \n 向量每一项对应一部电影的概率值\n \"\"\"\n\n batch_size = te_data.shape[0]\n #使用数组保存预测结果,索引为用户编号\n\n batch_item_code = np.zeros([batch_size,self.n_step,item_code_size])\n batch_u_code = np.zeros([batch_size,self.n_step,u_code_size])\n batch_r_code = np.zeros([batch_size,self.n_step,r_code_size])\n\n for i in range(batch_size):\n user = te_data[i][0]\n for j in range(self.n_step):\n #行首为用户编号,所以j+1\n item = te_data[i][1+j*2]\n rating = te_data[i][1+j*2+1]\n batch_item_code[i][j][item] = 1\n batch_u_code[i][j][user] = 1\n batch_r_code[i][j][rating-1] = 1\n \n \n pred_res = sess.run(self.Outs,feed_dict={\n self.item:batch_item_code,\n self.rating:batch_r_code,\n self.user:batch_u_code\n })\n\n #预测结果为[batch_size,item_onehot_size]\n pred_res = pred_res[:,-1,:]\n\n return pred_res\n\nif __name__ == \"__main__\":\n\n model = NetworkModel(n_step=9,hidden_size=10,item_code_size=3953,u_code_size=6041,r_code_size=5,beta=0.05)\n #test\n","sub_path":"papermethod/reviseOnehotRNN.py","file_name":"reviseOnehotRNN.py","file_ext":"py","file_size_in_byte":9110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"340255528","text":"from InstruccionesPL.TablaSimbolosPL.InstruccionPL import InstruccionPL\nfrom InstruccionesPL.Ends import Ends\nclass Elses(InstruccionPL):\n def __init__(self,InstrucionesPL, ContIf, tipo, linea, columna, strGram):\n InstruccionPL.__init__(self, tipo, linea, columna, strGram) \n self.InstruccionesPL = InstrucionesPL\n self.ContIf = ContIf\n\n def ejecutar(self, tabla, arbol):\n super().ejecutar(tabla,arbol)\n #ejecucion de una funcion\n\n def traducir(self, tabla, arbol):\n super().traducir(tabla, arbol)\n res = ''\n if type(self.InstruccionesPL)== list:\n if self.InstruccionesPL!=None:\n for ins in self.InstruccionesPL:\n ins.traducir(tabla, arbol)\n \n if isinstance(self.ContIf, Ends.Ends) == False:\n res = self.ContIf.traducir(tabla, arbol)\n \n return res\n\n","sub_path":"parser/fase2/team10/InstruccionesPL/Ifs/Elses.py","file_name":"Elses.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"386121884","text":"from Options import RSMControl, AnalControl, Data, ScanMaster\nfrom numpy import pi\nfrom matplotlib import use\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom tkinter import Tk, Button, Frame, Label, Checkbutton, GROOVE, OptionMenu, W, Entry, DISABLED, NORMAL\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\nfrom xrayutilities import maplog\nfrom xrayutilities.experiment import HXRD\nfrom xrayutilities.gridder2d import Gridder2D\nfrom xrayutilities.io.panalytical_xml import getxrdml_scan\nfrom xml.etree.ElementTree import ParseError\nuse('TkAgg')\n\n\nclass GUI:\n \"\"\"For reciprocal space maps\"\"\"\n def __init__(self, master):\n self.rsm_controls = RSMControl()\n self.analysis_control = AnalControl()\n self.data = Data()\n\n self.main_frame = Frame(master, bd=2, relief=GROOVE)\n\n self.control_frame = Frame(self.main_frame, bd=2, relief=GROOVE)\n self.fileselect_button = Button(self.control_frame, text=\"Select XRDML file\", command=self.select_file)\n\n self.rsm_control_frame = Frame(self.control_frame, bd=2, relief=GROOVE)\n self.rsm_label = Label(self.rsm_control_frame, text=\"RSM - Parameters\")\n self.rsm_scale_label = Label(self.rsm_control_frame, text=\"Scale\", anchor=W)\n self.rsm_scale_menu = OptionMenu(self.rsm_control_frame, self.rsm_controls.scale_var, \"Logarithmic\", \"Linear\")\n self.rsm_resolution_label = Label(self.rsm_control_frame, text=\"Resolution\", anchor=W)\n self.rsm_resolution_menu = OptionMenu(self.rsm_control_frame, self.rsm_controls.resolution_var,\n \"High\", \"Mid\", \"Low\")\n self.rsm_colormap_label = Label(self.rsm_control_frame, text=\"Color style\", anchor=W)\n self.rsm_colormap_menu = OptionMenu(self.rsm_control_frame, self.rsm_controls.colormap_var,\n *list(self.rsm_controls.colormap_dict.keys()))\n self.rsm_contourline_checkbox = Checkbutton(self.rsm_control_frame, var=self.rsm_controls.contourline_var,\n text=\"Draw contour lines\", anchor=W)\n self.rsm_space_label = Label(self.rsm_control_frame, text=\"Plot Space\", anchor=W)\n self.rsm_space_menu = OptionMenu(self.rsm_control_frame, self.rsm_controls.space_var, \"Reciprocal\", \"Angular\")\n self.rsm_create_button = Button(self.rsm_control_frame, text=\"Plot RSM\", command=self.create_rsm,\n state=DISABLED)\n self.rsm_savebutton = Button(self.rsm_control_frame, text=\"Save Figure\", state=DISABLED,\n command=lambda: savefigure(self.rsm_plot_figure))\n self.rsm_exportbutton = Button(self.rsm_control_frame, text=\"Export RSM Data\", command=self.export_rsm_data,\n state=DISABLED)\n\n self.analysis_control_frame = Frame(self.control_frame, bd=2, relief=GROOVE)\n self.analysis_label = Label(self.analysis_control_frame, text=\"Analysis Control\")\n self.analysis_scandir_label = Label(self.analysis_control_frame, text=\"Scan direction\", anchor=W)\n self.analysis_scandir_menu = OptionMenu(self.analysis_control_frame, self.analysis_control.scandir_var, \"Omega\",\n \"Two Theta\", \"q parallel\", \"q normal\", command=self.update_originspace)\n self.analysis_originspace_label = Label(self.analysis_control_frame, text=\"Origin Sel.\", anchor=W)\n self.analysis_originspace_menu = OptionMenu(self.analysis_control_frame, self.analysis_control.originspace_var,\n \"Angular\", \"Reciprocal\", command=self.update_origin_input)\n self.analysis_origincoordinate_1_label = Label(self.analysis_control_frame, text=\"q parallel\", anchor=W)\n self.analysis_origincoordinate_1_entry = Entry(self.analysis_control_frame)\n self.analysis_origincoordinate_2_label = Label(self.analysis_control_frame, text=\"q nornal\", anchor=W)\n self.analysis_origincoordinate_2_entry = Entry(self.analysis_control_frame)\n self.analysis_scanrange_label = Label(self.analysis_control_frame, text=\"Scan range\", anchor=W)\n self.analysis_scanrange_entry = Entry(self.analysis_control_frame)\n self.analysis_integration_width_label = Label(self.analysis_control_frame, text=\"Int. width\", anchor=W)\n self.analysis_integration_width_entry = Entry(self.analysis_control_frame)\n self.analysis_create_button = Button(self.analysis_control_frame, text=\"Plot Scan\",\n command=self.create_line_scan)\n self.analysis_savebutton = Button(self.analysis_control_frame, text=\"Save Figure\",\n command=lambda: savefigure(self.linescan_plot_figure))\n self.analysis_exportbutton = Button(self.analysis_control_frame, text=\"Export Linescan Data\",\n command=self.export_linescan_data)\n\n self.rsm_plot_frame = Frame(self.main_frame, relief=GROOVE, bd=2)\n self.rsm_plot_figure = Figure()\n self.rsm_canvas = FigureCanvasTkAgg(self.rsm_plot_figure, master=self.rsm_plot_frame)\n self.rsm_toolbar = NavigationToolbar2TkAgg(self.rsm_canvas, self.rsm_plot_frame)\n self.rsm_toolbar.update()\n self.rsm_canvas.show()\n\n self.linescan_plot_frame = Frame(self.main_frame, relief=GROOVE, bd=2)\n self.linescan_plot_figure = Figure()\n self.linescan_canvas = FigureCanvasTkAgg(self.linescan_plot_figure, master=self.linescan_plot_frame)\n self.linescan_toolbar = NavigationToolbar2TkAgg(self.linescan_canvas, self.linescan_plot_frame)\n self.linescan_toolbar.update()\n self.linescan_canvas.show()\n\n self.place_widgets()\n\n def place_widgets(self):\n self.main_frame.place(x=10, y=10, width=1340, height=535)\n self.control_frame.place(x=5, y=5, width=210, height=525)\n self.fileselect_button.place(x=5, y=5, width=200, height=25)\n\n self.rsm_control_frame.place(x=5, y=35, width=200, height=230)\n self.rsm_label.place(x=5, y=5, width=190, height=25)\n self.rsm_resolution_label.place(x=5, y=30, width=80, height=25)\n self.rsm_resolution_menu.place(x=95, y=30, width=100, height=25)\n self.rsm_colormap_label.place(x=5, y=55, width=80, height=25)\n self.rsm_colormap_menu.place(x=95, y=55, width=100, height=25)\n self.rsm_scale_label.place(x=5, y=80, width=80, height=25)\n self.rsm_scale_menu.place(x=95, y=80, width=100, height=25)\n self.rsm_space_label.place(x=5, y=105, width=80, height=25)\n self.rsm_space_menu.place(x=95, y=105, width=100, height=25)\n self.rsm_contourline_checkbox.place(x=5, y=135, width=190, height=25)\n self.rsm_create_button.place(x=5, y=165, width=90, height=25)\n self.rsm_savebutton.place(x=105, y=165, width=90, height=25)\n self.rsm_exportbutton.place(x=5, y=195, width=190, height=25)\n\n self.analysis_control_frame.place(x=5, y=270, width=200, height=250)\n self.analysis_label.place(x=5, y=5, width=190, height=25)\n self.analysis_scandir_label.place(x=5, y=30, width=80, height=25)\n self.analysis_scandir_menu.place(x=95, y=30, width=100, height=25)\n #self.analysis_originspace_label.place(x=5, y=55, width=80, height=25)\n #self.analysis_originspace_menu.place(x=95, y=55, width=100, height=25)\n self.analysis_origincoordinate_1_label.place(x=5, y=80, width=80, height=25)\n self.analysis_origincoordinate_1_entry.place(x=95, y=80, width=100, height=25)\n self.analysis_origincoordinate_2_label.place(x=5, y=105, width=80, height=25)\n self.analysis_origincoordinate_2_entry.place(x=95, y=105, width=100, height=25)\n self.analysis_integration_width_label.place(x=5, y=130, width=80, height=25)\n self.analysis_integration_width_entry.place(x=95, y=130, width=100, height=25)\n self.analysis_scanrange_label.place(x=5, y=155, width=80, height=25)\n self.analysis_scanrange_entry.place(x=95, y=155, width=100, height=25)\n self.analysis_create_button.place(x=5, y=185, width=90, height=25)\n self.analysis_savebutton.place(x=105, y=185, width=90, height=25)\n self.analysis_exportbutton.place(x=5, y=215, width=190, height=25)\n\n self.rsm_plot_frame.place(x=220, y=5, width=555, height=525)\n self.rsm_canvas.get_tk_widget().place(x=5, y=5, width=545, height=495)\n\n self.linescan_plot_frame.place(x=780, y=5, width=555, height=525)\n self.linescan_canvas.get_tk_widget().place(x=5, y=5, height=495, width=545)\n\n def select_file(self):\n self.data.file_path = askopenfilename()\n try:\n dummy, self.data.om, self.data.tt, self.data.intensity = getxrdml_scan(self.data.file_path, \"om\", \"tt\")\n self.rsm_create_button.configure(state=NORMAL)\n self.rsm_savebutton.configure(state=NORMAL)\n self.rsm_exportbutton.configure(state=NORMAL)\n except(FileNotFoundError, ParseError):\n pass\n\n def create_rsm(self):\n if self.rsm_controls.space_var.get() == \"Reciprocal\":\n self.data.experiment = HXRD(self.data.material.Q([1, 0, 0]), self.data.material.Q([0, 0, 1]))\n [qx, qy, qz] = self.data.experiment.Ang2Q(self.data.om, self.data.tt)\n self.data.q_parallel = qy/(2*pi)\n self.data.q_normal = qz/(2*pi)\n\n self.data.grid = Gridder2D(self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()],\n self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()])\n\n self.data.grid(self.data.q_parallel, self.data.q_normal, self.data.intensity)\n\n if self.rsm_controls.scale_var.get() == \"Logarithmic\":\n intens = maplog(self.data.grid.data.T, 8., 0)\n else:\n intens = self.data.grid.data\n self.rsm_plot_figure.clear()\n self.rsm_plot_figure.patch.set_facecolor('white')\n ax = self.rsm_plot_figure.gca()\n ax.clear()\n cf = ax.contourf(self.data.grid.xaxis, self.data.grid.yaxis, intens,\n self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()],\n cmap=self.rsm_controls.colormap_dict[self.rsm_controls.colormap_var.get()])\n if self.rsm_controls.contourline_var.get():\n ax.contour(self.data.grid.xaxis, self.data.grid.yaxis, intens,\n int(self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()] / 20),\n colors=\"black\")\n cb = self.rsm_plot_figure.colorbar(cf)\n if self.rsm_controls.scale_var.get() == \"Logarithmic\":\n cb.set_label(r\"$\\log(Intensity) [counts]$\")\n else:\n cb.set_label(r\"$Intensity [counts]$\")\n ax.set_ylabel(r\"$q_{\\perp} [\\AA^{-1}]$\")\n ax.set_xlabel(r\"$q_{\\parallel} [\\AA^{-1}]$\")\n ax.axis(\"equal\")\n self.rsm_plot_figure.subplots_adjust(left=0.15, bottom=0.15, right=0.95, top=0.95)\n self.rsm_canvas.draw()\n else:\n self.data.anggrid = Gridder2D(self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()],\n self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()])\n\n self.data.anggrid(self.data.om, self.data.tt, self.data.intensity)\n\n if self.rsm_controls.scale_var.get() == \"Logarithmic\":\n intens = maplog(self.data.anggrid.data.T, 8., 0)\n else:\n intens = self.data.anggrid.data\n self.rsm_plot_figure.clear()\n self.rsm_plot_figure.patch.set_facecolor('white')\n ax = self.rsm_plot_figure.gca()\n ax.clear()\n cf = ax.contourf(self.data.anggrid.xaxis, self.data.anggrid.yaxis, intens, 500,\n cmap=self.rsm_controls.colormap_dict[self.rsm_controls.colormap_var.get()])\n if self.rsm_controls.contourline_var.get():\n ax.contour(self.data.anggrid.xaxis, self.data.anggrid.yaxis, intens, 8, colors=\"black\")\n cb = self.rsm_plot_figure.colorbar(cf)\n if self.rsm_controls.scale_var.get() == \"Logarithmic\":\n cb.set_label(r\"$\\log(Intensity) [counts]$\")\n else:\n cb.set_label(r\"$Intensity [counts]$\")\n ax.set_ylabel(r\"$2\\theta [\\degree]$\")\n ax.set_xlabel(r\"$\\omega [\\degree]$\")\n ax.axis(\"equal\")\n self.rsm_plot_figure.subplots_adjust(left=0.15, bottom=0.15, right=0.95, top=0.95)\n self.rsm_canvas.draw()\n\n def export_rsm_data(self):\n name = asksaveasfilename()+\".txt\"\n with open(name, \"w+\") as file:\n file.write(\"Omega [°]\\tTwo theta [°]\\tIntensity\\tq_parallel [1/A]\\tq_normal [1/A]\\tIntensity\\n\")\n for om, tt, intang, q_parallel, q_normal, intq in zip(self.data.anggrid.xaxis.flatten(),\n self.data.anggrid.yaxisflatten(),\n self.data.anggrid.data.flatten(),\n self.data.grid.xaxis.flatten(),\n self.data.grid.yaxis.flatten(),\n self.data.grid.data.flatten()):\n file.write(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t\\n\" % (om, tt, intang, q_parallel, q_normal, intq))\n\n def create_line_scan(self):\n try:\n scanmaster = ScanMaster(self.data.grid.xaxis,\n self.data.grid.yaxis,\n self.data.grid.data,\n self.analysis_control.originspace_var.get(),\n float(self.analysis_origincoordinate_1_entry.get()),\n float(self.analysis_origincoordinate_2_entry.get()),\n self.analysis_control.scandir_var.get(),\n float(self.analysis_scanrange_entry.get()),\n float(self.analysis_integration_width_entry.get()),\n int(self.rsm_controls.resolution_dict[self.rsm_controls.resolution_var.get()]))\n\n\n\n self.data.linescan_x, self.data.linescan_y, self.data.linescan_x_dim = scanmaster.scan()\n\n self.linescan_plot_figure.patch.set_facecolor('white')\n bx = self.linescan_plot_figure.gca()\n bx.clear()\n bx.plot(self.data.linescan_x, self.data.linescan_y, '-o')\n bx.set_ylabel(r\"Intensity [abu]\")\n bx.set_xlabel(self.data.linescan_x_dim)\n bx.set_yscale(\"log\")\n self.linescan_canvas.draw()\n\n except AttributeError:\n self.rsm_controls.space_var.set(\"Reciprocal\")\n self.create_rsm()\n self.create_line_scan()\n\n def export_linescan_data(self):\n name = asksaveasfilename() + \".txt\"\n with open(name, \"w+\") as file:\n file.write(\"%s\\tIntensity\\n\") % self.data.linescan_x_dim\n for x, intens in zip(self.data.linescan_x.flatten(), self.data.linescan_y.flatten()):\n file.write(\"%s\\t%s\\n\" % (x, intens))\n\n def update_origin_input(self, dummy):\n if self.analysis_control.originspace_var.get() == \"Reciprocal\":\n self.analysis_origincoordinate_1_label.configure(text=\"q parallel\")\n self.analysis_origincoordinate_2_label.configure(text=\"q normal\")\n if self.analysis_control.originspace_var.get() == \"Angular\":\n self.analysis_origincoordinate_1_label.configure(text=\"Omega\")\n self.analysis_origincoordinate_2_label.configure(text=\"Two Theta\")\n\n def update_originspace(self, dummy):\n if self.analysis_control.scandir_var.get()[0] == \"q\":\n self.analysis_control.originspace_var.set(\"Reciprocal\")\n self.update_origin_input(dummy)\n self.analysis_originspace_menu.configure(state=DISABLED)\n self.analysis_scanrange_entry.configure(state=DISABLED)\n else:\n self.analysis_originspace_menu.configure(state=NORMAL)\n self.analysis_scanrange_entry.configure(state=NORMAL)\n\n\ndef savefigure(figure):\n if figure:\n figure.savefig(asksaveasfilename()+\".png\")\n\n\nroot = Tk()\nroot.geometry(\"1360x555\")\nroot.wm_title(\"Amerigo - Reciprocal Space Map Viewer\")\nmyGui = GUI(root)\nroot.mainloop()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":16885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"626192090","text":"from datetime import datetime\nimport random\nimport time\n\nodds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19,\n 21, 23, 25, 27, 29, 31, 33, 35, 37, 39,\n 41, 43, 45, 47, 49, 51, 53, 55, 57, 59]\nfor i in range(5):\n minutos = datetime.today().minute\n print(i)\n if minutos in odds:\n print(\"This minute seems a little odd\")\n else:\n print(\"No pasa nada\")\n\n tiempo_espera = random.randint(1, 60)\n time.sleep(tiempo_espera)\n print(\"bien echo Nico\")\n","sub_path":"cascada/ejemplo1.py","file_name":"ejemplo1.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41338948","text":"from data_checks import *\nfrom extract_repeat_donors import *\nimport argparse\nimport numpy as np\nimport pandas as pd\n\ndef find_repeat_donors(input_file,percentile_file,output_file):\n \"\"\"\n Uses the provided files to pull relevant data from pipe-delimited file of FEC donation records. Writes out rows\n containing information defined in the output directions of the Insight_Readme.md file.\n\n :param input_file: Filepath of file containing rows of 21 pipedelimited filed as defined by the FEC\n :param percentile_file: File containing one number 1-100 defining what percentile to use in calculations\n :param output_file: Filepath for output file for results of analysis to be written to\n :return: None\n \"\"\"\n\n records_names = ['CMTE_ID','NAME','ZIP_CODE','TRANS_DT', 'TRANS_AMT', 'OTHER_ID']\n\n # Open input file and read in as stream of data line by line\n with open(percentile_file,'r') as percent:\n percentile = float(percent.read())\n with open(input_file, 'r') as data:\n\n donors = pd.DataFrame(columns=records_names)\n holder = {'CMTE_ID':'','NAME':'','ZIP_CODE':'','TRANS_DT':0000,'TRANS_AMT':0,'COUNT':0}\n final_set = pd.DataFrame(data = holder,index=[0])\n outfile = open(output_file, 'w')\n\n for row in data:\n\n record_data = data_check(row)\n\n #find indices of all repeat donations in the current table (all rows read in)\n if record_data != False:\n previous_donations = map(int,donors.index[(donors['NAME'] == record_data['NAME']) &\n (donors['ZIP_CODE']== record_data['ZIP_CODE'])].tolist())\n\n # Check if all the subsequent donations by the same donor came after the first donation's date\n if previous_donations != []:\n\n if donors.iloc[previous_donations[0]]['TRANS_DT'] <= record_data['TRANS_DT']:\n # Adds the most recent donation by a given donor to the dataset that will be used to calculate\n # the aggregate donation data\n for i in previous_donations[-1:]:\n\n repeaters, final_set = extract_repeat_donors(record_data,final_set,percentile)\n\n # Write line of aggregated donations with total amount, percentile, and count for each\n # Candidate, zipcode, and year\n repeaters.tofile(outfile,sep='|',format='%s')\n outfile.write('\\n')\n\n donors = donors.append(record_data, ignore_index=True)\n\n outfile.close()\n data.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('input_file',\n help='filepath containing political donors input data')\n parser.add_argument('percentile',\n help='filepath containing percentile to be used in calculations')\n parser.add_argument('output_file',\n help='filepath to store output data')\n args = parser.parse_args()\n input_filepath = args.input_file\n percentile_filepath = args.percentile\n output_filepath = args.output_file\n find_repeat_donors(input_filepath,percentile_filepath,output_filepath)\n\n\n","sub_path":"src/donation-analytics.py","file_name":"donation-analytics.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438919577","text":"\"\"\"Find mean of a list of numbers.\"\"\"\n\n\ndef average(nums,n):\n \"\"\"Find mean of a list of numbers.\"\"\"\n return sum(nums) / n\n\n\ndef test_average():\n \"\"\"\n >>> test_average()\n \"\"\"\n assert 12.0 == average([3, 6, 9, 12, 15, 18, 21])\n assert 20 == average([5, 10, 15, 20, 25, 30, 35])\n assert 4.5 == average([1, 2, 3, 4, 5, 6, 7, 8])\n\n\nif __name__ == \"__main__\":\n n = int(input(\"Enter the length of the list: \"))\n list = [int(i) for i in range(n)]\n \"\"\"Call average module to find mean of a specific list of numbers.\"\"\"\n print(average(list,n))\n","sub_path":"maths/average_mean.py","file_name":"average_mean.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514019013","text":"from framework.db import delete_user\nfrom framework.db import save_user\nfrom framework.errors import MethodNotAllowed\nfrom framework.errors import NotFound\nfrom framework.types import RequestT\nfrom framework.types import ResponseT\nfrom framework.utils import build_reset_session_header\nfrom framework.utils import build_session_header\nfrom framework.utils import build_status\nfrom framework.utils import read_static\n\n\ndef handle_hello(request: RequestT) -> ResponseT:\n handlers = {\n \"greet\": _handle_hello_greet,\n \"reset\": _handle_hello_reset,\n }\n\n handler = handlers.get(request.kwargs.get(\"action\"), _handle_hello_index)\n if not handler:\n raise NotFound\n\n response = handler(request)\n return response\n\n\ndef _handle_hello_index(request: RequestT) -> ResponseT:\n if request.method != \"GET\":\n raise MethodNotAllowed\n\n base = read_static(\"_base.html\")\n base_html = base.content.decode()\n hello_html = read_static(\"hello.html\").content.decode()\n\n body = hello_html.format(\n address_header=request.user.address or \"the middle of fucking nowhere\",\n address_value=request.user.address or \"\",\n name_header=request.user.name or \"anonymous\",\n name_value=request.user.name or \"\",\n )\n\n document = base_html.format(body=body)\n\n status = build_status(200)\n\n headers = {\"Content-Type\": base.content_type}\n\n response = ResponseT(\n headers=headers,\n payload=document.encode(),\n status=status,\n )\n\n return response\n\n\ndef _handle_hello_greet(request: RequestT) -> ResponseT:\n if request.method != \"POST\":\n raise MethodNotAllowed\n\n name = request.form_data.get(\"name\", [None])[0]\n address = request.form_data.get(\"address\", [None])[0]\n\n request.user.name = name\n request.user.address = address\n\n save_user(request.user)\n\n status = build_status(302)\n\n cookie = build_session_header(request.user.id)\n\n headers = {\n \"Location\": \"/h/\",\n \"Set-Cookie\": cookie,\n }\n\n response = ResponseT(\n headers=headers,\n status=status,\n )\n\n return response\n\n\ndef _handle_hello_reset(request: RequestT) -> ResponseT:\n if request.method != \"POST\":\n raise MethodNotAllowed\n\n delete_user(request.user)\n\n status = build_status(302)\n\n cookie = build_reset_session_header(request.user.id)\n\n headers = {\n \"Location\": \"/h/\",\n \"Set-Cookie\": cookie,\n }\n\n response = ResponseT(\n headers=headers,\n status=status,\n )\n\n return response\n","sub_path":"src/handlers/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152753400","text":"from ..models.main_models import Country\nfrom pyramid.view import view_config\n\n@view_config(route_name='get_locations', renderer='json')\ndef get_location(request):\n locations = {'locations': []}\n countries = request.dbsession.query(Country)\n\n for country in countries: \n country_dictt = {'country': '', 'id': 0, 'subUnits': []}\n country_dictt['country'] = country.name\n country_dictt['id'] = country.id\n \n for subnational in country.sub_nationals:\n sub_dictt = {'id': 0, 'name': ''}\n sub_dictt['id']= subnational.id\n sub_dictt['name'] = subnational.name\n \n country_dictt['subUnits'].append(sub_dictt)\n\n locations['locations'].append(country_dictt)\n\n return locations","sub_path":"repoll/views/location_actions.py","file_name":"location_actions.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"565252228","text":"#!/usr/bin/env python\n\nimport sys, re, os, errno\n\n\noutput_dir = sys.argv[1]\nfile_names = sys.argv[2:]\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else: raise\n\n# Load all shaders\nshaders = {}\nfor file_name in file_names:\n parts = re.search('/(\\w+)\\.(vertex|fragment)\\.glsl$', file_name)\n if parts:\n shader_name = parts.group(1)\n shader_type = parts.group(2)\n if not shader_name in shaders:\n shaders[shader_name] = {}\n with open(file_name, \"r\") as f:\n shaders[shader_name][shader_type] = f.read()\n\n\ndef write_header():\n header = \"\"\"// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.\n\n#ifndef MBGL_SHADER_SHADERS\n#define MBGL_SHADER_SHADERS\n\nnamespace mbgl {\n\nstruct shader_source {\n const char *vertex;\n const char *fragment;\n};\n\nenum {\n%s\n SHADER_COUNT\n};\n\nextern const shader_source shaders[SHADER_COUNT];\n\n}\n\n#endif\n\"\"\" % '\\n'.join([' %s_SHADER,' % name.upper() for name in shaders.keys()])\n header_path = os.path.join(output_dir, 'include/mbgl/shader/shaders.hpp')\n mkdir_p(os.path.dirname(header_path))\n with open(header_path, 'w') as f: f.write(header)\n\n\ndef write_source(shader_platform, prefix, suffix):\n if shader_platform == 'gles2' or shader_platform == 'gles3':\n # OpenGL ES\n preamble = 'precision highp float;';\n else:\n # Desktop OpenGL\n preamble = '#version 120';\n\n shader_lines = [(\"\"\" {{\n R\"{name}_vert({preamble}\\n{vertex}){name}_vert\",\n R\"{name}_frag({preamble}\\n{fragment}){name}_frag\",\n }},\n\"\"\").format(\n name = shader,\n preamble = preamble,\n vertex = shaders[shader]['vertex'],\n fragment = shaders[shader]['fragment']\n) for shader in shaders]\n\n source = \"\"\"// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.\n#include \n{prefix}\n#include \n\nnamespace mbgl {{\n\nconst shader_source shaders[SHADER_COUNT] = {{\n{shaders}\n}};\n\n}}\n{suffix}\n\"\"\".format(\n prefix = prefix,\n suffix = suffix,\n shaders = ''.join(shader_lines)\n)\n\n source_path = os.path.join(output_dir, 'src/shader/shaders_' + shader_platform + '.cpp')\n mkdir_p(os.path.dirname(source_path))\n with open(source_path, 'w') as f: f.write(source)\n\nwrite_header()\nwrite_source('gl', '#ifndef GL_ES_VERSION_2_0', '#endif')\nwrite_source('gles2', '#ifdef GL_ES_VERSION_2_0', '#endif')\n","sub_path":"scripts/build-shaders.py","file_name":"build-shaders.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"518785091","text":"from __future__ import print_function, division\nimport os\nimport re\nimport codecs\nimport unicodedata\nfrom py_ner.lstm_cnn_crf_utils import create_dico, create_mapping, zero_digits\nfrom py_ner.lstm_cnn_crf_utils import iob2, iob_iobes\nimport py_ner.lstm_cnn_crf_model as model\nimport pandas as pd\n\nimport string\nimport random\nimport numpy as np\nimport pickle\n\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in string.ascii_letters + \" .,;'-\"\n )\n\ndef load_sentences(path, lower, zeros):\n \"\"\"\n Load sentences. A line must contain at least a word and its tag.\n Sentences are separated by empty lines.\n \"\"\"\n sentences = []\n sentence = []\n for line in codecs.open(path, 'r', 'utf-8'):\n line = zero_digits(line.rstrip()) if zeros else line.rstrip()\n if not line:\n if len(sentence) > 0:\n if 'DOCSTART' not in sentence[0][0]:\n sentences.append(sentence)\n sentence = []\n else:\n word = line.split()\n assert len(word) >= 2\n sentence.append(word)\n if len(sentence) > 0:\n if 'DOCSTART' not in sentence[0][0]:\n sentences.append(sentence)\n return sentences\n\n\ndef update_tag_scheme(sentences, tag_scheme):\n \"\"\"\n Check and update sentences tagging scheme to IOB2.\n Only IOB1 and IOB2 schemes are accepted.\n \"\"\"\n for i, s in enumerate(sentences):\n tags = [w[-1] for w in s]\n # Check that tags are given in the IOB format\n if not iob2(tags):\n s_str = '\\n'.join(' '.join(w) for w in s)\n raise Exception('Sentences should be given in IOB format! ' +\n 'Please check sentence %i:\\n%s' % (i, s_str))\n if tag_scheme == 'iob':\n # If format was IOB1, we convert to IOB2\n for word, new_tag in zip(s, tags):\n word[-1] = new_tag\n elif tag_scheme == 'iobes':\n new_tags = iob_iobes(tags)\n for word, new_tag in zip(s, new_tags):\n word[-1] = new_tag\n else:\n raise Exception('Unknown tagging scheme!')\n\n\ndef word_mapping(sentences, lower):\n \"\"\"\n Create a dictionary and a mapping of words, sorted by frequency.\n \"\"\"\n words = [[x[0].lower() if lower else x[0] for x in s] for s in sentences]\n dico = create_dico(words)\n\n dico[''] = 10000001\n dico[''] = 10000000\n dico = {k:v for k,v in dico.items() if v>=3}\n word_to_id, id_to_word = create_mapping(dico)\n\n print(\"Found %i unique words (%i in total)\" % (\n len(dico), sum(len(x) for x in words)\n ))\n return dico, word_to_id, id_to_word\n\n\ndef char_mapping(sentences):\n \"\"\"\n Create a dictionary and mapping of characters, sorted by frequency.\n \"\"\"\n chars = [\"\".join([w[0] for w in s]) for s in sentences]\n dico = create_dico(chars)\n dico[''] = 10000000\n # dico[';'] = 0\n char_to_id, id_to_char = create_mapping(dico)\n print(\"Found %i unique characters\" % len(dico))\n return dico, char_to_id, id_to_char\n\n\ndef tag_mapping(sentences):\n \"\"\"\n Create a dictionary and a mapping of tags, sorted by frequency.\n \"\"\"\n tags = [[word[-1] for word in s] for s in sentences]\n dico = create_dico(tags)\n dico[model.START_TAG] = -1\n dico[model.STOP_TAG] = -2\n tag_to_id, id_to_tag = create_mapping(dico)\n print(\"Found %i unique named entity tags\" % len(dico))\n return dico, tag_to_id, id_to_tag\n\n\ndef cap_feature(s):\n \"\"\"\n Capitalization feature:\n 0 = low caps\n 1 = all caps\n 2 = first letter caps\n 3 = one capital (not first letter)\n \"\"\"\n if s.lower() == s:\n return 0\n elif s.upper() == s:\n return 1\n elif s[0].upper() == s[0]:\n return 2\n else:\n return 3\n\n\ndef prepare_sentence(str_words, word_to_id, char_to_id, lower=False):\n \"\"\"\n Prepare a sentence for evaluation.\n \"\"\"\n def f(x): return x.lower() if lower else x\n words = [word_to_id[f(w) if f(w) in word_to_id else '']\n for w in str_words]\n chars = [[char_to_id[c] for c in w if c in char_to_id]\n for w in str_words]\n caps = [cap_feature(w) for w in str_words]\n return {\n 'str_words': str_words,\n 'words': words,\n 'chars': chars,\n 'caps': caps\n }\n\n\ndef prepare_dataset(sentences, word_to_id, char_to_id, tag_to_id, lower=True):\n \"\"\"\n Prepare the dataset. Return a list of lists of dictionaries containing:\n - word indexes\n - word char indexes\n - tag indexes\n \"\"\"\n def f(x): return x.lower() if lower else x\n data = []\n for s in sentences:\n str_words = [w[0] for w in s]\n words = [word_to_id[f(w) if f(w) in word_to_id else '']\n for w in str_words]\n # Skip characters that are not in the training set\n chars = [[char_to_id[c] for c in w if c in char_to_id]\n for w in str_words]\n caps = [cap_feature(w) for w in str_words]\n tags = [tag_to_id[w[-1]] for w in s]\n data.append({\n 'str_words': str_words,\n 'words': words,\n 'chars': chars,\n 'caps': caps,\n 'tags': tags,\n })\n return data\n\n\ndef augment_with_pretrained(dictionary, ext_emb_path, words):\n \"\"\"\n Augment the dictionary with words that have a pretrained embedding.\n If `words` is None, we add every word that has a pretrained embedding\n to the dictionary, otherwise, we only add the words that are given by\n `words` (typically the words in the development and test sets.)\n \"\"\"\n print('Loading pretrained embeddings from %s...' % ext_emb_path)\n assert os.path.isfile(ext_emb_path)\n\n # Load pretrained embeddings from file\n pretrained = set([\n line.rstrip().split()[0].strip()\n for line in codecs.open(ext_emb_path, 'r', 'utf-8')\n if len(ext_emb_path) > 0\n ])\n\n # We either add every word in the pretrained file,\n # or only words given in the `words` list to which\n # we can assign a pretrained embedding\n if words is None:\n for word in pretrained:\n if word not in dictionary:\n dictionary[word] = 0\n else:\n for word in words:\n if any(x in pretrained for x in [\n word,\n word.lower(),\n re.sub('\\d', '0', word.lower())\n ]) and word not in dictionary:\n dictionary[word] = 0\n\n word_to_id, id_to_word = create_mapping(dictionary)\n return dictionary, word_to_id, id_to_word\n\n\ndef pad_seq(seq, max_length, PAD_token=0):\n # add pads\n seq += [PAD_token for i in range(max_length - len(seq))]\n return seq\n\ndef get_batch(start, batch_size, datas, singletons=[]):\n input_seqs = []\n target_seqs = []\n chars2_seqs = []\n\n for data in datas[start:start+batch_size]:\n # pair is chosen from pairs randomly\n words = []\n for word in data['words']:\n if word in singletons and np.random.uniform() < 0.5:\n words.append(1)\n else:\n words.append(word)\n input_seqs.append(data['words'])\n target_seqs.append(data['tags'])\n chars2_seqs.append(data['chars'])\n\n if input_seqs == []:\n return [], [], [], [], [], []\n seq_pairs = sorted(zip(input_seqs, target_seqs, chars2_seqs), key=lambda p: len(p[0]), reverse=True)\n input_seqs, target_seqs, chars2_seqs = zip(*seq_pairs)\n\n chars2_seqs_lengths = []\n chars2_seqs_padded = []\n for chars2 in chars2_seqs:\n chars2_lengths = [len(c) for c in chars2]\n chars2_padded = [pad_seq(c, max(chars2_lengths)) for c in chars2]\n chars2_seqs_padded.append(chars2_padded)\n chars2_seqs_lengths.append(chars2_lengths)\n\n input_lengths = [len(s) for s in input_seqs]\n # input_padded is batch * max_length\n input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]\n target_lengths = [len(s) for s in target_seqs]\n assert target_lengths == input_lengths\n # target_padded is batch * max_length\n target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]\n\n # var is max_length * batch_size\n # input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)\n # target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)\n #\n # if use_gpu:\n # input_var = input_var.cuda()\n # target_var = target_var.cuda()\n\n return input_padded, input_lengths, target_padded, target_lengths, chars2_seqs_padded, chars2_seqs_lengths\n\n\ndef random_batch(batch_size, train_data, singletons=[]):\n input_seqs = []\n target_seqs = []\n chars2_seqs = []\n\n for i in range(batch_size):\n # pair is chosen from pairs randomly\n data = random.choice(train_data)\n words = []\n for word in data['words']:\n if word in singletons and np.random.uniform() < 0.5:\n words.append(1)\n else:\n words.append(word)\n input_seqs.append(data['words'])\n target_seqs.append(data['tags'])\n chars2_seqs.append(data['chars'])\n\n seq_pairs = sorted(zip(input_seqs, target_seqs, chars2_seqs), key=lambda p: len(p[0]), reverse=True)\n input_seqs, target_seqs, chars2_seqs = zip(*seq_pairs)\n\n chars2_seqs_lengths = []\n chars2_seqs_padded = []\n for chars2 in chars2_seqs:\n chars2_lengths = [len(c) for c in chars2]\n chars2_padded = [pad_seq(c, max(chars2_lengths)) for c in chars2]\n chars2_seqs_padded.append(chars2_padded)\n chars2_seqs_lengths.append(chars2_lengths)\n\n input_lengths = [len(s) for s in input_seqs]\n # input_padded is batch * max_length\n input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]\n target_lengths = [len(s) for s in target_seqs]\n assert target_lengths == input_lengths\n # target_padded is batch * max_length\n target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]\n\n # var is max_length * batch_size\n # input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)\n # target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)\n #\n # if use_gpu:\n # input_var = input_var.cuda()\n # target_var = target_var.cuda()\n\n return input_padded, input_lengths, target_padded, target_lengths, chars2_seqs_padded, chars2_seqs_lengths\n\ndef convert_to_df(text_file):\n dframe = pd.read_csv(text_file, encoding=\"ISO-8859-1\", error_bad_lines=False)\n dataset = dframe.drop(['Unnamed: 0', 'lemma', 'next-lemma', 'next-next-lemma', 'next-next-pos',\n 'next-next-shape', 'next-next-word', 'next-pos', 'next-shape',\n 'next-word', 'prev-iob', 'prev-lemma', 'prev-pos',\n 'prev-prev-iob', 'prev-prev-lemma', 'prev-prev-pos', 'prev-prev-shape',\n 'prev-prev-word', 'prev-shape', 'prev-word', 'shape'], axis=1)\n\n return dataset\n\ndef convert_to_df_for_ko_ner(sentences):\n pd.set_option('display.max_columns', None)\n document_df = pd.DataFrame()\n\n max = 500;\n for i, sent in enumerate(sentences):\n for ej_idx, token, postag, label in sent:\n document_df = document_df.append(pd.Series([int(i), token, postag, label]), ignore_index=True)\n i += 1\n\n if i >= max:\n break\n\n document_df.columns = ['sentence_idx', 'word', 'pos', 'tag']\n document_df = document_df.set_index('sentence_idx')\n tag_names = document_df['tag'].unique()\n\n return document_df, tag_names\n\ndef read_file(file_name):\n sents = []\n with open(file_name,'r',encoding='utf-8') as f:\n lines = f.readlines()\n for idx,l in enumerate(lines) :\n if l[0]==';' and lines[idx+1][0]=='$':\n this_sent = []\n elif l[0]=='$' and lines[idx-1][0]==';':\n continue\n elif l[0]=='\\n':\n sents.append(this_sent)\n else :\n this_sent.append(tuple(l.split()))\n return sents\n\ndef word2features(sent, i):\n last_p = sent[i][0]\n mor_idx = sent[i][1]\n word = sent[i][3]\n postag = sent[i][4]\n features = [\n 'bias',\n 'word=' + word,\n 'word[:1]=' + word[:1],\n 'word[:2]=' + word[:2],\n 'word[-3:]=' + word[-3:],\n 'word[-2:]=' + word[-2:],\n 'word.isdigit=%s' % word.isdigit(),\n 'postag=' + postag,\n 'postag[:2]=' + postag[:2],\n 'last_p=' + last_p,\n 'mor_i=' + mor_idx,\n 'len='+str(len(word))\n ]\n if i > 0:\n word1 = sent[i-1][3]\n postag1 = sent[i-1][4]\n features.extend([\n '-1:word=' + word1,\n '-1:postag=' + postag1,\n '-1:postag[:2]=' + postag1[:2],\n ])\n else:\n features.append('BOS')\n\n if i < len(sent) - 1:\n word1 = sent[i+1][3]\n postag1 = sent[i+1][4]\n features.extend([\n '+1:word=' + word1,\n '+1:postag=' + postag1,\n '+1:postag[:2]=' + postag1[:2],\n ])\n else:\n features.append('EOS')\n\n return features\n\ndef add_features_to_sent(sent):\n new_sent = []\n this_ej = []\n ej_idx = 1\n morph_idx = 1\n for w in sent:\n if int(w[0]) > ej_idx:\n assert(len(this_ej)>0)\n last_particle = '-'\n if this_ej[-1][3][0]=='J':\n last_particle=this_ej[-1][2]+'/'+this_ej[-1][3]\n this_ej = [(last_particle,)+m for m in this_ej]\n new_sent += this_ej\n this_ej = []\n ej_idx += 1\n morph_idx = 1\n this_ej.append((str(morph_idx),)+w)\n morph_idx += 1\n if len(this_ej) > 0:\n last_particle = '-'\n if this_ej[-1][3][0] == 'J':\n last_particle = this_ej[-1][2] + '/' + this_ej[-1][3]\n this_ej = [(last_particle,) + m for m in this_ej]\n new_sent += this_ej\n return new_sent\n\ndef sent2features(sent):\n sent = add_features_to_sent(sent)\n return [word2features(sent, i) for i in range(len(sent))]\n\ndef sent2labels(sent):\n return [label for ej_idx, token, postag, label in sent]\n\ndef sent2tokens(sent):\n return [token for ej_idx, token, postag, label in sent]\n\n\nclass SentenceGetter(object):\n def __init__(self, dataset):\n self.n_sent = 1\n self.dataset = dataset\n self.empty = False\n agg_func = lambda s: [(w, p, t) for w, p, t in zip(s[\"word\"].values.tolist(),\n s['pos'].values.tolist(),\n s[\"tag\"].values.tolist())]\n self.grouped = self.dataset.groupby(\"sentence_idx\").apply(agg_func)\n self.sentences = [s for s in self.grouped]\n\n def get_next(self):\n try:\n s = self.grouped[\"Sentence: {}\".format(self.n_sent)]\n self.n_sent += 1\n return s\n except:\n return None\n","sub_path":"py_ner/ner_data_loader.py","file_name":"ner_data_loader.py","file_ext":"py","file_size_in_byte":15070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"572145841","text":"import os\nimport json\nfrom data import ChapterList, StepList\n\nhome = '/home/siwon.sung/sandbox/11math'\nstepList = json.loads(StepList)\nfor step in stepList:\n step_idx = step['idx']\n chapter = step['chapter']\n no = step['no']\n title = step['title'].replace('/', '&').replace('@', '')\n grade = step['grade'][0]\n semester = step['grade'][1]\n dir = '{}/{}학년/{}학기/{}-{}.{}'.format(home, grade, semester, chapter, no, title)\n\n if grade == '3' and semester == '1':\n list = os.listdir(dir)\n for item in list:\n src = '{}/{}'.format(dir, item)\n dst = '{}/{}{}_{}-{}_{}'.format(dir, grade, semester, chapter, no, item)\n os.rename(src, dst)","sub_path":"11math/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"256995534","text":"import string\n\n# Numbers a and b are matching if (sum of divisors a - 1) == b and (sum of divisors b - 1) == a \n\ndef main():\n number_a = input(\"Please enter number a: \")\n if number_a.isdigit():\n number_a = int(number_a)\n else:\n print(\"Enter a number!\")\n number_b = input(\"Please enter number b: \")\n if number_b.isdigit():\n number_b = int(number_b)\n else:\n print(\"Enter a number!\")\n sum_divisors_a = generate_divisor(number_a)\n sum_divisors_b = generate_divisor(number_b)\n if (sum_divisors_b - 1) == number_a and (sum_divisors_a -1) == number_b:\n print(\"Numbers are matching\")\n else:\n print(\"Numbers not matching\")\n\ndef generate_divisor(number):\n\n divisors = []\n for each_number in range(1, number):\n if number % each_number == 0:\n divisors.append(each_number)\n else:\n pass\n divisors_sum = sum(divisors)\n return divisors_sum\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"matching_numbers.py","file_name":"matching_numbers.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"239932746","text":"from flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nclass Contacts(db.Model):\n\t__tablename__ = 'contacts' # I forgot to declare the name of table here\n\tuid = db.Column(db.Integer, primary_key = True)\n\tfirstname = db.Column(db.String(100))\n\tlastname = db.Column(db.String(100))\n\temail = db.Column(db.String(120), unique=True)\n\n\tdef __init__(self, firstname, lastname, email):\n\t\tself.firstname = firstname.title()\n\t\tself.lastname = lastname.title()\n\t\tself.email = email.lower()\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316945780","text":"import dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nfrom app import app\n\nimport pandas as pd\nimport numpy as np\n\n#import data\ndf = pd.read_csv('https://raw.githubusercontent.com/scottwmwork/datasets/master/tmdb_5000_movies.csv')\n\n#Create columns out of release date column\ndf['release_date'] = pd.to_datetime(df['release_date'],infer_datetime_format = True)\ndf['release_year'] = df['release_date'].dt.year\ndf['release_month'] = df['release_date'].dt.month\ndf['release_day'] = df['release_date'].dt.month\ndf = df.drop(columns = 'release_date')\n\ndef wrangle(X):\n \n X = X.copy()\n X = X.reset_index()\n\n #Engineer features:\n #create feature for genre\n\n genre = []\n for x in X['genres']:\n if x == '[]':\n genre.append(np.nan)\n elif \"Documentary\" in x:\n genre.append(\"Documentary\")\n elif \"Animation\" in x:\n genre.append(\"Animation\")\n elif \"Horror\" in x:\n genre.append(\"Horror\")\n elif \"Science Fiction\" in x:\n genre.append(\"Science Fiction\")\n elif \"Comedy\" in x:\n genre.append(\"Comedy\")\n elif \"Drama\" in x:\n genre.append(\"Drama\")\n elif \"Action\" in x:\n genre.append(\"Action\")\n else:\n genre.append(\"Other\")\n\n X['genre'] = genre\n return X\ndf_new = wrangle(df)\n\ntop_movies_temp = df.sort_values(by = 'revenue').tail()\ntop_movies = pd.DataFrame()\ntop_movies['title'] = top_movies_temp.title\ntop_movies['release_year'] = top_movies_temp.release_year\ntop_movies['revenue'] = top_movies_temp.revenue\n\n\n#Create plot\nimport plotly.express as px\nfig1 = px.scatter_3d(df, x = 'release_year', y = 'budget', z = 'revenue', color = 'revenue', opacity=0.7, size_max=8, title = 'Revenue of Movies
    Based on Budget and Release Year', template = 'plotly_dark')\n\ncolumn1 = dbc.Col(\n [\n dcc.Markdown(\n \"\"\"\n \n ## Insights\n\n We can see from this 3 Dimensional Graph that a movie's budget and release year greatly \n influence a movie's revenue. You may notice at the top of this graph is the movie called \"Avatar\" that \n came out in 2009 which had a budget of 237 million USD and produce 2.79 billion USD at the box.\n \n \"\"\"\n ),\n \n ],\n md=4,\n)\n\n\ncolumn2 = dbc.Col(\n [\n dcc.Graph(figure=fig1)\n ]\n)\n\nlayout = dbc.Row([column1, column2])","sub_path":"pages/insights.py","file_name":"insights.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522317371","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/7/23 4:23 PM\n# @Author : zhongch4g\n# @Site : \n# @File : 628. Maximum Subtree.py\n# @Software: IntelliJ IDEA\n\n\n\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nimport sys\nclass Solution:\n \"\"\"\n @param root: the root of binary tree\n @return: the maximum weight node\n \"\"\"\n def __init__(self):\n self.maximum = - sys.maxsize - 1\n self.result = None\n\n def findSubtree(self, root):\n if not root:\n return None\n self.maximum = self.search(root)\n return self.result\n\n # left tree max & right tree max & its node\n def search(self, root):\n # base case\n if not root:\n return 0\n\n leftmax = self.search(root.left)\n rightmax = self.search(root.right)\n\n # 最大子树指的是整棵子树\n if leftmax + rightmax + root.val > self.maximum or not self.result:\n self.maximum = leftmax + rightmax + root.val\n self.result = root\n return leftmax + rightmax + root.val\n","sub_path":"Lintcode/628. Maximum Subtree.py","file_name":"628. Maximum Subtree.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"55443394","text":"from enum import Enum\n\nfrom . import proto\n\nclass Cmd(Enum):\n SET_CARDNO = b'\\x30'\n GET_SI5 = b'\\x31'\n TRANS_REC = b'\\x33'\n SI5_WRITE = b'\\x43'\n SI5_DET = b'\\x46'\n TRANS_REC2 = b'\\x53'\n TRANS_TIME = b'\\x54'\n GET_SI6 = b'\\x61'\n SI6_WRITEPAGE = b'\\x62'\n SI6_READWORD = b'\\x63'\n SI6_WRITEWORD = b'\\x64'\n SI6_DET = b'\\x66'\n SET_MS = b'\\x70'\n GET_MS = b'\\x71'\n SET_SYS_VAL = b'\\x72'\n GET_SYS_VAL = b'\\x73'\n GET_BACKUP = b'\\x74'\n ERASE_BACKUP = b'\\x75'\n SET_TIME = b'\\x76'\n GET_TIME = b'\\x77'\n OFF = b'\\x78'\n RESET = b'\\x79'\n GET_BACKUP2 = b'\\x7a'\n SET_BAUD = b'\\x7e'\n\n\ndef instr(cmd, data):\n return (\n proto.Char.STX.value\n +\n cmd.value\n +\n data\n +\n proto.Char.ETX.value\n )\n\n\nclass LegacyProtocolInstruction(proto.Instruction):\n PROTOCOL = 'legacy'\n\n\nclass GetSystemData(LegacyProtocolInstruction):\n CMD = Cmd.GET_SYS_VAL\n","sub_path":"si/temp/legproto.py","file_name":"legproto.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"401781826","text":"from django.shortcuts import render\n\nfrom django.http import HttpResponse\nfrom apriori.apyori import apriori\nfrom django.template import loader\nfrom apriori.ap import runApriori, dataFromFile, getItemSetTransactionList\n# Create your views here.\nimport pandas as pd\nimport numpy\n\ndef index2(request):\n html = \"hi\"\n transactions = [\n ['beer', 'nuts'],\n ['beer', 'cheese'],\n ['beer','nuts','milk'],\n ['beer','nuts','coco'],\n ]\n results = list(apriori(transactions))\n html += str(results)\n return HttpResponse(html)\n\ndef index2(request):\n dataset = pd.read_csv('apriori/market.csv', header=None)\n transactions = []\n for i in range(0, 7501):\n print(i)\n transactions.append([str(dataset.values[i, j]) for j in range(0, 20)])\n\n rules = apriori(transactions, min_support=0.003, min_confidence=0.2, min_lift=3, min_length=2)\n\n results = list(rules)\n myResults = [list(x) for x in results]\n html = str(myResults)\n\n return HttpResponse(html)\n\n\ndef itemInput(request):\n inFile = dataFromFile('apriori/market.csv')\n input, T = getItemSetTransactionList(inFile)\n itemSet = []\n itemsort = []\n for x in input:\n itemSet.append(list(x))\n for i in itemSet:\n for x in i:\n itemsort.append(x)\n itemsort.sort()\n #print(itemsort)\n length = len(itemsort)\n\n print(length)\n context = {\n \"itemSet\": itemsort\n }\n #template = loader.get_template(\"apriori/output.html\")\n #return HttpResponse(template.render(context, request))\n return render(request, 'apriori/output.html', context)\n\ndef index(request):\n input = request.POST.getlist('ch[]')\n set(input)\n '''\n a = \"New York\"\n b = \"MBE\"\n itemSet = set()\n itemSet.add(a)\n itemSet.add(b)'''\n\n minSupport = 0.006\n minConfidence = 0.02\n inFile = dataFromFile('apriori/market.csv')\n html = \"\"\n items, rules = runApriori(inFile, minSupport, minConfidence)\n itemSet = set()\n for x in input:\n itemSet.add(x)\n '''logic'''\n final = set()\n temp = set()\n for item, support in items:\n list(item)\n set(item)\n print(item)\n #sorted(items, key=lambda support: support):\n #html += str(itemSet)\n #html += str(item)\n # print(support)\n if itemSet.issubset(item):\n for i in item:\n temp.add(i)\n if not temp.issubset(itemSet):\n final.add(i)\n print(i)\n temp.remove(i)\n html += \"

    Recommendations:



    \"\n for i in final:\n print(i)\n html += \"
    \"+ str(i) +\"
    \"\n html +=\"

    \"\n html += \"Confidence:
    \"\n for rule, confidence in rules:\n pre, post = rule\n html += \"%s -----> %s , %.3f
    \" % (str(pre), str(post), 100*confidence)\n return HttpResponse(html) #template.render(context, request))","sub_path":"apriori/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"51621096","text":"\"\"\"\nAuthor Rafael; Date 12/12/2019\n\"\"\"\nfrom configuracao import Configuracao\nfrom loggin import Loggin\n\n\ndef salvar(linha: object, nome_arquivo: object) -> object:\n \"\"\"\n\n :rtype:\n \"\"\"\n\n path_resultado = Configuracao.configuracao('path_resultado')\n arquivo_nome = path_resultado + '/' + nome_arquivo # 'solucao.csv'\n\n Loggin.log('salvar', arquivo_nome)\n arq = open(arquivo_nome, 'a+')\n primeira = True\n\n for coluna in linha:\n if coluna == 'Melhor':\n arq.close()\n arq = open(arquivo_nome, 'w')\n if not primeira:\n arq.write(',')\n primeira = False\n arq.write(\"{}\".format(coluna))\n arq.write(\"\\n\")\n arq.close()\n","sub_path":"solucao/Salvar.py","file_name":"Salvar.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147920605","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nmatrix = np.loadtxt(\"numa00_output.txt\")\nncores = matrix[:,0]\nband = matrix[:,1]\n\nNMes = 10; i = 0; j = 0; k = 0;\n\nn_c = np.zeros(6)\nmesures = np.zeros(6)\n\nwhile i < len(band):\n tmp = 0.\n for j in range(NMes):\n tmp += band[j + i]\n\n mesures[k] = tmp / NMes\n n_c[k] = ncores[i]\n i += NMes; k += 1\n\nmatrix = np.loadtxt(\"numa01_output.txt\")\nncores = matrix[:,0]\nband = matrix[:,1]\n\nNMes = 10; i = 0; j = 0; k = 0;\n\nmesures2 = np.zeros(6)\n\nwhile i < len(band):\n tmp = 0.\n for j in range(NMes):\n tmp += band[j + i]\n\n mesures2[k] = tmp / NMes\n i += NMes; k += 1\n\nplt.figure()\nplt.plot(n_c, mesures, '-o')\nplt.plot(n_c, mesures2, '-o')\nplt.xlabel('Number of cores')\nplt.ylabel('Bandwidth in MB/s')\nplt.savefig(\"numa_plot_smallvec.png\")\n","sub_path":"D4-hands-on/numa_plot.py","file_name":"numa_plot.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137657296","text":"import math, sys\r\nimport pygame\r\nfrom pygame.locals import *\r\n \r\npygame.init()\r\nscreen = pygame.display.set_mode((1024, 768), DOUBLEBUF)\r\nclock = pygame.time.Clock()\r\n \r\nclass SimpleSprite(pygame.sprite.Sprite):\r\n \r\n def __init__(self, image, position):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.user_src_image = pygame.image.load(image)\r\n self.user_position = position\r\n self.user_rotation = 30\r\n self.user_speed = 0\r\n self.user_rotation_speed = 0\r\n \r\n def update(self, deltat):\r\n # 속도, 회전 속도에 따라 위치 정보를 업데이트한다\r\n self.user_rotation += self.user_rotation_speed\r\n x, y = self.user_position\r\n rad = self.user_rotation * math.pi / 180\r\n x += -self.user_speed * math.sin(rad)\r\n y += -self.user_speed * math.cos(rad)\r\n self.user_position = (x, y)\r\n \r\n self.image = pygame.transform.rotate(self.user_src_image, self.user_rotation)\r\n self.rect = self.image.get_rect()\r\n self.rect.center = self.user_position\r\n \r\nclass BlockSprite(pygame.sprite.Sprite):\r\n \r\n def __init__(self, position):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.user_image_normal = pygame.image.load(\"triangl2.png\");\r\n self.user_image_hit = pygame.image.load(\"triangl2.png\");\r\n self.user_position = position;\r\n \r\n self.image = self.user_image_normal\r\n self.rect = self.image.get_rect()\r\n self.rect.center = self.user_position\r\n \r\n def update(self, hit_list):\r\n \r\n if self in hit_list:\r\n self.image = self.user_image_hit\r\n else:\r\n self.image = self.user_image_normal\r\n \r\n self.rect = self.image.get_rect()\r\n self.rect.center = self.user_position\r\n \r\nrect = screen.get_rect()\r\nsimple = SimpleSprite('blackdrone.png', rect.center)\r\nsimple_group = pygame.sprite.RenderPlain(simple)\r\nsimple.mask = pygame.mask.from_surface(simple.user_src_image) \r\nblocks = [\r\n BlockSprite((300, 400)),\r\n BlockSprite((800, 200)),\r\n BlockSprite((200, 600)),\r\n BlockSprite((800, 600))\r\n]\r\nblocks[0].mask = pygame.mask.from_surface(blocks[0].user_image_normal)\r\nblocks[1].mask = pygame.mask.from_surface(blocks[1].user_image_normal)\r\nblocks[2].mask = pygame.mask.from_surface(blocks[2].user_image_normal)\r\nblocks[3].mask = pygame.mask.from_surface(blocks[3].user_image_normal)\r\nblock_group = pygame.sprite.RenderPlain(*blocks)\r\n \r\nbackground = pygame.image.load('background1024768.png')\r\nscreen.blit(background, (0,0))\r\n \r\nfontObj = pygame.font.Font(None, 32)\r\ncounter = 0 \r\nwhile True:\r\n deltat = clock.tick(30)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n # 키입력에 따라 속도, 회전 속도를 설정\r\n if hasattr(event, 'key'):\r\n down = event.type == KEYDOWN\r\n if event.key == K_RIGHT:\r\n simple.user_rotation_speed = down * -5 # 시계 방향이 마이너스인 것에 유의\r\n elif event.key == K_LEFT:\r\n simple.user_rotation_speed = down * 5\r\n elif event.key == K_UP:\r\n simple.user_speed = down * 4\r\n elif event.key == K_DOWN:\r\n simple.user_speed = down * -4\r\n counter += 1/deltat\r\n simple_group.update(deltat)\r\n \r\n # collisions = pygame.sprite.spritecollide(simple, block_group, False)\r\n if(pygame.sprite.collide_mask(blocks[2],simple)):\r\n print(\"충돌\")\r\n \r\n if(pygame.sprite.collide_mask(blocks[1],simple)):\r\n print(\"충돌\")\r\n \r\n if(pygame.sprite.collide_mask(blocks[0],simple)):\r\n print(\"충돌\")\r\n \r\n if(pygame.sprite.collide_mask(blocks[3],simple)):\r\n print(\"충돌\")\r\n \r\n simple_group.clear(screen, background)\r\n block_group.clear(screen, background)\r\n simple_group.draw(screen)\r\n block_group.draw(screen)\r\n pygame.display.update()\r\n\r\n","sub_path":"study/tw_study/pygame_study3/spritebasic.py","file_name":"spritebasic.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"141577543","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nif __name__ == \"__main__\":\n data = pd.read_csv(\"results_parallel_10_05_2021-16_06_30.txt\", delimiter='\\t').to_numpy().transpose()\n n_par = data[1]\n t_par = data[0]\n\n plt.title(\"Results on lcc2 (for 1e6 repetitions)\")\n plt.plot(n_par, t_par, '-', lw=1)\n plt.xlabel(\"n = len(a) = len(b) = len(c)\")\n plt.ylabel(\"time in s\")\n plt.savefig(\"lcc2_results.pdf\", bbox_inches=\"tight\")","sub_path":"07/task2/lcc2_results/plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390854214","text":"from scipy.spatial import distance as dist\nfrom imutils import perspective\nfrom imutils import contours\nimport numpy as np\nimport argparse,math\nimport imutils\nimport cv2\nimport pickle\nimport settings,os\ndef midpoint(ptA, ptB):\n\treturn ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)\ndef image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):\n # initialize the dimensions of the image to be resized and\n # grab the image size\n dim = None\n (h, w) = image.shape[:2]\n\n # if both the width and height are None, then return the\n # original image\n if width is None and height is None:\n return image\n\n # check to see if the width is None\n if width is None:\n # calculate the ratio of the height and construct the\n # dimensions\n r = height / float(h)\n dim = (int(w * r), height)\n\n # otherwise, the height is None\n else:\n # calculate the ratio of the width and construct the\n # dimensions\n r = width / float(w)\n dim = (width, int(h * r))\n\n # resize the image\n resized = cv2.resize(image, dim, interpolation = inter)\n\n # return the resized image\n return resized\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True,\n\thelp=\"path to the input image\")\nap.add_argument(\"-w\", \"--width\", type=float, required=True,\n\thelp=\"width of the left-most object in the image (in inches)\")\nargs = vars(ap.parse_args())\nwith open(settings.CALIB_FILE_NAME, 'rb') as f:\n calib_data = pickle.load(f)\n mtx = calib_data[\"cam_matrix\"]\n dist_coeffs = calib_data[\"dist_coeffs\"]\nnewcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist_coeffs, (3008,4016), 1, (3008,4016))\n# load the image, convert it to grayscale, and blur it slightly\n#Here pixelpermetric is based on the first refrence card width that is found to check it for all image move it inside\n#the loop but be sure that every image then has a card placed on the leftmost portion\npixelsPerMetric = None\nfor image_file in os.listdir(args[\"image\"]):\n if image_file.endswith(\"jpg\"):\n image = cv2.imread(os.path.join(args[\"image\"], image_file))\n cv2.namedWindow('image',cv2.WINDOW_NORMAL)\n cv2.resizeWindow('image', 502, 376)\n print(image_file)\n # for i in range(2):\n # image=cv2.pyrDown(image)\n image = cv2.undistort(image, mtx, dist_coeffs, None, newcameramtx)\n# crop the image\n x, y, w, h = roi\n image = image[y:y+h, x:x+w]\n # cv2.imshow(\"image\",image)\n # cv2.waitKey(0)\n # cv2.imwrite(\"img1.png\",image)\n # cv2.destroyAllWindows()\n # print(image.shape)\n # image=cv2.pyrDown(image)\n # print(image.shape)\n # gray = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)[:,:,0] #this one shows good results best results till now.\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #this one shows good results best results till now.\n\n # cv2.imshow(\"image\",gray)\n # cv2.waitKey(0)\n gray = cv2.GaussianBlur(gray, (11, 11), 0)\n # cv2.imshow(\"image\",gray)\n # cv2.waitKey(0)\n # # cv2.imwrite(\"img1.png\",gray)\n # # cv2.destroyAllWindows()\n # # ret,gray=cv2.threshold(gray,125,255,cv2.THRESH_BINARY)\n # ret,gray=cv2.threshold(gray,90,255,cv2.THRESH_BINARY)\n\n # gray = cv2.bitwise_not(gray)\n # cv2.imshow(\"image\",gray)\n # cv2.waitKey(0)\n # cv2.imwrite(\"img1.png\",gray)\n # cv2.destroyAllWindows(\n # perform edge detection, then perform a dilation + erosion to\n # close gaps in between object edges\n edged = cv2.Canny(gray, 50, 100)\n # cv2.imshow(\"image\",edged)\n # cv2.waitKey(0)\n edged = cv2.dilate(edged, None, iterations=40)\n # cv2.imshow(\"image\",edged)\n # cv2.waitKey(0)\n edged = cv2.erode(edged, None, iterations=40)\n # cv2.imshow(\"image\",edged)\n # cv2.waitKey(0)\n # cv2.imwrite(\"img2.png\",edged)\n # cv2.destroyAllWindows()\n # find contours in the edge map\n # cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n cnts = imutils.grab_contours(cnts)\n\n # sort the contours from left-to-right and initialize the\n # 'pixels per metric' calibration variable\n (cnts, _) = contours.sort_contours(cnts)\n # test = gray.copy()\n # print(test.shape)\n # mask = np.zeros_like(test) # Create mask where white is what we want, black otherwise\n # cv2.drawContours(mask, cnts,-1, 255,-1) # Draw filled contour in mask\n # out = np.zeros_like(test) # Extract out the object and place into output image\n # out[mask == 255] = test[mask == 255]\n # ret,out=cv2.threshold(out,200,255,cv2.THRESH_BINARY)\n # cnts = cv2.findContours(out, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n # cnts = imutils.grab_contours(cnts)\n #\n # # sort the contours from left-to-right and initialize the\n # # 'pixels per metric' calibration variable\n # (cnts, _) = contours.sort_contours(cnts)\n # # #Now crop\n # # (y, x) = np.where(mask == 255)\n # # (topy, topx) = (np.min(y), np.min(x))\n # # (bottomy, bottomx) = (np.max(y), np.max(x))\n # # out = out[topy:bottomy+1, topx:bottomx+1]\n #\n # # Show the output image\n # cv2.imshow('image', out)\n # cv2.waitKey(0)\n for c in cnts:\n # if i<=3:\n # i=i+1\n # continue\n # if the contour is not sufficiently large, ignore it\n if cv2.contourArea(c) < 60025:\n continue\n #For croping out the images for more pixel accuracy\n\n\n # compute the rotated bounding box of the contour\n orig = image.copy()\n box = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)\n box = np.array(box, dtype=\"int\")\n\n # order the points in the contour such that they appear\n # in top-left, top-right, bottom-right, and bottom-left\n # order, then draw the outline of the rotated bounding\n # box\n box = perspective.order_points(box)\n # cv2.drawContours(orig, [box.astype(\"int\")], -1, (0, 255, 0), 2)\n # cv2.imshow(\"image\",orig)\n # cv2.waitKey(0)\n # # loop over the original points and draw them\n # for (x, y) in box:\n # cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)\n # cv2.imshow(\"image\",orig)\n # cv2.waitKey(0)\n # unpack the ordered bounding box, then compute the midpoint\n # between the top-left and top-right coordinates, followed by\n # the midpoint between bottom-left and bottom-right coordinates\n (tl, tr, br, bl) = box\n (tltrX, tltrY) = midpoint(tl, tr)\n (blbrX, blbrY) = midpoint(bl, br)\n\n # compute the midpoint between the top-left and top-right points,\n # followed by the midpoint between the top-righ and bottom-right\n (tlblX, tlblY) = midpoint(tl, bl)\n (trbrX, trbrY) = midpoint(tr, br)\n\n # draw the midpoints on the image\n # cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)\n # cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)\n # cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)\n # cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)\n # cv2.imshow(\"image\",orig)\n # cv2.waitKey(0)\n #\n # # draw lines between the midpoints\n # cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),(255, 0, 255), 2)\n # cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),(255, 0, 255), 2)\n # cv2.imshow(\"image\",orig)\n # cv2.waitKey(0)\n\n # compute the Euclidean distance between the midpoints\n dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))\n dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))\n # print(dA)\n # print(dB)\n # print(2*dA + 2*dB)\n # print(\"----------\")\n # if the pixels per metric has not been initialized, then\n # compute it as the ratio of pixels to supplied metric\n # (in this case, inches)\n if pixelsPerMetric is None:\n pixelsPerMetric = dB / args[\"width\"]\n # print(\"kjnffhf=----------------------------\",pixelsPerMetric)\n\n # compute the size of the object\n dimA = dA / pixelsPerMetric\n dimB = dB / pixelsPerMetric\n\n # draw the object sizes on the image\n # cv2.putText(orig, \"{:.1f}in\".format(dimA),(int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,0.65, (255, 255, 255), 2)\n # cv2.putText(orig, \"{:.1f}in\".format(dimB),(int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,0.65, (255, 255, 255), 2)\n\n # show the output image\n draw=image.copy()\n cv2.drawContours(draw,c,-1,(255,255,0),3)\n perimeter = cv2.arcLength(c, True)\n print(perimeter)\n perimeterpix = perimeter / pixelsPerMetric\n cv2.putText(draw, \"{:.3f}\".format(perimeterpix),(int(tltrX-50), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,4.5, (255, 0, 255),15)\n # Uncomment below lines if you want to show the images and then if you want to save them press s while runtime\n cv2.imshow(\"image\",draw)\n if cv2.waitKey(0)==ord('s'):\n count = 0\n while os.path.isfile(\"outputs/img\"+str(count)+\"_\"+str(int(perimeter))+\".png\"): # increase number until file not exists\n count += 1\n cv2.imwrite(\"outputs/img\"+str(count)+\"_\"+str(int(perimeter))+\".png\",draw)\n #Uncomment below lines if you want to save directly without showing the images\n # count = 0\n # while os.path.isfile(\"outputs/img\"+str(count)+\"_\"+str(int(perimeter))+\".png\"): # increase number until file not exists\n # count += 1\n # cv2.imwrite(\"outputs/img\"+str(count)+\"_\"+str(int(perimeter))+\".png\",draw)\n # i=i+1\n # cv2.imshow(\"Image\", orig)\n # cv2.waitKey(0)\n","sub_path":"object_size_2.py","file_name":"object_size_2.py","file_ext":"py","file_size_in_byte":11220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94401676","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 30 10:42:43 2020\r\n\r\n@author: liorfa\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nfrom mpl_toolkits import mplot3d\r\n# Import the PCA9685 module.\r\n#import Adafruit_PCA9685\r\n\r\n\r\n# import random \r\n\r\n#Transformation constant\r\n\r\nT_DR=np.pi/180\r\nT_RS=500/np.pi\r\n\r\n# Defining the spot class\r\nclass Spot:\r\n def __init__(self, Shin_L,Thigh_L,Hip_L,Body_W,Body_L):\r\n # fig = plt.figure()\r\n # self.ax = plt.axes(projection='3d')\r\n \r\n #Initialization of the servo expantion board\r\n #self.pwm=Adafruit_PCA9685.PCA9685()\r\n #self.pwm.set_pwm_freq(60)\r\n \r\n # step size for iterative inverse kinematic calculation\r\n self.S_inc=0.01 #defined in meters\r\n \r\n #Initialized position\r\n self.pos=np.array([0,0,0])\r\n # The continuous walking gates\r\n self.Walk_D=0.05\r\n self.Walk_L=0.03\r\n self.Walk_Se=[0,3,1,2] #sequence of walking legs\r\n \r\n self.Current_swing=5\r\n self.Vel_Dir=np.array([0,0,0]) # A three dimentional vecote indicating the referance direction of walking\r\n self.Goal=np.array([0.5,0,0])\r\n \r\n #these are the linkage length of the robot, in general they should be fixed\r\n self.S_L = Shin_L\r\n self.T_L = Thigh_L\r\n self.H_L=Hip_L\r\n self.B_W=Body_W\r\n self.B_L=Body_L\r\n \r\n # # Base angles---Home position \r\n # self.Servo_Cmd=0*np.array([250,530,440,480,230,270,290,500,490,480,200,320])\r\n self.Joint_Ang=np.array([180,-145,10,180,-145,-10,180,-145,10,180,-145,-10])*T_DR\r\n\r\n # #Base values\r\n # self.Servo_Cmd_base=np.array([270,520,430,450,250,270,290,530,450,470,200,300])\r\n # self.Joint_Ang_base=np.array([90 ,-90,0 , 90,-90,0 ,90,-90 ,0 ,90,-90 ,0])*T_DR\r\n # self.Direction=np.array([1,1,-1,-1,-1,-1,1,1,-1,-1,-1,-1])\r\n \r\n # Initialize the positions of the joints w.r.t. the initial angles \r\n self.LF_Forw_kin()\r\n self.RF_Forw_kin()\r\n self.LR_Forw_kin()\r\n self.RR_Forw_kin()\r\n self.Feet_array()\r\n \r\n # #Initializing the motor commands \r\n # for i in range(0,4,1):\r\n # self.Servo_Cmd_update(i)\r\n \r\n \r\n # # Workspace parameters\r\n # Xp=0.2\r\n # Xn=-0.2\r\n # Yp=0.2\r\n # Yn=-0.28\r\n # Zp=0.25\r\n # Zn=-0.25\r\n # #Setting the workspace for each leg\r\n # # LF\r\n # Up=np.array([[Xp,Yp,Zp],[Xp,-Yn,Zp],[Xp,Yp,Zp],[Xp,-Yn,Zp]])\r\n # Down=np.array([[Xn,Yn,Zn],[Xn,-Yp,Zn],[Xn,Yn,Zn],[Xn,-Yp,Zn]])\r\n # self.Upper_bnd=Up+self.F_pos\r\n # self.Lower_bnd=Down+self.F_pos\r\n \r\n # self.LF_bound_X=np.array([Xn,Xp])+self.LF_F_pos[0]\r\n # self.LF_bound_Y=np.array([Yn,Yp])+self.LF_F_pos[1]\r\n # self.LF_bound_Z=np.array([Zn,Zp])+self.LF_F_pos[2]\r\n # # RF \r\n # self.RF_bound_X=np.array([Xn,Xp])+self.RF_F_pos[0]\r\n # self.RF_bound_Y=-np.array([Yn,Yp])+self.RF_F_pos[1]\r\n # self.RF_bound_Z=np.array([Zn,Zp])+self.RF_F_pos[2]\r\n # # LR\r\n # self.LR_bound_X=np.array([Xn,Xp])+self.LR_F_pos[0]\r\n # self.LR_bound_Y=np.array([Yn,Yp])+self.LR_F_pos[1]\r\n # self.LR_bound_Z=np.array([Zn,Zp])+self.LR_F_pos[2]\r\n # # RR\r\n # self.RR_bound_X=np.array([Xn,Xp])+self.RR_F_pos[0]\r\n # self.RR_bound_Y=-np.array([Yn,Yp])+self.RR_F_pos[1]\r\n # self.RR_bound_Z=np.array([Zn,Zp])+self.RR_F_pos[2]\r\n \r\n \r\n self.LF_bound_check=np.array([0,0,0])\r\n self.RF_bound_check=np.array([0,0,0])\r\n self.LR_bound_check=np.array([0,0,0])\r\n self.RR_bound_check=np.array([0,0,0])\r\n def Feet_array(self):\r\n self.F_pos=np.array([self.LF_F_pos[0:3],self.RF_F_pos[0:3],self.LR_F_pos[0:3],self.RR_F_pos[0:3]])\r\n \r\n # def Servo_Cmd_update(self,m):\r\n # for i in range(m*3,3*(m+1),1):\r\n \r\n # self.Servo_Cmd[i]=self.Servo_Cmd_base[i]+T_RS*self.Direction[i]*(self.Joint_Ang[i]-(self.Joint_Ang_base[i]))\r\n # self.pwm.set_pwm(i, 0, int(self.Servo_Cmd[i]))\r\n # time.sleep(0.1)\r\n # #print(i)\r\n # #print(self.Joint_Ang[i]/T_DR)\r\n # #print(self.Servo_Cmd[i])\r\n \r\n \r\n \r\n #self.Body_Attitude(0,0,0)\r\n # def check_workspace(self,D,leg):\r\n # X=self.F_pos[leg,:]+D #progected pos\r\n # Up=self.Upper_bnd[leg,:]\r\n # Down=self.Lower_bnd[leg,:]\r\n # print(X)\r\n # print(Up)\r\n # print(Down)\r\n # DDx=np.array([0,0,0])\r\n # u=Up-X\r\n # u[u>0]=0\r\n # d=X-Down\r\n # d[d>0]=0\r\n # DDx=u-d\r\n # print(DDx)\r\n # c=sum(DDx!=0)\r\n # return [DDx,c];\r\n \r\n \r\n def LF_Forw_kin(self):\r\n \r\n #Soulder transformatiom\r\n T01 =np.array([[1,0,0,self.B_L/2],[0,np.cos(self.Joint_Ang[2]),-np.sin(self.Joint_Ang[2]),self.B_W/2],[0,np.sin(self.Joint_Ang[2]),np.cos(self.Joint_Ang[2]),0],[0,0,0,1]])\r\n #Hip transformation\r\n T12 =np.array([[np.cos(self.Joint_Ang[1]),0,np.sin(self.Joint_Ang[1]),0],[0,1,0,self.H_L],[-np.sin(self.Joint_Ang[1]),0,np.cos(self.Joint_Ang[1]),0],[0,0,0,1]])\r\n #knee transformation\r\n T23 =np.array([[np.cos(self.Joint_Ang[0]),0,np.sin(self.Joint_Ang[0]),-self.T_L],[0,1,0,0],[-np.sin(self.Joint_Ang[0]),0,np.cos(self.Joint_Ang[0]),0],[0,0,0,1]])\r\n \r\n #The Jackobian LF\r\n DT01=np.array([[0,0,0,0],[0,-np.sin(self.Joint_Ang[2]),-np.cos(self.Joint_Ang[2]),0],[0,np.cos(self.Joint_Ang[2]),-np.sin(self.Joint_Ang[2]),0],[0,0,0,0]])\r\n DT12=np.array([[-np.sin(self.Joint_Ang[1]),0,np.cos(self.Joint_Ang[1]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[1]),0,-np.sin(self.Joint_Ang[1]),0],[0,0,0,0]])\r\n DT23=np.array([[-np.sin(self.Joint_Ang[0]),0,np.cos(self.Joint_Ang[0]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[0]),0,-np.sin(self.Joint_Ang[0]),0],[0,0,0,0]])\r\n J1=np.matmul(DT01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J2=np.matmul(T01,np.matmul(DT12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J3=np.matmul(T01,np.matmul(T12,np.matmul(DT23,np.array([0,0,-self.S_L,1]))))\r\n \r\n J=np.array([J3,J2,J1])\r\n J=np.transpose(J)\r\n J=J[0:3,0:3]\r\n self.LF_J=J\r\n self.LF_inv_J=np.linalg.inv(J)\r\n \r\n # shoulder location\r\n self.LF_S_pos=np.matmul(T01,np.matmul(T12,np.array([0,0,0,1])))\r\n # knee location\r\n self.LF_K_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,0,1]))))\r\n #foot location\r\n self.LF_F_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n \r\n #self.ax.plot3D([self.LF_F_pos[0]],[self.LF_F_pos[1]],[self.LF_F_pos[2]],'k*')\r\n \r\n def LF_Inv_kin(self,DX):\r\n # [DDx,c]=self.check_workspace(DX,0)\r\n # DX=DX+DDx\r\n # self.LF_WC=c\r\n \r\n # Partition of the step size by the predetermined increment\r\n XF=np.array([self.LF_F_pos[0]+DX[0],self.LF_F_pos[1]+DX[1],self.LF_F_pos[2]+DX[2]])\r\n S=np.sqrt(DX.dot(DX))\r\n step_num=int(S/self.S_inc)+1\r\n dx=DX/step_num;\r\n \r\n for i in range(0,step_num,1):\r\n X=np.array([self.LF_F_pos[0],self.LF_F_pos[1],self.LF_F_pos[2]])\r\n dx=(XF-X)/(step_num-i)\r\n #print(dx)\r\n DT=np.matmul(self.LF_inv_J,dx)\r\n #print(DT)\r\n self.Joint_Ang[2]+=DT[2]\r\n self.Joint_Ang[1]+=DT[1]\r\n self.Joint_Ang[0]+=DT[0]\r\n self.LF_Forw_kin()\r\n \r\n #print([self.Joint_Ang[0]/T_DR,self.Joint_Ang[1]/T_DR,self.Joint_Ang[2]/T_DR])\r\n # self.Servo_Cmd_update(0)\r\n\r\n \r\n def RF_Forw_kin(self): \r\n #Soulder transformatiom\r\n T01=np.array([[1,0,0,self.B_L/2],[0,np.cos(self.Joint_Ang[5]),-np.sin(self.Joint_Ang[5]),-self.B_W/2],[0,np.sin(self.Joint_Ang[5]),np.cos(self.Joint_Ang[5]),0],[0,0,0,1]])\r\n #Hip transformation\r\n T12=np.array([[np.cos(self.Joint_Ang[4]),0,np.sin(self.Joint_Ang[4]),0],[0,1,0,-self.H_L],[-np.sin(self.Joint_Ang[4]),0,np.cos(self.Joint_Ang[4]),0],[0,0,0,1]])\r\n #knee transformation\r\n T23=np.array([[np.cos(self.Joint_Ang[3]),0,np.sin(self.Joint_Ang[3]),-self.T_L],[0,1,0,0],[-np.sin(self.Joint_Ang[3]),0,np.cos(self.Joint_Ang[3]),0],[0,0,0,1]])\r\n \r\n \r\n #The Jackobian\r\n DT01=np.array([[0,0,0,0],[0,-np.sin(self.Joint_Ang[5]),-np.cos(self.Joint_Ang[5]),0],[0,np.cos(self.Joint_Ang[5]),-np.sin(self.Joint_Ang[5]),0],[0,0,0,0]])\r\n DT12=np.array([[-np.sin(self.Joint_Ang[4]),0,np.cos(self.Joint_Ang[4]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[4]),0,-np.sin(self.Joint_Ang[4]),0],[0,0,0,0]])\r\n DT23=np.array([[-np.sin(self.Joint_Ang[3]),0,np.cos(self.Joint_Ang[3]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[3]),0,-np.sin(self.Joint_Ang[3]),0],[0,0,0,0]])\r\n J1=np.matmul(DT01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J2=np.matmul(T01,np.matmul(DT12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J3=np.matmul(T01,np.matmul(T12,np.matmul(DT23,np.array([0,0,-self.S_L,1]))))\r\n \r\n J=np.array([J3,J2,J1])\r\n # print(J)\r\n J=np.transpose(J)\r\n J=J[0:3,0:3]\r\n self.RF_J=J\r\n self.RF_inv_J=np.linalg.inv(J)\r\n \r\n # shoulder location\r\n self.RF_S_pos=np.matmul(T01,np.matmul(T12,np.array([0,0,0,1])))\r\n # knee location\r\n self.RF_K_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,0,1]))))\r\n #foot location\r\n self.RF_F_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n #self.ax.plot3D([self.RF_F_pos[0]],[self.RF_F_pos[1]],[self.RF_F_pos[2]],'b*')\r\n\r\n def RF_Inv_kin(self,DX):\r\n # [DDx,c]=self.check_workspace(DX,1)\r\n # DX=DX+DDx\r\n # self.RF_WC=c\r\n # Partition of the step size by the predetermined increment\r\n XF=np.array([self.RF_F_pos[0]+DX[0],self.RF_F_pos[1]+DX[1],self.RF_F_pos[2]+DX[2]])\r\n S=np.sqrt(DX.dot(DX))\r\n step_num=int(S/self.S_inc)+1\r\n dx=DX/step_num;\r\n \r\n for i in range(0,step_num,1):\r\n X=np.array([self.RF_F_pos[0],self.RF_F_pos[1],self.RF_F_pos[2]])\r\n dx=(XF-X)/(step_num-i)\r\n DT=np.matmul(self.RF_inv_J,dx)\r\n self.Joint_Ang[5]+=DT[2]\r\n self.Joint_Ang[4]+=DT[1]\r\n self.Joint_Ang[3]+=DT[0]\r\n self.RF_Forw_kin()\r\n \r\n # self.Servo_Cmd_update(1)\r\n \r\n def LR_Forw_kin(self):\r\n \r\n #Soulder transformatiom\r\n T01=np.array([[1,0,0,-self.B_L/2],[0,np.cos(self.Joint_Ang[8]),-np.sin(self.Joint_Ang[8]),self.B_W/2],[0,np.sin(self.Joint_Ang[8]),np.cos(self.Joint_Ang[8]),0],[0,0,0,1]])\r\n #Hip transformation\r\n T12=np.array([[np.cos(self.Joint_Ang[7]),0,np.sin(self.Joint_Ang[7]),0],[0,1,0,self.H_L],[-np.sin(self.Joint_Ang[7]),0,np.cos(self.Joint_Ang[7]),0],[0,0,0,1]])\r\n #knee transformation\r\n T23=np.array([[np.cos(self.Joint_Ang[6]),0,np.sin(self.Joint_Ang[6]),-self.T_L],[0,1,0,0],[-np.sin(self.Joint_Ang[6]),0,np.cos(self.Joint_Ang[6]),0],[0,0,0,1]])\r\n #The Jackobian\r\n DT01=np.array([[0,0,0,0],[0,-np.sin(self.Joint_Ang[8]),-np.cos(self.Joint_Ang[8]),0],[0,np.cos(self.Joint_Ang[8]),-np.sin(self.Joint_Ang[8]),0],[0,0,0,0]])\r\n DT12=np.array([[-np.sin(self.Joint_Ang[7]),0,np.cos(self.Joint_Ang[7]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[7]),0,-np.sin(self.Joint_Ang[7]),0],[0,0,0,0]])\r\n DT23=np.array([[-np.sin(self.Joint_Ang[6]),0,np.cos(self.Joint_Ang[6]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[6]),0,-np.sin(self.Joint_Ang[6]),0],[0,0,0,0]])\r\n J1=np.matmul(DT01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J2=np.matmul(T01,np.matmul(DT12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J3=np.matmul(T01,np.matmul(T12,np.matmul(DT23,np.array([0,0,-self.S_L,1]))))\r\n J=np.array([J3,J2,J1])\r\n # print(J)\r\n J=np.transpose(J)\r\n J=J[0:3,0:3]\r\n self.LR_J=J\r\n self.LR_inv_J=np.linalg.inv(J)\r\n \r\n # shoulder location\r\n self.LR_S_pos=np.matmul(T01,np.matmul(T12,np.array([0,0,0,1])))\r\n # knee location\r\n self.LR_K_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,0,1]))))\r\n #foot location\r\n self.LR_F_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n #self.ax.plot3D([self.LR_F_pos[0]],[self.LR_F_pos[1]],[self.LR_F_pos[2]],'g*')\r\n \r\n def LR_Inv_kin(self,DX):\r\n # [DDx,c]=self.check_workspace(DX,2)\r\n # DX=DX+DDx\r\n # self.LR_WC=c\r\n # Partition of the step size by the predetermined increment\r\n XF=np.array([self.LR_F_pos[0]+DX[0],self.LR_F_pos[1]+DX[1],self.LR_F_pos[2]+DX[2]])\r\n S=np.sqrt(DX.dot(DX))\r\n step_num=int(S/self.S_inc)+1\r\n dx=DX/step_num;\r\n \r\n for i in range(0,step_num,1):\r\n X=np.array([self.LR_F_pos[0],self.LR_F_pos[1],self.LR_F_pos[2]])\r\n dx=(XF-X)/(step_num-i)\r\n DT=np.matmul(self.LR_inv_J,dx)\r\n self.Joint_Ang[8]+=DT[2]\r\n self.Joint_Ang[7]+=DT[1]\r\n self.Joint_Ang[6]+=DT[0]\r\n self.LR_Forw_kin()\r\n \r\n # self.Servo_Cmd_update(2)\r\n \r\n def RR_Forw_kin(self):\r\n \r\n #Soulder transformatiom\r\n T01=np.array([[1,0,0,-self.B_L/2],[0,np.cos(self.Joint_Ang[11]),-np.sin(self.Joint_Ang[11]),-self.B_W/2],[0,np.sin(self.Joint_Ang[11]),np.cos(self.Joint_Ang[11]),0],[0,0,0,1]])\r\n #Hip transformation\r\n T12=np.array([[np.cos(self.Joint_Ang[10]),0,np.sin(self.Joint_Ang[10]),0],[0,1,0,-self.H_L],[-np.sin(self.Joint_Ang[10]),0,np.cos(self.Joint_Ang[10]),0],[0,0,0,1]])\r\n #knee transformation\r\n T23=np.array([[np.cos(self.Joint_Ang[9]),0,np.sin(self.Joint_Ang[9]),-self.T_L],[0,1,0,0],[-np.sin(self.Joint_Ang[9]),0,np.cos(self.Joint_Ang[9]),0],[0,0,0,1]])\r\n #The Jackobian\r\n DT01=np.array([[0,0,0,0],[0,-np.sin(self.Joint_Ang[11]),-np.cos(self.Joint_Ang[11]),0],[0,np.cos(self.Joint_Ang[11]),-np.sin(self.Joint_Ang[11]),0],[0,0,0,0]])\r\n DT12=np.array([[-np.sin(self.Joint_Ang[10]),0,np.cos(self.Joint_Ang[10]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[10]),0,-np.sin(self.Joint_Ang[10]),0],[0,0,0,0]])\r\n DT23=np.array([[-np.sin(self.Joint_Ang[9]),0,np.cos(self.Joint_Ang[9]),0],[0,0,0,0],[-np.cos(self.Joint_Ang[9]),0,-np.sin(self.Joint_Ang[9]),0],[0,0,0,0]])\r\n J1=np.matmul(DT01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J2=np.matmul(T01,np.matmul(DT12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n J3=np.matmul(T01,np.matmul(T12,np.matmul(DT23,np.array([0,0,-self.S_L,1]))))\r\n J=np.array([J3,J2,J1])\r\n # print(J)\r\n J=np.transpose(J)\r\n J=J[0:3,0:3]\r\n self.RR_J=J\r\n self.RR_inv_J=np.linalg.inv(J)\r\n \r\n # shoulder location\r\n self.RR_S_pos=np.matmul(T01,np.matmul(T12,np.array([0,0,0,1])))\r\n # knee location\r\n self.RR_K_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,0,1]))))\r\n #foot location\r\n self.RR_F_pos=np.matmul(T01,np.matmul(T12,np.matmul(T23,np.array([0,0,-self.S_L,1]))))\r\n #self.ax.plot3D([self.RR_F_pos[0]],[self.RR_F_pos[1]],[self.RR_F_pos[2]],'r*')\r\n\r\n def RR_Inv_kin(self,DX):\r\n # [DDx,c]=self.check_workspace(DX,3)\r\n # DX=DX+DDx\r\n # self.RR_WC=c\r\n # Partition of the step size by the predetermined increment\r\n XF=np.array([self.RR_F_pos[0]+DX[0],self.RR_F_pos[1]+DX[1],self.RR_F_pos[2]+DX[2]])\r\n S=np.sqrt(DX.dot(DX))\r\n step_num=int(S/self.S_inc)+1\r\n dx=DX/step_num;\r\n \r\n for i in range(0,step_num,1):\r\n X=np.array([self.RR_F_pos[0],self.RR_F_pos[1],self.RR_F_pos[2]])\r\n dx=(XF-X)/(step_num-i)\r\n DT=np.matmul(self.RR_inv_J,dx)\r\n self.Joint_Ang[11]+=DT[2]\r\n self.Joint_Ang[10]+=DT[1]\r\n self.Joint_Ang[9]+=DT[0]\r\n self.RR_Forw_kin()\r\n \r\n # self.Servo_Cmd_update(3)\r\n \r\n \r\n # def Body_Attitude(self,roll,pitch,yaw):\r\n \r\n # #roll transformatiom\r\n # T_roll=np.array([[1,0,0,0],[0,np.cos(roll),np.sin(roll),0],[0,-np.sin(roll),np.cos(roll),0],[0,0,0,1]])\r\n # #pitch transformation\r\n # T_pitch=np.array([[np.cos(pitch),0,-np.sin(pitch),0],[0,1,0,0],[np.sin(pitch),0,np.cos(pitch),0],[0,0,0,1]])\r\n # #yaw transformation\r\n # T_Yaw=np.array([[np.cos(yaw),np.sin(yaw),0,0],[-np.sin(yaw),np.cos(yaw),0,0],[0,0,1,0],[0,0,0,1]])\r\n # #Foot transformation\r\n # T=np.matmul(T_Yaw,np.matmul(T_pitch,T_roll))\r\n \r\n # # shoulder locations\r\n # self.LF_S_pos=np.matmul(T,self.LF_S_pos)\r\n # self.RF_S_pos=np.matmul(T,self.RF_S_pos)\r\n # self.LR_S_pos=np.matmul(T,self.LR_S_pos)\r\n # self.RR_S_pos=np.matmul(T,self.RR_S_pos)\r\n # # knee locations\r\n # self.LF_K_pos=np.matmul(T,self.LF_K_pos)\r\n # self.RF_K_pos=np.matmul(T,self.RF_K_pos)\r\n # self.LR_K_pos=np.matmul(T,self.LR_K_pos)\r\n # self.RR_K_pos=np.matmul(T,self.RR_K_pos)\r\n # #foot location\r\n # self.LF_F_pos=np.matmul(T,self.LF_F_pos)\r\n # self.RF_F_pos=np.matmul(T,self.RF_F_pos)\r\n # self.LR_F_pos=np.matmul(T,self.LR_F_pos)\r\n # self.RR_F_pos=np.matmul(T,self.RR_F_pos)\r\n \r\n #This function will alternate the swinf and stance of the feets\r\n # def Walk_seq_controller(self):\r\n # if self.Current_swing==5:\r\n # self.Current_swing_ind=0\r\n # else:\r\n # self.Current_swing_ind+=1\r\n # self.Current_swing_ind=self.Current_swing_ind % 4\r\n \r\n # self.Current_swing=self.Walk_Se[self.Current_swing_ind]\r\n \r\n \r\n \r\n # def Motion_per_leg(self):\r\n # #First lift swing leg\r\n # DX=np.array([0,0,self.Walk_L])\r\n # if self.Current_swing==0:\r\n # self.LF_Inv_kin(DX)\r\n # elif self.Current_swing==1:\r\n # self.RF_Inv_kin(DX)\r\n # elif self.Current_swing==2:\r\n # self.LR_Inv_kin(DX)\r\n # elif self.Current_swing==3:\r\n # self.RR_Inv_kin(DX)\r\n \r\n # # Move all legs ih needed direction \r\n # DX=(self.Vel_Dir/np.linalg.norm(self.Vel_Dir))*self.Walk_D\r\n # if self.Current_swing==0:\r\n # self.LF_Inv_kin(DX)\r\n # self.RF_Inv_kin(-DX/3)\r\n # self.LR_Inv_kin(-DX/3)\r\n # self.RR_Inv_kin(-DX/3)\r\n # elif self.Current_swing==1:\r\n # self.LF_Inv_kin(-DX/3)\r\n # self.RF_Inv_kin(DX)\r\n # self.LR_Inv_kin(-DX/3)\r\n # self.RR_Inv_kin(-DX/3)\r\n # elif self.Current_swing==2:\r\n # self.LF_Inv_kin(-DX/3)\r\n # self.RF_Inv_kin(-DX/3)\r\n # self.LR_Inv_kin(DX)\r\n # self.RR_Inv_kin(-DX/3)\r\n # elif self.Current_swing==3:\r\n # self.LF_Inv_kin(-DX/3)\r\n # self.RF_Inv_kin(-DX/3)\r\n # self.LR_Inv_kin(-DX/3)\r\n # self.RR_Inv_kin(DX)\r\n \r\n # self.pos=np.add(self.pos,DX/3)\r\n # #Last place swing leg\r\n # DX=np.array([0,0,-self.Walk_L])\r\n # if self.Current_swing==0:\r\n # self.LF_Inv_kin(DX)\r\n # elif self.Current_swing==1:\r\n # self.RF_Inv_kin(DX)\r\n # elif self.Current_swing==2:\r\n # self.LR_Inv_kin(DX)\r\n # elif self.Current_swing==3:\r\n # self.RR_Inv_kin(DX)\r\n \r\n \r\n # def Tragectory_controller(self):\r\n # self.Vel_Dir=self.Goal-self.pos\r\n # self.Walk_seq_controller()\r\n # self. Motion_per_leg()\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# # Define the suport functio for plotting the robots pos \r\ndef plot_spot(A,with_box):\r\n \r\n fig = plt.figure()\r\n ax = plt.axes(projection='3d')\r\n body_x=np.array([A.B_L/2, A.B_L/2, -A.B_L/2, -A.B_L/2, A.B_L/2])\r\n body_y=np.array([A.B_W/2, -A.B_W/2, -A.B_W/2, A.B_W/2, A.B_W/2])\r\n body_z=np.array([0,0,0,0,0])\r\n ax.plot3D(body_x, body_y, body_z, 'gray')\r\n #LF\r\n LF_S_x=np.array([A.B_L/2,A.LF_S_pos[0]])\r\n LF_S_y=np.array([A.B_W/2,A.LF_S_pos[1]])\r\n LF_S_z=np.array([0,A.LF_S_pos[2]])\r\n ax.plot3D(LF_S_x, LF_S_y, LF_S_z, 'green')\r\n LF_H_x=np.array([A.LF_S_pos[0],A.LF_K_pos[0]])\r\n LF_H_y=np.array([A.LF_S_pos[1],A.LF_K_pos[1]])\r\n LF_H_z=np.array([A.LF_S_pos[2],A.LF_K_pos[2]])\r\n ax.plot3D(LF_H_x, LF_H_y, LF_H_z, 'red')\r\n LF_F_x=np.array([A.LF_K_pos[0],A.LF_F_pos[0]])\r\n LF_F_y=np.array([A.LF_K_pos[1],A.LF_F_pos[1]])\r\n LF_F_z=np.array([A.LF_K_pos[2],A.LF_F_pos[2]])\r\n ax.plot3D(LF_F_x, LF_F_y, LF_F_z, 'blue')\r\n #RF\r\n RF_S_x=np.array([A.B_L/2,A.RF_S_pos[0]])\r\n RF_S_y=np.array([-A.B_W/2,A.RF_S_pos[1]])\r\n RF_S_z=np.array([0,A.RF_S_pos[2]])\r\n ax.plot3D(RF_S_x, RF_S_y, RF_S_z, 'green')\r\n RF_H_x=np.array([A.RF_S_pos[0],A.RF_K_pos[0]])\r\n RF_H_y=np.array([A.RF_S_pos[1],A.RF_K_pos[1]])\r\n RF_H_z=np.array([A.RF_S_pos[2],A.RF_K_pos[2]])\r\n ax.plot3D(RF_H_x, RF_H_y, RF_H_z, 'red')\r\n RF_F_x=np.array([A.RF_K_pos[0],A.RF_F_pos[0]])\r\n RF_F_y=np.array([A.RF_K_pos[1],A.RF_F_pos[1]])\r\n RF_F_z=np.array([A.RF_K_pos[2],A.RF_F_pos[2]])\r\n ax.plot3D(RF_F_x, RF_F_y, RF_F_z, 'blue')\r\n #LR\r\n LR_S_x=np.array([-A.B_L/2,A.LR_S_pos[0]])\r\n LR_S_y=np.array([A.B_W/2,A.LR_S_pos[1]])\r\n LR_S_z=np.array([0,A.LR_S_pos[2]])\r\n ax.plot3D(LR_S_x, LR_S_y, LR_S_z, 'green')\r\n LR_H_x=np.array([A.LR_S_pos[0],A.LR_K_pos[0]])\r\n LR_H_y=np.array([A.LR_S_pos[1],A.LR_K_pos[1]])\r\n LR_H_z=np.array([A.LR_S_pos[2],A.LR_K_pos[2]])\r\n ax.plot3D(LR_H_x, LR_H_y, LR_H_z, 'red')\r\n LR_F_x=np.array([A.LR_K_pos[0],A.LR_F_pos[0]])\r\n LR_F_y=np.array([A.LR_K_pos[1],A.LR_F_pos[1]])\r\n LR_F_z=np.array([A.LR_K_pos[2],A.LR_F_pos[2]])\r\n ax.plot3D(LR_F_x, LR_F_y, LR_F_z, 'blue')\r\n #RR\r\n RR_S_x=np.array([-A.B_L/2, A.RR_S_pos[0]])\r\n RR_S_y=np.array([-A.B_W/2, A.RR_S_pos[1]])\r\n RR_S_z=np.array([0,A.RR_S_pos[2]])\r\n ax.plot3D(RR_S_x, RR_S_y, RR_S_z, 'green')\r\n RR_H_x=np.array([A.RR_S_pos[0],A.RR_K_pos[0]])\r\n RR_H_y=np.array([A.RR_S_pos[1],A.RR_K_pos[1]])\r\n RR_H_z=np.array([A.RR_S_pos[2],A.RR_K_pos[2]])\r\n ax.plot3D(RR_H_x, RR_H_y, RR_H_z, 'red')\r\n RR_F_x=np.array([A.RR_K_pos[0],A.RR_F_pos[0]])\r\n RR_F_y=np.array([A.RR_K_pos[1],A.RR_F_pos[1]])\r\n RR_F_z=np.array([A.RR_K_pos[2],A.RR_F_pos[2]])\r\n ax.plot3D(RR_F_x, RR_F_y, RR_F_z, 'blue')\r\n if(with_box):#plotting the legs workspace\r\n #LF\r\n for i in range(0,4):\r\n X=np.array([A.Lower_bnd[i,0], A.Lower_bnd[i,0], A.Upper_bnd[i,0], A.Upper_bnd[i,0], A.Lower_bnd[i,0]])\r\n Y=np.array([A.Lower_bnd[i,1], A.Upper_bnd[i,1], A.Upper_bnd[i,1], A.Lower_bnd[i,1], A.Lower_bnd[i,1]])\r\n Z=np.array([A.Lower_bnd[i,2], A.Lower_bnd[i,2], A.Lower_bnd[i,2], A.Lower_bnd[i,2], A.Lower_bnd[i,2]])\r\n ax.plot3D(X, Y, Z, '--c')\r\n Z=np.array([A.Upper_bnd[i,2], A.Upper_bnd[i,2], A.Upper_bnd[i,2], A.Upper_bnd[i,2], A.Upper_bnd[i,2]])\r\n ax.plot3D(X, Y, Z, '--c')\r\n X=np.array([A.Lower_bnd[i,0], A.Lower_bnd[i,0], A.Lower_bnd[i,0], A.Lower_bnd[i,0], A.Lower_bnd[i,0]])\r\n Y=np.array([A.Lower_bnd[i,1], A.Upper_bnd[i,1], A.Upper_bnd[i,1], A.Lower_bnd[i,1], A.Lower_bnd[i,1]])\r\n Z=np.array([A.Lower_bnd[i,2], A.Lower_bnd[i,2], A.Upper_bnd[i,2], A.Upper_bnd[i,2], A.Lower_bnd[i,2]])\r\n ax.plot3D(X, Y, Z, '--c')\r\n X=np.array([A.Upper_bnd[i,0], A.Upper_bnd[i,0], A.Upper_bnd[i,0], A.Upper_bnd[i,0], A.Upper_bnd[i,0]])\r\n ax.plot3D(X, Y, Z, '--c')\r\n \r\n # ax.set_aspect('equal', adjustable='box')\r\n ax.view_init( 45, -90)\r\n\r\n\r\n# Initializing the spot class\r\nA=Spot(0.13,0.105,0.05,0.08,0.222)\r\nD=np.linalg.norm(A.Goal-A.pos)\r\nP=A.F_pos\r\n#while D>A.Walk_D:\r\nplot_spot(A,0)\r\nDX=np.array([A.Walk_D,0.,0.])\r\nA.LF_Inv_kin(-DX/3)\r\nA.RF_Inv_kin(DX/3)\r\nA.LR_Inv_kin(2*DX/3)\r\nplot_spot(A,0)\r\n\r\n# for i in range(0,10):\r\n# A.Tragectory_controller()\r\n# #plot_spot(A,0)\r\n \r\n# #print(A.Goal-A.pos)\r\n# print(A.Current_swing)\r\n \r\n\r\n# plot_spot(A,1)\r\n# DX=np.array([0.1,0.,0.])\r\n# A.LF_Inv_kin(DX)\r\n# plot_spot(A,1)\r\n# A.RF_Inv_kin(DX)\r\n# plot_spot(A,1)\r\n# A.LR_Inv_kin(DX)\r\n# plot_spot(A,1)\r\n# A.RR_Inv_kin(DX)\r\n# plot_spot(A,1)\r\n\r\n","sub_path":"IK/Spot_class.py","file_name":"Spot_class.py","file_ext":"py","file_size_in_byte":24576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"301737405","text":"from django.shortcuts import render\nfrom django.views.decorators.http import require_http_methods\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\nfrom django.http import HttpRequest\n\nfrom .models import Greeting\n\nimport requests\nimport httplib2\nimport sys\n\nfrom apiclient.discovery import build\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\n# Email of the service account\nSERVICE_ACCOUNT_EMAIL = '958723767204-34vg52mou3ihp6sdqpmtu778msi8kg1b@developer.gserviceaccount.com'\n\n# Path to the Service Account's Private Key file\nSERVICE_ACCOUNT_PKCS12_FILE_PATH = 'bases-finance-269c596b456d.p12'\n\ndef createDriveService():\n \"\"\"\n Builds and returns a Drive service object authorized with the given service account.\n\n Returns:\n Drive service object.\n \"\"\"\n f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')\n key = f.read()\n f.close()\n\n credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,\n scope='https://www.googleapis.com/auth/drive')\n http = httplib2.Http()\n http = credentials.authorize(http)\n return build('drive', 'v2', http=http)\n\n# Create your views here.\n@require_http_methods([\"GET\",\"POST\"])\n@csrf_exempt\ndef index(request):\n if request.method == \"GET\":\n r = requests.get('http://httpbin.org/status/418')\n print(r.text)\n return HttpResponse('
    '+r.text+'
    ')\n elif request.method == \"POST\":\n params = request.POST\n GoogleDriveServiceObject = createDriveService()\n return HttpResponse(params['name']+' '+params['email']+' '+params['team']+' '+params['requestType']+' '+params['amountRequested']+' '+params['vendor']+' '+params['explanation'])\n\n\ndef db(request):\n\n greeting = Greeting()\n greeting.save()\n\n greetings = Greeting.objects.all()\n\n return render(request, 'db.html', {'greetings': greetings})\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499679236","text":"import discord\nimport asyncio\nimport importlib\nimport modules.logging\nimport modules.sql_manager\nfrom discord.ext import commands\nimport modules.string_manager\n\nlog = modules.logging\nsql = modules.sql_manager\nstrings = modules.string_manager\n\n\nclass PollingCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.active = True\n\n def unload(self):\n self.active = False\n importlib.reload(strings)\n\n # # # EVENTS # # #\n\n @commands.Cog.listener()\n async def on_raw_message_delete(self, payload):\n await sql.unregister_poll(payload.message_id)\n\n # # # COMMANDS # # #\n\n @commands.command()\n @commands.has_role(\"O5\")\n async def role_enabler(self, ctx, channel_mention, message_text, emoji, role):\n role = discord.utils.get(ctx.guild.roles, name=role)\n if role is None:\n log_text = await strings.get(\"log_role_switcher_no_role\", ctx.guild)\n await ctx.send(log_text.format(role))\n return\n\n def check_reaction(payload):\n nonlocal user\n guild = discord.utils.get(self.bot.guilds, id=payload.guild_id)\n user = discord.utils.get(guild.members, id=payload.user_id)\n return payload.message_id == message.id and \\\n str(payload.emoji) == emoji and \\\n not user.bot\n \n channel_id = int(channel_mention[2:-1])\n channel = discord.utils.get(ctx.guild.channels, id=channel_id)\n message = await channel.send(message_text)\n await message.add_reaction(emoji)\n await sql.register_poll(message.id)\n\n user = None\n while await sql.is_active(message.id):\n try:\n payload = await self.bot.wait_for(\"raw_reaction_add\", timeout=60, check=check_reaction)\n message = await channel.fetch_message(payload.message_id)\n reaction = discord.utils.get(message.reactions, me=True)\n await reaction.remove(user)\n if role in user.roles:\n await log.remove_and_log(user, role)\n else:\n await log.give_and_log(user, role)\n\n except asyncio.TimeoutError:\n pass\n\n log_text = await strings.get(\"log_switcher_finish\", ctx.guild)\n await log.log(log.LogType.EVENT, log_text.format(message.id))\n\n @commands.command(aliases=[\"poll\", \"newpoll\", \"new_poll\", \"new-poll\"])\n @commands.has_role(\"O5\")\n async def make_poll(self, ctx, channel_mention, text, answer_mode, timeout, *emojis):\n if answer_mode not in (\"single\", \"multiple\"):\n return\n\n channel_id = int(channel_mention[2:-1])\n channel = discord.utils.get(ctx.guild.channels, id=channel_id)\n message = await channel.send(text)\n for reaction in emojis:\n await message.add_reaction(reaction)\n await sql.register_poll(message.id)\n\n def check_message(payload):\n nonlocal message\n if payload.message_id == message.id:\n guild = discord.utils.get(self.bot.guilds, id=payload.guild_id)\n member = discord.utils.get(guild.members, id=payload.user_id)\n return not member.bot\n else:\n return False\n\n update_every = 60\n timer = int(timeout)*3600\n while timer > 0 and await sql.is_active(message.id):\n try:\n payload = await self.bot.wait_for(\"raw_reaction_add\", timeout=update_every, check=check_message)\n message = await channel.fetch_message(payload.message_id)\n\n if answer_mode == \"single\":\n reaction = payload.emoji\n user = discord.utils.get(\n discord.utils.get(self.bot.guilds, id=payload.guild_id).members,\n id=payload.user_id)\n for r in message.reactions:\n print(str(r))\n if str(reaction) == str(r):\n continue\n\n users = await r.users().flatten()\n user_ids = [u.id for u in users]\n if user.id in user_ids:\n await r.remove(user)\n\n except asyncio.TimeoutError:\n timer -= update_every\n\n if not await sql.is_active(message.id):\n log_text = await strings.get(\"log_poll_finish\", ctx.guild)\n await log.log(log.LogType.EVENT, log_text.format(message.id))\n else:\n message = await message.channel.fetch_message(message.id)\n\n reactions = message.reactions\n votes = []\n total_votes = 0\n for r in reactions:\n print(str(r), r.count)\n votes.append(r.count-1)\n total_votes += r.count-1\n total_votes = 1 if total_votes == 0 else total_votes # Se no fa 0/0\n\n max_bars = 16\n result_text = text + await strings.get(\"poll_results_top\", ctx.guild)\n row = await strings.get(\"poll_results_row\", ctx.guild)\n for i in range(len(votes)):\n percentage = votes[i]*100 / total_votes\n full_bars = int(percentage/(100/max_bars))\n result_text += row.format(reactions[i], \"█\"*full_bars, \"░\"*(max_bars-full_bars), percentage)\n\n await message.clear_reactions()\n await message.edit(content=result_text)\n\n log_text = await strings.get(\"log_poll_timeout\", ctx.guild)\n await log.log(log.LogType.EVENT, log_text.format(message.id))\n\n\ndef setup(bot):\n bot.add_cog(PollingCog(bot))\n","sub_path":"cogs/polls.py","file_name":"polls.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"543104480","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom setuptools import find_packages, setup\n\n\ndef read(f):\n return open(f, 'r', encoding='utf-8').read()\n\n\ndef _extract_dependencies(filename):\n pkgs, deps = [], []\n with open(filename) as f:\n for line in f.readlines():\n if '://' in line:\n deps.append(line)\n else:\n pkgs.append(line)\n return pkgs, deps\n\n\ndef parse_requirements():\n install_packages, install_deps = _extract_dependencies('./requirements.txt')\n dev_packages, dev_deps = _extract_dependencies('./requirements-dev.txt')\n\n return (\n install_packages,\n dev_packages,\n install_deps + dev_deps,\n )\n\n\ninstall, dev_install, dependencies = parse_requirements()\n\nsetup(\n name='django-core-api',\n version='0.1.0a1',\n license='BSD',\n description='Django Core RESTFul API',\n long_description=read('README.md'),\n long_description_content_type='text/markdown',\n author='Joao Daher',\n author_email='joao@daher.dev',\n packages=find_packages(exclude=['test_*']),\n include_package_data=True,\n install_requires=install,\n tests_require=dev_install,\n dependency_links=dependencies,\n python_requires=\">=3.7\",\n zip_safe=False,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Framework :: Django :: 3.0',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Internet :: WWW/HTTP',\n ]\n)\n","sub_path":"pypi_install_script/django-core-api-0.1.0a1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569684160","text":"#/bin/python3\n\nimport sys\n\na0, a1, a2 = input().strip().split(' ')\na0,a1,a2 = [int(a0),int(a1),int(a2)]\nb0, b1, b2 = input().strip().split(' ')\nb0,b1,b2 = [int(b0),int(b1),int(b2)]\n\naliceScore = 0\nbobScore = 0\n\ndef compareScores(x, y):\n\tif a0 > b0:\n\t\taliceScore = aliceScore + 1\n\t\treturn aliceScore\n\telif a0 < b0:\n\t\tbobScore = bobScore + 1\n\t\treturn bobScore\n\ncompareScores(aliceScore, bobScore)\n\nprint(aliceScore)\nprint(bobScore)","sub_path":"Hackerrank/Compare_The_Triplets.py","file_name":"Compare_The_Triplets.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"643323961","text":"# Laboratory Assignment completed for SYSC 1005 A Fall 2016\r\n# Revised: November 8, 2016.\r\n\r\nimport sys # get_image calls exit\r\nfrom Cimpl import *\r\nfrom filters import *\r\n\r\ndef menu_commands():\r\n \"\"\"\r\n Use menu comands to load image or quit the program\r\n \"\"\"\r\n loaded = False\r\n while True:\r\n print (\"L)oad image \\nN)egative G)rayscale X)treme Contrast S)epia Tint E)dge Detect\\nQ)uit\")\r\n \r\n answer = input(\":\")\r\n \r\n if answer == \"L\":\r\n img = get_image()\r\n loaded = True\r\n show(img)\r\n \r\n \r\n if loaded == False:\r\n print (\"No Image Loaded\")\r\n \r\n \r\n elif answer == \"N\":\r\n negative_image(img)\r\n show(img)\r\n \r\n elif answer == \"G\":\r\n grayscale(img)\r\n show(img)\r\n \r\n elif answer == \"X\":\r\n extreme_contrast(img)\r\n show(img)\r\n \r\n elif answer == \"S\":\r\n sepia_tint(img)\r\n show(img)\r\n \r\n elif answer == \"E\":\r\n threshold = float(input(\"Threshold?:\"))\r\n detect_edges_better(img, threshold)\r\n show(img)\r\n \r\n elif answer == \"Q\":\r\n print (\"Exit\")\r\n \r\n if answer not in [\"L\", \"Q\", \"N\", \"G\", \"X\", \"S\", \"E\"]:\r\n print (\"No Such Command\")\r\n \r\n\r\ndef get_image():\r\n \"\"\"\r\n Interactively select an image file and return a Cimpl Image object\r\n containing the image loaded from the file.\r\n \"\"\"\r\n\r\n # Pop up a dialogue box to select a file\r\n file = choose_file()\r\n\r\n # Exit the program if the Cancel button is clicked.\r\n if file == \"\":\r\n sys.exit(\"File Open cancelled, exiting program\")\r\n\r\n # Open the file containing the image and load it\r\n img = load_image(file)\r\n\r\n return img\r\n\r\n# A bit of code to demonstrate how to use get_image().\r\n\r\nif __name__ == \"__main__\":\r\n menu_commands()\r\n img = get_image()\r\n show(img)\r\n \r\n \r\n\r\n\r\n \r\n \r\n","sub_path":"photo_editor.py","file_name":"photo_editor.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"92617043","text":"from _datetime import date, timedelta\nfrom django.db.models import Sum, F\nfrom business.models import Product, Sale, Expense, Inventory\nfrom .models import *\n\n\n\ndef sales_graph_data(*args, **kwargs):\n\tbusiness = kwargs.get('business')\n\t# Date list\n\tbase = date.today()\n\tdate_list = [base - timedelta(days=x) for x in range(7)]\n\tdate_list.reverse()\n\t\n\t# Data\n\tsales = []\n\tfor d in date_list:\n\t\tbusiness_dic = {'date':d.strftime('%d-%m-%Y')}\t\t\t\n\t\tfor b in business:\n\t\t\tsale = Sale.objects.filter(branch__business=b, created_at__date=d, status='Completed').aggregate(total_sales=Sum('amount_paid'))['total_sales']\n\t\t\tbusiness_dic.update({b.name:sale if sale != None else 0})\n\n\t\tsales.append(business_dic)\n\treturn sales\n\n\n\ndef expense_graph_data(*args, **kwargs):\n\tbusiness = kwargs.get('business')\n\n\t# Date Range\t\n\tdt = date.today() - timedelta(days=30)\n\t\n\t# Data\n\texpenses = []\n\tfor b in business:\n\t\texpense = Expense.objects.filter(created_at__date__gte=dt, created_at__date__lte=date.today(), business=b).aggregate(Sum('cost'))['cost__sum'] \t\t\t\n\t\tbusiness_dic = {'business':b.name, 'value':expense if expense != None else 0}\n\n\t\texpenses.append(business_dic)\n\n\treturn expenses\n\n\n\ndef stock_graph_data(*args, **kwargs):\n\tbusiness = kwargs.get('business')\t\n\t# Data\n\tstock = []\n\tfor b in business:\n\t\tinventory_qs = Inventory.objects.filter(business=b, exist=True).annotate(available=F('remain')-F('damage'))\n\t\tinventory = inventory_qs.aggregate(Sum('available'))['available__sum']\n\n\t\tbusiness_dic = {'business':b.name, 'value':inventory if inventory != None else 0}\n\n\t\tstock.append(business_dic)\n\treturn stock\n","sub_path":"administration/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"461519782","text":"import os\nimport requests\nfrom lxml import html\n\nfrom flask import request\nfrom flask import Flask\nfrom flask import Response\n\n\napp = Flask(__name__)\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36\"\n}\n\n@app.route('/', defaults={'path': 'google.com'})\n@app.route('/')\ndef root(path): \n url = 'https://' + path\n print('URL:', url)\n r = requests.get(url, verify=False, headers=headers)\n r.raise_for_status()\n rr = Response(response=r.content, status=r.status_code)\n rr.headers[\"Content-Type\"] = r.headers['Content-Type']\n return rr\n\n@app.route('/g/')\ndef gkeyword(keyword): \n url = 'https://www.google.com/search'\n payload = {'q':keyword, 'num':1, 'start':1, 'sourceid':'chrome', 'ie':'UTF-8', 'cr':'cr=countryUS'}\n r = requests.get(url, params=payload)\n rr = Response(response=r.content, status=r.status_code)\n rr.headers[\"Content-Type\"] = r.headers['Content-Type']\n return rr\n\n@app.route('/r//subscribers')\ndef gsubreddit(subreddit):\n url = 'https://old.reddit.com/r/' + subreddit\n xpath =\"//span[@class='subscribers']/span[@class='number']/text()\"\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n r = requests.get(url, headers=headers)\n tree = html.fromstring(r.content)\n subscribers = tree.xpath(xpath)\n rr = Response(response=subscribers, status=r.status_code)\n rr.headers[\"Content-Type\"] = r.headers['Content-Type']\n return rr\n\nif __name__ == '__main__':\n # Bind to PORT if defined, otherwise default to 5000.\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612258107","text":"# -*- coding: utf-8 -*-\n\"\"\"\nesparto\n=======\n\nSimple HTML and PDF document generator for Python.\n\nesparto represents documents as a tree structure consisting of Layout\nelements at the top and middle levels and Content elements in the leaves.\nThese objects are arranged in a fixed hierarchy, so esparto always knows\nhow to deal with new content if it hasn't been explicitly wrapped, or how\nto fix the structure if it doesn't adhere to the nesting requirements.\nIt helps to understand this hierarchy when using the API so that we know what\nto expect when adding content that required implicit wrapping and formatting.\n\nA document is created by first defining a Page object - this is the primary\ninterface for the library and all tasks should be achievable through methods\nattached to the page.\nManipulating a page is similar to working with a Python dictionary:\nsquare brackets are used for getting and setting items, while titles act as\nkeys and layout objects and content act as values.\n\n\nBasic Usage\n-----------\n\nimport esparto as es\n\n# Instantiating a Page\npage = es.Page(title=\"Research\")\n\n# Page layout hierarchy:\n# Page -> Section -> Row -> Column -> Content\n\n# Add or update content\n# Keys are used as titles\npage[\"Introduction\"][\"Part One\"][\"Item A\"] = \"./text/content.md\"\npage[\"Introduction\"][\"Part One\"][\"Item B\"] = \"./pictures/image1.jpg\"\n\n# Add content without a title\npage[\"Introduction\"][\"Part One\"][\"\"] = \"Hello, Wolrd!\"\n\n# Replace child at index - useful if no title given\npage[\"Introduction\"][\"Part One\"][-1] = \"Hello, World!\"\n\n# Set content and return input object\n# Useful in Jupyter Notebook as it will be displayed in cell output\npage[\"Methodology\"][\"Part One\"][\"Item A\"] << \"dolor sit amet\"\n# >>> \"dolor sit amet\"\n\n# Set content and return new layout\npage[\"Methodology\"][\"Part Two\"][\"Item B\"] >> \"foobar\"\n# >>> {'Item B': ['Markdown']}\n\n# Show document structure\npage.tree()\n# >>> {'Research': [{'Introduction': [{'Part One': [{'Item A': ['Markdown']},\n# {'Item B': ['Image']}]}]},\n# {'Methodology': [{'Part One': [{'Item A': ['Markdown']}]},\n# {'Part Two': [{'Item A': ['Markdown']}]}]}]}\n\n# Remove content\ndel page[\"Methodology\"][\"Part One\"][\"Item A\"]\ndel page.methodology.part_two.item_b\n\n# Access existing content as an attribute\npage.introduction.part_one.item_a = \"./pictures/image2.jpg\"\npage.introduction.part_one.tree()\n# >>> {'Part One': [{'Item A': ['Image']},\n# {'Item B': ['Image']},\n# {'Column 2': ['Markdown']}]}\n\n# Save the document\npage.save_html(\"my-page.html\")\npage.save_pdf(\"my-page.pdf\")\n\nDocumentation\n-------------\n\nPlease visit https://domvwt.github.io/esparto/ for documentation and examples.\n\n\"\"\"\n\nfrom importlib.util import find_spec as _find_spec\nfrom pathlib import Path as _Path\nfrom typing import Set as _Set\n\n__author__ = \"\"\"Dominic Thorn\"\"\"\n__email__ = \"dominic.thorn@gmail.com\"\n__version__ = \"1.3.0\"\n\n_MODULE_PATH: _Path = _Path(__file__).parent.absolute()\n\n\n_OPTIONAL_DEPENDENCIES: _Set[str] = {\n \"bs4\",\n \"IPython\",\n \"matplotlib\",\n \"pandas\",\n \"bokeh\",\n \"plotly\",\n \"weasyprint\",\n}\n\n_INSTALLED_MODULES: _Set[str] = {\n x.name for x in [_find_spec(dep) for dep in _OPTIONAL_DEPENDENCIES] if x\n}\n\nfrom esparto._content import (\n DataFramePd,\n FigureBokeh,\n FigureMpl,\n FigurePlotly,\n Image,\n Markdown,\n RawHTML,\n)\nfrom esparto._layout import Card, Column, Page, PageBreak, Row, Section, Spacer\nfrom esparto._options import options\n","sub_path":"esparto/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617129772","text":"from flask_restplus import fields\nfrom gifserver.api.restplus import api\n\npagination = api.model('A page of results', {\n 'page': fields.Integer(description='Number of this page of results'),\n 'pages': fields.Integer(description='Total number of pages of results'),\n 'per_page': fields.Integer(description='Number of items per page of results'),\n 'total': fields.Integer(description='Total number of results'),\n})\n\ntag = api.model('Tag', {\n 'name' : fields.String(required=True, description='Tag value'),\n})\n\ntags = api.model('Tags', {\n 'values' : fields.List(fields.Nested(tag))\n})\n\ngif = api.model('Gif', {\n 'id': fields.Integer(readOnly=True, description='The unique identifier of a gif'),\n 'name': fields.String(required=True, description='Filename of the gif'),\n 'upload_date': fields.DateTime,\n 'tags': fields.List(fields.Nested(tag)),\n})\n\npage_of_gifs = api.inherit('Page of gifs', pagination, {\n 'items': fields.List(fields.Nested(gif))\n})\n\npage_of_tags = api.inherit('Page of tags', pagination, {\n 'items': fields.List(fields.Nested(tag))\n})","sub_path":"gifserver/api/gif/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"566319391","text":"def hm_to_m(t):\n\th, m = map(int, t.split(':'))\n\treturn h * 60 + m\n\n\ndef m_to_hm(t):\n\th, m = divmod(t, 60)\n\treturn ':'.join([str(h).zfill(2), str(m).zfill(2)])\n\n\ndef fit_sequence(lst, dur):\n\tc = 0\n\tstart_time = 0\n\tfor i in range(1, len(lst)):\n\t\tif c >= dur-1:\n\t\t\tend_time = lst[i-1]\n\t\t\treturn [m_to_hm(start_time), m_to_hm(end_time)]\n\t\tif lst[i-1] + 1 == lst[i]:\n\t\t\tif start_time == 0:\n\t\t\t\tstart_time = lst[i-1]\n\t\t\tc += 1\n\t\telse:\n\t\t\tstart_time = 0\n\t\t\tc = 0\n\treturn [None, None]\n\n\ndef get_start_time(schedules, duration):\n\twork_time = ['09:00', '19:00']\n\tbusy_time = set()\n\tfor i in range(hm_to_m(work_time[0]), hm_to_m(work_time[1])+1):\n\n\t\tfor person in schedules:\n\t\t\tfor event in person:\n\t\t\t\tif i in range(hm_to_m(event[0]), hm_to_m(event[1])):\n\t\t\t\t\tbusy_time.add(i)\n\n\tfree_time = [i for i in range(hm_to_m(work_time[0]), hm_to_m(work_time[1])+1) if i not in busy_time]\n\treturn fit_sequence(sorted(list(free_time)), duration)[0]\n\n\n\nschedules = [\n [['09:00', '11:30'], ['13:30', '16:00'], ['16:00', '17:30'], ['17:45', '19:00']],\n [['09:15', '12:00'], ['14:00', '16:30'], ['17:00', '17:30']],\n [['11:30', '12:15'], ['15:00', '16:30'], ['17:45', '19:00']]\n]\nprint(get_start_time(schedules, 60), '12:15')\nprint(get_start_time(schedules, 90), None)\nprint(get_start_time(schedules, 75), '12:15')\n\n","sub_path":"3kyu_FindingAnAppointment.py","file_name":"3kyu_FindingAnAppointment.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"571459742","text":"'''\nnice problem add 1 to array , simple reccursive function can solve the problem\n'''\ndef sum(arr, n):\n i = n\n\n # if array element is less than\n # 9, then simply add 1 to this.\n if (arr[i] < 9):\n arr[i] = arr[i] + 1\n return\n\n # if array element is greater\n # than 9, replace it with 0\n # and decrement i\n arr[i] = 0\n i -= 1\n\n # recursive function\n sum(arr, i)\n\n\n# def addArray(arr):\n# if arr[-1] != 9:\n# arr[-1] += 1\n# else:\n# print ('in else')\n# count = 0\n# for i in range(-1,-1 * len(arr),-1):\n# print(i)\n# if arr[i] == 9:\n# arr[i] = 0\n# count += 1\n# else:\n# arr[i] += 1\n# break\n#\n# if count == len(arr):\n# arr = [1] + [0]*count\n# print(arr)\n#\n# arr = [9,9,9,9]\n# addArray(arr)\n\n\n\n\n\n","sub_path":"problems/add_1_to_Array.py","file_name":"add_1_to_Array.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"1276587","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import Warning\nclass hr_analytic_timesheet(models.Model):\n _inherit =\"hr.analytic.timesheet\"\n \n @api.one \n @api.depends('overtime_type','hourly_rate','unit_amount')\n def od_get_amount(self):\n hourly_rate = self.hourly_rate\n duration = self.unit_amount\n total = hourly_rate * duration\n self.normal_amount = total\n overtime_type = self.overtime_type\n overtime_amount = 0.0\n if overtime_type:\n if overtime_type.amount_select == 'percentage':\n amount_percentage = overtime_type.amount_percentage\n overtime_amount = total * (amount_percentage/100)\n self.overtime_amount = overtime_amount\n elif overtime_type.amount_select == 'fix':\n fix_amount = overtime_type.amount_fix\n overtime_amount = fix_amount * duration\n self.overtime_amount = overtime_amount\n amount = total + overtime_amount\n# self.amount = amount\n \n \n @api.onchange('hourly_rate','overtime_type')\n def onchange_hourly_rate(self):\n overtime_amount = self.overtime_amount\n normal_amount = self.normal_amount\n amount =normal_amount + overtime_amount\n self.amount = amount\n \n \n \n od_unit_cost = fields.Float(string=\"Nominal Value\",related=\"product_id.standard_price\")\n hourly_rate = fields.Float(string=\"Hourly Rate\")\n overtime_type = fields.Many2one('hr.salary.rule',string=\"Overtime Type\")\n overtime_percentage = fields.Float(string=\"Overtime Percentage\",related='overtime_type.amount_percentage',store=True)\n overtime_amount = fields.Float(string=\"Overtime Amount\",compute=\"od_get_amount\",store=True)\n normal_amount = fields.Float(string=\"Normal Amount\",compute=\"od_get_amount\",store=True)\n \n narration = fields.Char(string=\"Narration\")\n cancelled_by_owner = fields.Boolean(string=\"Cancelled By Owner\")\n cancelled_by_id = fields.Many2one('res.users',string=\"Cancelled By\")\n \n \n @api.model\n def create(self,vals):\n account_id = vals.get('account_id',False)\n if account_id:\n analytic_pool = self.env['account.analytic.account']\n analytic_obj = analytic_pool.browse(account_id)\n state = analytic_obj.state\n if state in ('cancelled','close'):\n raise Warning(\"This Analytic Account/Project Either Closed or Cancelled,You Cant Create Timesheet Further\")\n return super(hr_analytic_timesheet,self).create(vals)\n","sub_path":"orchid_beta_project/timesheet/analytic_timesheet.py","file_name":"analytic_timesheet.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292426960","text":"import time\nimport datetime\n\nfrom mist.api import config\n\nfrom mist.api.exceptions import BadRequestError\n\nfrom mist.api.users.models import Metric\nfrom mist.api.rules.models import Rule\nfrom mist.api.rules.models.main import NoDataRule\n\nfrom mist.api.logs.methods import log_event\n\nfrom mist.api.clouds.models import Cloud\nfrom mist.api.machines.models import Machine\n\n\n# TODO Deprecate.\ndef _alert_pretty_details(owner, rule_id, value, triggered, timestamp,\n cloud_id='', machine_id='', action=''):\n # Always pass (cloud_id, machine_id) explicitly instead of getting them\n # from the `Rule` instance, as before, since instances of `NoDataRule`\n # will most likely return multiple resources, which is not supported by\n # the current implementation.\n assert cloud_id and machine_id\n rule = Rule.objects.get(owner_id=owner.id, title=rule_id)\n\n cloud = Cloud.objects.get(owner=owner, id=cloud_id, deleted=None)\n machine = Machine.objects.get(cloud=cloud, machine_id=machine_id)\n\n if machine.monitoring.method.endswith('graphite'):\n metrics = config.GRAPHITE_BUILTIN_METRICS\n if machine.monitoring.method.endswith('influxdb'):\n metrics = config.INFLUXDB_BUILTIN_METRICS\n\n if isinstance(rule, NoDataRule):\n # no data alert\n condition = \"Monitoring data unavailable\"\n label = \"Monitoring data\"\n fval = \"unavailable\"\n else:\n # regular alert\n if not action:\n action = rule.action\n if rule.metric in metrics:\n mdict = metrics[rule.metric]\n metric = Metric(metric_id=rule.metric, name=mdict['name'],\n unit=mdict['unit'])\n else:\n try:\n metric = Metric.objects.get(owner=owner, metric_id=rule.metric)\n except Metric.DoesNotExist:\n raise BadRequestError(\n \"Metric '%s' is not a builtin rule metric, \"\n \"nor defined in .metrics.\" % rule.metric\n )\n label = metric.name or rule.metric.replace(\".\", \" \")\n if rule.operator == 'lt':\n operator = '<'\n elif rule.operator == 'gt':\n operator = '>'\n else:\n operator = rule.operator\n fthresh = metric.format_value(rule.value)\n condition = '%s %s %s' % (label, operator, fthresh)\n if rule.aggregate in ('any', 'avg'):\n condition += ' for %s value' % rule.aggregate\n if rule.reminder_offset:\n period = int(1 + rule.reminder_offset / 60)\n condition += ' within %s mins' % period\n fval = metric.format_value(value)\n\n state = \"WARNING\" if triggered else \"OK\"\n # calculate nice host label\n ips = \", \".join(machine.public_ips) if machine.public_ips else \", \".join(\n machine.private_ips)\n hostname = machine.hostname if (\n machine.hostname and machine.hostname != 'n/a') else ''\n if not hostname:\n host = ips\n else:\n host = \"%s (%s)\" % (hostname, ips)\n\n # calculate current time in human readable format\n local_time = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S')\n local_time = \"%s PDT (UTC-7)\" % local_time\n\n # calculate time ago in human readable format\n secs = abs(int(time.time() - timestamp))\n mins, secs = divmod(secs, 60)\n hours, mins = divmod(mins, 60)\n time_ago = \"\"\n if hours:\n time_ago += \"%dh\" % hours\n if mins:\n time_ago += \"%dm\" % mins\n if secs:\n time_ago += \"%ds\" % secs\n if time_ago:\n time_ago += \" ago\"\n else:\n time_ago = \"just now\"\n return {\n 'rule_id': rule.id,\n 'rule_title': rule.title,\n 'cloud_id': cloud_id,\n 'machine_id': machine_id,\n 'name': machine.name,\n 'host': host, # dns name or ip\n 'condition': condition, # all of load greater than 5 for 2 mins\n 'state': state, # WARNING or OK\n 'action': action, # reboot\n 'time': local_time, # time\n 'metric_name': label, # cpu or my_metric or Mon Data\n 'curr_value': fval, # current metric value\n 'since': time_ago, # relative time of trigger\n 'machine_link': '%s/machines/%s' % (config.CORE_URI, machine.id),\n 'uri': config.CORE_URI,\n }\n\n\n# TODO Deprecate.\ndef _log_alert(owner, rule_id, value, triggered, timestamp, incident_id,\n cloud_id='', machine_id='', action='', **kwargs):\n info = _alert_pretty_details(\n owner, rule_id, value, triggered, timestamp,\n cloud_id, machine_id, action\n )\n event_kwargs = {\n 'owner_id': owner.id,\n 'event_type': 'incident',\n 'action': 'rule_triggered' if triggered else 'rule_untriggered',\n 'cloud_id': info['cloud_id'],\n 'machine_id': info['machine_id'],\n 'condition': info['condition'],\n 'state': info['state'],\n 'value': info['curr_value'],\n 'machine_name': info['name'],\n 'host': info['host'],\n 'rule_action': info['action'],\n 'incident_id': incident_id,\n 'rule_id': info['rule_id'],\n 'rule_title': info['rule_title'],\n }\n event_kwargs.update(kwargs)\n log_event(**event_kwargs)\n","sub_path":"src/mist/api/notifications/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"150530489","text":"from entities import read_player_file\nimport math\nimport random\n\n\nclass Repo:\n def __init__(self):\n self.file_name = 'players.txt'\n self.players = read_player_file(self.file_name)\n\n def list(self):\n return self.players\n\n def play_round(self, player1, player2):\n if player1.strength > player2.strength:\n return 1\n else:\n return 2\n\n def generate_pairs(self, max):\n \"\"\"\n Randomly generates player pairs for the next round\n :param max: amount of players that needs to be sorted\n :return: randomixed list\n \"\"\"\n list = []\n for i in range(max):\n list.append(i)\n\n new_list = []\n for i in range(max - 1):\n player = random.randint(1, len(list) - 1)\n new_list.append(list[player])\n list.remove(list[player])\n new_list.append(list[0])\n\n return new_list\n\n def sort(self):\n self.players.sort(key=lambda player: player.strength, reverse=True)\n\n def play_qualifying_round(self):\n player_list = self.players\n temp_count = len(player_list)\n while not int(math.sqrt(temp_count) + 0.5) ** 2 == temp_count:\n temp_count -= 1\n\n random_list = self.generate_pairs(2 * (len(player_list) - temp_count))\n offset = len(player_list)-temp_count\n\n new_list = []\n for i in range(0, len(random_list), 2):\n if self.play_round(player_list[random_list[i]+offset], player_list[random_list[i+1]+offset]) == 1:\n player_list[random_list[i]+offset].inc_str()\n new_list.append(player_list[random_list[i]+offset])\n else:\n player_list[random_list[i+1]+offset].inc_str()\n new_list.append(player_list[random_list[i+1]+offset])\n\n self.players = player_list[:offset+1] + new_list\n\n def play_tourney(self):\n player_list = self.players\n print(len(self.players))\n\n index = len(self.players)\n past_list = player_list\n while index != 1:\n random_list = self.generate_pairs(len(past_list))\n new_list = []\n for i in range(0, len(random_list), 2):\n if self.play_round(player_list[random_list[i]], player_list[random_list[i+1]]) == 1:\n player_list[random_list[i]].inc_str()\n new_list.append(player_list[random_list[i]])\n else:\n player_list[random_list[i+1]].inc_str()\n new_list.append(player_list[random_list[i+1]])\n print('Round '+ math.sqrt(len(self.players)) +' : \\n'+ new_list + '\\n')\n pest_list = new_list\n index /= 2\n","sub_path":"t2-916-Popa-Andrei-Calin/repo.py","file_name":"repo.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136848269","text":"import numpy as np\nimport pandas as pd\nimport nibabel\nimport os\nfrom skimage.metrics import structural_similarity as ssim\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom paths import *\nimport shutil\nimport imageio\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.models import Sequential\n\n# import\nfrom get_data import extract, get_nii\nfrom general import make_dir, get_data, store_data, remove_dir, upzip_gz, show_data, list_directory, update_progress, make_archive, get_assigned\nfrom paths import *\n\nprint(\"loading model\")\nmodel = VGG16(weights=\"imagenet\", include_top=True)\n# eliminating the last layer of VGG16- 4096 features\ncust_model = Sequential()\nfor layer in model.layers[:-1]: # excluding last layer\n cust_model.add(layer)\n\ndf = pd.DataFrame(columns=['subject_id', 'type', 'mse', 'ssim', 'distance'])\n\nMEAN_SSIM = 0\nMEAN_MSE = 0\nMEAN_DIST = 0\n\n\ndef nii_dimension(file):\n data = np.asarray(nibabel.load(file).dataobj).T\n row = data.shape[1]\n col = data.shape[2]\n return [row, col]\n\n\ndef convert_img(nii_file, output_folder):\n os.system(\"med2image -i \" + nii_file + \" -o \" + output_folder)\n\n\ndef img_dimension(image):\n im = Image.open(image)\n print(im.size)\n\n\ndef mse(img1, img2):\n err = np.sum((img1.astype(\"float\") - img2.astype(\"float\")) ** 2)\n err /= float(img1.shape[0] * img1.shape[1])\n return err\n\n\ndef compare_images(img1, img2):\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n _mse = mse(img1, img2)\n _ssim = ssim(img1, img2)\n return [_mse, _ssim]\n\n\ndef extract_images(output_folder):\n files = os.listdir(output_folder)\n length = len(files)\n mid_img = files[length/2]\n upper_img = files[:(length/2)][length/4]\n lower_img = files[(length/2):][length/4]\n return [upper_img, mid_img, lower_img]\n\n\ndef get_image_features(image_file_name):\n image = load_img(image_file_name, target_size=(224, 224))\n image = img_to_array(image)\n image = np.expand_dims(image, axis=0)\n image = preprocess_input(image)\n features = cust_model.predict(image)\n return features\n\n\ndef adjust_gamma(image, gamma=0.15):\n gamma = 0.15\n invGamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** invGamma) * 255\n for i in np.arange(0, 256)]).astype(\"uint8\")\n image = cv2.LUT(image, table).astype(np.uint8)\n return image\n\n\ndef nii_jpg(inputfile, outputfile, type):\n print(\"Saving slice\")\n print(inputfile, outputfile, type)\n image_array = nibabel.load(inputfile).get_fdata()\n total_slices = image_array.shape[2]\n mid_slice = total_slices//2\n data = image_array[:, :, mid_slice]\n image_name = f\"{type}.jpg\"\n imageio.imwrite(image_name, data)\n if(type == 'mri'):\n img = cv2.imread(image_name, 0)\n img = adjust_gamma(img)\n cv2.imwrite(image_name, img)\n src = image_name\n try:\n os.remove(outputfile+\"/\"+image_name)\n except:\n pass\n shutil.move(src, outputfile)\n print(\"Slice Saved\")\n\n\ndef dimension_check(path, type):\n # print(\"\\nDIMENSION CHECK\\n\")\n dim = nii_dimension(path)\n if(dim[1] >= 192 and dim[1] <= 256):\n return True\n return False\n\n\ndef structural_similarity(path, type):\n # print(\"\\nSTRUCTURAL SIMILARITY\\n\")\n if type == \"mri\":\n slice_path = MRI_SLICE\n else:\n slice_path = PET_SLICE\n nii_jpg(path, SSIM, type)\n # total_mse = 0\n # total_ssim = 0\n # count = 0\n # for file in os.listdir(slice_path):\n # count += 1\n # path = os.path.join(slice_path, file)\n # img1 = cv2.imread(path)\n # img1 = cv2.resize(img1, (256, 256), interpolation=cv2.INTER_NEAREST)\n # img2 = cv2.imread(f\"{SSIM}/{type}.jpg\")\n # img2 = cv2.resize(img2, (256, 256), interpolation=cv2.INTER_NEAREST)\n # mse, ssim = compare_images(img1, img2)\n # total_mse += mse\n # total_ssim += ssim\n # mean_mse = total_mse//count\n # mean_ssim = total_ssim//(count/100)\n # global MEAN_MSE, MEAN_SSIM\n # MEAN_MSE = mean_mse\n # MEAN_SSIM = mean_ssim\n return True\n\n\ndef feature_selection(path, type):\n # print(\"\\nFEATURE SELECTION\\n\")\n threshold_mri = 55\n threshold_pet = 45\n if type == \"mri\":\n slice_path = MRI_SLICE\n else:\n slice_path = PET_SLICE\n print(slice_path)\n test_image = get_image_features(path)\n total_distance = 0\n count = 0\n for file in os.listdir(slice_path):\n count += 1\n path = os.path.join(slice_path, file)\n base_image = get_image_features(path)\n dist = np.linalg.norm(base_image-test_image)\n total_distance += dist\n mean_distance = total_distance//count\n global MEAN_DIST\n MEAN_DIST = mean_distance\n if type == \"mri\":\n if (mean_distance < threshold_mri ) : return True\n else:\n if (mean_distance < threshold_pet ) : return True\n return False\n\n\ndef get_folder_name(path):\n return path.split(\"/\")[-2]\n\n\ndef postprocess_file(subject_id, path, type, Dimension_Check=True, Feature_Selection=True, Structural_Similarity=True):\n print(\n f\"\\n------------------- {type.upper()} POSTPROCESS STARTED--------------------\\n\")\n if(Dimension_Check):\n if(not dimension_check(path, type)):\n return False\n if(Structural_Similarity):\n if(not structural_similarity(path, type)):\n return False\n if(Feature_Selection):\n if(not feature_selection(f\"{SSIM}/{type}.jpg\", type)):\n return False\n\n global MEAN_MSE, MEAN_SSIM, MEAN_DIST\n print(\n f'\\nsubject_id : {subject_id} mse: {MEAN_MSE} ssim : {MEAN_SSIM} distance : {MEAN_DIST}\\n')\n global df\n df = df.append({'subject_id': subject_id, 'type': type, 'mse': MEAN_MSE, 'ssim': MEAN_SSIM,\n 'distance': MEAN_DIST}, ignore_index=True)\n\n print(\n f\"\\n------------------- {type.upper()} POSTPROCESS COMPELETED--------------------\\n\")\n\n return True\n\n\ndef postprocess(key, src_name, sub_scan):\n scan = sub_scan[key]\n mri_path = scan['mri.nii']\n pet_path = scan['pet.nii']\n\n make_dir(POSTPROCESS_TEMP_PATHS)\n\n show_data(\"path\", [key, mri_path, pet_path])\n\n # Pipeline Configuration\n Dimension_Check = True\n Feature_Selection = True\n Structural_Similarity = True\n\n if(not postprocess_file(key, mri_path, \"mri\", Dimension_Check=Dimension_Check, Feature_Selection=Feature_Selection, Structural_Similarity=Structural_Similarity)):\n return False\n\n if(not postprocess_file(key, pet_path, \"pet\", Dimension_Check=Dimension_Check, Feature_Selection=Feature_Selection, Structural_Similarity=Structural_Similarity)):\n return False\n\n make_dir([f\"{POSTPROCESS}/{src_name}/{key}\"])\n make_dir([f\"{POSTPROCESS}/{src_name}/{key}/img\"])\n\n print(\"COPYING FILES\")\n\n shutil.copyfile(mri_path, f\"{POSTPROCESS}/{src_name}/{key}/mri.nii\")\n shutil.copyfile(pet_path, f\"{POSTPROCESS}/{src_name}/{key}/pet.nii\")\n shutil.copyfile(f\"{SSIM}/mri.jpg\",\n f\"{POSTPROCESS}/{src_name}/{key}/img/mri.jpg\")\n shutil.copyfile(f\"{SSIM}/pet.jpg\",\n f\"{POSTPROCESS}/{src_name}/{key}/img/pet.jpg\")\n\n remove_dir(POSTPROCESS_TEMP_PATHS)\n\n\ndef driver(extracted_files, src_name):\n postprocessed_files = []\n sub_scan = {}\n\n for i in extracted_files:\n folder = get_folder_name(i['path'])\n if(folder not in sub_scan.keys()):\n sub_scan[folder] = {}\n sub_scan[folder].update({i['name']: i['path']})\n else:\n sub_scan[folder].update({i['name']: i['path']})\n\n postprocessed_files = list_directory(f\"{POSTPROCESS}/{src_name}\")\n\n total_files = len(sub_scan)\n count = 0\n\n print(\"\\n\"+\"-\"*25+\"PROGRESS\"+\"-\"*25+\"\\n\")\n update_progress(count, total_files)\n print(\"\\n\"+\"-\"*58+\"\\n\")\n\n for k in sub_scan:\n count += 1\n if(k not in postprocessed_files):\n if(not postprocess(k, src_name, sub_scan)):\n continue\n print(\"\\n\"+\"-\"*25+\"PROGRESS\"+\"-\"*25+\"\\n\")\n update_progress(count, total_files)\n print(\"\\n\"+\"-\"*58+\"\\n\")\n\n\ndef post_preprocess():\n nii_files = []\n downloaded_files = []\n # Downloaded files\n for file_name in os.listdir(DOWNLOAD):\n file_path = f\"{DOWNLOAD}/{file_name}\"\n downloaded_files.append({\"name\": file_name, \"path\": file_path})\n\n for file in downloaded_files:\n src_name = file['name'][:-4]\n dest_name = src_name.replace(\"preprocessed\", \"postprocessed\")\n \n if(f\"{dest_name}.zip\" in os.listdir(POST_ZIPPED)):\n continue\n\n show_data(\"name\", [src_name, dest_name])\n\n extracted_paths = extract([file])\n extracted_files = get_nii(extracted_paths)\n\n print(f\"\\n{src_name.upper()} PREPROCESSING\\n\")\n driver(extracted_files, dest_name)\n\n global df\n df.to_csv(f\"{POSTPROCESS}/{dest_name}/postprocess.csv\")\n df = pd.DataFrame(columns=['subject_id', 'type', 'mse', 'ssim', 'distance'])\n\n print(f\"\\n{src_name.upper()} ZIPPING\\n\")\n make_archive(f\"{POSTPROCESS}/{dest_name}\", f\"{POST_ZIPPED}/{dest_name}.zip\")\n\n # print(\"REMOVING\")\n # shutil.rmtree(f\"{POSTPROCESS}\")\n\nif __name__ == \"__main__\":\n make_dir(DATA_PATHS)\n make_dir(SCRIPT_PATHS)\n df = pd.DataFrame(columns=['subject_id', 'type', 'mse', 'ssim', 'distance'])\n post_preprocess()\n","sub_path":"postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":9614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48973301","text":"print(\"Enter the number to check positive or negative :\")\na=raw_input()\ntry:\n int(a)\n\nexcept ValueError:\n print ('Not int')\n\nelse:\n a=int(a)\n if (a == 0):\n print(\"Zero\")\n elif (a > 0):\n print(\"positive\")\n else:\n print (\"negative\")\n","sub_path":"pos_or_neg.py","file_name":"pos_or_neg.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179134286","text":"\"\"\"this file executes the button_module program\"\"\"\n\nfrom time import sleep\nfrom sys import platform\nfrom random import randint\n\nfrom common.signals import register_signal_callback\nfrom client.comm import Comm\nfrom modules.button_module.module.mod import Module\n\nSHOULD_STOP = False\n\nclass TestButton:\n \"\"\"\n Button-dummy class that returns random True and False values on read.\n \"\"\"\n def read(self):\n \"\"\"\n Reads the button value. In this case the value is random.\n\n :return True: Button is pressed\n :return False: Button is unpressed\n \"\"\"\n return randint(0, 1) == 1\n\n\ndef main():\n \"\"\"\n Main function that starts the module\n\n :return:\n \"\"\"\n print(\"Starting application...\\n\")\n module = Module(Comm(), TestButton())\n print(\"Module created...\")\n\n register_signal_callback(module.stop)\n\n with module:\n while not module.stopped:\n module.process()\n sleep(0.05)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"modules/button_module/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249775720","text":"import matplotlib.pyplot as plt\nimport netomaton as ntm\nimport numpy as np\n\n\nif __name__ == '__main__':\n\n # NKS page 442 - Rule 122R\n network = ntm.topology.cellular_automaton(n=100)\n initial_conditions = [0]*40 + [1]*20 + [0]*40\n trajectory = ntm.evolve(initial_conditions=initial_conditions, network=network,\n activity_rule=ntm.ReversibleRule(ntm.rules.nks_ca_rule(122)),\n past_conditions=[initial_conditions], timesteps=1000)\n\n timestep = []\n average_node_entropies = []\n\n activities = ntm.get_activities_over_time_as_list(trajectory)\n for i, c in enumerate(activities):\n timestep.append(i)\n bit_string = ''.join([str(x) for x in c])\n average_node_entropies.append(ntm.average_node_entropy(activities[:i+1]))\n print(\"%s, %s\" % (i, average_node_entropies[-1]))\n\n plt.subplot(3, 1, (1, 2))\n plt.title(\"Avg. Node (Shannon) Entropy\")\n plt.gca().set_xlim(0, 1000)\n plt.gca().axes.xaxis.set_ticks([])\n plt.plot(timestep, average_node_entropies)\n\n plt.subplot(3, 1, 3)\n plt.gca().axes.yaxis.set_ticks([])\n ntm.plot_grid(np.array(activities).T.tolist())\n\n\n","sub_path":"demos/reversible_ca/rule122R_entropy_demo.py","file_name":"rule122R_entropy_demo.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217740764","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom typing import Optional, Tuple, List\nimport torch\nfrom torch.nn.utils.rnn import PackedSequence, pad_packed_sequence, pack_padded_sequence\nfrom allennlp.nn.util import ConfigurationError\nfrom allennlp.modules.augmented_lstm import AugmentedLstm\nfrom allennlp.modules.encoder_base import _EncoderBase\n\n\nclass LstmbiLm(_EncoderBase):\n def __init__(self, input_size: int,\n hidden_size: int,\n num_layers: int,\n dropout: float):\n super(LstmbiLm, self).__init__(stateful=False)\n self.hidden_size = hidden_size\n self.cell_size = hidden_size\n\n forward_layers = []\n backward_layers = []\n\n lstm_input_size = input_size\n for layer_index in range(num_layers):\n forward_layer = AugmentedLstm(input_size=lstm_input_size,\n hidden_size=hidden_size,\n go_forward=True,\n recurrent_dropout_probability=dropout)\n backward_layer = AugmentedLstm(input_size=lstm_input_size,\n hidden_size=hidden_size,\n go_forward=False,\n recurrent_dropout_probability=dropout)\n\n lstm_input_size = hidden_size\n self.add_module('forward_layer_{}'.format(layer_index), forward_layer)\n self.add_module('backward_layer_{}'.format(layer_index), backward_layer)\n forward_layers.append(forward_layer)\n backward_layers.append(backward_layer)\n self.forward_layers = forward_layers\n self.backward_layers = backward_layers\n\n def forward(self, inputs: torch.Tensor,\n mask: torch.Tensor):\n batch_size, total_sequence_length = mask.size()\n stacked_sequence_output, final_states, restoration_indices = \\\n self.sort_and_run_forward(self._lstm_forward, inputs, mask)\n\n num_layers, num_valid, returned_timesteps, encoder_dim = stacked_sequence_output.size()\n # Add back invalid rows which were removed in the call to sort_and_run_forward.\n if num_valid < batch_size:\n zeros = stacked_sequence_output.new_zeros(num_layers,\n batch_size - num_valid,\n returned_timesteps,\n encoder_dim)\n stacked_sequence_output = torch.cat([stacked_sequence_output, zeros], 1)\n\n # The states also need to have invalid rows added back.\n if self.stateful:\n new_states = []\n for state in final_states:\n state_dim = state.size(-1)\n zeros = state.new_zeros(num_layers, batch_size - num_valid, state_dim)\n new_states.append(torch.cat([state, zeros], 1))\n final_states = new_states\n\n # It's possible to need to pass sequences which are padded to longer than the\n # max length of the sequence to a Seq2StackEncoder. However, packing and unpacking\n # the sequences mean that the returned tensor won't include these dimensions, because\n # the RNN did not need to process them. We add them back on in the form of zeros here.\n sequence_length_difference = total_sequence_length - returned_timesteps\n if sequence_length_difference > 0:\n zeros = stacked_sequence_output.new_zeros(num_layers,\n batch_size,\n sequence_length_difference,\n stacked_sequence_output[0].size(-1))\n stacked_sequence_output = torch.cat([stacked_sequence_output, zeros], 2)\n\n if self.stateful:\n self._update_states(final_states, restoration_indices)\n\n # Restore the original indices and return the sequence.\n # Has shape (num_layers, batch_size, sequence_length, hidden_size)\n return stacked_sequence_output.index_select(1, restoration_indices)\n\n def _lstm_forward(self,\n inputs: PackedSequence,\n initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \\\n Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:\n if initial_state is None:\n hidden_states: List[Optional[Tuple[torch.Tensor,\n torch.Tensor]]] = [None] * len(self.forward_layers)\n elif initial_state[0].size()[0] != len(self.forward_layers):\n raise ConfigurationError(\"Initial states were passed to forward() but the number of \"\n \"initial states does not match the number of layers.\")\n else:\n hidden_states = list(zip(initial_state[0].split(1, 0), initial_state[1].split(1, 0)))\n\n forward_output_sequence = inputs\n backward_output_sequence = inputs\n\n final_states = []\n sequence_outputs = []\n for layer_index, state in enumerate(hidden_states):\n forward_layer = getattr(self, 'forward_layer_{}'.format(layer_index))\n backward_layer = getattr(self, 'backward_layer_{}'.format(layer_index))\n\n if state is not None:\n forward_hidden_state, backward_hidden_state = state[0].split(self.hidden_size, 2)\n forward_memory_state, backward_memory_state = state[1].split(self.cell_size, 2)\n forward_state = (forward_hidden_state, forward_memory_state)\n backward_state = (backward_hidden_state, backward_memory_state)\n else:\n forward_state = None\n backward_state = None\n\n forward_output_sequence, forward_state = forward_layer(forward_output_sequence,\n forward_state)\n backward_output_sequence, backward_state = backward_layer(backward_output_sequence,\n backward_state)\n\n unpacked_forward_output_sequence, _ = pad_packed_sequence(forward_output_sequence, batch_first=True)\n unpacked_backward_output_sequence, _ = pad_packed_sequence(backward_output_sequence, batch_first=True)\n\n sequence_outputs.append(torch.cat([unpacked_forward_output_sequence,\n unpacked_backward_output_sequence], -1))\n # Append the state tuples in a list, so that we can return\n # the final states for all the layers.\n final_states.append((torch.cat([forward_state[0], backward_state[0]], -1),\n torch.cat([forward_state[1], backward_state[1]], -1)))\n\n stacked_sequence_outputs: torch.FloatTensor = torch.stack(sequence_outputs)\n # Stack the hidden state and memory for each layer into 2 tensors of shape\n # (num_layers, batch_size, hidden_size) and (num_layers, batch_size, cell_size)\n # respectively.\n final_hidden_states, final_memory_states = zip(*final_states)\n final_state_tuple: Tuple[torch.FloatTensor,\n torch.FloatTensor] = (torch.cat(final_hidden_states, 0),\n torch.cat(final_memory_states, 0))\n return stacked_sequence_outputs, final_state_tuple\n","sub_path":"src/bilm/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":7618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597864949","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\npath = r'c:\\Users\\Administrator\\Desktop\\文件\\Python DataAnalysis\\chapter4\\demo\\data\\catering_sale.xls'\r\n\r\n\r\ndef getData(path):\r\n data = pd.read_excel(path)\r\n data['销量'][(data['销量'] > 5000) | (data['销量'] < 400)] = None\r\n return data\r\n\r\n\r\ndef lagrange_solve(s, n, k=5):\r\n # 拉格朗日插值\r\n from scipy.interpolate import lagrange\r\n y = s.reindex(list(range(n-k, n))+list(range(n+1, n+1+k)))\r\n y = y[y.notnull()]\r\n return lagrange(y.index, list(y))(n)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n data = getData(path)\r\n print(\"********\", data['销量'][2])\r\n for i in data.columns:\r\n for j in range(len(data)):\r\n if (data[i].isnull())[j]:\r\n data[i][j] = lagrange_solve(data[i], j)\r\n # data.to_excel(r'd:\\\\r.xls')\r\n opath = r'd:\\\\r.csv'\r\n # data = data.iloc[:, -1]\r\n # writer = pd.ExcelWriter(opath, )\r\n # data.to_excel(writer)\r\n data.to_csv(opath, index=False, mode='a', columns=['销量'])\r\n\r\n # writer.save()\r\n","sub_path":"python/拉格朗日插值.py","file_name":"拉格朗日插值.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"555032591","text":"import sys\nfrom os import path\n\nimport tkinter as tk\nfrom PIL import Image, ImageTk\nfrom random import randint\n\nMOVE_INCREMENT = 20\nmoves_per_second = 10\nGAME_SPEED = 1000 // moves_per_second\nWIDTH = 600\nHEIGHT = 620\n\nclass Snake(tk.Canvas):\n def __init__(self):\n super().__init__(width=WIDTH, height=HEIGHT, background=\"black\", highlightthickness=0)\n\n self.snake_positions = [(100,100),(80,100),(60,100)]\n self.food_position = self.set_new_food_position()\n self.score = 0\n self.direction = \"Right\"\n self.bind_all(\"\", self.on_key_press)\n\n self.load_assets()\n self.create_objects()\n self.after(GAME_SPEED, self.perform_actions)\n\n def load_assets(self):\n try:\n # Bundle directory... path.abspath important for --onefile export\n bundle_dir = getattr(sys, \"_MEIPASS\", path.abspath(path.dirname(__file__)))\n\n # Snake\n path_to_snake = path.join(bundle_dir, \"assets\", \"snake.png\")\n self.snake_body_image = Image.open(path_to_snake)\n self.snake_body = ImageTk.PhotoImage(self.snake_body_image)\n\n # Food\n path_to_food = path.join(bundle_dir, \"assets\", \"food.png\")\n self.food_image = Image.open(path_to_food)\n self.food = ImageTk.PhotoImage(self.food_image)\n \n except IOError as error:\n print(error)\n root.destroy()\n\n def create_objects(self):\n # Score Text\n self.create_text(\n 100,12,text=f\"Score {self.score} (Speed: {moves_per_second})\", tag=\"score\", fill=\"#fff\", font=(\"TkDefaultFont\",14)\n )\n # Snake Body\n for x_position, y_position in self.snake_positions:\n self.create_image(x_position,y_position,image=self.snake_body,tag=\"snake\")\n # Food\n self.create_image(self.food_position[0], self.food_position[1], image=self.food, tag=\"food\")\n\n # Rectangle (Game Boundaries)\n self.create_rectangle(7,27,593,613, outline=\"#EF5B3B\")\n\n def move_snake(self):\n head_x_position, head_y_position = self.snake_positions[0]\n\n if self.direction == \"Left\":\n new_head_position = (head_x_position - MOVE_INCREMENT, head_y_position)\n elif self.direction == \"Right\":\n new_head_position = (head_x_position + MOVE_INCREMENT, head_y_position)\n elif self.direction == \"Down\":\n new_head_position = (head_x_position, head_y_position + MOVE_INCREMENT)\n elif self.direction == \"Up\":\n new_head_position = (head_x_position, head_y_position - MOVE_INCREMENT)\n\n self.snake_positions = [new_head_position] + self.snake_positions[:-1]\n\n for segment, position in zip(self.find_withtag(\"snake\"), self.snake_positions):\n self.coords(segment, position)\n\n def perform_actions(self):\n if self.check_collisions():\n self.end_game()\n return\n self.check_food_collision()\n self.move_snake()\n self.after(GAME_SPEED, self.perform_actions)\n\n def check_collisions(self):\n head_x_position, head_y_position = self.snake_positions[0]\n\n return(\n head_x_position in (0,WIDTH)\n or head_y_position in (20,HEIGHT)\n or (head_x_position,head_y_position) in self.snake_positions[1:]\n )\n\n def on_key_press(self,e):\n new_direction = e.keysym\n all_directions = (\"Up\",\"Down\",\"Left\",\"Right\")\n opposites =({\"Up\",\"Down\"},{\"Left\",\"Right\"})\n\n if (new_direction in all_directions) and {new_direction, self.direction} not in opposites:\n self.direction = new_direction\n\n def check_food_collision(self):\n if self.snake_positions[0] == self.food_position:\n self.score += 1\n self.snake_positions.append(self.snake_positions[-1])\n\n if self.score % 5 == 0:\n global moves_per_second\n moves_per_second += 1\n\n self.create_image(\n *self.snake_positions[-1], image=self.snake_body, tag=\"snake\"\n )\n\n self.food_position = self.set_new_food_position()\n self.coords(self.find_withtag(\"food\"), self.food_position)\n\n score = self.find_withtag(\"score\")\n self.itemconfigure(score, text=f\"Score: {self.score} (Speed: {moves_per_second})\", tag=\"score\")\n\n def set_new_food_position(self):\n while True:\n x_position = randint(1,29)*MOVE_INCREMENT\n y_position = randint(3,30)*MOVE_INCREMENT\n food_position = (x_position,y_position)\n\n if food_position not in self.snake_positions:\n return food_position\n\n def end_game(self):\n self.delete(tk.ALL)\n self.create_text(\n self.winfo_width()/2,\n self.winfo_height()/2,\n text=f\"Game Over! You scored {self.score}\",\n fill=\"#fff\",\n font=(\"TkDefaultFont\",24)\n )\n\n# Create App\nroot = tk.Tk()\nroot.title(\"Snake Game\")\nroot.resizable(False,False)\n\n# Board\nboard = Snake()\nboard.pack()\n\n# Run App\nroot.mainloop()\n\n# ----- MAC & LINUX Deployment----- #\n\n# (1) Export in a FOLDER (Terminal shows):\n# >>> pyinstaller app.py --add-data=\"assets/*.png:assets\"\n\n# (2) Export in ONE FILE (Terminal shows):\n# >>> pyinstaller app.py --onefile --add-data=\"assets/*.png:assets\"\n\n# (3) Export in a FOLDER (Terminal HIDDEN): --->>> This one also creates a standalone!!! (BEST OPTION)\n# >>> pyinstaller app.py --add-data=\"assets/*.png:assets\" --windowed\n\n# (4) Export in ONE FILE (Terminal HIDDEN):\n# >>> pyinstaller app.py --onefile --add-data=\"assets/*.png:assets\" --windowed\n\n\n# ----- WINDOWS Deployment----- #\n\n# (1) Export in a FOLDER (Terminal shows):\n# >>> pyinstaller app.py --add-data \"assets;assets\"\n\n# (2) Export in ONE FILE (Terminal shows):\n# >>> pyinstaller app.py --onefile --add-data \"assets;assets\"\n\n# (3) Export in a FOLDER (Terminal HIDDEN):\n# >>> pyinstaller app.py --add-data \"assets;assets\" --windowed\n\n# (4) Export in ONE FILE (Terminal HIDDEN):\n# >>> pyinstaller app.py --onefile --add-data \"assets;assets\" --windowed\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"505459689","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 28 09:37:26 2019\n\n@author: weetee\n\"\"\"\nimport os\nimport math\nimport torch\nimport torch.nn as nn\nfrom ..misc import save_as_pickle, load_pickle\nfrom sklearn.metrics import f1_score as sklearn_f1_score\nimport logging\nfrom tqdm import tqdm\nimport numpy as np\nfrom collections import Counter\nimport sys\n\nlogging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', \\\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)\nlogger = logging.getLogger(__file__)\n\ndef load_state(net, optimizer, scheduler, args, load_best=False):\n \"\"\" Loads saved model and optimizer states if exists \"\"\"\n base_path = \"./my_model/\"\n amp_checkpoint = None\n checkpoint_path = os.path.join(base_path,\"task_test_checkpoint_%d.pth.tar\" % args.model_no)\n best_path = os.path.join(base_path,\"task_test_model_best_%d.pth.tar\" % args.model_no)\n start_epoch, best_pred, checkpoint = 0, 0, None\n if (load_best == True) and os.path.isfile(best_path):\n checkpoint = torch.load(best_path)\n logger.info(\"Loaded best model.\")\n elif os.path.isfile(checkpoint_path):\n checkpoint = torch.load(checkpoint_path)\n logger.info(\"Loaded checkpoint model.\")\n if checkpoint != None:\n start_epoch = checkpoint['epoch']\n best_pred = checkpoint['best_acc']\n net.load_state_dict(checkpoint['state_dict'])\n if optimizer is not None:\n optimizer.load_state_dict(checkpoint['optimizer'])\n if scheduler is not None:\n scheduler.load_state_dict(checkpoint['scheduler'])\n amp_checkpoint = checkpoint['amp']\n logger.info(\"Loaded model and optimizer.\") \n return start_epoch, best_pred, amp_checkpoint\n\ndef load_results(model_no=0):\n \"\"\" Loads saved results if exists \"\"\"\n losses_path = \"./my_model/task_test_losses_per_epoch_%d.pkl\" % model_no\n accuracy_path = \"./my_model/task_train_accuracy_per_epoch_%d.pkl\" % model_no\n f1_path = \"./my_model/task_test_f1_per_epoch_%d.pkl\" % model_no\n if os.path.isfile(losses_path) and os.path.isfile(accuracy_path) and os.path.isfile(f1_path):\n losses_per_epoch = load_pickle(\"./my_model/task_test_losses_per_epoch_%d.pkl\" % model_no)\n accuracy_per_epoch = load_pickle(\"./my_model/task_train_accuracy_per_epoch_%d.pkl\" % model_no)\n f1_per_epoch = load_pickle(\"./my_model/task_test_f1_per_epoch_%d.pkl\" % model_no)\n logger.info(\"Loaded results buffer\")\n else:\n losses_per_epoch, accuracy_per_epoch, f1_per_epoch = [], [], []\n return losses_per_epoch, accuracy_per_epoch, f1_per_epoch\n\n\ndef evaluate_(output, labels):\n\n o_labels = torch.softmax(output, dim=1).max(1)[1]\n l = labels.squeeze(dim=1); o = o_labels\n\n acc = (l == o).sum().item()/len(l)\n\n l = l.cpu().numpy().tolist() if l.is_cuda else l.numpy().tolist()\n o = o.cpu().numpy().tolist() if o.is_cuda else o.numpy().tolist()\n\n return acc, (o, l)\n\ndef semeval_files(args, true_labels, pred_labels, epoch):\n if not os.path.exists('./semeval_files/'):\n os.makedirs('./semeval_files/')\n\n f = open(\"./semeval_files/true_labels_epoch{}.txt\".format(epoch), \"w\")\n for i, true_label in enumerate(true_labels):\n f.write(str(i)+'\\t'+args.idx2rel[true_label]+'\\n')\n f.close()\n\n f = open(\"./semeval_files/pred_labels_epoch{}.txt\".format(epoch), \"w\")\n for i, pred_label in enumerate(pred_labels):\n f.write(str(i) + '\\t' + args.idx2rel[pred_label] + '\\n')\n f.close()\n\ndef KBP37_files(args, true_labels, pred_labels, epoch):\n if not os.path.exists('./kbp37_files/'):\n os.makedirs('./kbp37_files/')\n\n f = open(\"./kbp37_files/true_labels_epoch{}.txt\".format(epoch), \"w\")\n for i, true_label in enumerate(true_labels):\n f.write(str(i) + '\\t' + args.idx2rel[true_label] + '\\n')\n f.close()\n\n f = open(\"./kbp37_files/pred_labels_epoch{}.txt\".format(epoch), \"w\")\n for i, pred_label in enumerate(pred_labels):\n f.write(str(i) + '\\t' + str(pred_label) + '\\n')\n f.close()\n\ndef KBP37_scorer1(args, labels, preds):\n preds = np.array(preds).astype(dtype=\"int64\")\n labels = np.array(labels).astype(dtype=\"int64\")\n ignore_id = args.rel2idx['no_relation']\n num_labels = len(args.rel2idx)\n p_list = []\n r_list = []\n f1_list = []\n\n total = 0\n for i in range(num_labels):\n if i == ignore_id:\n continue\n tp = np.sum((labels == i) & (preds == i))\n tn = np.sum((labels != i) & (preds != i))\n fp = np.sum((labels != i) & (preds == i))\n fn = np.sum((labels == i) & (preds != i))\n\n if tp + fp == 0 or tp + fn == 0:\n continue\n p = tp / (tp + fp)\n r = tp / (tp + fn)\n f1 = (2 * p * r) / (p + r + 1e-8)\n p_list.append(p)\n r_list.append(r)\n f1_list.append(f1)\n total += 1\n\n macro_p = sum(p_list)/ (total + 1e-8)\n macro_r = sum(r_list)/ (total + 1e-8)\n macro_f1 = sum(f1_list) / (total + 1e-8)\n print('KBP37_scorer1')\n print('macro_p : {}'.format(macro_p))\n print('macro_r : {}'.format(macro_r))\n print('macro_f1 : {}'.format(macro_f1))\n return macro_p, macro_r, macro_f1, total\n\ndef TACRED_scorer(args, key, prediction, verbose=True):\n if args.task == 'TACRED':\n NO_RELATION = \"NA\"\n elif args.task == 'FewRel':\n NO_RELATION = \"\"\n\n correct_by_relation = Counter()\n guessed_by_relation = Counter()\n gold_by_relation = Counter()\n\n f1_list = []\n p_list = []\n r_list = []\n\n # Loop over the data to compute a score\n for row in range(len(key)):\n gold = args.idx2rel[key[row]]\n guess = args.idx2rel[prediction[row]]\n\n if gold == NO_RELATION and guess == NO_RELATION:\n pass\n elif gold == NO_RELATION and guess != NO_RELATION:\n guessed_by_relation[guess] += 1\n elif gold != NO_RELATION and guess == NO_RELATION:\n gold_by_relation[gold] += 1\n elif gold != NO_RELATION and guess != NO_RELATION:\n guessed_by_relation[guess] += 1\n gold_by_relation[gold] += 1\n if gold == guess:\n correct_by_relation[guess] += 1\n\n # Print verbose information\n if verbose:\n print(\"Per-relation statistics:\")\n relations = gold_by_relation.keys()\n longest_relation = 0\n for relation in sorted(relations):\n longest_relation = max(len(relation), longest_relation)\n for relation in sorted(relations):\n # (compute the score)\n correct = correct_by_relation[relation]\n guessed = guessed_by_relation[relation]\n gold = gold_by_relation[relation]\n prec = 1.0\n if guessed > 0:\n prec = float(correct) / float(guessed)\n recall = 0.0\n if gold > 0:\n recall = float(correct) / float(gold)\n f1 = 0.0\n if prec + recall > 0:\n f1 = 2.0 * prec * recall / (prec + recall)\n # (print the score)\n sys.stdout.write((\"{:<\" + str(longest_relation) + \"}\").format(relation))\n sys.stdout.write(\" P: \")\n if prec < 0.1: sys.stdout.write(' ')\n if prec < 1.0: sys.stdout.write(' ')\n sys.stdout.write(\"{:.2%}\".format(prec))\n sys.stdout.write(\" R: \")\n if recall < 0.1: sys.stdout.write(' ')\n if recall < 1.0: sys.stdout.write(' ')\n sys.stdout.write(\"{:.2%}\".format(recall))\n sys.stdout.write(\" F1: \")\n if f1 < 0.1: sys.stdout.write(' ')\n if f1 < 1.0: sys.stdout.write(' ')\n sys.stdout.write(\"{:.2%}\".format(f1))\n sys.stdout.write(\" #: %d\" % gold)\n sys.stdout.write(\"\\n\")\n f1_list.append(f1)\n p_list.append(prec)\n r_list.append(recall)\n print(\"\")\n\n # Print the aggregate score\n if verbose:\n print(\"Final Score:\")\n\n if args.task == 'TACRED':\n prec_micro = 1.0\n if sum(guessed_by_relation.values()) > 0:\n prec_micro = float(sum(correct_by_relation.values())) / float(sum(guessed_by_relation.values()))\n recall_micro = 0.0\n if sum(gold_by_relation.values()) > 0:\n recall_micro = float(sum(correct_by_relation.values())) / float(sum(gold_by_relation.values()))\n f1_micro = 0.0\n if prec_micro + recall_micro > 0.0:\n f1_micro = 2.0 * prec_micro * recall_micro / (prec_micro + recall_micro)\n print(\"Precision (micro): {:.3%}\".format(prec_micro))\n print(\" Recall (micro): {:.3%}\".format(recall_micro))\n print(\" F1 (micro): {:.3%}\".format(f1_micro))\n return prec_micro, recall_micro, f1_micro\n\n elif args.task == 'FewRel':\n prec_macro = sum(p_list) / len(p_list)\n recall_macro = sum(r_list) / len(r_list)\n f1_macro = sum(f1_list) / len(f1_list)\n print(\"Precision (macro): {:.3%}\".format(prec_macro))\n print(\" Recall (macro): {:.3%}\".format(recall_macro))\n print(\" F1 (macro): {:.3%}\".format(f1_macro))\n return prec_macro, recall_macro, f1_macro\n\n\ndef evaluate_results(net, test_loader, pad_id, cuda, args, epoch):\n logger.info(\"Evaluating test samples...\")\n acc = 0; out_labels = []; true_labels = []\n net.eval()\n with torch.no_grad():\n for i, data in tqdm(enumerate(test_loader), total=len(test_loader)):\n x, e1_e2_start, labels, _,_,_ = data\n attention_mask = (x != pad_id).float()\n token_type_ids = torch.zeros((x.shape[0], x.shape[1])).long()\n\n if args.only_evaluate == 2 and i >= 10:\n break\n\n if cuda:\n x = x.cuda()\n labels = labels.cuda()\n attention_mask = attention_mask.cuda()\n token_type_ids = token_type_ids.cuda()\n \n classification_logits = net(x, token_type_ids=token_type_ids, attention_mask=attention_mask, \\\n e1_e2_start=e1_e2_start)\n \n accuracy, (o, l) = evaluate_(classification_logits, labels)\n out_labels.extend(o); true_labels.extend(l) \n acc += accuracy\n\n accuracy = acc/(i + 1)\n\n results = {\n \"accuracy\": accuracy,\n \"sklearn f1-macro\": sklearn_f1_score(true_labels, out_labels, labels=list(range(args.num_classes)), average='macro'),\n \"sklearn f1-micro\": sklearn_f1_score(true_labels, out_labels, labels=list(range(args.num_classes)), average='micro')\n }\n\n if args.task == 'SemEval':\n logger.info(\"Generating additional files ...\")\n semeval_files(args, true_labels, out_labels, epoch+1)\n elif args.task == 'KBP37':\n KBP37_scorer1(args, true_labels, out_labels)\n KBP37_files(args, true_labels, out_labels, epoch+1)\n elif args.task == 'TACRED':\n TACRED_scorer(args, true_labels, out_labels)\n\n logger.info(\"***** Eval results *****\")\n for key in sorted(results.keys()):\n logger.info(\" %s = %s\", key, str(results[key]))\n \n return results\n ","sub_path":"src/tasks/train_funcs.py","file_name":"train_funcs.py","file_ext":"py","file_size_in_byte":11130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381617453","text":"import requests\nfrom random import randint\nimport hashlib\n\n\ndef get_md5(string):\n hlb = hashlib.md5()\n hlb.update(string.encode(encoding='utf-8'))\n return hlb.hexdigest()\n\n\ndef get_token():\n host = 'http://hkaccountcdn.chinesetvall.com/app/member/doLogin.do'\n data = {\n 'userName': 'yuuuuu2016@163.com',\n 'password': '12345678',\n 'sign': 'c9628e50454497d5b89556b57ba523b6',\n 'platform': 'mobile-android'\n }\n res = requests.post(url=host, data=data)\n return res.json()['token']\n\n\ndef get_video_title():\n \"\"\"\n 获取收藏中的某部影片\n \"\"\"\n host = 'http://hkaccountcdn.chinesetvall.com/app/member/doMyCollection.do'\n data = {\n 'token': get_token(),\n 'platform': 'mobile-android',\n 'albumId': '4751',\n 'albumTitle': '星座值守恋人',\n 'albumImg': 'http://hkvideocdn.chinesetvall.com/upload_imgs/20190821/7aeac662e0cd654d49787099d25176ea.jpg',\n 'sign': None\n }\n\n secret = data['token'] + data['platform']\n data['sign'] = get_md5(secret)\n print(data)\n res = requests.post(url=host, data=data).json()\n print(res)\n if res['collectionList']:\n collection = res['collectionList'][1]\n return collection['albumTitle']\n\n\nif __name__ == '__main__':\n # t = get_token()\n # print(t)\n r = get_collecttitle()\n print(r)\n","sub_path":"common/api_help.py","file_name":"api_help.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"379951247","text":"import pymongo\nfrom csv_2_dict import csv_dict\nimport pandas as pd\n\nclient = pymongo.MongoClient('mongodb://localhost:27017/')\n\nclass mongo_db_class:\n def __init__(self, database_name, collection_name):\n self.database = database_name\n self.collection = collection_name\n\n try:\n def create(self):\n mongodb = client['mongo_flask_db']\n collection = mongodb[self.collection]\n return collection\n except Exception as e:\n print(e)\n\n try:\n def insert_single_document(self):\n document_single = {'customer_id': 0,\n 'store_id': 0,\n 'first_name': 'shivansh',\n 'last_name': 'jayara',\n 'email': 'shivansh@gmail.com',\n 'address': 10,\n 'create_date': '01-06-2021'\n }\n self.create().insert_one(document_single)\n except Exception as e:\n print(e)\n\n try:\n def update_document(self):\n parent_data = {'last_name': 'jayara'}\n updated_data = {'$set': {'last_name': 'Singh'}}\n self.create().update_one(parent_data,updated_data)\n except Exception as e:\n print(e)\n\n try:\n def insert_many_document(self):\n document_many = csv_dict()\n convert = document_many.convert_to_dict()\n self.create().insert_many(convert)\n except Exception as e:\n print(e)\n\n try:\n def delete_document(self):\n delete_data = {'customer_id': {'$in': ['3', '5', '6']}}\n self.create().delete_many(delete_data)\n except Exception as e:\n print(e)\n\n try:\n def download(self):\n all_data = self.create().find({})\n df = pd.DataFrame(all_data)\n df.to_csv('mongodb_updated_customer_db.csv', index=False)\n except Exception as e:\n print(e)\n finally:\n client.close()\n","sub_path":"mongo_db.py","file_name":"mongo_db.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138800802","text":"#coding=utf-8\n\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth import authenticate, login, logout\nfrom .models import Item\nfrom .models import Record\nfrom .models import TodoItem\n\nimport base\n\nfrom datetime import date\nimport datetime\n\n# Create your views here.\ndef login_view(request):\n context = {'status' : 'anonymity'}\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if base.isAuth(request):\n return redirect('/index/')\n\n if(request.method == 'POST'):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is None:\n context['status'] = 'invalid'\n elif user.is_active:\n login(request, user)\n context['status'] = user.username\n return redirect('/index/')\n else:\n context['status'] = 'inactive'\n return render(request, 'mainpage/login.html', context)\n\ndef logout_view(request):\n logout(request)\n return redirect('/login/')\n\ndef base_view(request):\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n\n context = base.initialContext(request);\n\n return render(request, 'mainpage/base.html', context)\n\n\ndef index_view(request):\n 'Show records'\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n today = date.today()\n yesterday = today + datetime.timedelta(days=-1)\n\n recordList = Record.objects.filter(user_id=request.user.id, create_time=date.today())\n recordList = list(recordList)\n yesterdayRecordList = Record.objects.filter(user_id=request.user.id, create_time=yesterday)\n yesterdayRecordDictStatus = {}\n map(lambda record: yesterdayRecordDictStatus.setdefault(record.item_id, record.status), yesterdayRecordList)\n avaliableItemList = Item.objects.filter(user_id=request.user.id, status=1)\n avaliableItemList = list(avaliableItemList)\n itemDictSuccession = {}\n map(lambda item: itemDictSuccession.setdefault(item.id, item.currentSuccession), avaliableItemList)\n\n \"\"\"\n Find the uncreated Records and create them.\n Update the currentSuccession of Items.\n \"\"\"\n itemIdList = [item.id for item in avaliableItemList]\n recordItemIdList = [record.item_id for record in recordList]\n newRecordItemList = [itemId for itemId in itemIdList if itemId not in recordItemIdList]\n for itemId in newRecordItemList:\n newRecord = Record(item_id=itemId, user_id=request.user.id, status=0)\n recordList.append(newRecord)\n newRecord.save()\n\n itemYesterdayStatus = yesterdayRecordDictStatus.get(itemId)\n if itemYesterdayStatus and (itemYesterdayStatus == 1):\n Item.objects.filter(id=itemId).update(currentSuccession=(itemDictSuccession.get(itemId) + 1))\n else:\n Item.objects.filter(id=itemId).update(currentSuccession=0)\n\n avaliableItemList = Item.objects.filter(user_id=request.user.id, status=1)\n avaliableItemList = list(avaliableItemList)\n recordList = [record for record in recordList if record.item_id in itemIdList]\n for record in recordList:\n tmpRecord = [item for item in avaliableItemList if item.id == record.item_id][0]\n\n record.itemName, record.currentSuccession, record.comment, record.commentDisplay = (\n tmpRecord.item_name,\n tmpRecord.currentSuccession, \n tmpRecord.item_comment,\n tmpRecord.comment_display\n )\n\n context = base.initialContext(request)\n context.setdefault('recordList', enumerate(recordList))\n\n return render(request, 'mainpage/index_view.html', context)\n\ndef todoList_view(request):\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n context = base.initialContext(request);\n\n return render(request, 'mainpage/todoList_view.html', context)\n\ndef item_view(request):\n 'The view exhibits items of certain user.'\n \n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n itemList = Item.objects.filter(user_id=request.user.id, status__lte=1)\n\n context = base.initialContext(request);\n context.setdefault('itemList', enumerate(itemList));\n\n return render(request, 'mainpage/item_view.html', context)\n\ndef history_view(request):\n 'Display history information'\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n context = base.initialContext(request);\n\n return render(request, 'mainpage/history_view.html', context)\n\ndef addItems_view(request):\n 'Add item'\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n if(request.method == 'POST'):\n postDict = dict(request.POST.iterlists())\n postDict.setdefault('comment-display', False)\n itemName = postDict['item-name'][0]\n comment = postDict['item-comment'][0]\n commentDisplay = postDict['comment-display']\n newItem = Item(item_name=itemName, user_id=request.user.id, item_comment=comment, comment_display=commentDisplay)\n newItem.save()\n return redirect('/item/')\n\n context = base.initialContext(request);\n\n return render(request, 'mainpage/addItems_view.html', context)\n\ndef editItem_view(request, itemId):\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n if(request.method == 'POST'):\n postDict = dict(request.POST.iterlists())\n postDict.setdefault('comment-display', False)\n itemId = postDict['itemId'][0]\n comment = postDict['item-comment'][0]\n commentDisplay = postDict['comment-display']\n Item.objects.filter(id=itemId).update(item_comment=comment)\n Item.objects.filter(id=itemId).update(comment_display=commentDisplay)\n return redirect('/item/')\n\n\n context = base.initialContext(request);\n\n item = Item.objects.filter(id=itemId);\n context.setdefault('id', item[0].id)\n context.setdefault('name', item[0].item_name)\n context.setdefault('comment', item[0].item_comment)\n context.setdefault('commentDisplay', item[0].comment_display)\n context.setdefault('createTime', item[0].create_time.strftime('%Y-%m-%d'))\n\n return render(request, 'mainpage/editItem_view.html', context)\n\ndef addTodoItem_view(request):\n 'Add item'\n\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n if not base.isAuth(request):\n return redirect('/login/')\n\n if(request.method == 'POST'):\n itemName = request.POST['itemName']\n newTodoItem = TodoItem(item_name=itemName, user_id=request.user.id)\n newTodoItem.save()\n return redirect('/todoList/')\n\n context = base.initialContext(request);\n\n return render(request, 'mainpage/addTodoItem_view.html', context)\n\ndef game_view(request):\n 'Game'\n if not base.isMobileAgent(request):\n return HttpResponse('请用手机访问!')\n \n context = base.initialContext(request);\n\n return render(request, 'mainpage/gameQiXi_view.html', context);\n\ndef testReact(request):\n 'Test'\n\n return render(request, 'mainpage/testReact_view.html')\n","sub_path":"mainpage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80433535","text":"# 퀴즈 5\n# 은행에 가서 계좌를 개설하면 은행이름, 예금주, 계좌번호, 잔액이 설정된다.\n# Account 클래스를 생성한 후 객체 인스턴스를 구현하도록 프로그래밍하여라.\n# 객체 인스턴스는 예금주와 초기 잔액만 입력 받으며\n# 은행이름은 SC은행으로 계좌번호는 3자리-2자리-6자리 형태로 랜덤하게 생성한다.\n# random 모듈 이용\n'''\n고객명 김민수\n잔액 100\n은행 SC은행\n계좌 375-85-239565\n'''\n\n\n\n\n\n\n# 퀴즈 6\n# 퀴즈 5의 클래스에 클래스 변수를 사용해서\n# Account 클래스로부터 생성된 계좌 객체와 관련된 변수를 정의하고\n# 출력하도록 get_account_num() 메서드를 추가하여라.\n'''\n# 계좌를 3개 인스턴스화 한 경우 \nchio = Account(\"최진수\", 100)\nkim = Account(\"김민수\", 100)\nlee = Account(\"이민수\", 100)\nAccount.get_account_num()\n\n결과>>\n총 계좌수 : 3\n\n'''\n\n\n\n# 퀴즈 7\n# 위에서 정의한 Account 클래스에\n# 입금을 위한 deposit 메서드와\n# 출금을 위한 withdraw 메서드를 하여라.\n# 출금은 계좌의 잔고 이상으로 출금할 수는 없으며\n# 입금은 최소 1원 이상만 가능하다.\n'''\n# 객체 인스턴스 참고코드. \nk = Account(\"kim\", 100)\nk.deposit(100)\nk.withdraw(90)\nprint('잔액 => ',k.balance)\n\n# 잔액 => 110\n'''\n\n\n\n\n# 퀴즈 8\n# 위에서 정의한 Account 클래스에\n# Account 인스턴스에 저장된 정보를 출력하는 display_info() 메서드를\n# 추가하여라.\n'''\n# 객체 인스턴스 참고 소스 \nprint('$'*70)\np = Account(\"홍길동\", 10000)\np.display_info()\n\n# >> 결과 \n은행이름: SC은행\n예금주: 홍길동\n계좌번호: 098-29-285603\n잔고: 10000\n'''\n\n\nimport random\n\n# 계좌번호는 3자리-2자리-6자리\n# print(random.randint(100,999),'-',random.randint(10,99), '-', random.randint(100000,999999))\n# account_number = str(random.randint(100,999))+'-'+str(random.randint(10,99))+'-'+str(random.randint(100000,999999))\n# print(account_number)\n\n# class Account:\n# def __init__(self, name, balance):\n# self.name = name\n# self.balance = balance\n# self.bank = \"SC은행\"\n# self.account_number = str(random.randint(100,999)) + '-' \\\n# + str(random.randint(10,99)) + '-' \\\n# + str(random.randint(100000,999999))\n#\n# # 인스턴스 생성\n# kim = Account(\"김민수\", 100)\n# print('고객명 :', kim.name)\n# print('잔액 : ', kim.balance)\n# print('은행 : ',kim.bank)\n# print('계좌 : ', kim.account_number)\n\n\n# 퀴즈 6\n# 퀴즈 5의 클래스에 클래스 변수를 사용해서\n# Account 클래스로부터 생성된 계좌 객체와 관련된 변수를 정의하고\n# 출력하도록 get_account_num() 메서드를 추가하여라.\n'''\n# 계좌를 3개 인스턴스화 한 경우 \nchio = Account(\"최진수\", 100)\nkim = Account(\"김민수\", 100)\nlee = Account(\"이민수\", 100)\nAccount.get_account_num()\n\n결과>>\n총 계좌수 : 3\n\n'''\n\nclass Account:\n # 클래스 변수\n account_count = 0\n\n # 생성자 메서드\n def __init__(self, name, balance):\n self.name = name\n self.balance = balance\n self.bank = \"SC은행\"\n self.account_number = str(random.randint(100,999)) + '-' \\\n + str(random.randint(10,99)) + '-' \\\n + str(random.randint(100000,999999))\n # 계좌 생성시 누적 카운트\n # 클래스.클래스변수 로 접근 가능\n Account.account_count += 1\n\n # 생성된 인스턴스를 출력하는 메서드\n def get_account_num(self):\n print(f'총 계좌수 : {Account.account_count}')\n\n # self 값이 없는 메서드 => 클래스 메서드\n # 클래스명.메서드() 접근 가능\n def get_account_num2():\n print(f'총 계좌수 : {Account.account_count}')\n\n # 입금 메서드\n # 입금 금액은 1보다 커야한다.\n # 입금 금액은 잔액(balance)에 누적된다.\n def deposit(self, amount):\n if amount >= 1:\n self.balance += amount\n else:\n print('입금 오류')\n\n # 출금 메서드\n # 잔액에서 출금만큼 금액은 인출되어야 한다.\n # 출금 금액은 잔액보다 작아야한다.\n def withdraw(self, amount):\n if self.balance > amount:\n self.balance -= amount\n else:\n print('출금 오류')\n\n # 계좌 정보 출력 메서드\n def display_info(self):\n print(\"은행이름 : \", self.bank)\n print(\"예금주 : \", self.name)\n print(\"계좌번호 : \", self.account_number)\n print(\"잔고 : \", self.balance)\n\n\n# 인스턴스 생성\n# chio = Account(\"최진수\", 100)\n# print('계좌수는? ', Account.account_count)\n# kim = Account(\"김민수\", 100)\n# print('계좌수는? ', Account.account_count)\n# lee = Account(\"이민수\", 100)\n# print('계좌수는? ', Account.account_count)\n\n# 총 계좌수\n# 마지막으로 생성된 인스턴스.get_account_num()\n# lee.get_account_num()\n# 클래스명.get_account_num()\n# Account.get_account_num2()\n\n\nprint('#'*70)\n# chio = Account(\"최진수\", 100)\n# print('잔액 => ',chio.balance) # 잔액 => 100\n# chio.deposit(100)\n# print('잔액 => ',chio.balance) # 잔액 => 200\n# chio.withdraw(90)\n# print('잔액 => ',chio.balance) # 잔액 => 110\n# chio.deposit(0.5) # 입금 오류\n# chio.withdraw(300) # 출금 오류\n\nchio = Account(\"최진수\", 100)\nchio.display_info()\n","sub_path":"day7/day7_퀴즈_클래스_답2.py","file_name":"day7_퀴즈_클래스_답2.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560558578","text":"# Copyright 2020 Google LLC\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\"\"\" Fermionic Quantum Emulator data class for holding wavefunction data.\n\"\"\"\n#Expanding out simple iterator indexes is unnecessary\n#pylint: disable=invalid-name\n#imports are ungrouped for type hinting\n#pylint: disable=ungrouped-imports\n#numpy.zeros_like initializer is not accepted\n#pylint: disable=unsupported-assignment-operation\n#pylint: disable=too-many-lines\n#pylint: disable=too-many-locals\n#pylint: disable=too-many-branches\n#pylint: disable=too-many-arguments\n#pylint: disable=dangerous-default-value\nimport copy\nimport itertools\nfrom typing import List, Optional, Tuple, Callable, Iterator, \\\n TYPE_CHECKING\n\nimport numpy\nfrom scipy.special import binom\n\nfrom fqe.bitstring import integer_index, get_bit, count_bits_above\nfrom fqe.bitstring import set_bit, unset_bit, reverse_integer_index\nfrom fqe.util import rand_wfn, validate_config\nfrom fqe.fci_graph import FciGraph\nfrom fqe.fci_graph_set import FciGraphSet\nimport fqe.settings\n\nfrom fqe.lib.fqe_data import _lm_apply_array1, _make_dvec_part, \\\n _make_coeff_part, _make_dvec, _make_coeff, _diagonal_coulomb, \\\n _lm_apply_array12_same_spin_opt, _lm_apply_array12_diff_spin_opt, \\\n _apply_array12_lowfillingab, _apply_array12_lowfillingab2, \\\n _apply_array12_lowfillingaa, _apply_array12_lowfillingaa2, \\\n _apply_individual_nbody1_accumulate, _sparse_scale, \\\n _evaluate_map_each, _make_Hcomp, \\\n _sparse_apply_array1, _lm_apply_array1_alpha_column, \\\n _apply_diagonal_inplace, _evolve_diagonal_inplace, _make_nh123, \\\n _apply_diagonal_coulomb\nfrom fqe.lib.linalg import _zimatadd, _transpose\n\nif TYPE_CHECKING:\n from numpy import ndarray as Nparray\n from numpy import dtype as Dtype\n from fqe.fqe_data_set import FqeDataSet\n\n\nclass FqeData:\n \"\"\"This is a basic data structure for use in the FQE.\n \"\"\"\n\n def __init__(self,\n nalpha: int,\n nbeta: int,\n norb: int,\n fcigraph: Optional[FciGraph] = None,\n dtype: 'Dtype' = numpy.complex128) -> None:\n \"\"\"The FqeData structure holds the wavefunction for a particular\n configuration and provides an interace for accessing the data through\n the fcigraph functionality.\n\n Args:\n nalpha (int): the number of alpha electrons\n\n nbeta (int): the number of beta electrons\n\n norb (int): the number of spatial orbitals\n\n fcigraph (optional, FciGraph): the FciGraph to be used. When None, \\\n it is computed here\n\n dtype (optional, Dtype): numpy.dtype of the underlying array\n \"\"\"\n validate_config(nalpha, nbeta, norb)\n\n if not (fcigraph is None) and (nalpha != fcigraph.nalpha() or\n nbeta != fcigraph.nbeta() or\n norb != fcigraph.norb()):\n raise ValueError(\"FciGraph does not match other parameters\")\n\n if fcigraph is None:\n self._core = FciGraph(nalpha, nbeta, norb)\n else:\n self._core = fcigraph\n self._dtype = dtype\n\n if fqe.settings.use_accelerated_code:\n # Use the same C extension for both cases by default\n self._low_thresh = 0.0\n else:\n self._low_thresh = 0.3\n self._nele = self.nalpha() + self.nbeta()\n self._m_s = self.nalpha() - self.nbeta()\n self.coeff = numpy.zeros((self.lena(), self.lenb()), dtype=self._dtype)\n\n def __getitem__(self, key: Tuple[int, int]) -> complex:\n \"\"\"Get an item from the fqe data structure by using the knowles-handy\n pointers.\n\n Args:\n key (Tuple[int, int]): a pair of alpha and beta strings\n\n Returns:\n complex: the value of the corresponding element\n \"\"\"\n return self.coeff[self._core.index_alpha(key[0]),\n self._core.index_beta(key[1])]\n\n def __setitem__(self, key: Tuple[int, int], value: complex) -> None:\n \"\"\"Set an element in the fqe data strucuture\n\n Args:\n key (Tuple[int, int]): a pair of alpha and beta strings\n\n value: the value to be set\n \"\"\"\n self.coeff[self._core.index_alpha(key[0]),\n self._core.index_beta(key[1])] = value\n\n def __deepcopy__(self, memodict={}) -> 'FqeData':\n \"\"\"Construct new FqeData that has the same coefficient\n\n Returns:\n FqeData: an object that is deepcopied from self\n \"\"\"\n new_data = FqeData(nalpha=self.nalpha(),\n nbeta=self.nbeta(),\n norb=self._core.norb(),\n fcigraph=self._core,\n dtype=self._dtype)\n new_data._low_thresh = self._low_thresh\n new_data.coeff = self.coeff.copy()\n return new_data\n\n def get_fcigraph(self) -> 'FciGraph':\n \"\"\"\n Returns the underlying FciGraph object\n\n Returns:\n FciGraph: underlying FciGraph object for this object\n \"\"\"\n return self._core\n\n def apply_diagonal_inplace(self, array: 'Nparray') -> None:\n \"\"\"Iterate over each element and perform apply operation in place\n\n Args:\n array (Nparray): a diagonal operator to be applied to self. The size \\\n of this array is norb or 2*norb depending on the context\n \"\"\"\n beta_ptr = 0\n\n if array.size == 2 * self.norb():\n beta_ptr = self.norb()\n\n elif array.size != self.norb():\n raise ValueError('Non-diagonal array passed'\n ' into apply_diagonal_inplace')\n\n if not array.flags['C_CONTIGUOUS']:\n array = numpy.copy(array)\n\n if fqe.settings.use_accelerated_code:\n aarray = array[:self.norb()]\n barray = array[beta_ptr:]\n _apply_diagonal_inplace(self.coeff, aarray, barray,\n self._core.string_alpha_all(),\n self._core.string_beta_all())\n else:\n alpha = numpy.zeros((self._core.lena(),), dtype=numpy.complex128)\n beta = numpy.zeros((self._core.lenb(),), dtype=numpy.complex128)\n\n for alp_cnf in range(self._core.lena()):\n occupation = self._core.string_alpha(alp_cnf)\n diag_ele = 0.0\n for ind in integer_index(occupation):\n diag_ele += array[ind]\n alpha[alp_cnf] = diag_ele\n for bet_cnf in range(self._core.lenb()):\n occupation = self._core.string_beta(bet_cnf)\n diag_ele = 0.0\n for ind in integer_index(occupation):\n diag_ele += array[beta_ptr + ind]\n beta[bet_cnf] = diag_ele\n\n for alp_cnf in range(self._core.lena()):\n for bet_cnf in range(self._core.lenb()):\n self.coeff[alp_cnf,\n bet_cnf] *= alpha[alp_cnf] + beta[bet_cnf]\n\n def evolve_diagonal(self, array: 'Nparray',\n inplace: bool = False) -> 'Nparray':\n \"\"\"Iterate over each element and return the exponential scaled\n contribution.\n\n Args:\n array (Nparray): a diagonal operator using which time evolution is \\\n performed. The size of this array is norb or 2*norb depending \\\n on the context\n\n inplace (bool): toggle to specify if the result will be stored \\\n in-place or out-of-place\n\n Returns:\n Nparray: the numpy array that contains the result. If inplace is \\\n True, self.coeff is returned.\n \"\"\"\n beta_ptr = 0\n\n if array.size == 2 * self.norb():\n beta_ptr = self.norb()\n\n elif array.size != self.norb():\n raise ValueError('Non-diagonal array passed into evolve_diagonal')\n\n if inplace:\n data = self.coeff\n else:\n data = numpy.copy(self.coeff).astype(numpy.complex128)\n\n if not array.flags['C_CONTIGUOUS']:\n array = numpy.copy(array)\n\n if fqe.settings.use_accelerated_code:\n aarray = array[:self.norb()]\n barray = array[beta_ptr:]\n _evolve_diagonal_inplace(data, aarray, barray,\n self._core.string_alpha_all(),\n self._core.string_beta_all())\n else:\n for alp_cnf in range(self._core.lena()):\n occupation = self._core.string_alpha(alp_cnf)\n diag_ele = 0.0\n for ind in integer_index(self._core.string_alpha(alp_cnf)):\n diag_ele += array[ind]\n\n if diag_ele != 0.0:\n data[alp_cnf, :] *= numpy.exp(diag_ele)\n\n for bet_cnf in range(self._core.lenb()):\n occupation = self._core.string_beta(bet_cnf)\n diag_ele = 0.0\n for ind in integer_index(occupation):\n diag_ele += array[beta_ptr + ind]\n\n if diag_ele:\n data[:, bet_cnf] *= numpy.exp(diag_ele)\n\n return data\n\n def apply_diagonal_coulomb(self,\n diag: 'Nparray',\n array: 'Nparray',\n inplace: bool = False) -> 'Nparray':\n \"\"\"Apply a diagonal Coulomb Hamiltonian represented by the arrays\n and return the resulting coefficient.\n\n Args:\n diag: one-body part of the diagonal elements in the 1-D format\n\n array: two-body part of the diagonal elements in the 2-D format. \\\n The elements correspond to the coefficient for `n_i n_j`\n\n inplace (bool): toggle to specify if the result will be stored \\\n in-place or out-of-place\n\n Returns:\n Nparray: the numpy array that contains the result. If inplace is \\\n True, self.coeff is returned.\n \"\"\"\n if inplace:\n data = self.coeff\n else:\n data = numpy.copy(self.coeff)\n\n if fqe.settings.use_accelerated_code:\n _apply_diagonal_coulomb(data, self._core.string_alpha_all(),\n self._core.string_beta_all(), diag, array,\n self.lena(), self.lenb(), self.nalpha(),\n self.nbeta(), self.norb())\n else:\n alpha = numpy.zeros((self._core.lena(),), dtype=numpy.complex128)\n beta = numpy.zeros((self._core.lenb(),), dtype=numpy.complex128)\n\n for alp_cnf in range(self._core.lena()):\n occupation = self._core.string_alpha(alp_cnf)\n diag_ele = 0.0\n for ind in integer_index(occupation):\n diag_ele += diag[ind]\n for jnd in integer_index(occupation):\n diag_ele += array[ind, jnd]\n alpha[alp_cnf] = diag_ele\n\n for bet_cnf in range(self._core.lenb()):\n occupation = self._core.string_beta(bet_cnf)\n diag_ele = 0.0\n for ind in integer_index(occupation):\n diag_ele += diag[ind]\n for jnd in integer_index(occupation):\n diag_ele += array[ind, jnd]\n beta[bet_cnf] = diag_ele\n\n aarrays = numpy.empty((array.shape[1],), dtype=array.dtype)\n for alp_cnf in range(self._core.lena()):\n aoccs = self._core.string_alpha(alp_cnf)\n aarrays[:] = 0.0\n for ind in integer_index(aoccs):\n aarrays[:] += array[ind, :]\n aarrays[:] += array[:, ind]\n for bet_cnf in range(self._core.lenb()):\n ab = 0.0\n boccs = self._core.string_beta(bet_cnf)\n for jnd in integer_index(boccs):\n ab += aarrays[jnd]\n data[alp_cnf, bet_cnf] *= (ab + alpha[alp_cnf] +\n beta[bet_cnf])\n\n return data\n\n def evolve_diagonal_coulomb(self,\n diag: 'Nparray',\n array: 'Nparray',\n inplace: bool = False) -> 'Nparray':\n \"\"\"Perform time evolution using a diagonal Coulomb Hamiltonian represented\n by the input arrays and return the resulting coefficient.\n\n Args:\n diag: one-body part of the diagonal elements in the 1-D format\n\n array: two-body part of the diagonal elements in the 2-D format. \\\n The elements correspond to the coefficient for `n_i n_j`\n\n inplace (bool): toggle to specify if the result will be stored \\\n in-place or out-of-place\n\n Returns:\n Nparray: the numpy array that contains the result. If inplace is \\\n True, self.coeff is returned.\n \"\"\"\n if inplace:\n data = self.coeff\n else:\n data = numpy.copy(self.coeff)\n\n if fqe.settings.use_accelerated_code:\n _diagonal_coulomb(data, self._core.string_alpha_all(),\n self._core.string_beta_all(), diag, array,\n self.lena(), self.lenb(), self.nalpha(),\n self.nbeta(), self.norb())\n else:\n diagexp = numpy.exp(diag)\n arrayexp = numpy.exp(array)\n\n alpha_occ = numpy.zeros((self.lena(), self.nalpha()), dtype=int)\n alpha_diag = numpy.zeros((self.lena(),), dtype=numpy.complex128)\n for a, astring in enumerate(self._core.string_alpha_all()):\n occ = integer_index(astring)\n alpha_occ[a, :] = occ\n diag_ele = 1.0\n for ind in occ:\n diag_ele *= diagexp[ind]\n for jnd in occ:\n diag_ele *= arrayexp[ind, jnd]\n alpha_diag[a] = diag_ele\n\n beta_occ = numpy.zeros((self.lenb(), self.nbeta()), dtype=int)\n beta_diag = numpy.zeros((self.lenb(),), dtype=numpy.complex128)\n for b, bstring in enumerate(self._core.string_beta_all()):\n occ = integer_index(bstring)\n beta_occ[b, :] = occ\n diag_ele = 1.0\n for ind in occ:\n diag_ele *= diagexp[ind]\n for jnd in occ:\n diag_ele *= arrayexp[ind, jnd]\n beta_diag[b] = diag_ele\n\n aarrays = numpy.empty((array.shape[1],), dtype=array.dtype)\n for a in range(self.lena()):\n aarrays[:] = 1.0\n for ind in alpha_occ[a]:\n aarrays[:] *= arrayexp[ind, :]\n for b in range(self.lenb()):\n diag_ele = 1.0\n for ind in beta_occ[b]:\n diag_ele *= aarrays[ind]\n data[a, b] *= diag_ele * diag_ele * alpha_diag[\n a] * beta_diag[b]\n\n return data\n\n def apply(self, array: Tuple['Nparray']) -> 'FqeData':\n \"\"\"\n API for application of dense operators (1- through 4-body operators) to\n the wavefunction self. The result is stored out of place and returned.\n\n Args:\n array: (Tuple[Nparray]): numpy arrays that represent 1- through 4-body \\\n Hamiltonian elements\n\n Returns:\n FqeData: the FqeData that contains the result of the Hamiltonian application\n \"\"\"\n\n out = copy.deepcopy(self)\n out.apply_inplace(array)\n return out\n\n def apply_inplace(self, array: Tuple['Nparray', ...]) -> None:\n \"\"\"\n API for application of dense operators (1- through 4-body operators) to\n the wavefunction self. The result is stored in-place.\n\n Args:\n array: (Tuple[Nparray]): numpy arrays that represent 1- through 4-body \\\n Hamiltonian elements\n \"\"\"\n\n len_arr = len(array)\n if (len_arr < 1 or len_arr > 4):\n raise ValueError(\"Number of operators in tuple must be \"\n \"between 1 and 4.\")\n\n # Get the first numpy array (i.e. a non-None object) in array\n # and use its dimensions to determine whether we have spatial or spin orbitals\n # Necessary since 1-body operator cam be absent\n array_for_dimensions = next(\n filter(lambda x: isinstance(x, numpy.ndarray), array), False)\n\n if isinstance(array_for_dimensions, bool):\n # this can only be False\n assert (not array_for_dimensions)\n return\n\n spatial = array_for_dimensions.shape[0] == self.norb()\n ## check correct dimensions in case of spin orbitals\n if not spatial and array_for_dimensions.shape[0] != 2 * self.norb():\n raise ValueError(\"Inconsistent number of spin-orbitals in \"\n \"operators and wavefunction.\")\n if len_arr == 1:\n if spatial:\n self.coeff = self._apply_array_spatial1(array[0])\n else:\n self.coeff = self._apply_array_spin1(array[0])\n elif len_arr == 2:\n if spatial:\n self.coeff = self._apply_array_spatial12(array[0], array[1])\n else:\n self.coeff = self._apply_array_spin12(array[0], array[1])\n elif len_arr == 3:\n if spatial:\n self.coeff = self._apply_array_spatial123(\n array[0], array[1], array[2])\n else:\n self.coeff = self._apply_array_spin123(array[0], array[1],\n array[2])\n elif len_arr == 4:\n if spatial:\n self.coeff = self._apply_array_spatial1234(\n array[0], array[1], array[2], array[3])\n else:\n self.coeff = self._apply_array_spin1234(array[0], array[1],\n array[2], array[3])\n\n def _apply_array_spatial1(self, h1e: 'Nparray') -> 'Nparray':\n \"\"\"\n API for application of 1-body spatial operators to the\n wavefunction self. It returns array that corresponds to the\n output wave function data. If h1e only contains a single column,\n it goes to a special code path\n \"\"\"\n assert h1e.shape == (self.norb(), self.norb())\n\n # Check if only one column of h1e is non-zero\n ncol = 0\n jorb = 0\n for j in range(self.norb()):\n if numpy.any(h1e[:, j]):\n ncol += 1\n jorb = j\n if ncol > 1:\n break\n\n def dense_apply_array_spatial1(self, h1e):\n out = numpy.zeros(self.coeff.shape, dtype=self._dtype)\n out_b = numpy.zeros(self.coeff.shape[::-1], dtype=self._dtype)\n cT = numpy.empty(self.coeff.shape[::-1], dtype=self._dtype)\n _transpose(cT, self.coeff)\n\n _lm_apply_array1(self.coeff,\n h1e,\n self._core._dexca,\n self.lena(),\n self.lenb(),\n self.norb(),\n True,\n out=out)\n _lm_apply_array1(cT,\n h1e,\n self._core._dexcb,\n self.lenb(),\n self.lena(),\n self.norb(),\n True,\n out=out_b)\n _zimatadd(out, out_b, 1.)\n return out\n\n if fqe.settings.use_accelerated_code:\n out = dense_apply_array_spatial1(self, h1e)\n else:\n if ncol > 1:\n dvec = self.calculate_dvec_spatial()\n out = numpy.tensordot(h1e, dvec, axes=((0, 1), (0, 1)))\n else:\n dvec = self.calculate_dvec_spatial_fixed_j(jorb)\n out = numpy.tensordot(h1e[:, jorb], dvec, axes=1)\n\n return out\n\n def _apply_array_spin1(self, h1e: 'Nparray') -> 'Nparray':\n \"\"\"\n API for application of 1-body spatial operators to the\n wavefunction self. It returns numpy.ndarray that corresponds to the\n output wave function data.\n \"\"\"\n norb = self.norb()\n assert h1e.shape == (norb * 2, norb * 2)\n\n ncol = 0\n jorb = 0\n for j in range(self.norb() * 2):\n if numpy.any(h1e[:, j]):\n ncol += 1\n jorb = j\n if ncol > 1:\n break\n\n def dense_apply_array_spin1_lm(self, h1e):\n out = _lm_apply_array1(self.coeff, h1e[:norb, :norb],\n self._core._dexca, self.lena(), self.lenb(),\n self.norb(), True)\n _lm_apply_array1(self.coeff,\n h1e[norb:, norb:],\n self._core._dexcb,\n self.lena(),\n self.lenb(),\n self.norb(),\n False,\n out=out)\n return out\n\n if fqe.settings.use_accelerated_code:\n out = dense_apply_array_spin1_lm(self, h1e)\n else:\n if ncol > 1:\n (dveca, dvecb) = self.calculate_dvec_spin()\n out = numpy.tensordot(h1e[:norb, :norb], dveca) \\\n + numpy.tensordot(h1e[norb:, norb:], dvecb)\n else:\n dvec = self.calculate_dvec_spin_fixed_j(jorb)\n if jorb < norb:\n h1eview = h1e[:norb, jorb]\n else:\n h1eview = h1e[norb:, jorb]\n out = numpy.tensordot(h1eview, dvec, axes=1)\n\n return out\n\n def _apply_array_spatial12(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n API for application of 1- and 2-body spatial operators to the\n wavefunction self. It returns numpy.ndarray that corresponds to the\n output wave function data. Depending on the filling, it automatically\n chooses an efficient code.\n \"\"\"\n norb = self.norb()\n assert h1e.shape == (norb, norb)\n assert h2e.shape == (norb, norb, norb, norb)\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n\n thresh = self._low_thresh\n if nalpha < norb * thresh and nbeta < norb * thresh:\n graphset = FciGraphSet(2, 2)\n graphset.append(self._core)\n if nalpha - 2 >= 0:\n graphset.append(FciGraph(nalpha - 2, nbeta, norb))\n if nalpha - 1 >= 0 and nbeta - 1 >= 0:\n graphset.append(FciGraph(nalpha - 1, nbeta - 1, norb))\n if nbeta - 2 >= 0:\n graphset.append(FciGraph(nalpha, nbeta - 2, norb))\n return self._apply_array_spatial12_lowfilling(h1e, h2e)\n\n return self._apply_array_spatial12_halffilling(h1e, h2e)\n\n def _apply_array_spin12(self, h1e: 'Nparray', h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n API for application of 1- and 2-body spin-orbital operators to the\n wavefunction self. It returns numpy.ndarray that corresponds to the\n output wave function data. Depending on the filling, it automatically\n chooses an efficient code.\n \"\"\"\n norb = self.norb()\n assert h1e.shape == (norb * 2, norb * 2)\n assert h2e.shape == (norb * 2, norb * 2, norb * 2, norb * 2)\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n\n thresh = self._low_thresh\n if nalpha < norb * thresh and nbeta < norb * thresh:\n graphset = FciGraphSet(2, 2)\n graphset.append(self._core)\n if nalpha - 2 >= 0:\n graphset.append(FciGraph(nalpha - 2, nbeta, norb))\n if nalpha - 1 >= 0 and nbeta - 1 >= 0:\n graphset.append(FciGraph(nalpha - 1, nbeta - 1, norb))\n if nbeta - 2 >= 0:\n graphset.append(FciGraph(nalpha, nbeta - 2, norb))\n return self._apply_array_spin12_lowfilling(h1e, h2e)\n\n return self._apply_array_spin12_halffilling(h1e, h2e)\n\n def _apply_array_spatial12_halffilling(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Standard code to calculate application of 1- and 2-body spatial\n operators to the wavefunction self. It returns numpy.ndarray that\n corresponds to the output wave function data.\n \"\"\"\n if fqe.settings.use_accelerated_code:\n return self._apply_array_spatial12_lm(h1e, h2e)\n else:\n h1e = copy.deepcopy(h1e)\n h2e = numpy.moveaxis(copy.deepcopy(h2e), 1, 2) * (-1.0)\n norb = self.norb()\n for k in range(norb):\n h1e[:, :] -= h2e[:, k, k, :]\n\n if numpy.iscomplex(h1e).any() or numpy.iscomplex(h2e).any():\n dvec = self.calculate_dvec_spatial()\n out = numpy.einsum(\"ij,ijkl->kl\", h1e, dvec)\n dvec = numpy.einsum(\"ijkl,klmn->ijmn\", h2e, dvec)\n out += self._calculate_coeff_spatial_with_dvec(dvec)\n else:\n nij = norb * (norb + 1) // 2\n h1ec = numpy.zeros((nij), dtype=self._dtype)\n h2ec = numpy.zeros((nij, nij), dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1):\n ijn = j + i * (i + 1) // 2\n h1ec[ijn] = h1e[i, j]\n for k in range(norb):\n for l in range(k + 1):\n kln = l + k * (k + 1) // 2\n h2ec[ijn, kln] = h2e[i, j, k, l]\n dvec = self._calculate_dvec_spatial_compressed()\n out = numpy.einsum(\"i,ikl->kl\", h1ec, dvec)\n dvec = numpy.einsum(\"ik,kmn->imn\", h2ec, dvec)\n for i in range(self.norb()):\n for j in range(self.norb()):\n ijn = min(i, j) + max(i, j) * (max(i, j) + 1) // 2\n work = self._core.alpha_map(j, i)\n for source, target, parity in work:\n out[source, :] += dvec[ijn, target, :] * parity\n work = self._core.beta_map(j, i)\n for source, target, parity in work:\n out[:, source] += dvec[ijn, :, target] * parity\n\n return out\n\n def _apply_array_spatial12_lm(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-memory version to apply_array_spatial12.\n No construction of dvec.\n \"\"\"\n h1e = copy.deepcopy(h1e)\n h2e = numpy.moveaxis(copy.deepcopy(h2e), 1, 2) * (-1.0)\n h1e -= numpy.einsum('ikkj->ij', h2e)\n\n out = _lm_apply_array12_same_spin_opt(self.coeff, h1e, h2e,\n self._core._dexca, self.lena(),\n self.lenb(), self.norb())\n out += _lm_apply_array12_same_spin_opt(self.coeff.T, h1e, h2e,\n self._core._dexcb, self.lenb(),\n self.lena(), self.norb()).T\n\n _lm_apply_array12_diff_spin_opt(self.coeff,\n h2e + numpy.einsum('ijkl->klij', h2e),\n self._core._dexca,\n self._core._dexcb,\n self.lena(),\n self.lenb(),\n self.norb(),\n out=out)\n return out\n\n def _apply_array_spin12_halffilling(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Standard code to calculate application of 1- and 2-body spin-orbital\n operators to the wavefunction self. It returns numpy.ndarray that\n corresponds to the output wave function data.\n \"\"\"\n if fqe.settings.use_accelerated_code:\n #return self._apply_array_spin12_blocked(h1e, h2e)\n return self._apply_array_spin12_lm(h1e, h2e)\n else:\n h1e = copy.deepcopy(h1e)\n h2e = numpy.moveaxis(copy.deepcopy(h2e), 1, 2) * (-1.0)\n norb = self.norb()\n for k in range(norb * 2):\n h1e[:, :] -= h2e[:, k, k, :]\n\n (dveca, dvecb) = self.calculate_dvec_spin()\n out = numpy.einsum(\"ij,ijkl->kl\", h1e[:norb, :norb], dveca) \\\n + numpy.einsum(\"ij,ijkl->kl\", h1e[norb:, norb:], dvecb)\n ndveca = numpy.einsum(\"ijkl,klmn->ijmn\",\n h2e[:norb, :norb, :norb, :norb], dveca) \\\n + numpy.einsum(\"ijkl,klmn->ijmn\",\n h2e[:norb, :norb, norb:, norb:], dvecb)\n ndvecb = numpy.einsum(\"ijkl,klmn->ijmn\",\n h2e[norb:, norb:, :norb, :norb], dveca) \\\n + numpy.einsum(\"ijkl,klmn->ijmn\",\n h2e[norb:, norb:, norb:, norb:], dvecb)\n out += self._calculate_coeff_spin_with_dvec((ndveca, ndvecb))\n return out\n\n def _apply_array_spin12_lm(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-memory version to apply_array_spin12.\n No construction of dvec.\n \"\"\"\n h1e = copy.deepcopy(h1e)\n h2e = numpy.moveaxis(copy.deepcopy(h2e), 1, 2) * (-1.0)\n norb = self.norb()\n h1e -= numpy.einsum('ikkj->ij', h2e)\n\n out = _lm_apply_array12_same_spin_opt(self.coeff, h1e[:norb, :norb],\n h2e[:norb, :norb, :norb, :norb],\n self._core._dexca, self.lena(),\n self.lenb(), self.norb())\n out += _lm_apply_array12_same_spin_opt(self.coeff.T, h1e[norb:, norb:],\n h2e[norb:, norb:, norb:, norb:],\n self._core._dexcb, self.lenb(),\n self.lena(), self.norb()).T\n\n h2e_c = h2e[:norb, :norb, norb:, norb:] \\\n + numpy.einsum('ijkl->klij', h2e[norb:, norb:, :norb, :norb])\n _lm_apply_array12_diff_spin_opt(self.coeff,\n h2e_c,\n self._core._dexca,\n self._core._dexcb,\n self.lena(),\n self.lenb(),\n self.norb(),\n out=out)\n return out\n\n def _apply_array_spatial12_lowfilling(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-filling specialization of the code to calculate application of\n 1- and 2-body spatial operators to the wavefunction self. It returns\n numpy.ndarray that corresponds to the output wave function data.\n Wrapper to distinguish between C and Python functions\n \"\"\"\n if fqe.settings.use_accelerated_code:\n return self._apply_array_spatial12_lowfilling_fast(h1e, h2e)\n else:\n return self._apply_array_spatial12_lowfilling_python(h1e, h2e)\n\n def _apply_array_spatial12_lowfilling_fast(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-filling specialization of the code to calculate application of\n 1- and 2-body spatial operators to the wavefunction self. It returns\n numpy.ndarray that corresponds to the output wave function data.\n \"\"\"\n out = self._apply_array_spatial1(h1e)\n\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n lena = self.lena()\n lenb = self.lenb()\n nlt = norb * (norb + 1) // 2\n\n h2ecomp = numpy.zeros((nlt, nlt), dtype=self._dtype)\n h2etemp = numpy.ascontiguousarray(h2e)\n _make_Hcomp(norb, nlt, h2etemp, h2ecomp)\n\n if nalpha - 2 >= 0:\n alpha_map, _ = self._core.find_mapping(-2, 0)\n alpha_array = self._to_array1(alpha_map, norb)\n intermediate = numpy.zeros(\n (nlt, int(binom(norb, nalpha - 2)), lenb), dtype=self._dtype)\n _apply_array12_lowfillingaa(self.coeff, alpha_array, intermediate)\n\n intermediate = numpy.tensordot(h2ecomp, intermediate, axes=1)\n\n _apply_array12_lowfillingaa2(intermediate, alpha_array, out)\n\n if self.nalpha() - 1 >= 0 and self.nbeta() - 1 >= 0:\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n nastates = int(binom(norb, nalpha - 1))\n nbstates = int(binom(norb, nbeta - 1))\n intermediate = numpy.zeros((norb, norb, nastates, nbstates),\n dtype=self._dtype)\n\n alpha_array = self._to_array2(alpha_map, norb)\n beta_array = self._to_array2(beta_map, norb)\n _apply_array12_lowfillingab(self.coeff, alpha_array, beta_array,\n nalpha, nbeta, intermediate)\n intermediate = numpy.tensordot(h2e, intermediate, axes=2)\n _apply_array12_lowfillingab2(alpha_array, beta_array, nalpha, nbeta,\n intermediate, out)\n\n if self.nbeta() - 2 >= 0:\n _, beta_map = self._core.find_mapping(0, -2)\n beta_array = self._to_array1(beta_map, norb)\n intermediate = numpy.zeros((nlt, lena, int(binom(norb, nbeta - 2))),\n dtype=self._dtype)\n _apply_array12_lowfillingaa(self.coeff,\n beta_array,\n intermediate,\n alpha=False)\n\n intermediate = numpy.tensordot(h2ecomp, intermediate, axes=1)\n\n _apply_array12_lowfillingaa2(intermediate,\n beta_array,\n out,\n alpha=False)\n return out\n\n def _to_array1(self, maps, norb):\n \"\"\"Convert maps to arrays for passing to C code\n \"\"\"\n nstate = len(maps[(0, 1)])\n nlt = norb * (norb + 1) // 2\n arrays = numpy.zeros((nlt, nstate, 3), dtype=numpy.int32)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for k, data in enumerate(maps[(i, j)]):\n arrays[ijn, k, 0] = data[0]\n arrays[ijn, k, 1] = data[1]\n arrays[ijn, k, 2] = data[2]\n return arrays\n\n def _to_array2(self, maps, norb):\n \"\"\"Convert maps to arrays for passing to C code\n \"\"\"\n nstate = len(maps[(0,)])\n arrays = numpy.zeros((norb, nstate, 3), dtype=numpy.int32)\n for i in range(norb):\n for k, data in enumerate(maps[(i,)]):\n arrays[i, k, 0] = data[0]\n arrays[i, k, 1] = data[1]\n arrays[i, k, 2] = data[2]\n return arrays\n\n def _apply_array_spatial12_lowfilling_python(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-filling specialization of the code to calculate application of\n 1- and 2-body spatial operators to the wavefunction self. It returns\n numpy.ndarray that corresponds to the output wave function data.\n Python version\n \"\"\"\n out = self._apply_array_spatial1(h1e)\n\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n lena = self.lena()\n lenb = self.lenb()\n nlt = norb * (norb + 1) // 2\n\n h2ecomp = numpy.zeros((nlt, nlt), dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for k in range(norb):\n for l in range(k + 1, norb):\n h2ecomp[ijn, k + l * (l + 1) // 2] = (h2e[i, j, k, l] -\n h2e[i, j, l, k] -\n h2e[j, i, k, l] +\n h2e[j, i, l, k])\n\n if nalpha - 2 >= 0:\n alpha_map, _ = self._core.find_mapping(-2, 0)\n intermediate = numpy.zeros(\n (nlt, int(binom(norb, nalpha - 2)), lenb), dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, parity in alpha_map[(i, j)]:\n work = self.coeff[source, :] * parity\n intermediate[ijn, target, :] += work\n\n intermediate = numpy.tensordot(h2ecomp, intermediate, axes=1)\n\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, parity in alpha_map[(i, j)]:\n out[source, :] -= intermediate[ijn, target, :] * parity\n\n if self.nalpha() - 1 >= 0 and self.nbeta() - 1 >= 0:\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n intermediate = numpy.zeros((norb, norb, int(binom(\n norb, nalpha - 1)), int(binom(norb, nbeta - 1))),\n dtype=self._dtype)\n\n for i in range(norb):\n for j in range(norb):\n for sourcea, targeta, paritya in alpha_map[(i,)]:\n sign = ((-1)**(nalpha - 1)) * paritya\n for sourceb, targetb, parityb in beta_map[(j,)]:\n work = self.coeff[sourcea, sourceb] * sign * parityb\n intermediate[i, j, targeta, targetb] += 2 * work\n\n intermediate = numpy.tensordot(h2e, intermediate, axes=2)\n\n for i in range(norb):\n for j in range(norb):\n for sourcea, targeta, paritya in alpha_map[(i,)]:\n sign = ((-1)**nalpha) * paritya\n for sourceb, targetb, parityb in beta_map[(j,)]:\n work = intermediate[i, j, targeta, targetb] * sign\n out[sourcea, sourceb] += work * parityb\n\n if self.nbeta() - 2 >= 0:\n _, beta_map = self._core.find_mapping(0, -2)\n intermediate = numpy.zeros((nlt, lena, int(binom(norb, nbeta - 2))),\n dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, parity in beta_map[(i, j)]:\n work = self.coeff[:, source] * parity\n intermediate[ijn, :, target] += work\n\n intermediate = numpy.tensordot(h2ecomp, intermediate, axes=1)\n\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, sign in beta_map[(min(i, j), max(i,\n j))]:\n out[:, source] -= intermediate[ijn, :, target] * sign\n return out\n\n def _apply_array_spin12_lowfilling(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-filling specialization of the code to calculate application of\n 1- and 2-body spin-orbital operators to the wavefunction self. It\n returns numpy.ndarray that corresponds to the output wave function data.\n \"\"\"\n if fqe.settings.use_accelerated_code:\n return self._apply_array_spin12_lowfilling_fast(h1e, h2e)\n else:\n return self._apply_array_spin12_lowfilling_python(h1e, h2e)\n\n def _apply_array_spin12_lowfilling_fast(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-filling specialization of the code to calculate application of\n 1- and 2-body spin-orbital operators to the wavefunction self. It\n returns numpy.ndarray that corresponds to the output wave function data.\n Accelerated C version\n \"\"\"\n out = self._apply_array_spin1(h1e)\n\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n lena = self.lena()\n lenb = self.lenb()\n nlt = norb * (norb + 1) // 2\n\n h2ecompa = numpy.zeros((nlt, nlt), dtype=self._dtype)\n h2ecompb = numpy.zeros((nlt, nlt), dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for k in range(norb):\n for l in range(k + 1, norb):\n kln = k + l * (l + 1) // 2\n h2ecompa[ijn, kln] = (h2e[i, j, k, l] -\n h2e[i, j, l, k] -\n h2e[j, i, k, l] + h2e[j, i, l, k])\n ino = i + norb\n jno = j + norb\n kno = k + norb\n lno = l + norb\n h2ecompb[ijn, kln] = (h2e[ino, jno, kno, lno] -\n h2e[ino, jno, lno, kno] -\n h2e[jno, ino, kno, lno] +\n h2e[jno, ino, lno, kno])\n\n if nalpha - 2 >= 0:\n alpha_map, _ = self._core.find_mapping(-2, 0)\n alpha_array = self._to_array1(alpha_map, norb)\n intermediate = numpy.zeros(\n (nlt, int(binom(norb, nalpha - 2)), lenb), dtype=self._dtype)\n _apply_array12_lowfillingaa(self.coeff, alpha_array, intermediate)\n\n intermediate = numpy.tensordot(h2ecompa, intermediate, axes=1)\n _apply_array12_lowfillingaa2(intermediate, alpha_array, out)\n\n if self.nalpha() - 1 >= 0 and self.nbeta() - 1 >= 0:\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n intermediate = numpy.zeros((norb, norb, int(binom(\n norb, nalpha - 1)), int(binom(norb, nbeta - 1))),\n dtype=self._dtype)\n\n alpha_array = self._to_array2(alpha_map, norb)\n beta_array = self._to_array2(beta_map, norb)\n _apply_array12_lowfillingab(self.coeff, alpha_array, beta_array,\n nalpha, nbeta, intermediate)\n intermediate = numpy.tensordot(h2e[:norb, norb:, :norb, norb:],\n intermediate,\n axes=2)\n _apply_array12_lowfillingab2(alpha_array, beta_array, nalpha, nbeta,\n intermediate, out)\n\n if self.nbeta() - 2 >= 0:\n _, beta_map = self._core.find_mapping(0, -2)\n beta_array = self._to_array1(beta_map, norb)\n intermediate = numpy.zeros((nlt, lena, int(binom(norb, nbeta - 2))),\n dtype=self._dtype)\n _apply_array12_lowfillingaa(self.coeff,\n beta_array,\n intermediate,\n alpha=False)\n\n intermediate = numpy.tensordot(h2ecompb, intermediate, axes=1)\n _apply_array12_lowfillingaa2(intermediate,\n beta_array,\n out,\n alpha=False)\n return out\n\n def _apply_array_spin12_lowfilling_python(self, h1e: 'Nparray',\n h2e: 'Nparray') -> 'Nparray':\n \"\"\"\n Low-filling specialization of the code to calculate application of\n 1- and 2-body spin-orbital operators to the wavefunction self. It\n returns numpy.ndarray that corresponds to the output wave function data.\n Python version\n \"\"\"\n out = self._apply_array_spin1(h1e)\n\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n lena = self.lena()\n lenb = self.lenb()\n nlt = norb * (norb + 1) // 2\n\n h2ecompa = numpy.zeros((nlt, nlt), dtype=self._dtype)\n h2ecompb = numpy.zeros((nlt, nlt), dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for k in range(norb):\n for l in range(k + 1, norb):\n kln = k + l * (l + 1) // 2\n h2ecompa[ijn, kln] = (h2e[i, j, k, l] -\n h2e[i, j, l, k] -\n h2e[j, i, k, l] + h2e[j, i, l, k])\n ino = i + norb\n jno = j + norb\n kno = k + norb\n lno = l + norb\n h2ecompb[ijn, kln] = (h2e[ino, jno, kno, lno] -\n h2e[ino, jno, lno, kno] -\n h2e[jno, ino, kno, lno] +\n h2e[jno, ino, lno, kno])\n\n if nalpha - 2 >= 0:\n alpha_map, _ = self._core.find_mapping(-2, 0)\n intermediate = numpy.zeros(\n (nlt, int(binom(norb, nalpha - 2)), lenb), dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, parity in alpha_map[(i, j)]:\n work = self.coeff[source, :] * parity\n intermediate[ijn, target, :] += work\n\n intermediate = numpy.tensordot(h2ecompa, intermediate, axes=1)\n\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, parity in alpha_map[(i, j)]:\n out[source, :] -= intermediate[ijn, target, :] * parity\n\n if self.nalpha() - 1 >= 0 and self.nbeta() - 1 >= 0:\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n intermediate = numpy.zeros((norb, norb, int(binom(\n norb, nalpha - 1)), int(binom(norb, nbeta - 1))),\n dtype=self._dtype)\n\n for i in range(norb):\n for j in range(norb):\n for sourcea, targeta, paritya in alpha_map[(i,)]:\n sign = ((-1)**(nalpha - 1)) * paritya\n for sourceb, targetb, parityb in beta_map[(j,)]:\n work = self.coeff[sourcea, sourceb] * sign * parityb\n intermediate[i, j, targeta, targetb] += 2 * work\n\n intermediate = numpy.tensordot(h2e[:norb, norb:, :norb, norb:],\n intermediate,\n axes=2)\n\n for i in range(norb):\n for j in range(norb):\n for sourcea, targeta, paritya in alpha_map[(i,)]:\n paritya *= (-1)**nalpha\n for sourceb, targetb, parityb in beta_map[(j,)]:\n work = intermediate[i, j, targeta, targetb]\n out[sourcea, sourceb] += work * paritya * parityb\n\n if self.nbeta() - 2 >= 0:\n _, beta_map = self._core.find_mapping(0, -2)\n intermediate = numpy.zeros((nlt, lena, int(binom(norb, nbeta - 2))),\n dtype=self._dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, parity in beta_map[(i, j)]:\n work = self.coeff[:, source] * parity\n intermediate[ijn, :, target] += work\n\n intermediate = numpy.tensordot(h2ecompb, intermediate, axes=1)\n\n for i in range(norb):\n for j in range(i + 1, norb):\n ijn = i + j * (j + 1) // 2\n for source, target, sign in beta_map[(min(i, j), max(i,\n j))]:\n out[:, source] -= intermediate[ijn, :, target] * sign\n return out\n\n def _apply_array_spatial123(self,\n h1e: Optional['Nparray'],\n h2e: Optional['Nparray'],\n h3e: 'Nparray',\n dvec: Optional['Nparray'] = None,\n evec: Optional['Nparray'] = None) -> 'Nparray':\n \"\"\"\n Code to calculate application of 1- through 3-body spatial operators to\n the wavefunction self. It returns numpy.ndarray that corresponds to the\n output wave function data.\n \"\"\"\n norb = self.norb()\n assert h3e.shape == (norb, norb, norb, norb, norb, norb)\n\n out = None\n if h1e is not None and h2e is not None:\n nh1e = numpy.copy(h1e)\n nh2e = numpy.copy(h2e)\n\n for i in range(norb):\n for j in range(norb):\n for k in range(norb):\n nh2e[j, k, :, :] += (-h3e[k, j, i, i, :, :] -\n h3e[j, i, k, i, :, :] -\n h3e[j, k, i, :, i, :])\n nh1e[:, :] += h3e[:, i, j, i, j, :]\n\n out = self._apply_array_spatial12_halffilling(nh1e, nh2e)\n\n if dvec is None:\n odvec = self.calculate_dvec_spatial()\n else:\n odvec = dvec\n\n if evec is None:\n dvec = numpy.zeros_like(odvec)\n for i in range(norb):\n for j in range(norb):\n tmp = odvec[i, j, :, :]\n tmp2 = self._calculate_dvec_spatial_with_coeff(tmp)\n dvec += numpy.tensordot(h3e[:, :, i, :, :, j],\n tmp2,\n axes=((1, 3), (0, 1)))\n else:\n dvec = numpy.tensordot(h3e, evec, axes=((1, 4, 2, 5), (0, 1, 2, 3)))\n\n if out is not None:\n out -= self._calculate_coeff_spatial_with_dvec(dvec)\n else:\n out = -self._calculate_coeff_spatial_with_dvec(dvec)\n return out\n\n def _apply_array_spin123(self,\n h1e: 'Nparray',\n h2e: 'Nparray',\n h3e: 'Nparray',\n dvec: Optional[Tuple['Nparray', 'Nparray']] = None,\n evec: Optional[Tuple['Nparray', 'Nparray', 'Nparray', 'Nparray']] \\\n = None) -> 'Nparray':\n \"\"\"\n Code to calculate application of 1- through 3-body spin-orbital\n operators to the wavefunction self. It returns numpy.ndarray that\n corresponds to the output wave function data.\n \"\"\"\n norb = self.norb()\n assert h3e.shape == (norb * 2,) * 6\n assert not (dvec is None) ^ (evec is None)\n\n from1234 = (dvec is not None) and (evec is not None)\n\n nh1e = numpy.copy(h1e)\n nh2e = numpy.copy(h2e)\n\n for i in range(norb * 2):\n for j in range(norb * 2):\n for k in range(norb * 2):\n nh2e[j, k, :, :] += (-h3e[k, j, i, i, :, :] -\n h3e[j, i, k, i, :, :] -\n h3e[j, k, i, :, i, :])\n\n nh1e[:, :] += h3e[:, i, j, i, j, :]\n\n out = self._apply_array_spin12_halffilling(nh1e, nh2e)\n\n n = norb # This is just shorter\n if not from1234:\n symfac = 2.0\n axes = ((1, 3), (0, 1))\n (odveca, odvecb) = self.calculate_dvec_spin()\n dveca = numpy.zeros_like(odveca)\n dvecb = numpy.zeros_like(odvecb)\n\n for i in range(norb):\n for j in range(norb):\n evecaa, _ = self._calculate_dvec_spin_with_coeff(\n odveca[i, j, :, :])\n evecab, evecbb = self._calculate_dvec_spin_with_coeff(\n odvecb[i, j, :, :])\n\n dveca += numpy.tensordot(h3e[:n, :n, i, :n, :n, j],\n evecaa,\n axes=axes)\n dveca += numpy.tensordot(h3e[:n, :n, n + i, :n, :n, n + j],\n evecab,\n axes=axes) * symfac\n dveca += numpy.tensordot(h3e[:n, n:, n + i, :n, n:, n + j],\n evecbb,\n axes=axes)\n\n dvecb += numpy.tensordot(h3e[n:, :n, i, n:, :n, j],\n evecaa,\n axes=axes)\n dvecb += numpy.tensordot(h3e[n:, :n, n + i, n:, :n, n + j],\n evecab,\n axes=axes) * symfac\n dvecb += numpy.tensordot(h3e[:n, n:, n + i, :n, n:, n + j],\n evecbb,\n axes=axes)\n else:\n symfac = 1.0\n axes = ((1, 4, 2, 5), (0, 1, 2, 3)) # type: ignore\n dveca, dvecb = dvec # type: ignore\n evecaa, evecab, evecba, evecbb = evec # type: ignore\n\n dveca = numpy.tensordot(h3e[:n, :n, :n, :n, :n, :n],\n evecaa, axes=axes) \\\n + numpy.tensordot(h3e[:n, :n, n:, :n, :n, n:],\n evecab, axes=axes) * symfac \\\n + numpy.tensordot(h3e[:n, n:, n:, :n, n:, n:],\n evecbb, axes=axes) + \\\n + numpy.tensordot(h3e[:n, n:, :n, :n, n:, :n],\n evecba, axes=axes)\n\n dvecb = numpy.tensordot(h3e[n:, :n, :n, n:, :n, :n],\n evecaa, axes=axes) \\\n + numpy.tensordot(h3e[n:, :n, n:, n:, :n, n:],\n evecab, axes=axes) * symfac \\\n + numpy.tensordot(h3e[n:, n:, n:, n:, n:, n:],\n evecbb, axes=axes) + \\\n + numpy.tensordot(h3e[n:, n:, :n, n:, n:, :n],\n evecba, axes=axes)\n\n out -= self._calculate_coeff_spin_with_dvec((dveca, dvecb))\n return out\n\n def _apply_array_spatial1234(self, h1e: 'Nparray', h2e: 'Nparray',\n h3e: 'Nparray', h4e: 'Nparray') -> 'Nparray':\n \"\"\"\n Code to calculate application of 1- through 4-body spatial operators to\n the wavefunction self. It returns numpy.ndarray that corresponds to the\n output wave function data.\n \"\"\"\n norb = self.norb()\n assert h4e.shape == (norb, norb, norb, norb, norb, norb, norb, norb)\n lena = self.lena()\n lenb = self.lenb()\n\n nh1e = numpy.copy(h1e)\n nh2e = numpy.copy(h2e)\n nh3e = numpy.copy(h3e)\n\n for i in range(norb):\n for j in range(norb):\n for k in range(norb):\n nh1e[:, :] -= h4e[:, j, i, k, j, i, k, :]\n for l in range(norb):\n nh2e[i, j, :, :] += (h4e[j, l, i, k, l, k, :, :] +\n h4e[i, j, l, k, l, k, :, :] +\n h4e[i, l, k, j, l, k, :, :] +\n h4e[j, i, k, l, l, k, :, :] +\n h4e[i, k, j, l, k, :, l, :] +\n h4e[j, i, k, l, k, :, l, :] +\n h4e[i, j, k, l, :, k, l, :])\n nh3e[i, j, k, :, :, :] += (h4e[k, i, j, l, l, :, :, :] +\n h4e[j, i, l, k, l, :, :, :] +\n h4e[i, l, j, k, l, :, :, :] +\n h4e[i, k, j, l, :, l, :, :] +\n h4e[i, j, l, k, :, l, :, :] +\n h4e[i, j, k, l, :, :, l, :])\n\n dvec = self.calculate_dvec_spatial()\n evec = numpy.zeros((norb, norb, norb, norb, lena, lenb),\n dtype=self._dtype)\n\n for i in range(norb):\n for j in range(norb):\n tmp = dvec[i, j, :, :]\n tmp2 = self._calculate_dvec_spatial_with_coeff(tmp)\n evec[:, :, i, j, :, :] = tmp2[:, :, :, :]\n\n out = self._apply_array_spatial123(nh1e, nh2e, nh3e, dvec, evec)\n\n evec = numpy.transpose(numpy.tensordot(h4e,\n evec,\n axes=((2, 6, 3, 7), (0, 1, 2,\n 3))),\n axes=[0, 2, 1, 3, 4, 5])\n\n dvec2 = numpy.zeros(dvec.shape, dtype=self._dtype)\n for i in range(norb):\n for j in range(norb):\n dvec[:, :, :, :] = evec[i, j, :, :, :, :]\n cvec = self._calculate_coeff_spatial_with_dvec(dvec)\n dvec2[i, j, :, :] += cvec[:, :]\n\n out += self._calculate_coeff_spatial_with_dvec(dvec2)\n return out\n\n def _apply_array_spin1234(self, h1e: 'Nparray', h2e: 'Nparray',\n h3e: 'Nparray', h4e: 'Nparray') -> 'Nparray':\n \"\"\"\n Code to calculate application of 1- through 4-body spin-orbital\n operators to the wavefunction self. It returns numpy.ndarray that\n corresponds to the output wave function data.\n \"\"\"\n norb = self.norb()\n tno = 2 * norb\n assert h4e.shape == (tno, tno, tno, tno, tno, tno, tno, tno)\n lena = self.lena()\n lenb = self.lenb()\n\n nh1e = numpy.copy(h1e)\n nh2e = numpy.copy(h2e)\n nh3e = numpy.copy(h3e)\n\n if fqe.settings.use_accelerated_code:\n _make_nh123(norb, h4e, nh1e, nh2e, nh3e)\n else:\n for i in range(norb * 2):\n for j in range(norb * 2):\n for k in range(norb * 2):\n nh1e[:, :] -= h4e[:, j, i, k, j, i, k, :]\n for l in range(norb * 2):\n nh2e[i, j, :, :] += (h4e[j, l, i, k, l, k, :, :] +\n h4e[i, j, l, k, l, k, :, :] +\n h4e[i, l, k, j, l, k, :, :] +\n h4e[j, i, k, l, l, k, :, :] +\n h4e[i, k, j, l, k, :, l, :] +\n h4e[j, i, k, l, k, :, l, :] +\n h4e[i, j, k, l, :, k, l, :])\n nh3e[i, j, k, :, :, :] += (\n h4e[k, i, j, l, l, :, :, :] +\n h4e[j, i, l, k, l, :, :, :] +\n h4e[i, l, j, k, l, :, :, :] +\n h4e[i, k, j, l, :, l, :, :] +\n h4e[i, j, l, k, :, l, :, :] +\n h4e[i, j, k, l, :, :, l, :])\n\n (dveca, dvecb) = self.calculate_dvec_spin()\n evecaa = numpy.zeros((norb, norb, norb, norb, lena, lenb),\n dtype=self._dtype)\n evecab = numpy.zeros((norb, norb, norb, norb, lena, lenb),\n dtype=self._dtype)\n evecba = numpy.zeros((norb, norb, norb, norb, lena, lenb),\n dtype=self._dtype)\n evecbb = numpy.zeros((norb, norb, norb, norb, lena, lenb),\n dtype=self._dtype)\n for i in range(norb):\n for j in range(norb):\n tmp = self._calculate_dvec_spin_with_coeff(dveca[i, j, :, :])\n evecaa[:, :, i, j, :, :] = tmp[0][:, :, :, :]\n evecba[:, :, i, j, :, :] = tmp[1][:, :, :, :]\n\n tmp = self._calculate_dvec_spin_with_coeff(dvecb[i, j, :, :])\n evecab[:, :, i, j, :, :] = tmp[0][:, :, :, :]\n evecbb[:, :, i, j, :, :] = tmp[1][:, :, :, :]\n\n out = self._apply_array_spin123(nh1e, nh2e, nh3e, (dveca, dvecb),\n (evecaa, evecab, evecba, evecbb))\n\n def ncon(A, B):\n \"\"\"Tensor contraction and transposition corresponding with\n einsum 'ikmojlnp,mnopxy->ijklxy'\n \"\"\"\n return numpy.transpose(numpy.tensordot(A,\n B,\n axes=((2, 6, 3, 7), (0, 1, 2,\n 3))),\n axes=(0, 2, 1, 3, 4, 5))\n\n n = norb # shorter\n nevecaa = ncon(h4e[:n, :n, :n, :n, :n, :n, :n, :n], evecaa) \\\n + 2.0 * ncon(h4e[:n, :n, :n, n:, :n, :n, :n, n:], evecab) \\\n + ncon(h4e[:n, :n, n:, n:, :n, :n, n:, n:], evecbb)\n\n nevecab = ncon(h4e[:n, n:, :n, :n, :n, n:, :n, :n], evecaa) \\\n + 2.0 * ncon(h4e[:n, n:, :n, n:, :n, n:, :n, n:], evecab) \\\n + ncon(h4e[:n, n:, n:, n:, :n, n:, n:, n:], evecbb)\n\n nevecbb = ncon(h4e[n:, n:, :n, :n, n:, n:, :n, :n], evecaa) \\\n + 2.0 * ncon(h4e[n:, n:, :n, n:, n:, n:, :n, n:], evecab) \\\n + ncon(h4e[n:, n:, n:, n:, n:, n:, n:, n:], evecbb)\n\n dveca2 = numpy.zeros(dveca.shape, dtype=self._dtype)\n dvecb2 = numpy.zeros(dvecb.shape, dtype=self._dtype)\n for i in range(norb):\n for j in range(norb):\n dveca[:, :, :, :] = nevecaa[i, j, :, :, :, :]\n dvecb[:, :, :, :] = nevecab[i, j, :, :, :, :]\n cvec = self._calculate_coeff_spin_with_dvec((dveca, dvecb))\n dveca2[i, j, :, :] += cvec[:, :]\n\n dveca[:, :, :, :] = nevecab[:, :, i, j, :, :]\n dvecb[:, :, :, :] = nevecbb[i, j, :, :, :, :]\n cvec = self._calculate_coeff_spin_with_dvec((dveca, dvecb))\n dvecb2[i, j, :, :] += cvec[:, :]\n\n out += self._calculate_coeff_spin_with_dvec((dveca2, dvecb2))\n return out\n\n def _apply_columns_recursive_alpha(self, mat: 'Nparray', buf: 'Nparray'):\n \"\"\"\n Apply only alpha-alpha operator that is represented by mat, whose\n dimension is norb times norb\n \"\"\"\n norb = self.norb()\n matT = mat.T.copy()\n index, exc, diag = self._core._map_to_deexc_alpha_icol()\n\n if fqe.settings.use_accelerated_code:\n for icol in range(norb):\n _lm_apply_array1_alpha_column(self.coeff, matT[icol, :],\n index[icol], exc[icol],\n diag[icol], self.lena(),\n self.lenb(), icol)\n else:\n na, ne = exc.shape[1:3]\n na2 = diag.shape[1]\n for icol in range(norb):\n for a in range(na):\n target = index[icol, a]\n for e in range(ne):\n source, ishift, parity = exc[icol, a, e]\n self.coeff[target, :] += parity * matT[\n icol, ishift] * self.coeff[source, :]\n for a2 in range(na2):\n target = diag[icol, a2]\n self.coeff[target, :] *= (1 + matT[icol, icol])\n\n def apply_columns_recursive_inplace(self, mat1: 'Nparray',\n mat2: 'Nparray') -> None:\n \"\"\"\n Apply column operators recursively to perform wave function transformation\n under the unitary transfomration of the orbitals. Only called from\n Wavefunction.transform. The results are stored in-place.\n\n Args:\n mat1 (Nparray): the alpha-alpha part of the transformation matrix\n\n mat2 (Nparray): the beta-beta part of the transformation matrix\n \"\"\"\n trans = FqeData(self.nbeta(),\n self.nalpha(),\n self.norb(),\n self._core.alpha_beta_transpose(),\n dtype=self.coeff.dtype)\n buf = trans.coeff.reshape(self.lena(), self.lenb())\n self._apply_columns_recursive_alpha(mat1, buf)\n\n if fqe.settings.use_accelerated_code:\n _transpose(trans.coeff, self.coeff)\n else:\n trans.coeff[:, :] = self.coeff.T[:, :]\n buf = self.coeff.reshape(self.lenb(), self.lena())\n trans._apply_columns_recursive_alpha(mat2, buf)\n\n if fqe.settings.use_accelerated_code:\n _transpose(self.coeff, trans.coeff)\n else:\n self.coeff[:, :] = trans.coeff.T[:, :]\n\n def apply_inplace_s2(self) -> None:\n \"\"\"\n Apply the S squared operator to self.\n \"\"\"\n norb = self.norb()\n orig = numpy.copy(self.coeff)\n s_z = (self.nalpha() - self.nbeta()) * 0.5\n self.coeff *= s_z + s_z * s_z + self.nbeta()\n\n if self.nalpha() != self.norb() and self.nbeta() != 0:\n dvec = numpy.zeros((norb, norb, self.lena(), self.lenb()),\n dtype=self._dtype)\n for i in range(norb):\n for j in range(norb):\n for source, target, parity in self.alpha_map(i, j):\n dvec[i, j, target, :] += orig[source, :] * parity\n for i in range(self.norb()):\n for j in range(self.norb()):\n for source, target, parity in self.beta_map(j, i):\n self.coeff[:, source] -= dvec[j, i, :, target] * parity\n\n def apply_individual_nbody(self, coeff: complex, daga: List[int],\n undaga: List[int], dagb: List[int],\n undagb: List[int]) -> 'FqeData':\n \"\"\"\n Apply function with an individual operator represented in arrays.\n It is assumed that the operator is spin conserving.\n\n Args:\n coeff (complex): scalar coefficient to be multiplied to the result\n\n daga (List[int]): indices corresponding to the alpha creation \\\n operators in the Hamiltonian\n\n undaga (List[int]): indices corresponding to the alpha annihilation \\\n operators in the Hamiltonian\n\n dagb (List[int]): indices corresponding to the beta creation \\\n operators in the Hamiltonian\n\n undagb (List[int]): indices corresponding to the beta annihilation \\\n operators in the Hamiltonian\n\n Returns:\n FqeData: FqeData object that stores the result of application\n \"\"\"\n\n out = copy.deepcopy(self)\n out.coeff.fill(0.0)\n out.apply_individual_nbody_accumulate(coeff, self, daga, undaga, dagb,\n undagb)\n return out\n\n def apply_individual_nbody_accumulate(self, coeff: complex,\n idata: 'FqeData', daga: List[int],\n undaga: List[int], dagb: List[int],\n undagb: List[int]) -> None:\n \"\"\"\n Apply function with an individual operator represented in arrays.\n It is assumed that the operator is spin conserving. The result will\n be accumulated to self\n\n Args:\n coeff (complex): scalar coefficient to be multiplied to the result\n\n idata (FqeData): input FqeData to which the operators are applied\n\n daga (List[int]): indices corresponding to the alpha creation \\\n operators in the Hamiltonian\n\n undaga (List[int]): indices corresponding to the alpha annihilation \\\n operators in the Hamiltonian\n\n dagb (List[int]): indices corresponding to the beta creation \\\n operators in the Hamiltonian\n\n undagb (List[int]): indices corresponding to the beta annihilation \\\n operators in the Hamiltonian\n \"\"\"\n assert len(daga) == len(undaga) and len(dagb) == len(undagb)\n\n ualphamap = numpy.zeros((self.lena(), 3), dtype=numpy.uint64)\n ubetamap = numpy.zeros((self.lenb(), 3), dtype=numpy.uint64)\n\n acount = self._core.make_mapping_each(ualphamap, True, daga, undaga)\n if acount == 0:\n return\n bcount = self._core.make_mapping_each(ubetamap, False, dagb, undagb)\n if bcount == 0:\n return\n\n ualphamap = ualphamap[:acount, :]\n ubetamap = ubetamap[:bcount, :]\n\n alphamap = numpy.zeros((acount, 3), dtype=numpy.int64)\n sourceb_vec = numpy.zeros((bcount,), dtype=numpy.int64)\n targetb_vec = numpy.zeros((bcount,), dtype=numpy.int64)\n parityb_vec = numpy.zeros((bcount,), dtype=numpy.int64)\n\n alphamap[:, 0] = ualphamap[:, 0]\n for i in range(acount):\n alphamap[i, 1] = self._core.index_alpha(ualphamap[i, 1])\n alphamap[:, 2] = 1 - 2 * ualphamap[:, 2]\n\n sourceb_vec[:] = ubetamap[:, 0]\n for i in range(bcount):\n targetb_vec[i] = self._core.index_beta(ubetamap[i, 1])\n parityb_vec[:] = 1 - 2 * ubetamap[:, 2]\n\n if fqe.settings.use_accelerated_code:\n _apply_individual_nbody1_accumulate(coeff, self.coeff, idata.coeff,\n alphamap, targetb_vec,\n sourceb_vec, parityb_vec)\n else:\n FqeData._apply_individual_nbody1_accumulate_python(\n coeff, self.coeff, idata.coeff, alphamap, targetb_vec,\n sourceb_vec, parityb_vec)\n\n @staticmethod\n def _apply_individual_nbody1_accumulate_python(\n coeff: 'Nparray', ocoeff: 'Nparray', icoeff: 'Nparray',\n amap: 'Nparray', btarget: 'Nparray', bsource: 'Nparray',\n bparity: 'Nparray') -> None:\n \"\"\"\n Python version of _apply_individual_nbody1_accumulate\n ported from C from fqe_data.c for compatibility\n \"\"\"\n for sourcea, targeta, paritya in amap:\n ocoeff[targeta, btarget] += coeff * paritya * numpy.multiply(\n icoeff[sourcea, bsource], bparity)\n\n def rdm1(self, bradata: Optional['FqeData'] = None) -> Tuple['Nparray']:\n \"\"\"\n API for calculating 1-particle RDMs given a wave function. When bradata\n is given, it calculates transition RDMs. Depending on the filling, the\n code selects an optimal algorithm.\n\n Args:\n bradata (optional, FqeData): FqeData for the bra wavefunction. When \\\n not given, the ket function is also used for the bra wavefunction\n\n Returns:\n Tuple[Nparray]: tuple of length 1 that contains numpy array for 1RDM\n \"\"\"\n return self._rdm1_blocked(bradata)\n\n def _rdm1_blocked(self,\n bradata: Optional['FqeData'] = None,\n max_states: int = 100) -> Tuple['Nparray']:\n \"\"\"\n API for calculating 1-particle RDMs given a wave function. When bradata\n is given, it calculates transition RDMs. Depending on the filling, the\n code selects an optimal algorithm.\n \"\"\"\n bradata = self if bradata is None else bradata\n\n if fqe.settings.use_accelerated_code:\n mappings = bradata._core._get_block_mappings(max_states=max_states)\n norb = bradata.norb()\n coeff_a = bradata.coeff\n coeff_b = bradata.coeff.T.copy()\n\n coeffconj = self.coeff.conj()\n rdm = numpy.zeros((norb, norb), dtype=bradata._dtype)\n for alpha_range, beta_range, alpha_maps, beta_maps in mappings:\n dvec = _make_dvec_part(coeff_a, alpha_maps, alpha_range,\n beta_range, norb, self.lena(),\n self.lenb(), True)\n dvec = _make_dvec_part(coeff_b,\n beta_maps,\n alpha_range,\n beta_range,\n norb,\n self.lena(),\n self.lenb(),\n False,\n out=dvec)\n\n rdm[:, :] += numpy.tensordot(\n dvec, coeffconj[alpha_range.start:alpha_range.\n stop, beta_range.start:beta_range.stop])\n\n return (numpy.transpose(rdm.conj()),)\n else:\n dvec2 = self.calculate_dvec_spatial()\n return (numpy.transpose(\n numpy.tensordot(dvec2.conj(), self.coeff,\n axes=((2, 3), (0, 1)))),)\n\n def rdm12(self, bradata: Optional['FqeData'] = None\n ) -> Tuple['Nparray', 'Nparray']:\n \"\"\"\n API for calculating 1- and 2-particle RDMs given a wave function.\n When bradata is given, it calculates transition RDMs. Depending on the\n filling, the code selects an optimal algorithm.\n\n Args:\n bradata (optional, FqeData): FqeData for the bra wavefunction. When \\\n not given, the ket function is also used for the bra wavefunction\n\n Returns:\n Tuple[Nparray]: tuple of length 2 that contains numpy array for 1 \\\n and 2RDM\n \"\"\"\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n\n thresh = self._low_thresh\n if nalpha < norb * thresh and nbeta < norb * thresh:\n graphset = FciGraphSet(2, 2)\n graphset.append(self._core)\n if nalpha - 2 >= 0:\n graphset.append(FciGraph(nalpha - 2, nbeta, norb))\n if nalpha - 1 >= 0 and nbeta - 1 >= 0:\n graphset.append(FciGraph(nalpha - 1, nbeta - 1, norb))\n if nbeta - 2 >= 0:\n graphset.append(FciGraph(nalpha, nbeta - 2, norb))\n if fqe.settings.use_accelerated_code:\n return self._rdm12_lowfilling(bradata)\n else:\n return self._rdm12_lowfilling_python(bradata)\n\n return self._rdm12_halffilling(bradata)\n\n def _rdm12_halffilling(self, bradata: Optional['FqeData'] = None\n ) -> Tuple['Nparray', 'Nparray']:\n \"\"\"\n Standard code for calculating 1- and 2-particle RDMs given a\n wavefunction. When bradata is given, it calculates transition RDMs.\n \"\"\"\n if fqe.settings.use_accelerated_code:\n return self._rdm12_halffilling_blocked(bradata)\n else:\n dvec = self.calculate_dvec_spatial()\n dvec2 = dvec if bradata is None \\\n else bradata.calculate_dvec_spatial()\n out1 = numpy.transpose(numpy.tensordot(dvec2.conj(), self.coeff))\n out2 = numpy.transpose(numpy.tensordot(\n dvec2.conj(), dvec, axes=((2, 3), (2, 3))),\n axes=(1, 2, 0, 3)) * (-1.0)\n\n for i in range(self.norb()):\n out2[:, i, i, :] += out1[:, :]\n return out1, out2\n\n def _rdm12_halffilling_blocked(self,\n bradata: Optional['FqeData'] = None,\n max_states: int = 100\n ) -> Tuple['Nparray', 'Nparray']:\n \"\"\"\n Standard code for calculating 1- and 2-particle RDMs given a\n wavefunction. When bradata is given, it calculates transition RDMs.\n \"\"\"\n bradata = self if bradata is None else bradata\n\n mappings = self._core._get_block_mappings(max_states=max_states)\n norb = bradata.norb()\n coeff_a = self.coeff\n coeff_b = self.coeff.T.copy()\n bcoeff_a = bradata.coeff\n bcoeff_b = bradata.coeff.T.copy()\n\n rdm1 = numpy.zeros((norb,) * 2, dtype=bradata._dtype)\n rdm2 = numpy.zeros((norb,) * 4, dtype=bradata._dtype)\n for alpha_range, beta_range, alpha_maps, beta_maps in mappings:\n dvec = _make_dvec_part(coeff_a, alpha_maps, alpha_range, beta_range,\n norb, self.lena(), self.lenb(), True)\n dvec = _make_dvec_part(coeff_b,\n beta_maps,\n alpha_range,\n beta_range,\n norb,\n self.lena(),\n self.lenb(),\n False,\n out=dvec)\n\n dvec2 = _make_dvec_part(bcoeff_a, alpha_maps,\n alpha_range, beta_range, norb, self.lena(),\n self.lenb(), True)\n dvec2 = _make_dvec_part(bcoeff_b,\n beta_maps,\n alpha_range,\n beta_range,\n norb,\n self.lena(),\n self.lenb(),\n False,\n out=dvec2)\n\n dvec2conj = dvec2.conj()\n rdm1[:, :] += numpy.tensordot(\n dvec2conj, self.coeff[alpha_range.start:alpha_range.\n stop, beta_range.start:beta_range.stop])\n rdm2[:, :, :, :] += \\\n numpy.tensordot(dvec2conj, dvec, axes=((2, 3), (2, 3)))\n\n rdm2 = -rdm2.transpose(1, 2, 0, 3)\n for i in range(self.norb()):\n rdm2[:, i, i, :] += rdm1[:, :]\n return (numpy.transpose(rdm1), rdm2)\n\n def _rdm12_lowfilling_python(self, bradata: Optional['FqeData'] = None\n ) -> Tuple['Nparray', 'Nparray']:\n \"\"\"\n Low-filling specialization of the code for Calculating 1- and 2-particle\n RDMs given a wave function. When bradata is given, it calculates\n transition RDMs.\n \"\"\"\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n lena = self.lena()\n lenb = self.lenb()\n nlt = norb * (norb + 1) // 2\n\n outpack = numpy.zeros((nlt, nlt), dtype=self.coeff.dtype)\n outunpack = numpy.zeros((norb, norb, norb, norb),\n dtype=self.coeff.dtype)\n if nalpha - 2 >= 0:\n alpha_map, _ = self._core.find_mapping(-2, 0)\n\n def compute_intermediate0(coeff):\n tmp = numpy.zeros((nlt, int(binom(norb, nalpha - 2)), lenb),\n dtype=self.coeff.dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n for source, target, parity in alpha_map[(i, j)]:\n tmp[i + j * (j + 1) //\n 2, target, :] += coeff[source, :] * parity\n return tmp\n\n inter = compute_intermediate0(self.coeff)\n inter2 = inter if bradata is None else compute_intermediate0(\n bradata.coeff)\n outpack += numpy.tensordot(inter2.conj(),\n inter,\n axes=((1, 2), (1, 2)))\n\n if self.nalpha() - 1 >= 0 and self.nbeta() - 1 >= 0:\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n\n def compute_intermediate1(coeff):\n tmp = numpy.zeros((norb, norb, int(binom(\n norb, nalpha - 1)), int(binom(norb, nbeta - 1))),\n dtype=self.coeff.dtype)\n for i in range(norb):\n for j in range(norb):\n for sourcea, targeta, paritya in alpha_map[(i,)]:\n paritya *= (-1)**(nalpha - 1)\n for sourceb, targetb, parityb in beta_map[(j,)]:\n work = coeff[sourcea,\n sourceb] * paritya * parityb\n tmp[i, j, targeta, targetb] += work\n return tmp\n\n inter = compute_intermediate1(self.coeff)\n inter2 = inter if bradata is None else compute_intermediate1(\n bradata.coeff)\n outunpack += numpy.tensordot(inter2.conj(),\n inter,\n axes=((2, 3), (2, 3)))\n\n if self.nbeta() - 2 >= 0:\n _, beta_map = self._core.find_mapping(0, -2)\n\n def compute_intermediate2(coeff):\n tmp = numpy.zeros((nlt, lena, int(binom(norb, nbeta - 2))),\n dtype=self.coeff.dtype)\n for i in range(norb):\n for j in range(i + 1, norb):\n for source, target, parity in beta_map[(i, j)]:\n tmp[i + j * (j + 1) //\n 2, :, target] += coeff[:, source] * parity\n\n return tmp\n\n inter = compute_intermediate2(self.coeff)\n inter2 = inter if bradata is None else compute_intermediate2(\n bradata.coeff)\n outpack += numpy.tensordot(inter2.conj(),\n inter,\n axes=((1, 2), (1, 2)))\n\n out = numpy.zeros_like(outunpack)\n for i in range(norb):\n for j in range(norb):\n ij = min(i, j) + max(i, j) * (max(i, j) + 1) // 2\n parityij = 1.0 if i < j else -1.0\n for k in range(norb):\n for l in range(norb):\n parity = parityij * (1.0 if k < l else -1.0)\n out[i, j, k,\n l] -= outunpack[i, j, k, l] + outunpack[j, i, l, k]\n mnkl, mxkl = min(k, l), max(k, l)\n work = outpack[ij, mnkl + mxkl * (mxkl + 1) // 2]\n out[i, j, k, l] -= work * parity\n\n return self.rdm1(bradata)[0], out\n\n def _rdm12_lowfilling(self, bradata: Optional['FqeData'] = None\n ) -> Tuple['Nparray', 'Nparray']:\n \"\"\"\n Low-filling specialization of the code for Calculating 1- and 2-particle\n RDMs given a wave function. When bradata is given, it calculates\n transition RDMs.\n \"\"\"\n norb = self.norb()\n nalpha = self.nalpha()\n nbeta = self.nbeta()\n lena = self.lena()\n lenb = self.lenb()\n nlt = norb * (norb + 1) // 2\n\n outpack = numpy.zeros((nlt, nlt), dtype=self.coeff.dtype)\n outunpack = numpy.zeros((norb, norb, norb, norb),\n dtype=self.coeff.dtype)\n if nalpha - 2 >= 0:\n alpha_map, _ = self._core.find_mapping(-2, 0)\n alpha_array = self._to_array1(alpha_map, norb)\n\n def compute_intermediate0(coeff):\n tmp = numpy.zeros((nlt, int(binom(norb, nalpha - 2)), lenb),\n dtype=self.coeff.dtype)\n _apply_array12_lowfillingaa(self.coeff, alpha_array, tmp)\n return tmp\n\n inter = compute_intermediate0(self.coeff)\n inter2 = inter if bradata is None else compute_intermediate0(\n bradata.coeff)\n outpack += numpy.tensordot(inter2.conj(),\n inter,\n axes=((1, 2), (1, 2)))\n\n if self.nalpha() - 1 >= 0 and self.nbeta() - 1 >= 0:\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n inter = numpy.zeros((norb, norb, int(binom(\n norb, nalpha - 1)), int(binom(norb, nbeta - 1))),\n dtype=self._dtype)\n\n alpha_array = self._to_array2(alpha_map, norb)\n beta_array = self._to_array2(beta_map, norb)\n\n alpha_map, beta_map = self._core.find_mapping(-1, -1)\n _apply_array12_lowfillingab(self.coeff, alpha_array, beta_array,\n nalpha, nbeta, inter)\n\n if bradata is None:\n inter2 = inter\n else:\n inter2 = numpy.zeros((norb, norb, int(binom(\n norb, nalpha - 1)), int(binom(norb, nbeta - 1))),\n dtype=self._dtype)\n _apply_array12_lowfillingab(bradata.coeff, alpha_array, beta_array, \\\n nalpha, nbeta, inter2)\n\n # 0.25 needed since _apply_array12_lowfillingab adds a factor 2\n outunpack += numpy.tensordot(\n inter2.conj(), inter, axes=((2, 3), (2, 3))) * 0.25\n\n if self.nbeta() - 2 >= 0:\n _, beta_map = self._core.find_mapping(0, -2)\n beta_array = self._to_array1(beta_map, norb)\n\n def compute_intermediate2(coeff):\n tmp = numpy.zeros((nlt, lena, int(binom(norb, nbeta - 2))),\n dtype=self.coeff.dtype)\n _apply_array12_lowfillingaa(self.coeff,\n beta_array,\n tmp,\n alpha=False)\n\n return tmp\n\n inter = compute_intermediate2(self.coeff)\n inter2 = inter if bradata is None else compute_intermediate2(\n bradata.coeff)\n outpack += numpy.tensordot(inter2.conj(),\n inter,\n axes=((1, 2), (1, 2)))\n\n out = numpy.zeros_like(outunpack)\n for i in range(norb):\n for j in range(norb):\n ij = min(i, j) + max(i, j) * (max(i, j) + 1) // 2\n parityij = 1.0 if i < j else -1.0\n for k in range(norb):\n for l in range(norb):\n parity = parityij * (1.0 if k < l else -1.0)\n out[i, j, k,\n l] -= outunpack[i, j, k, l] + outunpack[j, i, l, k]\n mnkl, mxkl = min(k, l), max(k, l)\n work = outpack[ij, mnkl + mxkl * (mxkl + 1) // 2]\n out[i, j, k, l] -= work * parity\n\n return self.rdm1(bradata)[0], out\n\n def rdm123(self,\n bradata: Optional['FqeData'] = None,\n dvec: 'Nparray' = None,\n dvec2: 'Nparray' = None,\n evec2: 'Nparray' = None\n ) -> Tuple['Nparray', 'Nparray', 'Nparray']:\n \"\"\"\n Calculates 1- through 3-particle RDMs given a wave function. When\n bradata is given, it calculates transition RDMs.\n\n Args:\n bradata (optional, FqeData): FqeData for the bra wavefunction. When \\\n not given, the ket function is also used for the bra wavefunction\n\n Returns:\n Tuple[Nparray]: tuple of length 3 that contains numpy array for 1, \\\n 2, and 3RDM\n \"\"\"\n norb = self.norb()\n if dvec is None:\n dvec = self.calculate_dvec_spatial()\n if dvec2 is None:\n dvec2 = dvec if bradata is None else bradata.calculate_dvec_spatial(\n )\n\n out1 = numpy.transpose(numpy.tensordot(dvec2.conj(), self.coeff))\n out2 = numpy.transpose(numpy.tensordot(\n dvec2.conj(), dvec, axes=((2, 3), (2, 3))),\n axes=(1, 2, 0, 3)) * (-1.0)\n for i in range(norb):\n out2[:, i, i, :] += out1[:, :]\n\n if evec2 is not None:\n out3 = -numpy.transpose(numpy.tensordot(\n evec2.conj(), dvec, axes=((4, 5), (2, 3))),\n axes=(3, 1, 4, 2, 0, 5))\n else:\n out3 = numpy.empty((norb,) * 6, dtype=dvec.dtype)\n dvec_conj = dvec.conj()\n for i in range(norb):\n for j in range(norb):\n tmp = dvec2[i, j, :, :]\n evec_ij = self._calculate_dvec_spatial_with_coeff(tmp)\n out3[j, i, :, :, :, :] = -numpy.tensordot(\n evec_ij, dvec_conj, axes=((2, 3), (2, 3)))\n out3 = numpy.transpose(out3.conj(), axes=(0, 3, 4, 1, 2, 5))\n\n for i in range(norb):\n out3[:, i, :, i, :, :] -= out2[:, :, :, :]\n out3[:, :, i, :, i, :] -= out2[:, :, :, :]\n for j in range(norb):\n out3[:, i, j, i, j, :] += out1[:, :]\n for k in range(norb):\n out3[j, k, i, i, :, :] -= out2[k, j, :, :]\n return (out1, out2, out3)\n\n def rdm1234(self, bradata: Optional['FqeData'] = None\n ) -> Tuple['Nparray', 'Nparray', 'Nparray', 'Nparray']:\n \"\"\"\n Calculates 1- through 4-particle RDMs given a wave function. When\n bradata is given, it calculates transition RDMs.\n\n Args:\n bradata (optional, FqeData): FqeData for the bra wavefunction. When \\\n not given, the ket function is also used for the bra wavefunction\n\n Returns:\n Tuple[Nparray]: tuple of length 4 that contains numpy array for 1, \\\n 2, 3, and 4RDM\n \"\"\"\n norb = self.norb()\n dvec = self.calculate_dvec_spatial()\n dvec2 = dvec if bradata is None else bradata.calculate_dvec_spatial()\n\n def make_evec(current_dvec: 'Nparray') -> 'Nparray':\n current_evec = numpy.zeros(\n (norb, norb, norb, norb, self.lena(), self.lenb()),\n dtype=self._dtype)\n for i in range(norb):\n for j in range(norb):\n tmp = current_dvec[i, j, :, :]\n tmp2 = self._calculate_dvec_spatial_with_coeff(tmp)\n current_evec[:, :, i, j, :, :] = tmp2[:, :, :, :]\n return current_evec\n\n evec = make_evec(dvec)\n evec2 = evec if bradata is None else make_evec(dvec2)\n\n (out1, out2, out3) = self.rdm123(bradata, dvec, dvec2, evec2)\n\n out4 = numpy.transpose(numpy.tensordot(evec2.conj(),\n evec,\n axes=((4, 5), (4, 5))),\n axes=(3, 1, 4, 6, 2, 0, 5, 7))\n for i in range(norb):\n for j in range(norb):\n for k in range(norb):\n out4[:, j, i, k, j, i, k, :] -= out1[:, :]\n for l in range(norb):\n out4[j, l, i, k, l, k, :, :] += out2[i, j, :, :]\n out4[i, j, l, k, l, k, :, :] += out2[i, j, :, :]\n out4[i, l, k, j, l, k, :, :] += out2[i, j, :, :]\n out4[j, i, k, l, l, k, :, :] += out2[i, j, :, :]\n out4[i, k, j, l, k, :, l, :] += out2[i, j, :, :]\n out4[j, i, k, l, k, :, l, :] += out2[i, j, :, :]\n out4[i, j, k, l, :, k, l, :] += out2[i, j, :, :]\n out4[k, i, j, l, l, :, :, :] += out3[i, j, k, :, :, :]\n out4[j, i, l, k, l, :, :, :] += out3[i, j, k, :, :, :]\n out4[i, l, j, k, l, :, :, :] += out3[i, j, k, :, :, :]\n out4[i, k, j, l, :, l, :, :] += out3[i, j, k, :, :, :]\n out4[i, j, l, k, :, l, :, :] += out3[i, j, k, :, :, :]\n out4[i, j, k, l, :, :, l, :] += out3[i, j, k, :, :, :]\n return (out1, out2, out3, out4)\n\n def calculate_dvec_spatial(self) -> 'Nparray':\n \"\"\"Generate\n\n .. math::\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n using self.coeff as an input\n\n Returns:\n Nparray: result of computation\n \"\"\"\n return self._calculate_dvec_spatial_with_coeff(self.coeff)\n\n def calculate_dvec_spin(self) -> Tuple['Nparray', 'Nparray']:\n \"\"\"Generate a pair of\n\n .. math::\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n using self.coeff as an input.\n\n Returns:\n Tuple[Nparray, Nparray]: result of computation. Alpha and beta \\\n are seperately packed in the tuple to be returned\n \"\"\"\n return self._calculate_dvec_spin_with_coeff(self.coeff)\n\n def calculate_dvec_spatial_fixed_j(self, jorb: int) -> 'Nparray':\n \"\"\"Generate, for a fixed j,\n\n .. math::\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n using self.coeff as an input\n\n Args:\n jorb (int): specify j in the above expression\n\n Returns:\n Nparray: result of computation.\n \"\"\"\n return self._calculate_dvec_spatial_with_coeff_fixed_j(self.coeff, jorb)\n\n def calculate_dvec_spin_fixed_j(self, jorb: int) -> 'Nparray':\n \"\"\"Generate a pair of the following, for a fixed j\n\n .. math::\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n using self.coeff as an input. Alpha and beta are seperately packed in\n the tuple to be returned\n\n Args:\n jorb (int): specify j in the above expression\n\n Returns:\n Nparray: result of computation.\n \"\"\"\n return self._calculate_dvec_spin_with_coeff_fixed_j(self.coeff, jorb)\n\n def _calculate_dvec_spatial_with_coeff(self, coeff: 'Nparray') -> 'Nparray':\n \"\"\"Generate\n\n .. math::\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n \"\"\"\n norb = self.norb()\n dvec = numpy.zeros((norb, norb, self.lena(), self.lenb()),\n dtype=self._dtype)\n if fqe.settings.use_accelerated_code:\n _make_dvec(dvec, coeff, [\n self.alpha_map(i, j) for i in range(norb) for j in range(norb)\n ], self.lena(), self.lenb(), True)\n _make_dvec(\n dvec, coeff,\n [self.beta_map(i, j) for i in range(norb) for j in range(norb)],\n self.lena(), self.lenb(), False)\n else:\n for i in range(norb):\n for j in range(norb):\n for source, target, parity in self.alpha_map(i, j):\n dvec[i, j, target, :] += coeff[source, :] * parity\n for source, target, parity in self.beta_map(i, j):\n dvec[i, j, :, target] += coeff[:, source] * parity\n return dvec\n\n def _calculate_dvec_spin_with_coeff(self, coeff: 'Nparray'\n ) -> Tuple['Nparray', 'Nparray']:\n \"\"\"Generate\n\n .. math::\n\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n in the spin-orbital case\n \"\"\"\n norb = self.norb()\n dveca = numpy.zeros((norb, norb, self.lena(), self.lenb()),\n dtype=self._dtype)\n dvecb = numpy.zeros((norb, norb, self.lena(), self.lenb()),\n dtype=self._dtype)\n if fqe.settings.use_accelerated_code:\n alpha_maps = [\n self.alpha_map(i, j) for i in range(norb) for j in range(norb)\n ]\n beta_maps = [\n self.beta_map(i, j) for i in range(norb) for j in range(norb)\n ]\n _make_dvec(dveca, coeff, alpha_maps, self.lena(), self.lenb(), True)\n _make_dvec(dvecb, coeff, beta_maps, self.lena(), self.lenb(), False)\n else:\n for i in range(norb):\n for j in range(norb):\n for source, target, parity in self.alpha_map(i, j):\n dveca[i, j, target, :] += coeff[source, :] * parity\n for source, target, parity in self.beta_map(i, j):\n dvecb[i, j, :, target] += coeff[:, source] * parity\n return (dveca, dvecb)\n\n def _calculate_dvec_spatial_with_coeff_fixed_j(self, coeff: 'Nparray',\n jorb: int) -> 'Nparray':\n \"\"\"Generate, for fixed j,\n\n .. math::\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n \"\"\"\n norb = self.norb()\n assert (jorb < norb and jorb >= 0)\n dvec = numpy.zeros((norb, self.lena(), self.lenb()), dtype=self._dtype)\n for i in range(norb):\n for source, target, parity in self.alpha_map(i, jorb):\n dvec[i, target, :] += coeff[source, :] * parity\n for source, target, parity in self.beta_map(i, jorb):\n dvec[i, :, target] += coeff[:, source] * parity\n return dvec\n\n def _calculate_dvec_spin_with_coeff_fixed_j(self, coeff: 'Nparray',\n jorb: int) -> 'Nparray':\n \"\"\"Generate, fixed j,\n\n .. math::\n\n D^J_{ij} = \\\\sum_I \\\\langle J|a^\\\\dagger_i a_j|I\\\\rangle C_I\n\n in the spin-orbital case\n \"\"\"\n norb = self.norb()\n assert (jorb < norb * 2 and jorb >= 0)\n dvec = numpy.zeros((norb, self.lena(), self.lenb()), dtype=self._dtype)\n for i in range(norb):\n if jorb < norb:\n for source, target, parity in self.alpha_map(i, jorb):\n dvec[i, target, :] += coeff[source, :] * parity\n else:\n for source, target, parity in self.beta_map(i, jorb - norb):\n dvec[i, :, target] += coeff[:, source] * parity\n return dvec\n\n def _calculate_coeff_spatial_with_dvec(self, dvec: 'Nparray') -> 'Nparray':\n \"\"\"Generate\n\n .. math::\n\n C_I = \\\\sum_J \\\\langle I|a^\\\\dagger_i a_j|J\\\\rangle D^J_{ij}\n \"\"\"\n norb = self.norb()\n out = numpy.zeros(self.coeff.shape, dtype=self._dtype)\n if fqe.settings.use_accelerated_code:\n alpha_maps = [\n self.alpha_map(j, i) for i in range(norb) for j in range(norb)\n ]\n beta_maps = [\n self.beta_map(j, i) for i in range(norb) for j in range(norb)\n ]\n _make_coeff(dvec, out, alpha_maps, self.lena(), self.lenb(), True)\n _make_coeff(dvec, out, beta_maps, self.lena(), self.lenb(), False)\n else:\n for i in range(self.norb()):\n for j in range(self.norb()):\n for source, target, parity in self.alpha_map(j, i):\n out[source, :] += dvec[i, j, target, :] * parity\n for source, target, parity in self.beta_map(j, i):\n out[:, source] += dvec[i, j, :, target] * parity\n return out\n\n def _calculate_dvec_spatial_compressed(self) -> 'Nparray':\n \"\"\"Generate\n\n .. math::\n\n D^J_{i 'Nparray':\n \"\"\"Generate\n\n .. math::\n\n C_I = \\\\sum_J \\\\langle I|a^\\\\dagger_i a_j|J\\\\rangle D^J_{ij}\n \"\"\"\n norb = self.norb()\n out = numpy.zeros(self.coeff.shape, dtype=self._dtype)\n if fqe.settings.use_accelerated_code:\n alpha_maps = [\n self.alpha_map(j, i) for i in range(norb) for j in range(norb)\n ]\n beta_maps = [\n self.beta_map(j, i) for i in range(norb) for j in range(norb)\n ]\n _make_coeff(dvec[0], out, alpha_maps, self.lena(), self.lenb(),\n True)\n _make_coeff(dvec[1], out, beta_maps, self.lena(), self.lenb(),\n False)\n else:\n for i in range(self.norb()):\n for j in range(self.norb()):\n for source, target, parity in self.alpha_map(j, i):\n out[source, :] += dvec[0][i, j, target, :] * parity\n for source, target, parity in self.beta_map(j, i):\n out[:, source] += dvec[1][i, j, :, target] * parity\n return out\n\n def evolve_inplace_individual_nbody_trivial(self, time: float,\n coeff: complex, opa: List[int],\n opb: List[int]) -> None:\n \"\"\"\n This is the time evolution code for the cases where individual nbody\n becomes number operators (hence hat{T}^2 is nonzero) coeff includes\n parity due to sorting. opa and opb are integer arrays. The result will be\n stored in-place.\n\n Args:\n time (float): time to be used for time propagation\n\n coeff (complex): scalar coefficient\n\n opa (List[int]): index list for alpha\n\n opb (List[int]): index list for beta\n \"\"\"\n n_a = len(opa)\n n_b = len(opb)\n coeff *= (-1)**(n_a * (n_a - 1) // 2 + n_b * (n_b - 1) // 2)\n\n amap = numpy.zeros((self.lena(),), dtype=numpy.int64)\n bmap = numpy.zeros((self.lenb(),), dtype=numpy.int64)\n amask = reverse_integer_index(opa)\n bmask = reverse_integer_index(opb)\n count = 0\n for index in range(self.lena()):\n current = int(self._core.string_alpha(index))\n if (~current) & amask == 0:\n amap[count] = index\n count += 1\n amap = amap[:count]\n count = 0\n for index in range(self.lenb()):\n current = int(self._core.string_beta(index))\n if (~current) & bmask == 0:\n bmap[count] = index\n count += 1\n bmap = bmap[:count]\n\n factor = numpy.exp(-time * numpy.real(coeff) * 2.j)\n if amap.size != 0 and bmap.size != 0:\n xi, yi = numpy.meshgrid(amap, bmap, indexing='ij')\n if fqe.settings.use_accelerated_code:\n _sparse_scale(xi, yi, factor, self.coeff)\n else:\n self.coeff[xi, yi] *= factor\n\n def evolve_individual_nbody_nontrivial(self, time: float, coeff: complex,\n daga: List[int], undaga: List[int],\n dagb: List[int],\n undagb: List[int]) -> 'FqeData':\n \"\"\"\n This code time-evolves a wave function with an individual n-body\n generator which is spin-conserving. It is assumed that :math:`\\\\hat{T}^2 = 0`.\n Using :math:`TT = 0` and :math:`TT^\\\\dagger` is diagonal in the determinant\n space, one could evaluate as\n\n .. math::\n \\\\exp(-i(T+T^\\\\dagger)t)\n &= 1 + i(T+T^\\\\dagger)t - \\\\frac{1}{2}(TT^\\\\dagger + T^\\\\dagger T)t^2\n - i\\\\frac{1}{6}(TT^\\\\dagger T + T^\\\\dagger TT^\\\\dagger)t^3 + \\\\cdots \\\\\\\\\n &= -1 + \\\\cos(t\\\\sqrt{TT^\\\\dagger}) + \\\\cos(t\\\\sqrt{T^\\\\dagger T})\n - iT\\\\frac{\\\\sin(t\\\\sqrt{T^\\\\dagger T})}{\\\\sqrt{T^\\\\dagger T}}\n - iT^\\\\dagger\\\\frac{\\\\sin(t\\\\sqrt{TT^\\\\dagger})}{\\\\sqrt{TT^\\\\dagger}}\n\n Args:\n time (float): time to be used for time propagation\n\n coeff (complex): scalar coefficient\n\n daga (List[int]): index list for alpha creation operators\n\n undaga (List[int]): index list for alpha annihilation operators\n\n dagb (List[int]): index list for beta creation operators\n\n undagb (List[int]): index list for beta annihilation operators\n\n Returns:\n FqeData: result is returned as an FqeData object\n \"\"\"\n\n def isolate_number_operators(dag: List[int], undag: List[int],\n dagwork: List[int], undagwork: List[int],\n number: List[int]) -> int:\n \"\"\"\n Pair-up daggered and undaggered operators that correspond to the\n same spin-orbital and isolate them, because they have to be treated\n differently.\n \"\"\"\n par = 0\n for current in dag:\n if current in undag:\n index1 = dagwork.index(current)\n index2 = undagwork.index(current)\n par += len(dagwork) - (index1 + 1) + index2\n dagwork.remove(current)\n undagwork.remove(current)\n number.append(current)\n return par\n\n dagworka = copy.deepcopy(daga)\n dagworkb = copy.deepcopy(dagb)\n undagworka = copy.deepcopy(undaga)\n undagworkb = copy.deepcopy(undagb)\n numbera: List[int] = []\n numberb: List[int] = []\n\n parity = 0\n parity += isolate_number_operators(daga, undaga, dagworka, undagworka,\n numbera)\n parity += isolate_number_operators(dagb, undagb, dagworkb, undagworkb,\n numberb)\n ncoeff = coeff * (-1)**parity\n absol = numpy.absolute(ncoeff)\n sinfactor = numpy.sin(time * absol) / absol\n\n out = copy.deepcopy(self)\n\n out.apply_cos_inplace(time, ncoeff, numbera + dagworka, undagworka,\n numberb + dagworkb, undagworkb)\n\n out.apply_cos_inplace(time, ncoeff, numbera + undagworka, dagworka,\n numberb + undagworkb, dagworkb)\n phase = (-1)**((len(daga) + len(undaga)) * (len(dagb) + len(undagb)))\n work_cof = numpy.conj(coeff) * phase * (-1.0j)\n\n out.apply_individual_nbody_accumulate(work_cof * sinfactor, self,\n undaga, daga, undagb, dagb)\n\n out.apply_individual_nbody_accumulate(coeff * (-1.0j) * sinfactor, self,\n daga, undaga, dagb, undagb)\n return out\n\n def _evaluate_map(self, opa: List[int], oha: List[int], opb: List[int],\n ohb: List[int]):\n \"\"\"\n Utility internal function that performs part of the operations in\n evolve_inplace_individual_nbody_nontrivial, in which alpha and beta\n mappings are created.\n \"\"\"\n amap = numpy.zeros((self.lena(),), dtype=numpy.int64)\n bmap = numpy.zeros((self.lenb(),), dtype=numpy.int64)\n apmask = reverse_integer_index(opa)\n ahmask = reverse_integer_index(oha)\n bpmask = reverse_integer_index(opb)\n bhmask = reverse_integer_index(ohb)\n if fqe.settings.use_accelerated_code:\n count = _evaluate_map_each(amap, self._core._astr, self.lena(),\n apmask, ahmask)\n amap = amap[:count]\n count = _evaluate_map_each(bmap, self._core._bstr, self.lenb(),\n bpmask, bhmask)\n bmap = bmap[:count]\n else:\n counter = 0\n for index in range(self.lena()):\n current = int(self._core.string_alpha(index))\n if ((~current) & apmask) == 0 and (current & ahmask) == 0:\n amap[counter] = index\n counter += 1\n amap = amap[:counter]\n counter = 0\n for index in range(self.lenb()):\n current = int(self._core.string_beta(index))\n if ((~current) & bpmask) == 0 and (current & bhmask) == 0:\n bmap[counter] = index\n counter += 1\n bmap = bmap[:counter]\n return amap, bmap\n\n def apply_cos_inplace(self, time: float, ncoeff: complex, opa: List[int],\n oha: List[int], opb: List[int],\n ohb: List[int]) -> None:\n \"\"\"\n Utility internal function that performs part of the operations in\n evolve_inplace_individual_nbody_nontrivial. This function processes\n both TTd and TdT cases simultaneously and in-place without allocating\n memory.\n\n Args:\n time (float): time to be used for time propagation\n\n ncoeff (complex): scalar coefficient\n\n opa (List[int]): index list for alpha creation operators\n\n oha (List[int]): index list for alpha annihilation operators\n\n opb (List[int]): index list for beta creation operators\n\n ohb (List[int]): index list for beta annihilation operators\n \"\"\"\n absol = numpy.absolute(ncoeff)\n factor = numpy.cos(time * absol)\n\n amap, bmap = self._evaluate_map(opa, oha, opb, ohb)\n\n if amap.size != 0 and bmap.size != 0:\n xi, yi = numpy.meshgrid(amap, bmap, indexing='ij')\n if fqe.settings.use_accelerated_code:\n _sparse_scale(xi, yi, factor, self.coeff)\n else:\n self.coeff[xi, yi] *= factor\n\n def alpha_map(self, iorb: int, jorb: int) -> List[Tuple[int, int, int]]:\n \"\"\"Access the mapping for a singlet excitation from the current\n sector for alpha orbitals\n\n Args:\n iorb: index for creation\n\n jorb: index for annihilation\n\n Returns:\n List[Tuple[int, int, int]]: mapping informatin for the index pairs\n \"\"\"\n return self._core.alpha_map(iorb, jorb)\n\n def beta_map(self, iorb: int, jorb: int) -> List[Tuple[int, int, int]]:\n \"\"\"Access the mapping for a singlet excitation from the current\n sector for beta orbitals\n\n Args:\n iorb: index for creation\n\n jorb: index for annihilation\n\n Returns:\n List[Tuple[int, int, int]]: mapping informatin for the index pairs\n \"\"\"\n return self._core.beta_map(iorb, jorb)\n\n def ax_plus_y(self, sval: complex, other: 'FqeData') -> 'FqeData':\n \"\"\"Scale and add the data in the fqedata structure\n\n self.coeff += sval * other.coeff\n\n Args:\n sval (complex): scalar coefficient\n\n other (FqeData): FqeData object to be added to self\n \"\"\"\n assert hash(self) == hash(other)\n self.coeff += other.coeff * sval\n return self\n\n def __hash__(self):\n \"\"\"Fqedata sructures are unqiue in nele, s_z and the dimension.\n \"\"\"\n return hash((self._nele, self._m_s))\n\n def conj(self) -> None:\n \"\"\"Conjugate the coefficients\n \"\"\"\n numpy.conjugate(self.coeff, self.coeff)\n\n def lena(self) -> int:\n \"\"\"Length of the alpha configuration space\n\n Returns:\n int: length of the alpha configuration space\n \"\"\"\n return self._core.lena()\n\n def lenb(self) -> int:\n \"\"\"Length of the beta configuration space\n\n Returns:\n int: length of the beta configuration space\n \"\"\"\n return self._core.lenb()\n\n def nalpha(self) -> int:\n \"\"\"Number of alpha electrons\n\n Returns:\n int: the number of alpha electrons\n \"\"\"\n return self._core.nalpha()\n\n def nbeta(self) -> int:\n \"\"\"Number of beta electrons\n\n Returns:\n int: the number of beta electrons\n \"\"\"\n return self._core.nbeta()\n\n def n_electrons(self) -> int:\n \"\"\"Particle number getter\n\n Returns:\n int: the number of electrons in total\n \"\"\"\n return self._nele\n\n def generator(self) -> Iterator[Tuple[int, int, complex]]:\n \"\"\"Generator for configurations in the FqeData object\n \"\"\"\n for inda in range(self._core.lena()):\n alpha_str = self._core.string_alpha(inda)\n for indb in range(self._core.lenb()):\n beta_str = self._core.string_beta(indb)\n yield alpha_str, beta_str, self.coeff[inda, indb]\n\n def norb(self) -> int:\n \"\"\"Number of beta electrons\n\n Returns:\n int: the number of orbitals\n \"\"\"\n return self._core.norb()\n\n def norm(self) -> float:\n \"\"\"Return the norm of the the sector wavefunction\n\n Returns:\n float: norm\n \"\"\"\n return numpy.linalg.norm(self.coeff)\n\n def print_sector(self,\n pformat: Optional[Callable[[int, int], str]] = None,\n threshold: Optional[float] = 0.0001):\n \"\"\"Iterate over the strings and coefficients and print then\n using the print format\n\n Args:\n pformat (Callable[[int, int], str]): custom format\n\n threshold (float): threshold above which the elements are \\\n printed\n \"\"\"\n if pformat is None:\n\n def print_format(astr, bstr):\n return '{0:b}:{1:b}'.format(astr, bstr)\n\n pformat = print_format\n\n print('Sector N = {} : S_z = {}'.format(self._nele, self._m_s))\n for inda in range(self._core.lena()):\n alpha_str = self._core.string_alpha(inda)\n for indb in range(self._core.lenb()):\n beta_str = self._core.string_beta(indb)\n if numpy.abs(self.coeff[inda, indb]) > threshold:\n print('{} {}'.format(pformat(alpha_str, beta_str),\n self.coeff[inda, indb]))\n\n def beta_inversion(self) -> 'Nparray':\n \"\"\"Return the coefficients with an inversion of the beta strings.\n\n Returns:\n int: resulting coefficient in numpy array\n \"\"\"\n return numpy.flip(self.coeff, 1)\n\n def scale(self, sval: complex) -> None:\n \"\"\" Scale the wavefunction by the value sval\n\n Args:\n sval (complex): value to scale by\n \"\"\"\n self.coeff = self.coeff.astype(numpy.complex128) * sval\n\n def fill(self, value: complex) -> None:\n \"\"\" Fills the wavefunction with the value specified\n\n Args:\n value (complex): value to be filled\n \"\"\"\n self.coeff.fill(value)\n\n def set_wfn(self,\n strategy: Optional[str] = None,\n raw_data: 'Nparray' = numpy.empty(0)) -> None:\n \"\"\"Set the values of the fqedata wavefunction based on a strategy\n\n Args:\n strategy (str): the procedure to follow to set the coeffs\n\n raw_data (numpy.array(dim(self.lena(), self.lenb()), \\\n dtype=numpy.complex128)): the values to use \\\n if setting from data. If vrange is supplied, the first column \\\n in data will correspond to the first index in vrange\n \"\"\"\n\n strategy_args = ['ones', 'zero', 'random', 'from_data', 'hartree-fock']\n\n if strategy is None and raw_data.shape == (0,):\n raise ValueError('No strategy and no data passed.'\n ' Cannot initialize')\n\n if strategy == 'from_data' and raw_data.shape == (0,):\n raise ValueError('No data passed to initialize from')\n\n if raw_data.shape != (0,) and strategy not in ['from_data', None]:\n raise ValueError('Inconsistent strategy for set_vec passed with'\n 'data')\n\n if strategy not in strategy_args:\n raise ValueError('Unknown Argument passed to set_vec')\n\n if strategy == 'from_data':\n chkdim = raw_data.shape\n if chkdim[0] != self.lena() or chkdim[1] != self.lenb():\n raise ValueError('Dim of data passed {},{} is not compatible' \\\n ' with {},{}'.format(chkdim[0],\n chkdim[1],\n self.lena(),\n self.lenb()))\n\n if strategy == 'ones':\n self.coeff.fill(1. + .0j)\n elif strategy == 'zero':\n self.coeff.fill(0. + .0j)\n elif strategy == 'random':\n self.coeff[:, :] = rand_wfn(self.lena(), self.lenb())\n elif strategy == 'from_data':\n self.coeff = numpy.copy(raw_data)\n elif strategy == 'hartree-fock':\n self.coeff.fill(0 + .0j)\n self.coeff[0, 0] = 1.\n\n def empty_copy(self) -> 'FqeData':\n \"\"\"create a copy of the self with zero coefficients\n\n Returns:\n FqeData: a new object with zero coefficients\n \"\"\"\n new_data = FqeData(nalpha=self.nalpha(),\n nbeta=self.nbeta(),\n norb=self._core.norb(),\n fcigraph=self._core,\n dtype=self._dtype)\n new_data._low_thresh = self._low_thresh\n new_data.coeff = numpy.zeros_like(self.coeff)\n return new_data\n\n def get_spin_opdm(self) -> Tuple['Nparray', 'Nparray']:\n \"\"\"calculate the alpha-alpha and beta-beta block of the 1-RDM\n\n Returns:\n Tuple[Nparray, Nparray]: alpha and beta 1RDM\n \"\"\"\n dveca, dvecb = self.calculate_dvec_spin()\n alpha_opdm = numpy.tensordot(dveca, self.coeff.conj(), axes=2)\n beta_opdm = numpy.tensordot(dvecb, self.coeff.conj(), axes=2)\n return alpha_opdm, beta_opdm\n\n def get_ab_tpdm(self) -> 'Nparray':\n \"\"\"Get the alpha-beta block of the 2-RDM\n\n tensor[i, j, k, l] = \n\n Returns:\n Nparray: the above quantity in numpy array\n \"\"\"\n dveca, dvecb = self.calculate_dvec_spin()\n tpdm_ab = numpy.transpose(numpy.tensordot(dveca.conj(),\n dvecb,\n axes=((2, 3), (2, 3))),\n axes=(1, 2, 3, 0))\n return tpdm_ab\n\n def get_aa_tpdm(self) -> Tuple['Nparray', 'Nparray']:\n \"\"\"Get the alpha-alpha block of the 1- and 2-RDMs\n\n tensor[i, j, k, l] = \n\n Returns:\n Tuple[Nparray, Nparray]: alpha-alpha block of the 1- and 2-RDMs\n \"\"\"\n dveca, _ = self.calculate_dvec_spin()\n alpha_opdm = numpy.tensordot(dveca, self.coeff.conj(), axes=2)\n nik_njl_aa = numpy.transpose(numpy.tensordot(dveca.conj(),\n dveca,\n axes=((2, 3), (2, 3))),\n axes=(1, 2, 0, 3))\n for ii in range(nik_njl_aa.shape[1]):\n nik_njl_aa[:, ii, ii, :] -= alpha_opdm\n return alpha_opdm, -nik_njl_aa\n\n def get_bb_tpdm(self):\n \"\"\"Get the beta-beta block of the 1- and 2-RDMs\n\n tensor[i, j, k, l] = \n\n Returns:\n Tuple[Nparray, Nparray]: beta-beta block of the 1- and 2-RDMs\n \"\"\"\n _, dvecb = self.calculate_dvec_spin()\n beta_opdm = numpy.tensordot(dvecb, self.coeff.conj(), axes=2)\n nik_njl_bb = numpy.transpose(numpy.tensordot(dvecb.conj(),\n dvecb,\n axes=((2, 3), (2, 3))),\n axes=(1, 2, 0, 3))\n for ii in range(nik_njl_bb.shape[1]):\n nik_njl_bb[:, ii, ii, :] -= beta_opdm\n return beta_opdm, -nik_njl_bb\n\n def get_openfermion_rdms(self) -> Tuple['Nparray', 'Nparray']:\n \"\"\"\n Generate spin-rdms and return in openfermion format\n\n Returns:\n Tuple[Nparray, Nparray]: 1 and 2 RDMs in the OpenFermion \\\n format in numpy arrays\n \"\"\"\n opdm_a, tpdm_aa = self.get_aa_tpdm()\n opdm_b, tpdm_bb = self.get_bb_tpdm()\n tpdm_ab = self.get_ab_tpdm()\n nqubits = 2 * opdm_a.shape[0]\n tpdm = numpy.zeros((nqubits, nqubits, nqubits, nqubits),\n dtype=tpdm_ab.dtype)\n opdm = numpy.zeros((nqubits, nqubits), dtype=opdm_a.dtype)\n opdm[::2, ::2] = opdm_a\n opdm[1::2, 1::2] = opdm_b\n # same spin\n tpdm[::2, ::2, ::2, ::2] = tpdm_aa\n tpdm[1::2, 1::2, 1::2, 1::2] = tpdm_bb\n\n # mixed spin\n tpdm[::2, 1::2, 1::2, ::2] = tpdm_ab\n tpdm[::2, 1::2, ::2, 1::2] = -tpdm_ab.transpose(0, 1, 3, 2)\n tpdm[1::2, ::2, ::2, 1::2] = tpdm_ab.transpose(1, 0, 3, 2)\n tpdm[1::2, ::2, 1::2, ::2] = \\\n -tpdm[1::2, ::2, ::2, 1::2].transpose(0, 1, 3, 2)\n\n return opdm, tpdm\n\n def get_three_spin_blocks_rdm(self) -> 'Nparray':\n r\"\"\"\n Generate 3-RDM in the spin-orbital basis.\n\n 3-RDM has Sz spin-blocks (aaa, aab, abb, bbb). The strategy is to\n use this blocking to generate the minimal number of p^ q r^ s t^ u\n blocks and then generate the other components of the 3-RDM through\n symmeterization. For example,\n\n p^ r^ t^ q s u = -p^ q r^ s t^ u - d(q, r) p^ t^ s u + d(q, t)p^ r^ s u\n - d(s, t)p^ r^ q u + d(q,r)d(s,t)p^ u\n\n It is formulated in this way so we can use the dvec calculation.\n\n Given:\n ~D(p, j, Ia, Ib)(t, u) = \\sum_{Ka, Kb}\\sum_{LaLb}C(La,Lb)\n\n then:\n p^ q r^ s t^ u = \\sum_{Ia, Ib}D(p, q, Ia, Ib).conj(), ~D(p, j, Ia, Ib)(t, u)\n\n Example:\n\n p, q, r, s, t, u = 5, 5, 0, 4, 5, 1\n\n .. code-block:: python\n\n tdveca, tdvecb = fqe_data._calculate_dvec_spin_with_coeff(dveca[5, 1, :, :])\n test_ccc = np.einsum('liab,ab->il', dveca.conj(), tdveca[0, 4, :, :])[5, 5]\n\n Returns:\n Nparray: above RDM in numpy array\n \"\"\"\n norb = self.norb()\n # p^q r^s t^ u spin-blocks\n ckckck_aaa = numpy.zeros((norb, norb, norb, norb, norb, norb),\n dtype=self._dtype)\n ckckck_aab = numpy.zeros((norb, norb, norb, norb, norb, norb),\n dtype=self._dtype)\n ckckck_abb = numpy.zeros((norb, norb, norb, norb, norb, norb),\n dtype=self._dtype)\n ckckck_bbb = numpy.zeros((norb, norb, norb, norb, norb, norb),\n dtype=self._dtype)\n\n dveca, dvecb = self.calculate_dvec_spin()\n dveca_conj, dvecb_conj = dveca.conj().copy(), dvecb.conj().copy()\n opdm, tpdm = self.get_openfermion_rdms()\n # alpha-alpha-alpha\n for t, u in itertools.product(range(self.norb()), repeat=2):\n tdveca_a, _ = self._calculate_dvec_spin_with_coeff(\n dveca[t, u, :, :])\n tdveca_b, tdvecb_b = self._calculate_dvec_spin_with_coeff(\n dvecb[t, u, :, :])\n for r, s in itertools.product(range(self.norb()), repeat=2):\n # p(:)^ q(:) r^ s t^ u\n # a-a-a\n pq_rdm = numpy.tensordot(dveca_conj, tdveca_a[r, s, :, :]).T\n ckckck_aaa[:, :, r, s, t, u] = pq_rdm\n # a-a-b\n pq_rdm = numpy.tensordot(dveca_conj, tdveca_b[r, s, :, :]).T\n ckckck_aab[:, :, r, s, t, u] = pq_rdm\n # a-b-b\n pq_rdm = numpy.tensordot(dveca_conj, tdvecb_b[r, s, :, :]).T\n ckckck_abb[:, :, r, s, t, u] = pq_rdm\n # b-b-b\n pq_rdm = numpy.tensordot(dvecb_conj, tdvecb_b[r, s, :, :]).T\n ckckck_bbb[:, :, r, s, t, u] = pq_rdm\n\n # p^ r^ t^ u s q = p^ q r^ s t^ u + d(q, r) p^ t^ s u - d(q, t)p^ r^ s u\n # + d(s, t)p^ r^ q u - d(q,r)d(s,t)p^ u\n tpdm_swapped = tpdm.transpose(0, 2, 1, 3).copy()\n\n for ii in range(ckckck_aaa.shape[0]):\n ckckck_aaa[:, ii, ii, :, :, :] += tpdm_swapped[::2, ::2, ::2, ::2]\n ckckck_aaa[:, ii, :, :, ii, :] -= tpdm[::2, ::2, ::2, ::2]\n ckckck_aaa[:, :, :, ii, ii, :] += tpdm_swapped[::2, ::2, ::2, ::2]\n for jj in range(ckckck_aaa.shape[0]):\n ckckck_aaa[:, ii, ii, jj, jj, :] -= opdm[::2, ::2]\n ccckkk_aaa = ckckck_aaa.transpose(0, 2, 4, 5, 3, 1).copy()\n\n for ii in range(ckckck_aab.shape[0]):\n ckckck_aab[:, ii, ii, :, :, :] += tpdm_swapped[::2, ::2, 1::2, 1::2]\n ccckkk_aab = ckckck_aab.transpose(0, 2, 4, 5, 3, 1).copy()\n\n for ii in range(ckckck_abb.shape[0]):\n ckckck_abb[:, :, :, ii, ii, :] += tpdm_swapped[::2, ::2, 1::2, 1::2]\n ccckkk_abb = ckckck_abb.transpose(0, 2, 4, 5, 3, 1).copy()\n\n for ii in range(ckckck_bbb.shape[0]):\n ckckck_bbb[:, ii, ii, :, :, :] += tpdm_swapped[1::2, 1::2, 1::2, 1::\n 2]\n ckckck_bbb[:, ii, :, :, ii, :] -= tpdm[1::2, 1::2, 1::2, 1::2]\n ckckck_bbb[:, :, :, ii, ii, :] += tpdm_swapped[1::2, 1::2, 1::2, 1::\n 2]\n for jj in range(ckckck_bbb.shape[0]):\n ckckck_bbb[:, ii, ii, jj, jj, :] -= opdm[1::2, 1::2]\n ccckkk_bbb = ckckck_bbb.transpose(0, 2, 4, 5, 3, 1).copy()\n\n return ccckkk_aaa, ccckkk_aab, ccckkk_abb, ccckkk_bbb\n\n def get_three_pdm(self):\n norbs = self.norb()\n ccckkk = numpy.zeros((2 * norbs,) * 6, dtype=self._dtype)\n ccckkk_aaa, ccckkk_aab, ccckkk_abb, ccckkk_bbb = \\\n self.get_three_spin_blocks_rdm()\n\n # same spin\n ccckkk[::2, ::2, ::2, ::2, ::2, ::2] = ccckkk_aaa\n ccckkk[1::2, 1::2, 1::2, 1::2, 1::2, 1::2] = ccckkk_bbb\n\n # different spin-aab\n # (aab,baa), (aab,aba), (aab,aab)\n # (aba,baa), (aba,aba), (aba,aab)\n # (baa,baa), (baa,aba), (baa,aab)\n ccckkk[::2, ::2, 1::2, 1::2, ::2, ::2] = ccckkk_aab\n ccckkk[::2, ::2, 1::2, ::2, 1::2, ::2] = numpy.einsum(\n 'pqrstu->pqrtsu', -ccckkk_aab)\n ccckkk[::2, ::2, 1::2, ::2, ::2, 1::2] = numpy.einsum(\n 'pqrstu->pqrtus', ccckkk_aab)\n\n ccckkk[::2, 1::2, ::2, 1::2, ::2, ::2] = numpy.einsum(\n 'pqrstu->prqstu', -ccckkk_aab)\n ccckkk[::2, 1::2, ::2, ::2, 1::2, ::2] = numpy.einsum(\n 'pqrstu->prqtsu', ccckkk_aab)\n ccckkk[::2, 1::2, ::2, ::2, ::2, 1::2] = numpy.einsum(\n 'pqrstu->prqtus', -ccckkk_aab)\n\n ccckkk[1::2, ::2, ::2, 1::2, ::2, ::2] = numpy.einsum(\n 'pqrstu->rpqstu', ccckkk_aab)\n ccckkk[1::2, ::2, ::2, ::2, 1::2, ::2] = numpy.einsum(\n 'pqrstu->rpqtsu', -ccckkk_aab)\n ccckkk[1::2, ::2, ::2, ::2, ::2, 1::2] = numpy.einsum(\n 'pqrstu->rpqtus', ccckkk_aab)\n\n # different spin-abb\n # (abb,bba), (abb,bab), (abb,abb)\n # (bab,bba), (bab,bab), (bab,abb)\n # (abb,bba), (abb,bab), (abb,abb)\n ccckkk[::2, 1::2, 1::2, 1::2, 1::2, ::2] = ccckkk_abb\n ccckkk[::2, 1::2, 1::2, 1::2, ::2, 1::2] = numpy.einsum(\n 'pqrstu->pqrsut', -ccckkk_abb)\n ccckkk[::2, 1::2, 1::2, ::2, 1::2, 1::2] = numpy.einsum(\n 'pqrstu->pqrust', ccckkk_abb)\n\n ccckkk[1::2, ::2, 1::2, 1::2, 1::2, ::2] = numpy.einsum(\n 'pqrstu->qprstu', -ccckkk_abb)\n ccckkk[1::2, ::2, 1::2, 1::2, ::2, 1::2] = numpy.einsum(\n 'pqrstu->qprsut', ccckkk_abb)\n ccckkk[1::2, ::2, 1::2, ::2, 1::2, 1::2] = numpy.einsum(\n 'pqrstu->qprust', -ccckkk_abb)\n\n ccckkk[1::2, 1::2, ::2, 1::2, 1::2, ::2] = numpy.einsum(\n 'pqrstu->qrpstu', ccckkk_abb)\n ccckkk[1::2, 1::2, ::2, 1::2, ::2, 1::2] = numpy.einsum(\n 'pqrstu->qrpsut', -ccckkk_abb)\n ccckkk[1::2, 1::2, ::2, ::2, 1::2, 1::2] = numpy.einsum(\n 'pqrstu->qrpust', ccckkk_abb)\n\n return ccckkk\n","sub_path":"src/fqe/fqe_data.py","file_name":"fqe_data.py","file_ext":"py","file_size_in_byte":130770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83385322","text":"import threading\nimport os\nimport shutil\nimport time\n\nimport file\nimport settings\n\n\nclass Upload(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.concurrent_uploads = 0\n self.max_concurrent_uploads = settings.max_concurrent_uploads\n self.target = file.File(settings.target_main)\n self.uploads = {}\n\n def run(self):\n self.move_warcs()\n\n def move_warcs(self):\n while True:\n for dir_ in [dir_ for dir_ in os.listdir('.') if os.path.isdir(dir_)]:\n if dir_ == settings.dir_ready:\n continue\n while not settings.upload_running:\n time.sleep(1)\n files = [file for file in os.listdir(dir_) if os.path.isfile(os.path.join(dir_, file)) and file.endswith('.warc.gz')]\n grab_finished = len(filter(lambda file: file.endswith('-meta.warc.gz'), files)) != 0\n if grab_finished:\n for file in files:\n os.rename(os.path.join(dir_, file), os.path.join(settings.dir_ready, file))\n else:\n for file in files:\n warc_num = int(file[-13:-8])\n warc_num_second = str(warc_num + 1).zfill(5)\n if file[:-13] + warc_num_second + '.warc.gz' in files:\n os.rename(os.path.join(dir_, file), os.path.join(settings.dir_ready, file))\n if grab_finished:\n shutil.rmtree(dir_)\n self.upload()\n time.sleep(10)\n\n def set_max_concurrent_uploads(self, change):\n if self.max_concurrent_uploads + change > settings.max_concurrent_uploads:\n self.max_concurrent_uploads = settings.max_concurrent_uploads\n return\n if self.max_concurrent_uploads + change < 1:\n return\n self.max_concurrent_uploads += change\n\n def upload(self):\n for file in [file for file in os.listdir(settings.dir_ready) if file.endswith('.warc.gz')\n and not os.path.isfile(os.path.join(settings.dir_ready, file+'.upload'))]:\n while not settings.upload_running:\n time.sleep(1)\n time.sleep(1)\n while self.concurrent_uploads > self.max_concurrent_uploads:\n time.sleep(1)\n self.uploads[file] = threading.Thread(target=self.upload_single, args=(file,))\n self.uploads[file].daemon = True\n self.uploads[file].start()\n\n def upload_single(self, file):\n self.concurrent_uploads += 1\n open(os.path.join(settings.dir_ready, file+'.upload'), 'a').close()\n os.system('rsync -avz --no-o --no-g --progress --remove-source-files {file} {target}'.format(\n file=os.path.join(settings.dir_ready, file), target=self.target.read()))\n self.concurrent_uploads -= 1\n os.remove(os.path.join(settings.dir_ready, file+'.upload'))\n if os.path.isfile(os.path.join(settings.dir_ready, file)):\n settings.irc_bot.send('PRIVMSG', '{name} synced unsuccessful to main server.'.format(\n name=file), settings.irc_channel_bot)\n self.set_max_concurrent_uploads(-1)\n else:\n self.set_max_concurrent_uploads(1)","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597456302","text":"from org.csstudio.opibuilder.scriptUtil import PVUtil\nfrom org.csstudio.opibuilder.scriptUtil import ColorFontUtil\n# from org.csstudio.opibuilder.scriptUtil import ConsoleUtil\n\nfunc = display.getPropertyValue(\"name\")\ntype = widget.getPropertyValue(\"name\")\nwidgetType = \"ellipse\";\nvarName = \"XXXXXXX\";\n\nif \"PSH\" in type:\n varName = \"-SYSHLTS\";\nif \"PCF\" in type:\n varName = \"-SYSHLTS\";\nif \"SRV\" in type:\n varName = \"-SYSHLTS\";\nif \"PLC\" in type:\n varName = \"-PLCHLTS\";\nif \"COM\" in type:\n varName = \"-SYSHLTS\";\nif \"CHS\" in type:\n varName = \"-SYSHLTS\";\n# if \"IOM\" in type:\n# varName = \"-BS\";\nif \"CUB\" in type:\n varName = \"-CUBHLTS\";\nif \"Box\" in type:\n widgetType = \"rectangle\";\n\nif varName in triggerPV.getName():\n# ConsoleUtil.writeInfo(\"Trigger PV found: \" +triggerPV.getName());\n \n s = PVUtil.getSeverity(triggerPV)\n\n color = ColorFontUtil.WHITE\n if s == 0:\n color = ColorFontUtil.GREEN\n elif s == 1:\n color = ColorFontUtil.RED\n elif s == 2:\n color = ColorFontUtil.YELLOW\n elif s == 3:\n color = ColorFontUtil.PINK\n elif s == 4:\n color = ColorFontUtil.GREEN \n \n if \"ellipse\" == widgetType:\n widget.setPropertyValue(\"foreground_color\", color)\n \n tooltip = PVUtil.getString(triggerPV)\n widget.setPropertyValue(\"tooltip\", tooltip)\n\nif \"IOM\" in type:\n if \".SIMM\" not in triggerPV.getName():\n \n s = PVUtil.getSeverity(triggerPV)\n color = ColorFontUtil.WHITE\n if s == 0:\n color = ColorFontUtil.GREEN\n elif s == 1:\n color = ColorFontUtil.RED\n elif s == 2:\n color = ColorFontUtil.YELLOW\n elif s == 3:\n color = ColorFontUtil.PINK\n elif s == 4:\n color = ColorFontUtil.GREEN\n \n widget.setPropertyValue(\"foreground_color\", color)\n \n tooltip = PVUtil.getString(triggerPV)\n widget.setPropertyValue(\"tooltip\", tooltip)","sub_path":"codac/units/m-DAN-sample/src/main/boy/sdd/full_hd/scripts/DisplayPVValuesInCubicleContent.py","file_name":"DisplayPVValuesInCubicleContent.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"22281059","text":" # -*- coding: utf-8 -*-\n#Author: jjurado@systeg.mx\n#Descripcion: Modulo de P.G. Conceptos\n#Modulos: [padron.fomentoeconomico]\n#Herencias: 'mail.thread', 'ir.needaction_mixin'\n#Extra: \nfrom odoo import fields,api,models\nfrom odoo import exceptions, _\nimport math\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom dateutil.relativedelta import relativedelta\nimport dateutil.parser\nimport odoo.addons.decimal_precision as dp\nclass padrones_genericos_conceptos(models.Model):\n _name = 'padronesgenericos.conceptos'\n _order = 'date_adeudo asc, id asc'\n \n def _get_default_currency_id(self):\n return self.env.user.company_id.currency_id.id\n \n @api.multi\n @api.depends('monto')\n def pagar(self):\n self.write({'state':'pagada'}) \n self.ref.tablasaldo()\n \n @api.model\n def _get_document_types(self):\n records = self.env['ir.model'].search(['|',('model', '=', 'recaudador.recupobra'),('model', '=', 'recaudador.multmun')])\n return [(record.model, record.name) for record in records] + [('', '')]\n\n\n active = fields.Boolean(string=\"Activo\",default=True)\n name = fields.Char(string='Folio de Movimiento', )\n active = fields.Boolean(string='Esta Activo', default=True)\n concepto_id = fields.Many2one('product.template',string='Concepto', track_visibility=\"onchange\")\n date_adeudo = fields.Date(string='Fecha de adeudo')\n monto_uni = fields.Float(string='Cargo')\n interes = fields.Float(String='Intéres',track_visibility=\"onchange\")\n monto = fields.Float(digits=dp.get_precision('Discount'),string='Monto total', store=True, index=True)\n restante = fields.Float(string='Monto restante', default='0.00')\n pagado = fields.Boolean(string='Pagado', default=False, track_visibility=\"onchange\")\n descripcion = fields.Char(string=\"Descripción\", track_visibility=\"onchange\")\n is_descuento = fields.Boolean(string='Descuento(?)', default=False)\n concepto_desc_id = fields.Many2one('padronesgenericos.conceptos',string='Concepto del Descuento')\n state = fields.Selection([\n ('borrador','Borrador'),\n ('aprobado','aprobado'),\n ('pagada','Pagada'),\n ('inactiva','Inactiva') ,\n ('historica','Historica')\n ],String='Estado', readonly=False, default=\"borrador\", track_visibility='onchange')\n ref = fields.Reference(string='Referencia de Documento', selection='_get_document_types')\n currency_id = fields.Many2one('res.currency', 'Currency', default=_get_default_currency_id)\n sdare_id=fields.Many2one('fomentoeconomico.sdare')\n protec_id=fields.Many2one('proteccion.civil')\n no_unidades=fields.Integer(string=\"No. Unidades\", default=1)\n superficie_baja=fields.Float(string=\"Superficie baja\", store=True)\n superficie_alta=fields.Float(string=\"Superficie alta\")\n value_domain=fields.Char(default=lambda self: self.env['cri.concepto'].search([('codigo', '=', '4307030')]).id)\n cantidad_explosivos=fields.Float(string=\"Cantidad explosivos\", store=True)\n no_ambulancias=fields.Integer(string=\"Cantidad de ambulancias y/o bombreros\", store=True)\n no_asistentes=fields.Integer(string=\"Numero de asistentes\", store=True)\n otros_niveles=fields.Integer(string=\"Otros niveles\", store=True)\n tramite_proteccion=fields.Char(store=True)\n metros_2=fields.Float(string=\"Mts²\", store=True)\n carta=fields.Selection([\n ('chica', 'Chica'),\n ('grande', 'Grande'),\n ],string=u\"Tamaño\")\n hectarea=fields.Float(string=\"Hectáreas\", store=True)\n tipo_revision=fields.Selection([\n ('fracc', 'Fraccionamientos'),\n ('condominios', 'Condominios'),\n ], string=\"Revisión\")\n tipo_regimen=fields.Selection([\n ('fracc', 'Fraccionamiento'),\n ('predio', 'Predio'),\n ],string=\"Régimen\")\n lote=fields.Integer(string=\"Lote\", store=True)\n pieza= fields.Integer(string=\"Pieza(s)\", store=True)\n dias=fields.Integer(string=\"Dia(s)\", store=True)\n zona=fields.Selection([\n ('monumentos', 'Zona Centro'),\n ('transicion', 'Zona de Transición'),\n ],string=\"Zona:\", store= True, track_visibility=\"onchange\")\n tipo=fields.Selection([\n ('interes', 'Interés Social'),\n ('popular', 'Popular'),\n ('medio', 'Medio'),\n ('residencia', 'Residencial'),\n ('comercial', 'Comercial'),\n ('campestre', 'Campestre'),\n ], string=\"Tipo\")\n code_default= fields.Char(store=True, related='concepto_id.default_code')\n tipo_cobro = fields.Selection([\n ('1','Impuestos'),\n ('2','Recargos'),\n ('3','Multas'),\n ('4','Gastos'),\n ('5','Desctos. Impuestos'),\n ('6','Desctos. Recargos'),\n ('7','Desctos. Multas'),\n ('8','Desctos. Gastos'),\n ],store=True, string='Tipo de Cobro', default='1')\n tipo_obra = fields.Selection([\n ('menores', 'Obras menores'),\n ('proyectos', 'Proyectos'),\n ], string=\"Tipo obra\")\n id_municipio=fields.Char(store=True)\n fecha_pago=fields.Date(string=\"Fecha de pago\")\n numero_viviendas= fields.Integer(string=\"Numero de viviendas\")\n tipo_pago= fields.Selection([\n ('micro', 'Microcreditos'),\n ('focmed', 'FOCMED'),\n ],string=\"tipo credito\", store=True)\n date_generate = fields.Date(string=\"Fecha Generacion\")\n programa_aprobado = fields.Boolean(default=False)\n n_juegos= fields.Integer(string=\"Cantidad de Juegos\")\n tipo_instalacion = fields.Selection([\n ('itinerantes', 'Itinerantes'),\n ('circo_varios', 'Circo y estructura varias')\n ], string=\"Tipo intalaciones\")\n tamano_empresa = fields.Selection([\n ('micro', 'Micro empresa'),\n (u'pequeña', 'Pequeña empresa'),\n ('mediana', 'Mediana empresa'),\n ('grande', 'Grande empresa'),\n ], string=\"Tamaño empresas\")\n tipo_construccion = fields.Selection([\n ('casa', 'Habitacional - casa o departamento residencial'),\n ('fracc', 'Habitacional – Fraccionamiento'),\n ('comercial','Comercial micro, pequeña y mediana empresa'),\n ('industrial','Industrial')\n ],string=\"Tipo construcción\")\n tamano_empresa = fields.Selection([\n ('micro', 'Micro empresa'),\n (u'pequeña', 'Pequeña empresa'),\n ('mediana', 'Mediana empresa'),\n ('grande', 'Grande empresa'),\n ],string=\"Tamaño empresa\")\n cantidad_ninos = fields.Integer(string=\"Cantidad de niños\")\n tipo_institucion = fields.Selection([\n ('prescolar', 'Preescolar'),\n ('primaria', 'Primaria'),\n ('secundaria', 'Secundaria'),\n ('preparatoria', 'Preparatoria o bachillerato'),\n ('superior', 'Educación superior o Licenciatura'),\n ('posgrado', 'Estudio de Posgrado'),\n ('investigacion', 'Centro de investigación')\n ], string=\"Tipo Institución\")\n presupuesto_urbanizacion = fields.Float(string=\"Presupuesto de Urbanización\")\n monto_contrato = fields.Float(string=\"Monto Contrato\")\n vencimiento = fields.Date(string=\"Fecha de vencimiento\")\n print_solicitud = fields.Boolean(string=\"Solicitud impresa(?)\")\n bimestre = fields.Integer(string=\"bimestre\")\n default_code = fields.Char( string='codigo')\n cuenta_contable_valor = fields.Char(string=\"Cuenta\")\n \n \n \n\n @api.onchange('concepto_id')\n def get_defaultcode(self):\n if self.concepto_id:\n self.default_code = self.concepto_id\n\n \n @api.multi\n @api.onchange('pagado')\n def check_fechapago(self):\n if self.pagado == True and self.tipo_pago in ['micro', 'focmed']:\n\n monto_concepto = self.monto\n fecha_pago = str(datetime.now().date())\n tipo_credito = self.tipo_pago\n data_ingreso= {\n 'monto': monto_concepto, \n 'fecha_pago': fecha_pago, \n 'tipo_credito': tipo_credito,\n }\n self.update({'fecha_pago': fecha_pago})\n self.env['pagos.fomento'].create(data_ingreso)\n \n def elimina_concepto(self,concepto): \n boleta = self.env[concepto['modelo'].split(',')[0]].search([('id','=',concepto['modelo'].split(',')[1])])\n boleta.message_post(body=u\"Se elimino un cobro con la siguiente información:
      -Concepto:\"+self.concepto_id.name+\"
      -Descripcion: \"+self.descripcion+\"
      -Monto: \"+str(self.monto)+\".\",subject=\"Record Updated\")\n boleta.elimina_concepto(concepto) \n return {'type':'ir.actions.client','tag':'reload'}\n \n \"\"\"elif self.pagado == False and self.tipo_pago in ['micro', 'focmed']:\n pagos_fomento = self.env['pagos.fomento'].search([('id_pago', '=', self.id)], limit=1)\n pagos_fomento.unlink()\"\"\"\n\n\n \n \"\"\"@api.onchange('superficie_baja', 'concepto_id', 'tipo_revision','otros_niveles','carta', 'no_unidades', 'tipo_regimen', 'tipo', 'superficie_alta', 'metros_2', 'hectarea', 'lote', 'zona', 'pieza', 'cantidad_explosivos', 'no_ambulancias', 'no_asistentes')\n def calcule_total(self):\n for values in self:\n if values.tramite_proteccion == False:\n values.tramite_proteccion = values.protec_id.clave_tramite\n if values.concepto_id.id != False and (values.superficie_baja != False or values.hectarea != False or values.metros_2 != False or values.lote != False or values.pieza != False or values.carta != False or values.no_unidades != False):#\n monto= self.env['desarrollo.formulaconcepto'].search([])\n montof = {}\n for mont in monto:\n if mont.aplicar == 'grupo':\n for conceptos in mont.product_tmpl_ids:\n if values.concepto_id.id == conceptos.id:\n montof = mont\n break\n elif mont.aplicar == 'concepto':\n if mont.product_tmpl_id.id == values.concepto_id.id:\n montof= mont\n break\n elif mont.aplicar == 'categoria':\n for conceptos in mont.categoria_id.subconcepto_ids:\n if values.concepto_id.id == conceptos.id:\n montof = mont\n break\n print \"-----------%s\"%montof\n no_unidades = values.no_unidades\n superficie_baja = values.superficie_baja\n superficie_alta = values.superficie_alta\n otros_niveles = values.otros_niveles\n tipo = values.tipo\n tipo_regimen = values.tipo_regimen\n hectarea= values.hectarea\n tipo_revision = values.tipo_revision\n lote = values.lote\n metros_2 = values.metros_2\n cantidad_explosivos = values.cantidad_explosivos\n no_ambulancias = values.no_ambulancias\n no_asistentes = values.no_asistentes\n tramite_proteccion = values.tramite_proteccion\n zona =values.zona\n pieza = values.pieza\n concepto_id = values.concepto_id.list_price\n carta = values.carta\n values.monto =montof.get_calcule(no_unidades, superficie_baja, superficie_alta, otros_niveles, tipo, tipo_regimen, hectarea, tipo_revision, zona, lote, metros_2, pieza, concepto_id, carta, cantidad_explosivos, no_ambulancias, no_asistentes, tramite_proteccion) \"\"\"\n\n\n \n\n \nclass padrones_genericos_conceptos_predial(models.Model):\n _name = 'padronesgenericos.conceptos.predial'\n _order = 'date_adeudo asc, id asc'\n \n def _get_default_currency_id(self):\n return self.env.user.company_id.currency_id.id\n \n @api.multi\n @api.depends('monto')\n def pagar(self):\n self.write({'state':'pagada'}) \n self.ref.tablasaldo()\n \n @api.model\n def _get_document_types(self):\n records = self.env['ir.model'].search(['|',('model', '=', 'recaudador.predial'),('model','=','recaudador.altanotas')])\n return [(record.model, record.name) for record in records] + [('', '')]\n \n active = fields.Boolean(string=\"Activo\",default=True)\n name = fields.Char(string='Folio de Movimiento')\n active = fields.Boolean(string='Esta Activo', default=True)\n concepto_id = fields.Many2one('product.template',string='Concepto')\n default_code = fields.Char(related = 'concepto_id.default_code', store=True)\n date_adeudo = fields.Date(string='Fecha de adeudo')\n monto_uni = fields.Float(string='Cargo', digits=dp.get_precision('Discount'))\n interes = fields.Float(String='Intéres')\n monto = fields.Float(string='Monto total', digits=dp.get_precision('Discount'))\n restante = fields.Float(string='Monto restante', default='0.00', digits=dp.get_precision('Discount'))\n pagado = fields.Boolean(string='Pagado', default=False)\n descripcion = fields.Char(string=\"Descripción\")\n is_descuento = fields.Boolean(string='Descuento(?)', default=False)\n concepto_desc_id = fields.Many2one('padronesgenericos.conceptos.predial',string='Concepto del Descuento')\n state = fields.Selection([\n ('borrador','Borrador'),\n ('aprobado','aprobado'),\n ('pagada','Pagada'),\n ('inactiva','Inactiva') ,\n ('historica','Historica')\n ],String='Estado', readonly=False, default=\"borrador\", track_visibility='onchange')\n bimestre = fields.Integer(compute='_calc_bimestre', store=True)\n tipo_cobro = fields.Selection([\n ('1','Impuestos'),\n ('2','Recargos'),\n ('3','Multas'),\n ('4','Gastos'),\n ('5','Desctos. Impuestos'),\n ('6','Desctos. Recargos'),\n ('7','Desctos. Multas'),\n ('8','Desctos. Gastos'),\n ],store=True, string='Tipo de Cobro', default='1')\n ref = fields.Reference(string='Referencia de Documento', selection='_get_document_types')\n currency_id = fields.Many2one('res.currency', 'Currency', default=_get_default_currency_id)\n id_muncipio=fields.Char(store=True)\n vencimiento = fields.Date(string=\"Fecha de vencimiento\") #TD se agrega line\n cuenta_contable_valor = fields.Char(string=\"Cuenta\")\n \n @api.onchange('concepto_id')\n def get_defaultcode(self):\n if self.concepto_id:\n self.default_code = self.concepto_id\n\n @api.one\n @api.depends('date_adeudo')\n def _calc_bimestre(self):\n if self.date_adeudo:\n f1=float(self.date_adeudo[5:7])\n mes = float(f1/2)\n bim = math.ceil(mes)\n self.bimestre = bim\n #return self\n \nclass padrones_genericos_conceptos_infracciones(models.Model):\n _name = 'padronesgenericos.conceptos.infracciones'\n _order = 'date_adeudo asc, id asc'\n \n def _get_default_currency_id(self):\n return self.env.user.company_id.currency_id.id\n \n @api.multi\n @api.depends('monto')\n def pagar(self):\n self.write({'state':'pagada'}) \n self.ref.tablasaldo()\n \n @api.model\n def _get_document_types(self):\n records = self.env['ir.model'].search([('model', '=', 'recaudador.infracciones')])\n return [(record.model, record.name) for record in records] + [('', '')]\n active = fields.Boolean(string=\"Activo\",default=True)\n name = fields.Char(string='Folio de Movimiento')\n concepto_id = fields.Many2one('product.template',string='Concepto')#domain=\"[('check_concepto_cobro', '=', True)]\"\n date_adeudo = fields.Date(string='Fecha de adeudo')\n monto_uni = fields.Float(string='Cargo',digits=dp.get_precision('Discount'))\n interes = fields.Float(String='Intéres',digits=dp.get_precision('Discount'))\n monto = fields.Float(string='Monto total',digits=dp.get_precision('Discount'))\n tarifa_min = fields.Float(string='Tarifa mínima',digits=dp.get_precision('Discount'))\n tarifa_max = fields.Float(string='Tarifa máxima',digits=dp.get_precision('Discount'))\n restante = fields.Float(string='Monto restante', default='0.00',digits=dp.get_precision('Discount'))\n pagado = fields.Boolean(string='Pagado', default=False)\n descripcion = fields.Char(string=\"Descripción\")\n is_descuento = fields.Boolean(string='Descuento(?)', default=False)\n concepto_desc_id = fields.Many2one('padronesgenericos.conceptos.infracciones',string='Concepto del Descuento')\n state = fields.Selection([\n ('borrador','Borrador'),\n ('aprobado','aprobado'),\n ('pagada','Pagada'),\n ('inactiva','Inactiva') ,\n ('historica','Historica')\n ],String='Estado', readonly=False, default=\"borrador\", track_visibility='onchange')\n ref = fields.Reference(string='Referencia de Documento', selection='_get_document_types')\n currency_id = fields.Many2one('res.currency', 'Currency', default=_get_default_currency_id)\n tipo_cobro = fields.Selection([\n ('1','Impuestos'),\n ('2','Recargos'),\n ('3','Multas'),\n ('4','Gastos'),\n ('5','Desctos. Impuestos'),\n ('6','Desctos. Recargos'),\n ('7','Desctos. Multas'),\n ('8','Desctos. Gastos'),\n ],store=True, string='Tipo de Cobro', default='1')\n id_muncipio=fields.Char(store=True)\n #Campo para heredar el valor del estado de la cabecera\n estado = fields.Char(string='Estatus de la cabecera',compute=\"_hereda_state\",store=False)\n cargo_especial=fields.Boolean(string='Cargo especial',default=False)\n opcional=fields.Boolean(string='¿Opcional?',default=False)\n cuenta_contable_valor = fields.Char(string=\"Cuenta\")\n def elimina_concepto(self,concepto):\n boleta = self.env[concepto['modelo'].split(',')[0]].search([('id','=',concepto['modelo'].split(',')[1])])\n boleta.elimina_concepto(concepto)\n return {'type':'ir.actions.client','tag':'reload'}\n \n @api.multi\n def _hereda_state(self):\n for record in self:\n record.estado=record.ref.state\n","sub_path":"extrasGDL/recaudador/models/models_padronesgenericos_conceptos.py","file_name":"models_padronesgenericos_conceptos.py","file_ext":"py","file_size_in_byte":18167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471035529","text":"from django.shortcuts import render, HttpResponseRedirect, reverse\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.decorators import login_required\n\nfrom forms.forms import SimpleSearchForm, ContactSortSearchForm\nfrom scripts.search import get_query\n\nfrom . import models\nfrom .forms import ContactsForm\n\n\nclass ContactCreateView(LoginRequiredMixin, CreateView):\n model = models.Contact\n template_name = \"contacts_new.html\"\n form_class = ContactsForm\n \n\n@login_required\ndef contacts_detail(request, pk):\n contact = models.Contact.objects.get(pk=pk)\n\n if request.method == \"POST\":\n if \"delete_contact\" in request.POST:\n contact.delete()\n \n return HttpResponseRedirect(reverse('contacts:contacts_list'))\n\n context_dict = {\n 'contact': contact\n }\n\n return render(request, 'contacts_detail.html', context=context_dict)\n\n\nclass ContactUpdateView(LoginRequiredMixin, UpdateView):\n model = models.Contact\n template_name = \"contacts_update.html\"\n context_object_name = \"contact\"\n form_class = ContactsForm\n \n\nclass ContactDeleteView(LoginRequiredMixin, DeleteView):\n model = models.Contact\n template_name = \"contacts_delete.html\"\n success_url = reverse_lazy(\"contacts:contacts_list\")\n context_object_name = \"contact\"\n\n@login_required\ndef contacts_redirect_list_view(request):\n return HttpResponseRedirect(reverse('contacts:contacts_list'))\n\n@login_required\ndef contacts_list(request):\n \"\"\"\n Contacts List:\n Lists rental_projects based on sorting selection.\n If search, it is sorted by the sorting selection.\n \"\"\"\n\n contacts_list = models.Contact.objects.all().order_by('first_name')\n sorting_search_form = ContactSortSearchForm()\n query_string = None\n\n # if sort_options == 'first':\n # filtering = 'first_name'\n # contacts_list = contacts_list.order_by(filtering)\n # elif sort_options == 'last':\n # filtering = 'last_name'\n # contacts_list = contacts_list.order_by(filtering)\n\n sorting_options = {\n \"0\": \"first_name\",\n \"1\": \"last_name\"\n }\n \n if request.method == \"GET\":\n if 'search_filter' in request.GET or 'clear_search' in request.GET:\n sorting = sorting_options[request.GET['name_sorting']]\n print(sorting)\n contacts_list = models.Contact.objects.all().order_by(sorting)\n if request.GET['search_field'] == '':\n sorting_search_form = ContactSortSearchForm(request.GET)\n else:\n query_string = request.GET['search_field']\n query = get_query(\n query_string, ['first_name', 'last_name',])\n contacts_list = contacts_list.filter(query).order_by(sorting)\n sorting_search_form = ContactSortSearchForm(request.GET)\n \n context_dict = {\n 'contacts_list': contacts_list,\n 'sorting_search_form': sorting_search_form,\n 'results': query_string,\n }\n\n return render(request, 'contacts_list.html', context_dict)\n\n","sub_path":"contacts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210358833","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n#############################################\n# CARLLOS PULIDO MARQUEZ NIA: 163842 #\n# ALBERT BOVE CASTELLVI NIA: 163729 #\n#############################################\n\nfrom util import manhattanDistance\nfrom game import Directions\nimport random, util\n\nfrom game import Agent\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {North, South, West, East, Stop}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n\n return legalMoves[chosenIndex]\n\n def evaluationFunction(self, currentGameState, action):\n \"\"\"\n Design a better evaluation function here.\n\n The evaluation function takes in the current and proposed successor\n GameStates (pacman.py) and returns a number, where higher numbers are better.\n\n The code below extracts some useful information from the state, like the\n remaining food (newFood) and Pacman position after moving (newPos).\n newScaredTimes holds the number of moves that each ghost will remain\n scared because of Pacman having eaten a power pellet.\n\n Print out these variables to see what you're getting, then combine them\n to create a masterful evaluation function.\n \"\"\"\n # Useful information you can extract from a GameState (pacman.py)\n\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n newPos = successorGameState.getPacmanPosition()\n newFood = successorGameState.getFood()\n newGhostStates = successorGameState.getGhostStates()\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n\n \"*** YOUR CODE HERE ***\"\n\n #obtener el food actual y lo convertimos en lista para despues usarlo\n food = currentGameState.getFood()\n foodList = food.asList()\n\n newGhostPosition = successorGameState.getGhostPositions() #nuevas posiciones de los ghost\n distFood = set() #creamos una lista para luego guardar la distancia a los food\n score = 0 #inicializamos la puntuacion a 0\n\n #distancia entre posicion del pacman y cada food\n for food in foodList:\n distFood.add(manhattanDistance(food, newPos))\n\n #Miramos la distancia entre cada uno de los ghost\n for ghost in newGhostPosition:\n if manhattanDistance(newPos, ghost) < 2 :#Si la distancia hacia el ghost es inferior a 2, penalizamos con -50 puntos\n return score-50\n\n #Si vemos que el pacman esta parado, penalizamos con -50 puntos\n if currentGameState.getPacmanPosition() is Directions.STOP:\n return score-50\n\n #Comprobamos si queda comida y si queda, miramos la distancia minima\n if len(foodList)>0:\n score = min(distFood)\n\n return -score\n #retornamos un score negativo ya que sino cuando tengamos distancia 2, que estemos cerca del food, nuestro pacman no comera ya que el getAction se queda con el maximo\n #return successorGameState.getScore() \n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n return currentGameState.getScore()\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action from the current gameState using self.depth\n and self.evaluationFunction.\n\n Here are some method calls that might be useful when implementing minimax.\n\n gameState.getLegalActions(agentIndex):\n Returns a list of legal actions for an agent\n agentIndex=0 means Pacman, ghosts are >= 1\n\n gameState.generateSuccessor(agentIndex, action):\n Returns the successor game state after an agent takes an action\n\n gameState.getNumAgents():\n Returns the total number of agents in the game\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n #Evaluar\n def evaluate(depth, state, agentIndex):\n #Si es el ultimo agente, bajamos la profundidad\n #y empezamos otra vez\n if agentIndex is state.getNumAgents():\n depth-= 1\n agentIndex = 0\n \n #Turno pacman\n if agentIndex is 0:\n #Evaluamos state,indice,profundidad\n if depth is 0 or state.isLose() or state.isWin():\n return self.evaluationFunction(state)\n\n value = float(\"-inf\")\n for action in state.getLegalActions(agentIndex):\n nextState = state.generateSuccessor(agentIndex, action)\n value = max( value, evaluate(depth, nextState, agentIndex+1))\n return value\n\n #turno ghost\n else:\n #comprobar si es un terminal o profundidad limite\n if depth is 0 or state.isLose() or state.isWin():\n return self.evaluationFunction(state)\n\n value = float(\"inf\")\n for action in state.getLegalActions(agentIndex):\n nextState = state.generateSuccessor(agentIndex, action)\n value = min(value, evaluate(depth, nextState, agentIndex+1))\n return value\n\n #Main\n score = float(\"-inf\")\n bestAction = Directions.STOP\n\n #Recorremos acciones legales de pacman\n for action in gameState.getLegalActions(self.index):\n fill = gameState.generateSuccessor(self.index, action)\n newScore = evaluate(self.depth, fill, self.index+1)\n\n #Actualizamos el score y nos quedamos con el mayor\n if newScore > score:\n score = newScore\n bestAction = action\n return bestAction\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action using self.depth and self.evaluationFunction\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n #Evaluar\n def evaluate(depth, state, agentIndex, alpha, beta):\n #Si es el ultimo agente, bajamos laprofundidad\n #y empezamos otra vez\n if agentIndex is state.getNumAgents():\n depth-= 1\n agentIndex = 0\n \n #Turno pacman\n if agentIndex is 0:\n #Evaluamos state,indice,profundidad\n if depth is 0 or state.isLose() or state.isWin():\n return self.evaluationFunction(state)\n value = float(\"-inf\")\n\n for action in state.getLegalActions(agentIndex):\n nextState = state.generateSuccessor(agentIndex, action)\n value = max( value, evaluate(depth, nextState, agentIndex+1, alpha, beta))\n if value > beta: return value\n alpha = max(value, alpha)\n return value\n\n #turno ghost\n else:\n #comprobar si es un terminal o profundidad limite\n if depth is 0 or state.isLose() or state.isWin():\n return self.evaluationFunction(state)\n\n value = float(\"inf\")\n for action in state.getLegalActions(agentIndex):\n nextState = state.generateSuccessor(agentIndex, action)\n value = min(value, evaluate(depth, nextState, agentIndex+1, alpha, beta))\n if value < alpha: return value\n beta = min(value, beta)\n return value\n\n #Main\n score = alpha = float(\"-inf\")\n bestAction = Directions.STOP\n beta = float('inf')\n\n #Recorremos acciones legales de pacman\n for action in gameState.getLegalActions(self.index):\n fill = gameState.generateSuccessor(self.index, action)\n newScore = evaluate(self.depth, fill, self.index+1, alpha, beta)\n alpha = max(newScore, alpha)\n\n #Actualizamos el score y nos quedamos con el mayor\n if newScore > score:\n score = newScore\n bestAction = action\n return bestAction\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n util.raiseNotDefined()\n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"*** YOUR CODE HERE ***\"\n util.raiseNotDefined()\n\n# Abbreviation\nbetter = betterEvaluationFunction\n\n","sub_path":"P2/multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":11537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398473352","text":"import os\n\n\ndef get_anns(root_path, ann_file):\n root_path = '/home/zcj/github/od_fovea_location/data/fovea'\n with open(os.path.join(root_path, 'annotations.txt'), 'w') as tr1:\n with open(os.path.join(root_path, ann_file), 'r') as tr:\n annos = tr.readlines()\n for i, ann in enumerate(annos):\n print(i, ann.strip().split()[0])\n ann_list = ann.strip().split()\n\n filename = ann_list[0]+'.jpg'\n x1 = str(int(ann_list[1])-60)\n y1 = str(int(ann_list[2])-60)\n x2 = str(int(ann_list[1])+60)\n y2 = str(int(ann_list[2])+60)\n # print(x1, y1, x2, y2)\n ann = ' '.join([filename, '1', x1, y1, x2, y2])+'\\n'\n print(ann)\n tr1.write(ann)\n\nget_anns(root_path='/home/zcj/github/od_fovea_location/data/fovea', ann_file='id.fovea.txt')\nprint(\"add code to github\")\n# print(annos)","sub_path":"data/convert_filename_to_jpg.py","file_name":"convert_filename_to_jpg.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630662182","text":"# !/usr/bin/env python\n# _*_ coding:utf-8 _*_\n\n\nimport urllib.request\n\n\ndef load_data():\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko\",\n }\n\n url = 'http://www.baidu.com'\n # 请求对象\n request = urllib.request.Request(url, headers=headers)\n request.add_header('Connection', '123')\n\n # 发送请求 request对象\n response = urllib.request.urlopen(request)\n\n # 获取请求头的信息- key 首字母大写 其他的是小写\n request_user_agnet = request.get_header('Connection')\n\n # 读取数据 read() --bytes\n print(request_user_agnet)\n\n\nif __name__ == '__main__':\n load_data()\n","sub_path":"scrapy_lian/laoshi02/07urllib_request_headers.py","file_name":"07urllib_request_headers.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180084242","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport os,sys\nfrom matplotlib import rc\n\nrc('text', usetex=True)\nif len(sys.argv) < 3:\n\tprint (\"exec \")\n\texit(1)\n\nband_path = sys.argv[1] \ngap_path = sys.argv[2]\nID = os.path.basename(gap_path).split('_')[-1]\nID = ID.split('.')[0]\n\nf = open(band_path,'r')\nlines= f.readlines()\nf.close()\n\nFixs = [] # \nfor i in np.arange(3,24,3):\n\ttmp = lines[i].strip()\n\ttmp = tmp.split(' ')\n\ttmp2 = lines[i+1].strip()\n\ttmp2 = tmp2.split(' ')\n\tFixs.append(np.array([tmp[0],tmp[1],tmp2[1]],dtype=np.float))\n\nFixs = np.array(Fixs)\t\nFixs = np.vstack((Fixs,np.array([0.0,Fixs[0,1],Fixs[0,2]])))\nbands = []\nband= []\nfor l in np.arange(24,len(lines),1):\n\tlines[l] = lines[l].strip()\n\tbands.append(np.array(lines[l].split(' '),dtype=np.float))\n\nbands= np.array(bands)\n\n## get points in each band\ntmp = np.sort(np.argwhere(bands[:,0]<1.0e-10))\nNpoint = int( (tmp[1] - tmp[0]+1)/2 )\n\nbands = bands.reshape((int(len(bands)/Npoint),Npoint,2))\nNband = len(bands)\nprint (\"N band : %d\"%(Nband))\nprint (\"N point per band : %d\"%(Npoint))\nfor b in range(Nband):\n\tnew_band = bands[b,np.argsort(bands[b,:,0])]\n\tbands[b] = new_band\n\t\n\n## read the LUMO & HOMO \nf = open(gap_path,'r')\nlines = f.readlines()\nf.close()\nfnxt = 0\nEgap = 0\nlumo_id , homo_id , lumo_E,homo_E = 0,0,0,0\nfor line in lines:\n\tif fnxt == 1:\n\t\tEgap = np.float(line.strip())\n\tif 'LUMO' in line:\n\t\tline = line.split(' ')\n\t\tlumo_id = int(line[2])\n\t\tlumo_E = float(line[5])\n\t\n\telif 'HOMO' in line:\n\t\tline = line.split(' ')\n\t\thomo_id = int(line[2])\n\t\thomo_E = float(line[5])\n\telif 'E gap' in line:\n\t\tfnxt = 1\nprint (\"LUMO : band : %d E = %f\"%(lumo_id,lumo_E))\nprint (\"HOMO : band : %d E = %f\"%(homo_id,homo_E))\nprint (\"band gap = %f\"%(Egap))\n\nplt.figure(1)\nfor b in range(Nband):\n\tif b == lumo_id - 1:\n\t\tplt.plot(bands[b,:,0],bands[b,:,1],'r-',label='LUMO')\n\telif b == homo_id -1:\t\n\t\tplt.plot(bands[b,:,0],bands[b,:,1],'b-',label='HOMO')\n\telse:\n\t\tplt.plot(bands[b,:,0],bands[b,:,1],'k-')\n\nfor ft in Fixs:\n\tplt.axvline(ft[0], color='0.2', linestyle='-',linewidth=0.2)\n\n\nnew_tick_loc = np.sort(np.unique(Fixs[:,0]))\nprint (len(new_tick_loc))\nnew_tick_label = [r\"$\\Gamma$\",\"X\",\"W\",\"L\",r\"$\\Gamma$\"]\n#print plt.xticks()[0]\nplt.xticks(new_tick_loc,new_tick_label)\nplt.xlim([0,1])\nplt.legend()\nplt.title(ID.upper() + ' band structure')\nplt.savefig(ID+'.png',format='png',dpi=100)\nplt.show()\n\n\n","sub_path":"hw3/Material/q3/band.py","file_name":"band.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124618688","text":"\"\"\"ops URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/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.conf.urls import url, include\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework.documentation import include_docs_urls\n# 正式api\nfrom users.views import (\n UsersLoginViewSet,\n UsersRegisterViewSet,\n UsersOperationsViewSet,\n UsersChangePasswordViewSet,\n UsersGroupViewSet,\n UsersAddViewSet,\n PersonalInfoViewSet,\n PersonalChangePasswordViewSet,\n UsersOpenViewSet,\n)\nfrom permission.views import (\n CheckPagePermissionCheckViewSet,\n PermissionGroupViewSet,\n)\nfrom operation.views import (\n GlobalOperatingLogViewSet,\n MessageMailLogViewSet,\n GlobalSearchViewSet,\n)\nfrom message.views import (\n InnerMessageViewSet,\n InnerMessageUnreadCountViewSet,\n InnerMessageOperationViewSet,\n MessagePushViewSet,\n)\nfrom common.views import (\n CommonSettingMessageViewSet,\n CommonSettingMessageTestViewSet,\n CommonSettingCmdbViewSet,\n CommonSettingAppViewSet,\n CommonSettingSshProxyViewSet,\n CommonSettingCodePublishViewSet,\n)\nfrom cmdb.cloud.views import (\n AliyunKeyViewSet,\n AliyunECSViewSet,\n AliyunEcsAutoViewSet,\n AliyunGraphViewSet,\n AliyunEcsClassfiyViewSet,\n AliyunKey2ECsViewSet,\n AliyunEcsAppRelViewSet,\n AliyunRdsClassfiyViewSet,\n AliyunRdsGraphViewSet,\n AliyunKey2RdsViewSet,\n AliyunRdsProcessListViewSet,\n)\nfrom cmdb.native.views import (\n NativeHostViewSet,\n NativeClassifyViewSet,\n NativeHostAppsRelViewSet,\n NativeHostGraphViewSet,\n NativeHostGraphCounterViewSet,\n)\nfrom cmdb.cmdb_common.views import (\n TagsViewSet,\n TagsAliyunEcsRelViewSet,\n TagsNativeHostRelViewSet,\n AnisbleUpdateHostInfoViewSet,\n AnsibleAddHostInfoViewSet,\n AllHostViewSet,\n)\nfrom apps.views import (\n AppDetailViewSet,\n AppHostRelViewSet,\n AppAliveUrlookerViewSet,\n)\nfrom monitor.views import (\n MonitorAppAliveGraphViewSet,\n MonitorAppAliveLatestDataViewSet,\n MonitorAppAliveTactics,\n MonitorThirdPartyStrategyViewSet,\n MonitorTPGraphViewSet,\n MonitorUpdateTPView,\n MonitorTPDomainViewSet,\n MonitorTPECSViewSet,\n MonitorTPNASViewSet,\n MonitorTPRDSViewSet,\n MonitorTPTencentSmsViewSet,\n MonitorTPVpnViewSet,\n MonitorTPXunChengEryaosuViewSet,\n MonitorTPWanweiyiyuanBankIdentityViewSet,\n MonitorTPYueXinSmsViewSet,\n MonitorThirdPartyJitterStrategyViewSet,\n MonitorTPBaseStrategyItemView,\n MonitorTPJitterStrategyItemView,\n MonitorDockerAppGraphViewSet,\n)\nfrom activity.business.views import (\n AccessAlarmStrategyViewSet,\n AccessAlarmAvgViewSet,\n)\nfrom openapi.views import (\n OpenApiFalconAlarmViewSet,\n OpenApiMysqlQueryViewSet,\n OpenApiAnsibleHostViewSet,\n OpenApiAliyunSLBCtrlViewSet\n)\nfrom code_publish.views import (\n CodePublishMainConfViewSet,\n CodePublishStatusViewSet,\n CodePublishWebMainConfViewSet,\n CodePublishWebDockerfileViewSet,\n CodePublishWebDockerOptsViewSet,\n CodePublishWebJarOptsViewSet,\n CodePublishWebStepsOptsViewSet,\n CodePublishWebJavaOptsViewSet,\n CodePublishWebMvnOptsViewSet,\n CodePublishWebGradleOptsViewSet,\n CodePublishEnvViewSet,\n CodePublishReplaceIpViewSet,\n CodePublishCopyConfigViewSet,\n CodePublishSetStepsViewSet,\n CodePublishAppDetailViewSet,\n CodePublishControlAppDetailViewSet,\n CodePublishTaskStatusViewSet,\n CodePublishControlViewSet,\n CodePublishStopBuildViewSet,\n CodePublishCheckCodeBranch,\n CodePublishBatchCopyConfigViewSet,\n CodePublishHasBeenPublishedViewSet,\n CodePublishGetRTSteps,\n CodePublishRTTaskStatusViewSet,\n CodePublishAlreadyPublishedVerViewSet,\n CodePublishAppEndpointViewSet,\n CodePublishUnlockPublishIp,\n CodePublishMainConfAppDetailViewSet,\n CodePublishEnvLockViewSet,\n CodePublishEnvUnLockViewSet,\n CodePublishEnvLockChoseEnvApp\n)\n\n# 测试api\nfrom message.tests import (\n TestSenderView\n)\nfrom cmdb.cloud.tests import (\n TestAliyunEcsViewSet,\n TestAliyunGraphViewSet,\n)\nfrom cmdb.cmdb_common.tests import (\n TestAnsibleUpdateCron,\n TestAliyunUpdateCron,\n)\nfrom activity.business.tests import (\n TestAccessAlarmStrategyView,\n)\nfrom monitor.tests import (\n TestThirdPartySaveDataViewSet,\n TestPushDataToFalcon,\n TestTPPushJitterData,\n)\nfrom code_publish.tests import (\n TestCodePublishCron,\n)\nfrom common.tests import (\n TestGetAppAliveStatistics,\n)\n\nrouter_v1 = DefaultRouter()\napi_v1_prefix = '^api/v1/'\n# 用���ApiView,但是尽量使用ViewSet来定义api (基础代码中有足够的参考)\nrouter_v1_view_urls = []\n\"\"\"\n以下url还没完全明确如何规范,暂时的想法: f'^{app_name}/[{target_range}|{target}]/target'\n至于需要连写直接使用横杠即可,如 users/change-passwd\n\"\"\"\n\n# 用户相关\nrouter_v1.register(r'^users/register', UsersRegisterViewSet, base_name='users_register')\nrouter_v1.register(r'^users/login', UsersLoginViewSet, base_name='users_login')\nrouter_v1.register(r'^users/operations', UsersOperationsViewSet, base_name='users_operations')\nrouter_v1.register(r'^users/change-passwd', UsersChangePasswordViewSet, base_name='users_changePassword')\nrouter_v1.register(r'^users/group', UsersGroupViewSet, base_name='users_group')\nrouter_v1.register(r'^users/add', UsersAddViewSet, base_name='users_add')\nrouter_v1.register(r'^users/open', UsersOpenViewSet, base_name='users_open_list')\n\n# 个人信息相关\nrouter_v1.register(r'^personal/info', PersonalInfoViewSet, base_name='personal_info')\nrouter_v1.register(r'^personal/password', PersonalChangePasswordViewSet, base_name='personal_password')\n\n# 权限相关\nrouter_v1.register(r'^permission/page/check', CheckPagePermissionCheckViewSet, base_name='permission_page_check')\nrouter_v1.register(r'^permission/group', PermissionGroupViewSet, base_name='permission_group')\n\n# 操作记录相关\nrouter_v1.register(r'^operation/log/global', GlobalOperatingLogViewSet, base_name='operation_log_global')\nrouter_v1.register(r'^operation/log/message/mail', MessageMailLogViewSet, base_name='op_log_message_mail')\n# 全局搜索\nrouter_v1.register(r'^operation/global-search', GlobalSearchViewSet, base_name='operation_global_search')\n\n# 消息相关\nrouter_v1.register(r'^message/inner', InnerMessageViewSet, base_name='inner_message')\nrouter_v1.register(r'^message/count', InnerMessageUnreadCountViewSet, base_name='inner_message_unread_count')\nrouter_v1.register(r'^message/operation', InnerMessageOperationViewSet, base_name='inner_message_operation')\nrouter_v1.register(r'^message/push', MessagePushViewSet, base_name='message_push')\n\n# 通用设置相关\nrouter_v1.register(r'^common/setting/message', CommonSettingMessageViewSet, base_name='common_setting_message')\nrouter_v1.register(r'^common/setting/message/test', CommonSettingMessageTestViewSet,\n base_name='common_setting_message_mail_test')\nrouter_v1.register(r'^common/setting/cmdb', CommonSettingCmdbViewSet, base_name='common_setting_cmdb')\nrouter_v1.register(r'^common/setting/app', CommonSettingAppViewSet, base_name='common_setting_app')\nrouter_v1.register(r'^common/setting/ssh-proxy', CommonSettingSshProxyViewSet, base_name='common_setting_sshProxy')\nrouter_v1.register(r'^common/setting/code-publish', CommonSettingCodePublishViewSet,\n base_name='common_setting_codePublish')\n\n# cmdb Aliyun 相关\nrouter_v1.register(r'^cmdb/aliyun/keys', AliyunKeyViewSet, base_name='cmdb_aliyun_keys')\nrouter_v1.register(r'^cmdb/aliyun/ecs', AliyunECSViewSet, base_name='cmdb_aliyun_ecs')\nrouter_v1.register(r'^cmdb/aliyun/ecs-auto', AliyunEcsAutoViewSet, base_name='cmdb_aliyun_ecsAuto')\nrouter_v1.register(r'^cmdb/aliyun/graph', AliyunGraphViewSet, base_name='cmdb_aliyun_graph')\nrouter_v1.register(r'^cmdb/aliyun/classify', AliyunEcsClassfiyViewSet, base_name='cmdb_aliyun_classify')\nrouter_v1.register(r'^cmdb/aliyun/key2ecs', AliyunKey2ECsViewSet, base_name='cmdb_aliyun_key2ecs')\nrouter_v1.register(r'^cmdb/aliyun/rel/ecs-app', AliyunEcsAppRelViewSet, base_name='cmdb_aliyun_rel_ecsApp')\nrouter_v1.register(r'^cmdb/aliyun/rds/classify', AliyunRdsClassfiyViewSet, base_name='cmdb_aliyun_rds_classify')\nrouter_v1.register(r'^cmdb/aliyun/rds/graph', AliyunRdsGraphViewSet, base_name='cmdb_aliyun_rds_graph')\nrouter_v1.register(r'^cmdb/aliyun/key2rds', AliyunKey2RdsViewSet, base_name='cmdb_aliyun_key2rds')\nrouter_v1.register(r'^cmdb/aliyun/rds/processlist', AliyunRdsProcessListViewSet,\n base_name='cmdb_aliyun_rds_processlist')\n\n# cmdb native 相关\nrouter_v1.register(r'^cmdb/native/host', NativeHostViewSet, base_name='cmdb_native_host')\nrouter_v1.register(r'^cmdb/native/classify', NativeClassifyViewSet, base_name='cmdb_native_classify')\nrouter_v1.register(r'^cmdb/native/rel/host-app', NativeHostAppsRelViewSet, base_name='cmdb_native_rel_hostApp')\nrouter_v1.register(r'^cmdb/native/graph', NativeHostGraphViewSet, base_name='cmdb_native_graph')\nrouter_v1.register(r'^cmdb/native/graph-counter', NativeHostGraphCounterViewSet, base_name='cmdb_native_graphCounter')\n\n# cmdb tag相关\nrouter_v1.register(r'^cmdb/tags', TagsViewSet, base_name='cmdb_native_tags')\nrouter_v1.register(r'^cmdb/tags-rel/aliyun-ecs', TagsAliyunEcsRelViewSet, base_name='cmdb_aliyunEcs_rel')\nrouter_v1.register(r'^cmdb/tags-rel/native-host', TagsNativeHostRelViewSet, base_name='cmdb_nativeHost_rel')\n\n# cmdb ansible Api 相关\nrouter_v1.register(r'^cmdb/ansible/update', AnisbleUpdateHostInfoViewSet, base_name='cmdb_ansible_update')\nrouter_v1.register(r'^cmdb/ansible/add', AnsibleAddHostInfoViewSet, base_name='cmdb_ansible_add')\n\n# cmdb 通用\nrouter_v1.register(r'^cmdb/common/all-hosts', AllHostViewSet, base_name='cmdb_common_all_hosts')\n\n# app 相关\nrouter_v1.register(r'^app/detail', AppDetailViewSet, base_name='app_detail')\nrouter_v1.register(r'^app/rel/host', AppHostRelViewSet, base_name='app_host_rel')\nrouter_v1.register(r'^app/alive/urlooker', AppAliveUrlookerViewSet, base_name='app_alive_urlooker')\n\n# monitor 相关\nrouter_v1.register(r'^monitor/app/alive-graph', MonitorAppAliveGraphViewSet, base_name='monitor_app_alive')\nrouter_v1.register(r'^monitor/app/alive-data/latest', MonitorAppAliveLatestDataViewSet,\n base_name='monitor_app_alive_latest_data')\nrouter_v1.register(r'^monitor/app/tactics', MonitorAppAliveTactics, base_name='monitor_app_tactics')\nrouter_v1.register(r'^monitor/third-party/strategy', MonitorThirdPartyStrategyViewSet, base_name='monitor_tp_strategy')\nrouter_v1.register(r'^monitor/third-party/graph', MonitorTPGraphViewSet, base_name='monitor_tp_graph')\nrouter_v1.register(r'^monitor/third-party/info/ecs', MonitorTPECSViewSet, base_name='monitor_tp_info_ecs')\nrouter_v1.register(r'^monitor/third-party/info/rds', MonitorTPRDSViewSet, base_name='monitor_tp_info_rds')\nrouter_v1.register(r'^monitor/third-party/info/nas', MonitorTPNASViewSet, base_name='monitor_tp_info_nas')\nrouter_v1.register(r'^monitor/third-party/info/domain', MonitorTPDomainViewSet, base_name='monitor_tp_info_domain')\nrouter_v1.register(r'^monitor/third-party/info/vpn', MonitorTPVpnViewSet, base_name='monitor_tp_info_vpn')\nrouter_v1.register(r'^monitor/third-party/info/yuexin-sms', MonitorTPYueXinSmsViewSet,\n base_name='monitor_tp_info_yuexin_sms')\nrouter_v1.register(r'^monitor/third-party/info/xuncheng-eryaosu', MonitorTPXunChengEryaosuViewSet,\n base_name='monitor_tp_info_xuncheng_eryaosu')\nrouter_v1.register(r'^monitor/third-party/info/wanweiyiyuan-bankidentity', MonitorTPWanweiyiyuanBankIdentityViewSet,\n base_name='monitor_tp_info_wanweiyiyuan_bankIdentity')\nrouter_v1.register(r'^monitor/third-party/info/tencent-sms', MonitorTPTencentSmsViewSet,\n base_name='monitor_tp_info_tencent_sms')\nrouter_v1.register(r'^monitor/third-party/jitter-strategy', MonitorThirdPartyJitterStrategyViewSet,\n base_name='monitor_tp_jitter_strategy')\nmonitor_update_tp_url = url(\n f'{api_v1_prefix}monitor/third-party/data',\n MonitorUpdateTPView.as_view(), name=\"monitor_update_tp\")\nmonitor_tp_base_item_url = url(\n f'{api_v1_prefix}monitor/third-party/item/strategy-base',\n MonitorTPBaseStrategyItemView.as_view(), name=\"monitor_tp_item_strategyBase\")\nmonitor_tp_jitter_item_url = url(\n f'{api_v1_prefix}monitor/third-party/item/strategy-jitter',\n MonitorTPJitterStrategyItemView.as_view(), name=\"monitor_tp_item_jitterBase\")\nrouter_v1.register(r'^monitor/docker/graph', MonitorDockerAppGraphViewSet, base_name=\"monitor_docker_graph\")\n\n# business 业务相关\nrouter_v1.register(r'^business/access-alarm/strategy',\n AccessAlarmStrategyViewSet,\n base_name='business_access_alarm_strategy')\nrouter_v1.register(r'^business/access-alarm/avg', AccessAlarmAvgViewSet, base_name='business_access_alarm_ayg')\n\n# open api 相关\nrouter_v1.register(r'^openapi/falcon/alarm', OpenApiFalconAlarmViewSet, base_name='openapi_falcon_alarm')\nrouter_v1.register(r'^openapi/mysql/excute', OpenApiMysqlQueryViewSet, base_name='openapi_mysql_excute')\nrouter_v1.register(r'^openapi/ansible/host', OpenApiAnsibleHostViewSet, base_name='openapi_ansible_host')\nrouter_v1.register(r'^openapi/aliyun/lbs', OpenApiAliyunSLBCtrlViewSet, base_name='openapi_aliyun_lbs')\n\n# code_publish\nrouter_v1.register(r'^code-publish/get/main-conf', CodePublishMainConfViewSet, base_name='code_publish_main_conf')\nrouter_v1.register(r'^code-publish/status', CodePublishStatusViewSet, base_name='code_publish_status')\nrouter_v1.register(r'^code-publish/web/main-conf', CodePublishWebMainConfViewSet,\n base_name='code_publish_web_main_conf')\nrouter_v1.register(r'^code-publish/web/steps', CodePublishWebStepsOptsViewSet, base_name='code_publish_steps_opts')\nrouter_v1.register(r'^code-publish/web/jar-opts', CodePublishWebJarOptsViewSet, base_name='code_publish_jar_opts')\nrouter_v1.register(r'^code-publish/web/java-opts', CodePublishWebJavaOptsViewSet, base_name='cp_java_opts')\nrouter_v1.register(r'^code-publish/web/docker-opts', CodePublishWebDockerOptsViewSet, base_name='cp_docker_opts')\nrouter_v1.register(r'^code-publish/web/dockerfile', CodePublishWebDockerfileViewSet, base_name='cp_dockerfile')\nrouter_v1.register(r'^code-publish/web/mvn-opts', CodePublishWebMvnOptsViewSet, base_name='cp_mvn_opts')\nrouter_v1.register(r'^code-publish/web/gradle-opts', CodePublishWebGradleOptsViewSet, base_name='cp_gradle_opts')\nrouter_v1.register(r'^code-publish/web/env', CodePublishEnvViewSet, base_name='cp_web_env')\nrouter_v1.register(r'^code-publish/web/replace-ip', CodePublishReplaceIpViewSet, base_name='cp_web_replaceIp')\nrouter_v1.register(r'^code-publish/web/copy-conf', CodePublishCopyConfigViewSet, base_name='cp_web_copyConf')\nrouter_v1.register(r'^code-publish/web/setting/steps', CodePublishSetStepsViewSet, base_name='cp_setting_setSteps')\nrouter_v1.register(r'^code-publish/web/app-detail', CodePublishAppDetailViewSet, base_name='cp_appDetail')\nrouter_v1.register(r'^code-publish/web/control/app-detail', CodePublishControlAppDetailViewSet,\n base_name='cp_control_app_detail')\nrouter_v1.register(r'^code-publish/web/control/main-conf', CodePublishMainConfAppDetailViewSet,\n base_name='cp_control_mainConf')\nrouter_v1.register(r'^code-publish/web/control/task-status', CodePublishTaskStatusViewSet,\n base_name='cp_ctrl_taskStatus')\nrouter_v1.register(r'^code-publish/web/control/main', CodePublishControlViewSet, base_name='cp_control_main')\nrouter_v1.register(r'^code-publish/web/stop-building', CodePublishStopBuildViewSet, base_name='cp_stopBuilding')\nrouter_v1.register(r'^code-publish/web/get-branch', CodePublishCheckCodeBranch, base_name='cp_getBranch')\nrouter_v1.register(r'^code-publish/web/batch/copy-config', CodePublishBatchCopyConfigViewSet,\n base_name='cp_batch_copyConfig')\nrouter_v1.register(r'^code-publish/web/has-been-published', CodePublishHasBeenPublishedViewSet,\n base_name='cp_hasBeenPublished')\nrouter_v1.register(r'^code-publish/web/real-time/steps', CodePublishGetRTSteps, base_name='cp_realTime_steps')\nrouter_v1.register(r'^code-publish/web/real-time/task-status', CodePublishRTTaskStatusViewSet,\n base_name='cp_realTime_taskStatus')\nrouter_v1.register(r'^code-publish/web/already-version', CodePublishAlreadyPublishedVerViewSet,\n base_name='cp_already_ver')\nrouter_v1.register(r'^code-publish/web/app-name/endpoint', CodePublishAppEndpointViewSet,\n base_name='cp_appName_endPoint')\nrouter_v1.register(r'^code-publish/web/unlock/publish-ip', CodePublishUnlockPublishIp, base_name='cp_unlock_publishIp')\nrouter_v1.register(r'^code-publish/web/lock-env', CodePublishEnvLockViewSet, base_name='cp_env_lock')\nrouter_v1.register(r'^code-publish/web/unlock-env', CodePublishEnvUnLockViewSet, base_name='cp_env_unlock')\nrouter_v1.register(r'^code-publish/web/lock-env-app', CodePublishEnvLockChoseEnvApp, base_name='cp_lock_env_app')\n\n\n# 测试接口\nrouter_v1.register(r'^test/aliyun/ecs', TestAliyunEcsViewSet, base_name='test_aliyun_ecs')\nrouter_v1.register(r'^test/aliyun/ecs-graph', TestAliyunGraphViewSet, base_name='test_aliyun_ecs_graph')\nrouter_v1.register(r'^test/cmdb/cron/ansible', TestAnsibleUpdateCron, base_name='test_ansible_update_cron')\nrouter_v1.register(r'^test/cmdb/cron/aliyun', TestAliyunUpdateCron, base_name='test_aliyun_update_cron')\nrouter_v1.register(r'^test/monitor/third-party/save-data', TestThirdPartySaveDataViewSet,\n base_name='test_thirdParty_saveData')\nrouter_v1.register(r'^test/monitor/third-party/push-data', TestPushDataToFalcon, base_name='test_thirdParty_pushData')\nrouter_v1.register(r'^test/monitor/third-party/push-jitter-data', TestTPPushJitterData,\n base_name='test_thirdParty_pushJitterData')\nrouter_v1.register(r'^test/code-publish/cron', TestCodePublishCron, base_name='test_cp_cron')\nrouter_v1.register(r'^test/common/collect-failed-point', TestGetAppAliveStatistics, base_name='common_failed_point')\n\n# 生产的ApiView\nrouter_v1_product_url = [\n monitor_update_tp_url,\n monitor_tp_base_item_url,\n monitor_tp_jitter_item_url,\n]\n\ntest_url = [\n # 消息发送接口\n url(f'{api_v1_prefix}test/sender', TestSenderView.as_view(), name=\"test_sender\"),\n url(f'{api_v1_prefix}test/business/ngx-access-alarm',\n TestAccessAlarmStrategyView.as_view(),\n name='test_business_alarm_strategy')\n]\n\nurlpatterns = [\n url(f'{api_v1_prefix}', include(router_v1.urls)),\n url(r'^api-auth/', include('rest_framework.urls')),\n url(r'^api/docs/', include_docs_urls(title=\"Shadow Ops\"))\n]\n\nurlpatterns.extend(router_v1_view_urls)\nurlpatterns.extend(router_v1_product_url)\nurlpatterns.extend(test_url)\n","sub_path":"src/ops/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":19366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34948210","text":"# Library of helper functions for processing output of tcpdump command\n\n# Represents flags of TCP packet as an 8-bit number\ndef get_flags(words):\n flags = words[6][1:-2]\n accum = 0\n if 'W' in flags:\n accum += 1\n if 'E' in flags:\n accum += 2\n if 'U' in flags:\n accum += 4\n if '.' in flags:\n accum += 8\n if 'P' in flags:\n accum += 16\n if 'R' in flags:\n accum += 32\n if 'S' in flags:\n accum += 64\n if 'F' in flags:\n accum += 128\n return accum\n\ndef get_src_host(words):\n src_host_full = words[2].split('.')\n return '.'.join(src_host_full[:-1])\n\ndef get_dst_host(words):\n dst_host_full = words[4].split('.')\n return '.'.join(dst_host_full[:-1])\n\n# Get timestamp, represented as the number of microseconds modulo minutes\ndef get_time(words):\n time_full = words[0].split(':')\n time_secs = time_full[2].split('.')\n return 1000000*int(time_secs[0]) + int(time_secs[1][:6]) # Time, in microseconds\n\n# Get a sorted source/destination pair, to store uniquely in the PAIRS map\ndef get_canonical_pair(words):\n src = get_src_host(words)\n dst = get_dst_host(words)\n if src < dst:\n return (src, dst)\n else:\n return (dst, src)\n","sub_path":"tcp_process.py","file_name":"tcp_process.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128976835","text":"import os\nimport random\nfrom frame_extraction import frame_extractor\nimport cPickle\n\nclass datasets(object):\n def __init__(self, batch_size=64, val_split=0.005, test_split=0.005, heigth=64, width=64, DIR='../../data', output_filename='../../all_videos.txt', ):\n self.file_path = os.path.abspath(os.path.dirname(__file__))\n self.DIR = os.path.join(self.file_path,DIR)\n self.output_filename = os.path.join(self.file_path,output_filename)\n self.batch_size = batch_size\n self.flagged_activities = ['PlayingDaf', 'BodyWeightSquats', 'Nunchucks', 'ShavingBeard', 'SkyDiving']\n self.data = None\n self.frame_ext = frame_extractor(heigth=heigth,width=width)\n self.videos_to_text_file()\n self.load_problematic_videos()\n self.train_test_split(val_split,test_split)\n\n def load_problematic_videos(self):\n _frames_file = os.path.join(self.file_path, 'frames.pickle')\n _problem_videos_file = os.path.join(self.file_path, 'problematic_videos.pickle')\n with open(_frames_file, 'rb') as fp:\n short_frames = cPickle.load(fp)\n with open(_problem_videos_file, 'rb') as fp:\n problematic_videos = cPickle.load(fp)\n\n self.blacklist = set(short_frames + problematic_videos)\n\n def videos_to_text_file(self):\n with open(self.output_filename, \"w\") as a:\n for path, subdirs, files in os.walk(self.DIR):\n for filename in files:\n f = os.path.join(path, filename)\n a.write(str(f) + os.linesep)\n\n\n def train_test_split(self, split_test_data, split_validation_data):\n \"\"\"\n split_test_data : '%' of test data to split between 0 to 1\n \"\"\"\n data = {}\n unseen = []\n seen = []\n for line in open(self.output_filename):\n line = line.rstrip('\\n')\n if line in self.blacklist:\n continue\n if any(substring in line for substring in self.flagged_activities):\n unseen.append(line)\n else:\n seen.append(line)\n\n datasize = len(seen)\n\n #Random Shuffle\n random.shuffle(seen)\n\n validation_index = int(datasize * split_validation_data)\n data['validation'] = seen[:validation_index]\n\n seen = seen[validation_index:]\n test_index = int(datasize * split_test_data)\n data['train'] = seen[test_index:]\n data['test'] = seen[:test_index]\n data['unseen'] = unseen\n\n self.data = data\n\n def train_next_batch(self,):\n \"\"\"Returns lists of length batch_size.\n This is a generator function, and it returns lists of the\n entries from the supplied iterator. Each list will have\n batch_size entries, although the final list may be shorter.\n \"\"\"\n train_iter = iter(self.data['train'])\n while True:\n curr_batch = []\n while len(curr_batch) < self.batch_size:\n entry = None\n try:\n entry = train_iter.next()\n except StopIteration:\n # Shuffle data for next rollover ...\n random.shuffle(self.data['train'])\n train_iter = iter(self.data['train'])\n if entry != None:\n curr_batch.append(entry)\n if curr_batch:\n yield self.frame_ext.get_frames(curr_batch)\n\n def fixed_next_batch(self,data_iter):\n is_done = False\n while True:\n curr_batch = []\n while len(curr_batch) < self.batch_size:\n entry = None\n try:\n entry = data_iter.next()\n except StopIteration:\n is_done = True\n break\n if entry != None:\n curr_batch.append(entry)\n if len(curr_batch)==self.batch_size:\n yield self.frame_ext.get_frames(curr_batch)\n if is_done:\n break\n\n def val_next_batch(self,):\n \"\"\"\n Returns lists of length batch_size.\n This is a generator function, and it returns lists of the\n entries from the supplied iterator. Each list will have\n batch_size entries, although the final list may be shorter.\n \"\"\"\n val_iter = iter(self.data['validation'])\n return self.fixed_next_batch(val_iter)\n\n def test_next_batch(self,):\n \"\"\"Returns lists of length batch_size.\n This is a generator function, and it returns lists of the\n entries from the supplied iterator. Each list will have\n batch_size entries, although the final list may be shorter.\n \"\"\"\n val_iter = iter(self.data['test'])\n return self.fixed_next_batch(val_iter)\n","sub_path":"datasets/batch_generator.py","file_name":"batch_generator.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"23398526","text":"import time\nfrom functools import wraps\n\nfrom flask_restful import abort\nfrom sqlalchemy import exc\n\nfrom servise_api import logger\nfrom servise_api.models.models import City\nfrom ..controllers.auth_controller import AuthController\n\n\ndef check_city_date(func):\n '''Validate input date and city name'''\n\n def func_wrapper(s, city_id, start_date, finish_date, token):\n date_limit = 863999\n logger.debug('TOKEN {} passed first validation in get_weather')\n try:\n city_id_it = int(city_id)\n location = City.filter_by(id=city_id_it).first()\n start_date_unix = int(time.mktime(time.strptime(start_date, '%Y-%m-%d')))\n finish_date_unix = int(time.mktime(time.strptime(finish_date, '%Y-%m-%d')))\n delta = abs(finish_date_unix) - abs(start_date_unix)\n\n if location == None:\n # city credinal not found in database\n logger.error('404, City not found in database')\n abort(404, description={'data': city_id, 'errors': 'City not found in database'})\n\n elif delta < 0 or delta > date_limit:\n # when we have wrong input date range\n logger.error('400, Dates range error')\n abort(400, description={'data': str([start_date, finish_date]), 'errors': 'Dates range error'})\n else:\n # when location and (delta < date_limit) and delta > 0:\n if AuthController.check_session(token):\n logger.debug('VALIDATION PASSED')\n args = {'longitude': location.longitude,\n 'latitude': location.latitude,\n 'city_id': location.id}\n return func(s, start_date, finish_date, token, **args)\n except ValueError:\n # return error if user input wrong date format\n logger.error('400, ValueError of input data')\n abort(400, description={'data': 'Input value error', 'errors': str(ValueError)})\n except exc.SQLAlchemyError as e:\n # return error code if something crashes in database logic\n logger.error('400, Database error')\n abort(400, description={'data': 'City format error', 'errors': str(e)})\n\n return func_wrapper\n\n\ndef temperature_humidity_parser(func):\n @wraps(func)\n def func_wrapper(s, temperature, humidity, *args, **kwargs):\n try:\n temperature = float(temperature)\n except ValueError:\n temperature = None\n try:\n humidity = float(humidity)\n except ValueError:\n humidity = None\n return func(s, temperature, humidity, *args, **kwargs)\n\n return func_wrapper\n","sub_path":"servise_api/helpers/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"481431903","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\nimport sphinx_rtd_theme\n\nimport mock\nDEPLOY = os.environ.get(\"READTHEDOCS\") == \"True\"\n\n# -- Project information -----------------------------------------------------\n\nproject = 'easycore'\ncopyright = '2020, Yuxin Zhao'\nauthor = 'Yuxin Zhao'\n\ntry:\n import torch\nexcept ImportError:\n for m in [\n \"torch\",\n \"torchvision\",\n \"torch.nn\",\n \"torch.nn.parallel\",\n \"torch.distributed\",\n \"torch.multiprocessing\",\n \"torch.autograd\",\n \"torch.autograd.function\",\n \"torch.nn.modules\",\n \"torch.nn.modules.utils\",\n \"torch.utils\",\n \"torch.utils.data\",\n \"torchvision\",\n \"torchvision.ops\",\n ]:\n sys.modules[m] = mock.Mock(name=m)\n\nfor m in [\n \"yaml\",\n \"cv2\",\n \"portalocker\",\n]:\n sys.modules[m] = mock.Mock(name=m)\n\nsys.modules[\"cv2\"].__version__ = \"3.4\"\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.napoleon',\n \"sphinx.ext.viewcode\",\n \"sphinx.ext.githubpages\",\n 'sphinx_rtd_theme',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = []\n\n# -- Configurations for plugins ------------\nnapoleon_google_docstring = True\nnapoleon_include_init_with_doc = True\nnapoleon_include_special_with_doc = True\nnapoleon_numpy_docstring = False\nnapoleon_use_rtype = False\nautodoc_inherit_docstrings = False\nautodoc_member_order = \"bysource\"\n\nif DEPLOY:\n intersphinx_timeout = 10\nelse:\n # skip this when building locally\n intersphinx_timeout = 0.1\n\nintersphinx_mapping = {\n \"python\": (\"https://docs.python.org/3.6\", None),\n \"numpy\": (\"https://docs.scipy.org/doc/numpy/\", None),\n \"torch\": (\"https://pytorch.org/docs/master/\", None),\n}\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_rtd_theme'\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n\nsource_parsers = {\n '.md': 'recommonmark.parser.CommonMarkParser',\n}\n\nsource_suffix = ['.rst', '.md']\n\nmaster_doc = 'index'\n","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269407548","text":"import hdf\nimport pandas as pd\n\nimport numpy as np\nsigs = pd.read_csv(r'C:\\Users\\evans\\Dropbox\\Shade\\database\\sigs.csv', index_col=0)\n# expr=hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\jiaoshenmehaoen.h5\")[0][['L1','L2','S5_1','S5_2','S15_1','S15_2','S30_1','S30_2']]\n\nexpr = hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\jiaoshenmehaoen.h5\")['prot_RMP_nopoint_dupmean'][['L1', 'L2', 'S5_1', 'S5_2', 'S15_1', 'S15_2', 'S30_1', 'S30_2']]\n\n\ndef cal_regulate(df):\n def divide_filter(s1, s2):\n '''\n input two dataframe Series\n output one dataframe Series\n '''\n # o = np.log(s1 / s2)\n o = s1 / s2\n o.name = str(s1.name) + '/' + str(s2.name)\n return o\n ratio5 = divide_filter(df[['S5_1', 'S5_2']].mean(\n axis=1), (df[['L1', 'L2']].mean(axis=1)))\n ratio15 = divide_filter(df[['S15_1', 'S15_2']].mean(\n axis=1), (df[['L1', 'L2']].mean(axis=1)))\n ratio30 = divide_filter(df[['S30_1', 'S30_2']].mean(\n axis=1), (df[['L1', 'L2']].mean(axis=1)))\n return pd.DataFrame({'ratio5': ratio5, 'ratio15': ratio15, 'ratio30': ratio30}).dropna()\n\n\ncal_regulate(expr.loc[sigs[sigs['label'].isin([1, 4])].index])\n\ncal_regulate(expr.loc[set(sigs[sigs.columns[0]].tolist())]\n ).to_csv('ratios.csv')\n\n\ncal_downregulate(expr.loc[sigs[sigs['label'].isin([2, 5])].index])\n\nsm.anova.anova_lm()\n","sub_path":"proteomap.py","file_name":"proteomap.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261280051","text":"import numpy as np\n# https://stackoverflow.com/questions/1987694/how-to-print-the-full-numpy-array-without-truncation\nnp.set_printoptions(threshold=np.nan)\n# np.set_printoptions(threshold=np.inf)\nimport pdb\nimport operator\nimport csv\nimport networkx as nx\nfrom itertools import combinations as combos\n\n#digraph as in Directed graph (as opposed to undirected - bidirectional edges)\nclass DiGraph:\n \"\"\"A class for representing directed graphs via their adjacency matrices.\n\n Attributes:\n (fill this out after completing DiGraph.__init__().)\n \"\"\"\n\n def __init__(self, A, labels=None):\n \"\"\"Modify A so that there are no sinks in the corresponding graph,\n then calculate Ahat. Save Ahat, as \"modified,\" and the labels as attributes.\n\n Parameters:\n A ((n,n) ndarray): the adjacency matrix of a directed graph.\n A[i,j] is the weight of the edge from node j to node i.\n labels (list(str)): labels for the n nodes in the graph.\n If None, defaults to [0, 1, ..., n-1].\n \"\"\"\n #raise error if incorrect number of labels given\n size = np.shape(A)[0]\n\n if labels is not None and len(labels) != size:\n raise ValueError(\"Incorrect number of labels given\")\n\n #save as an attribute for use in linsolve\n self.size = size\n #save labels as attributes\n if labels is None:\n self.labels = [i for i in range(size)]\n else:\n self.labels = labels\n #modify copy of A so that there are no sinks\n modified = np.array(A,dtype='float64',copy=True)\n #sum the columns, if resulting norm is zero then modify columns\n norms = np.sum(np.abs(A),axis=0)\n\n #verify if there are not sinks\n if np.count_nonzero(norms) == len(norms):\n pass\n else:\n #adjust the sinks through iterating through array\n #modify each column to be divided by the sum of that column\n #thus each column is normalized to sum to one\n # pdb.set_trace()\n for i in range(size):\n value = norms[i]\n if value == 0:\n modified[:,i] = np.ones((size)) / size\n else:\n modified[:,i] = modified[:,i] * ( np.ones(size) / value)\n\n self.adjacency = modified\n\n def linsolve(self, epsilon=0.85):\n \"\"\"Compute the PageRank vector using the linear system method.\n\n Parameters:\n epsilon (float): the damping factor, between 0 and 1.\n\n Returns:\n dict(str -> float): A dictionary mapping labels to PageRank values.\n \"\"\"\n #find limit of each node as an array\n #system of equations in solve method are according to 14.6 on page 136 of textbook\n limits = np.linalg.solve((np.eye(self.size)-epsilon*self.adjacency),\n ((1-epsilon / self.size)*np.ones(self.size)))\n #normalize the vector w/ respect to 1 norm\n limits /= np.linalg.norm(limits,1)\n #construct dictinary, iterate through elements in limits\n values = dict()\n for i in range(len(self.labels)):\n values.update({self.labels[i]:limits[i]})\n return values\n\n def eigensolve(self, epsilon=0.85):\n \"\"\"Compute the PageRank vector using the eigenvalue method.\n Normalize the resulting eigenvector so its entries sum to 1.\n\n Parameters:\n epsilon (float): the damping factor, between 0 and 1.\n\n Return:\n dict(str -> float): A dictionary mapping labels to PageRank values.\n \"\"\"\n E = np.ones_like(self.adjacency)\n # E = np.ones((self.size,self.size))\n #parenthesis around (1-epsilon) are essential because it was changing my output\n B = (epsilon*self.adjacency) + ((1-epsilon) / self.size) * E\n #find eigenvector of B\n #np.lin.eig returns eigenvalues & eigenvectors\n e_values, e_vectors = np.linalg.eig(B)\n # return e_values, e_vectors\n #np.argmax will return index of eigenvalue = 1, we want corresponding eigenvector\n p = e_vectors[:, np.argmax(e_values)]\n # limits = p\n #normalize p so that it sums to one\n # limits = p / (np.linalg.norm(p,1))\n limits = p / (np.sum(p)) #this doesn't change output\n # assert np.allclose( (p / np.linalg.norm(p,1) ) , (p / np.sum(p) ) ), \"there is a difference in normalizations\"\n # return limit\n # return np.sum(limits) # NOTE: this shows that it sums to one\n #construct dictinary, iterate through elements in limits\n values = dict()\n for i in range(self.size):\n values.update({self.labels[i]:limits[i]})\n return values\n\n def itersolve(self, epsilon=0.85, maxiter=100, tol=1e-12):\n \"\"\"Compute the PageRank vector using the iterative method.\n\n Parameters:\n epsilon (float): the damping factor, between 0 and 1.\n maxiter (int): the maximum number of iterations to compute.\n tol (float): the convergence tolerance.\n\n Return:\n dict(str -> float): A dictionary mapping labels to PageRank values.\n \"\"\"\n #iteratively compute limit of p, with initial guess of p0\n p0 = np.ones(self.size) / self.size\n prev = p0\n for i in range(maxiter):\n new = (epsilon*(self.adjacency @ prev) +\n ((1-epsilon / self.size)*np.ones(self.size)))\n # if difference is less than tolerance then break\n if np.linalg.norm(new - prev,1) < tol:\n break\n prev = new\n #normalize the vector w/ respect to 1 norm\n new /= (np.linalg.norm(new,1))\n #construct dictinary, iterate through elements in limits\n values = dict()\n for i in range(len(self.labels)):\n values.update({self.labels[i]:new[i]})\n return values\n\ndef test_constructor():\n \"\"\" test the constructor to the DiGraph\"\"\"\n A = np.array([\n [0., 0, 0],\n [3, 0, 0],\n [0, 0, 4]\n ])\n A_1 = np.array([\n [0., 1/3, 0],\n [1, 1/3, 0],\n [0, 1/3, 1]\n ])\n B = np.array([ #matrix must be a float, or values do integer division to zero\n [1., 1, 0],\n [3, 1, 0],\n [1, 1, 0]\n ])\n B_1 = np.array([\n [0.2, 1/3, 1/3],\n [0.6, 1/3, 1/3],\n [0.2, 1/3, 1/3]\n ])\n\n print(\"proceeding through constructor testing\")\n\n one = DiGraph(A)\n # print(one.adjacency)\n # print(A_1)\n assert np.allclose(one.adjacency,A_1), \"test case 1 failed\"\n\n two = DiGraph(B)\n # print(two.adjacency)\n # print(B_1)\n assert np.allclose(two.adjacency,B_1), \"test case 2 failed\"\n\n try:\n another = DiGraph(A,labels=['a','b','c','d','e','f','g'])\n except ValueError:\n print(\"correctly threw error for test case of incorrect labels given\")\n\ndef limit_test():\n \"\"\" test the linsolve, eigensolve, and itersolve, methods\"\"\"\n A = np.array([\n [0., 0, 0,0],\n [1., 0, 1,0],\n [1., 0, 0,1],\n [1., 0, 1,0]\n ])\n ##instantiate an object of this class according to example in book\n example = DiGraph(A,['a','b','c','d'])\n # print(example.adjacency)\n ex_lin = example.linsolve().values()\n print(\"linsolve output:\\n\",ex_lin)\n ## print(np.linalg.norm(example.eigensolve(),1)) #useful when returning limit\n ex_eig = example.eigensolve().values()\n print(\"eigensolve output\\n\",ex_eig)\n # print(\"the sum of eigensolve output is \\n\",sum(e[0]x_eig)) #when outputing the vector\n\n ex_iter = example.itersolve().values()\n print(\"itersolve output\\n\",ex_iter)\n # assert ex_lin == ex_eig == ex_iter, \"comparison of output from linsolve, eigensolve, itersolve, from first test case failed\"\n\n \"\"\" #just comment out the second test case so it runs faster\n B = np.array([\n [1.,0,1],\n [0,0,1],\n [1,0,0]\n ])\n test2 = DiGraph(B)\n t2_lin = test2.linsolve()\n t2_eig = test2.eigensolve()\n t2_iter = test2.itersolve()\n # print(\"\\nlinsolve output for second test case:\\n\",t2_lin)\n # print(\"eigensolve output for second test case\\n\",t2_eig)\n # print(\"itersolve output for second test case:\\n\",t2_iter)\n # assert t2_lin == t2_eig == t2_iter, \"comparison of output from linsolve, eigensolve, itersolve, from second test case failed\"\n \"\"\"\n\n #testing for equality in the dictionaries isn't great because there are differences after like 10 decimals\n # print(\"PASSED BOTH TEST CASES OF TRIPLE METHOD SOLVERS EQUALITY in limit_test function \")\n\ndef get_ranks(d):\n \"\"\"Construct a sorted list of labels based on the PageRank vector.\n\n Parameters:\n d (dict(str -> float)): a dictionary mapping labels to PageRank values.\n\n Returns:\n (list) the keys of d, sorted by PageRank value from greatest to least.\n \"\"\"\n #get keys as an array since ndarrays are fancy indexable\n keys = np.array(list(d.keys()))\n ##using fancy index, return indices that would\n ##sort array by values, in reverse (descending) order\n indices = np.argsort(list(d.values()))[::-1]\n # indices = np.argsort(list(d.values()))\n return list(keys[indices])\n\n ##ALTERNATIVE METHOD BELOW, doesn't work as well, it was my first attempt\n #using an operator, iterate through values/ items and return 0th element\n #itemgetter(n) where n refers to the item in this case of the tuple,\n #ask others to show me their solution\n # return (list(d.values()).sort()) #returned None\n #having itemgetter(0) sorts according to zero elements, or the keys of dictionaries\n # return [a[0] for a in sorted(d.items(), key=operator.itemgetter(1), reverse = True) ]\n\ndef ranks_tester():\n \"\"\" test various functions like get_ranks \"\"\"\n A = np.array([\n [0., 0, 0,0],\n [1., 0, 1,0],\n [1., 0, 0,1],\n [1., 0, 1,0]\n ])\n ##instantiate an object of this class according to example in book\n example = DiGraph(A,['a','b','c','d'])\n d = example.linsolve()\n # sorted yields : [('a', 0.09575863576738086), ('b', 0.2741582859641452), ('d', 0.2741582859641452), ('c', 0.3559247923043289)]\n # i found a complex solution, i bet there is an easier way\n test = {'a':7,'b':2,'c':90,'d':4,'e':-1}\n # print(get_ranks(test))\n textbook_case = get_ranks(d)\n assert (textbook_case == ['c', 'b', 'd', 'a']) or (textbook_case == ['c', 'd', 'b', 'a']), \"test case failed for array {}'\\n'\".format(A)\n assert get_ranks(test) == ['c','a','d','b','e'], \"test case failed for get_ranks for \\n{}\".format(test)\n print(\"test cases passed in rank tester\")\n\ndef rank_websites(filename=\"web_stanford.txt\", epsilon=0.85):\n \"\"\"Read the specified file and construct a graph where node j points to\n node i if webpage j has a hyperlink to webpage i. Use the DiGraph class\n and its itersolve() method to compute the PageRank values of the webpages,\n then rank them with get_ranks().\n\n Each line of the file has the format\n a/b/c/d/e/f...\n meaning the webpage with ID 'a' has hyperlinks to the webpages with IDs\n 'b', 'c', 'd', and so on.\n\n Parameters:\n filename (str): the file to read from.\n epsilon (float): the damping factor, between 0 and 1.\n\n Returns:\n (list(str)): The ranked list of webpage IDs.\n \"\"\"\n #read in the data\n with open(filename,'r') as infile:\n # data = infile.read().strip('\\n').split('/') #this works but makes just one list, with newline characters\n # data = infile.readlines().split('\\n')\n data = infile.readlines()\n\n #format the data to be a list of lists,\n #each list represents the connections of the node, where\n #node is first element, followed by connecting node as elements\n labels = set()\n indices = dict()\n for i in range(len(data)):\n data[i] = data[i].strip().split('/')\n #labels will be used as parameter in constructor\n #data[][] notation is for list of lists\n # NOTE: most critical part, is that some nodes get mapped to, but don't map to anything\n for word in data[i]:\n labels.add(word)\n\n #construct dictionary out of sorted list (from set)\n #sort the list to match test driver format\n # labels = sorted(list(labels))\n labels = sorted(labels) #NOTE: this is what I had before\n for i in range(len(labels)):\n indices.update({labels[i]:i})\n\n # construct the adjacency matrix\n #create adjacency\n A = np.zeros((len(labels),len(labels)))\n # for a given word line[0]\n for line in data:\n #index of primary word\n i = indices[line[0]]\n #for each corresponding word\n for label in line[1:]:\n #index of corresponding word\n j = indices[label]\n #label as one\n A[j][i] = 1\n\n # # \"\"\" for comparison purposes, this following code didn't work,\n # it gives different output from above\n # n = len(labels)\n # A = np.zeros((n,n))\n # for line in data:\n # node_index = indices[line[0]]\n # # through slicing make sure not to make a connection from a node to itself\n # for label in labels[1:]:\n # #the primary node maps to a node calculated connection\n # connection_index = indices[label]\n # A[connection_index][node_index] = 1\n # # \"\"\"\n\n #constuct Digraph\n diGraph = DiGraph(A,labels)\n #itersolve will return a dictionary mapping label to pagerank value\n pageRanks = diGraph.itersolve(epsilon)\n return get_ranks(pageRanks)\n\ndef rank_ncaa_teams(filename, epsilon=0.85):\n \"\"\"Read the specified file and construct a graph where node j points to\n node i with weight w if team j was defeated by team i in w games. Use the\n DiGraph class and its itersolve() method to compute the PageRank values of\n the teams, then rank them with get_ranks().\n\n Each line of the file has the format\n A,B\n meaning team A defeated team B.\n\n\n Parameters:\n filename (str): the name of the data file to read.\n epsilon (float): the damping factor, between 0 and 1.\n\n Returns:\n (list(str)): The ranked list of team names.\n \"\"\"\n labels = set()\n indices = dict()\n with open(filename) as f:\n #casting csv.reader as a list, allows for easy manipulation\n data = list(csv.reader(f))\n for line in data:\n a,b = line[0],line[1]\n if a != \"Winner\":\n labels.add(a)\n labels.add(b)\n # labels = sorted(labels)\n labels = list(labels)\n #fill the indices dictionary\n for i in range(len(labels)):\n indices[labels[i]] = i\n #make adjacency matrix\n n = len(labels)\n A = np.zeros((n,n))\n for line in data:\n winner, loser = line[0],line[1]\n #we don't want header that says \"Winner, Loser\"\n if winner != \"Winner\":\n #edges point from loser(column) to winner(row)\n A[indices[winner]][indices[loser]] += 1\n return get_ranks(DiGraph(A,labels).itersolve(epsilon))\n\ndef rank_actors(filename=\"top250movies.txt\", epsilon=0.85):\n \"\"\"Read the specified file and construct a graph where node a points to\n node b with weight w if actor a and actor b were in w movies together but\n actor b was listed first. Use NetworkX to compute the PageRank values of\n the actors, then rank them with get_ranks().\n\n Each line of the file has the format\n title/actor1/actor2/actor3/...\n meaning actor2 and actor3 should each have an edge pointing to actor1,\n and actor3 should have an edge pointing to actor2.\n \"\"\"\n movies = nx.DiGraph()\n data = []\n actors = set()\n with open(filename,\"r\",encoding = \"utf-8\") as file:\n for line in file.readlines():\n #format the data into a list of lists, where each list is a movie\n line = line.strip().split('/')\n #delete the movie titles. Irrelevant info.\n delete = line.pop(0)\n data.append(line)\n #get a comprehensive list of actors\n for line in data:\n for actor in line:\n #comprehensive lists is a set to avoid repeats\n actors.add(actor)\n actors = list(actors) #there are almost 15k actors\n # n = len(actors)\n #construct graph with edges\n for line in data:\n #combos is an iterator object so must be accessed in this way\n for i in combos(line,2):\n high_paid, low_paid = i\n #edges point to higher-billed actors\n if movies.has_edge(low_paid,high_paid) is True:\n movies[low_paid][high_paid][\"weight\"] += 1\n else:\n movies.add_edge(low_paid,high_paid,weight = 1)\n return get_ranks(nx.pagerank(movies,alpha = epsilon))\n # return data[0]\n\n\nif __name__ == '__main__':\n pass\n # test_constructor()\n # limit_test()\n # ranks_tester()\n\n print(\"\\nbelow is result for epsilon = 0.85, showing last term of the first 20 terms:\")\n print(rank_websites(epsilon=0.85)[:20][-1:])\n print(\"\\nbelow is result for epsilon = 0.62, showing last 5th, 4th of the first 20 terms:\")\n print(rank_websites(epsilon=0.62)[:20][-5:-3])\n\n # print(rank_ncaa_teams('ncaa2010.csv')) #i should have 607 teams, but I have 606, or 608\n # print(rank_ncaa_teams('ncaa2010.csv')[:5]) #epsilon 0.3 yields BYU\n # print(rank_actors(epsilon=0.7)[:5])\n # print(rank_actors())\n\n print(\"this code is complete, it appears there were some test driver complications \")\n","sub_path":"PageRank/PageRank.py","file_name":"PageRank.py","file_ext":"py","file_size_in_byte":17853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151334436","text":"#!/usr/bin/env python3\n\nimport os\nfrom pymongo import MongoClient\n\nclients = MongoClient().db.clients\nclients.find_one_and_update(\n {\"cn\": os.environ[\"X509_0_CN\"]},\n {\"$set\": {\n \"ip\": os.environ[\"ifconfig_pool_remote_ip\"]\n }}\n)\n\n","sub_path":"conf/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381491166","text":"from typing import Tuple\n\nfrom ..linalg import Vector3, Matrix4, Quaternion\nfrom ._orbit import get_screen_vectors_in_world_cords\n\n\nclass PanZoomControls:\n \"\"\"A class implementing two-dimensional pan-zoom camera control.\"\"\"\n\n def __init__(\n self,\n eye: Vector3 = None,\n target: Vector3 = None,\n up: Vector3 = None,\n zoom: float = 1.0,\n min_zoom: float = 0.0001,\n ) -> None:\n self.rotation = Quaternion()\n if eye is None:\n eye = Vector3(50.0, 50.0, 50.0)\n if target is None:\n target = Vector3()\n if up is None:\n up = Vector3(0.0, 1.0, 0.0)\n self.zoom_value = zoom\n self.min_zoom = min_zoom\n\n # State info used during a pan or rotate operation\n self._pan_info = None\n\n # Temp objects (to avoid garbage collection)\n self._m = Matrix4()\n self._v = Vector3()\n\n # Initialize orientation\n self.look_at(eye, target, up)\n\n def look_at(self, eye: Vector3, target: Vector3, up: Vector3) -> \"PanZoomControls\":\n self.distance = eye.distance_to(target)\n self.target = target\n self.up = up\n self.rotation.set_from_rotation_matrix(self._m.look_at(eye, target, up))\n return self\n\n def pan(self, vec3: Vector3) -> \"PanZoomControls\":\n \"\"\"Pan in 3D world coordinates.\"\"\"\n self.target.add(vec3)\n return self\n\n def pan_start(\n self,\n pos: Tuple[float, float],\n canvas_size: Tuple[float, float],\n camera: \"Camera\",\n ) -> \"PanZoomControls\":\n # Using this function may be a bit overkill. We can also simply\n # get the ortho cameras world_size (camera.visible_world_size).\n # However, now the panzoom controls work with a perspecive camera ...\n vecx, vecy = get_screen_vectors_in_world_cords(self.target, canvas_size, camera)\n self._pan_info = {\"last\": pos, \"vecx\": vecx, \"vecy\": vecy}\n return self\n\n def pan_stop(self) -> \"PanZoomControls\":\n self._pan_info = None\n return self\n\n def pan_move(self, pos: Tuple[float, float]) -> \"PanZoomControls\":\n \"\"\"Pan the camera, based on a (2D) screen location. Call pan_start first.\"\"\"\n if self._pan_info is None:\n return\n delta = tuple((pos[i] - self._pan_info[\"last\"][i]) for i in range(2))\n self.pan(\n self._pan_info[\"vecx\"]\n .clone()\n .multiply_scalar(-delta[0])\n .add_scaled_vector(self._pan_info[\"vecy\"], +delta[1])\n )\n self._pan_info[\"last\"] = pos\n return self\n\n def zoom(self, multiplier: float) -> \"PanZoomControls\":\n self.zoom_value = max(self.min_zoom, float(multiplier) * self.zoom_value)\n return self\n\n def zoom_to_point(\n self,\n multiplier: float,\n pos: Tuple[float, float],\n canvas_size: Tuple[float, float],\n camera: \"Camera\",\n ) -> \"PanZoomControls\":\n\n # Apply zoom\n zoom_old = self.zoom_value\n self.zoom(multiplier)\n zoom_ratio = zoom_old / self.zoom_value # usually == multiplier\n\n # Now pan such that what was previously under the mouse is again under the mouse.\n vecx, vecy = get_screen_vectors_in_world_cords(self.target, canvas_size, camera)\n delta = tuple(pos[i] - canvas_size[i] / 2 for i in (0, 1))\n delta1 = vecx.multiply_scalar(delta[0]).add(vecy.multiply_scalar(-delta[1]))\n delta2 = delta1.clone().multiply_scalar(zoom_ratio)\n self.pan(delta1.sub(delta2))\n return self\n\n def get_view(self) -> Tuple[Vector3, Vector3, float]:\n self._v.set(0, 0, self.distance).apply_quaternion(self.rotation).add(\n self.target\n )\n return self.rotation, self._v, self.zoom_value\n\n def update_camera(self, camera: \"Camera\") -> \"PanZoomControls\":\n rot, pos, zoom = self.get_view()\n camera.rotation.copy(rot)\n camera.position.copy(pos)\n camera.zoom = zoom\n return self\n","sub_path":"pygfx/controls/_panzoom.py","file_name":"_panzoom.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"301178201","text":"import numpy as np\nfrom packs.directories import data_loaded\nfrom packs.utils import constants as ctes\nfrom ..stability_check import StabilityCheck\nfrom .properties_calculation import PropertiesCalc\nfrom .composition_solver import RK3, Euler\nimport scipy.sparse as sp\nfrom packs.compositional import prep_FR as ctes_FR\nimport math\nimport time\n\n'Todo esse código vai ainda ser ajeitado! As funções de Flux devem ser funçoes para \\\ncalculo independente do fluxo. Funcoes de rotina. E algumas funçes do MUSCL devem também \\\nseguir essa logica (sao funçoes que nao pertencem ao metodo em si mas sao auxiliares a ele \\\ne acabam sendo necessarias a outros metodos tambem)'\n\nclass Flux:\n \"\"\" Class created for computing flux accondingly to the First Order Upwind \\\n Method - actually, it's only Flux because of the choice of mobilities and \\\n other properties to be taken as function of the potencial gradient. But here \\\n flux is computed at the interfaces, and then, volumes, only that.\"\"\"\n\n def update_flux(self, M, fprop, Ft_internal_faces, rho_j_internal_faces,\n mobilities_internal_faces):\n ''' Main function that calls others '''\n self.Nk = fprop.Nk\n Fj_internal_faces = self.update_Fj_internal_faces(Ft_internal_faces,\n rho_j_internal_faces, mobilities_internal_faces, fprop.Pcap[:,ctes.v0],\n ctes.z[ctes.v0], ctes.pretransmissibility_internal_faces)\n Fk_internal_faces = self.update_Fk_internal_faces(\n fprop.xkj_internal_faces, fprop.Csi_j_internal_faces, Fj_internal_faces)\n Fk_vols_total = self.update_flux_volumes(Fk_internal_faces)\n return Fk_vols_total\n\n def update_Fj_internal_faces(self, Ft_internal_faces, rho_j_internal_faces,\n mobilities_internal_faces, Pcap_face, z_face,\n pretransmissibility_internal_faces):\n ''' Function to calculate phase flux '''\n\n frj = mobilities_internal_faces[0,...] / \\\n np.sum(mobilities_internal_faces[0,...], axis = 0)\n\n Fj_internal_faces = frj[np.newaxis,...] * (Ft_internal_faces +\n pretransmissibility_internal_faces * (np.sum(mobilities_internal_faces *\n (Pcap_face[:,:,1] - Pcap_face[:,:,0] - ctes.g * rho_j_internal_faces *\n (z_face[:,1] - z_face[:,0])), axis=1) - np.sum(mobilities_internal_faces,\n axis=1) * (Pcap_face[:,:,1] - Pcap_face[:,:,0] - ctes.g *\n rho_j_internal_faces * (z_face[:,1] - z_face[:,0]))))\n\n return Fj_internal_faces\n\n def update_Fk_internal_faces(self, xkj_internal_faces, Csi_j_internal_faces, Fj_internal_faces):\n ''' Function to compute component molar flux '''\n Fk_internal_faces = np.sum(xkj_internal_faces * Csi_j_internal_faces *\n Fj_internal_faces, axis = 1)\n return Fk_internal_faces\n\n def update_flux_volumes(self, Fk_internal_faces):\n ''' Function to compute component molar flux balance through the control \\\n volume interfaces '''\n cx = np.arange(ctes.n_components)\n lines = np.array([np.repeat(cx,len(ctes.v0[:,0])), np.repeat(cx,len(ctes.v0[:,1]))]).astype(int).flatten()\n cols = np.array([np.tile(ctes.v0[:,0],ctes.n_components), np.tile(ctes.v0[:,1], ctes.n_components)]).flatten()\n data = np.array([-Fk_internal_faces, Fk_internal_faces]).flatten()\n Fk_vols_total = sp.csc_matrix((data, (lines, cols)), shape = (ctes.n_components, ctes.n_volumes)).toarray()\n\n '''\n inds = np.array([0,-1])\n a = (self.Nk[:,inds] - abs(self.Nk[:,inds]))/2\n a = a[:,self.v0]\n if a>=0:\n Fk_contour_face = self.Nk[0,-1] **2/2*len(self.Nk[-1])\n else:\n Fk_contour_face = self.Nk[0,0]**2/2*len(self.Nk[0])\n Fk_contour_face = self.Nk[0,-1]**2/2*len(self.Nk[0])\n Fk_vols_total[:,0] = -(Fk_internal_faces[:,0] - Fk_contour_face)\n Fk_vols_total[:,-1] = -(Fk_contour_face - Fk_internal_faces[:,1])'''\n\n return Fk_vols_total\n\n def wave_velocity_upw(self, M, fprop, mobilities, rho_j, xkj, Csi_j, Ft_internal_faces):\n #grad = Fk_internal_faces>0 #Pot_hidr(i+1) - Pot_hidr(i)\n\n Nk_face = fprop.Nk[:,ctes.v0]\n\n RS = RiemannSolvers(ctes.v0, ctes.pretransmissibility_internal_faces)\n #ponteiro[0] = False\n #alpha = fprop.Fk_vols_total\n Fj_internal_faces_L = self.update_Fj_internal_faces(Ft_internal_faces,\n rho_j[:,:,ctes.v0[:,0]], mobilities[:,:,ctes.v0[:,0]], fprop.Pcap[:,ctes.v0],\n ctes.z[ctes.v0], ctes.pretransmissibility_internal_faces)\n Fj_internal_faces_R = self.update_Fj_internal_faces(Ft_internal_faces,\n rho_j[:,:,ctes.v0[:,1]], mobilities[:,:,ctes.v0[:,1]], fprop.Pcap[:,ctes.v0],\n ctes.z[ctes.v0], ctes.pretransmissibility_internal_faces)\n Fk_internal_faces_L = self.update_Fk_internal_faces(\n xkj[:,:,ctes.v0[:,0]], Csi_j[:,:,ctes.v0[:,0]], Fj_internal_faces_L)\n Fk_internal_faces_R = self.update_Fk_internal_faces(\n xkj[:,:,ctes.v0[:,1]], Csi_j[:,:,ctes.v0[:,1]], Fj_internal_faces_R)\n\n Nk = (fprop.Nk[:,ctes.v0[:,0]] + fprop.Nk[:,ctes.v0[:,1]])/2\n Vp = fprop.Vp[ctes.v0].sum(axis=-1)/2\n P_face = fprop.P[ctes.v0].sum(axis=-1)/2\n alpha = (Fk_internal_faces_R - Fk_internal_faces_L)/(fprop.Nk[:,ctes.v0[:,1]] - fprop.Nk[:,ctes.v0[:,0]])\n ponteiro = np.zeros_like(alpha[0],dtype=bool)\n ponteiro[np.sum(abs(fprop.Nk[:,ctes.v0[:,1]] - fprop.Nk[:,ctes.v0[:,0]])<1e-16,axis=0,dtype=bool)] = True\n alpha[:,ponteiro] = RS.medium_wave_velocity(M, fprop, Nk[:,ponteiro], P_face, Vp[ponteiro], Ft_internal_faces, ponteiro)\n\n #alpha[:,ponteiro] = 0\n #ponteiro[arg_vols] = True\n #alpha2 = RiemannSolvers(ctes.v0, ctes.pretransmissibility_internal_faces).\\\n # LR_wave_velocity(M, fprop, Nk_face, P_face, Ft_internal_faces, ponteiro)\n\n return alpha\n\nclass RiemannSolvers:\n def __init__(self, v0, pretransmissibility):\n self.v0 = v0\n self.pretransmissibility = pretransmissibility\n\n def LLF(self, M, fprop, Nk_face, P_face, ftotal, Fk_face, ponteiro_LLF):\n ponteiro = np.ones_like(ponteiro_LLF[ponteiro_LLF], dtype=bool)\n ponteiro[~np.sum((Nk_face[:,ponteiro_LLF,0]!=Nk_face[:,ponteiro_LLF,1]),axis=0,dtype=bool)] = False\n alpha = np.empty((ctes.n_components, len(ponteiro_LLF[ponteiro_LLF]), 5))\n if any(ponteiro):\n alpha[:,ponteiro] = self.wave_velocity_LLF(M, fprop, Nk_face[:,ponteiro_LLF],\n P_face[ponteiro_LLF], ftotal[:,ponteiro_LLF], np.copy(ponteiro))\n alpha[:,~ponteiro] = 0\n Fk_internal_faces, alpha_LLF = self.update_flux_LLF(Fk_face[:,ponteiro_LLF], Nk_face[:,ponteiro_LLF], alpha)\n return Fk_internal_faces, alpha_LLF\n\n def MDW(self, M, fprop, Nk_face, P_face, ftotal, Fk_face, ponteiro_MDW):\n ponteiro = np.zeros_like(ponteiro_MDW[ponteiro_MDW], dtype=bool)\n ponteiro[~np.sum((Nk_face[:,ponteiro_MDW,0]!=Nk_face[:,ponteiro_MDW,1]),axis=0,dtype=bool)] = True\n alpha_MDW = np.zeros((ctes.n_components, len(ponteiro_MDW[ponteiro_MDW]),4))\n if any(~ponteiro):\n alpha_MDW[:,~ponteiro] = self.wave_velocity_MDW( M, fprop, Nk_face[:,ponteiro_MDW],\n P_face[ponteiro_MDW], ftotal[:,ponteiro_MDW], Fk_face[:,ponteiro_MDW], np.copy(~ponteiro))\n Fk_internal_faces = self.update_flux_MDW(Fk_face[:,ponteiro_MDW], Nk_face[:,ponteiro_MDW], alpha_MDW)\n return Fk_internal_faces, alpha_MDW\n\n def reshape_constant_property(self, y, ponteiro, v):\n\n y_aux0 = y[self.v0][:,ponteiro,0]\n y_aux1 = y[self.v0][:,ponteiro,1]\n\n y_reshaped1 = np.tile(y_aux0,(int(v/2) * \\\n (np.sign(v - ctes.n_components)**2) + int(v)*(1 - np.sign(v -\n ctes.n_components)**2)))\n y_reshaped2 = np.tile(y_aux1,(int(v/2) * \\\n (np.sign(v - ctes.n_components)**2) + int(v/(ctes.n_components+1))*(1 -\n np.sign(v-ctes.n_components))))\n\n y_reshaped = np.concatenate((y_reshaped1, y_reshaped2), axis=-1)\n\n if v==3:\n y_reshaped3 = (y_aux0 + y_aux1)*0.5\n y_reshaped = np.concatenate((y_reshaped, y_reshaped3))\n\n if ctes.FR:\n if self.v0.shape[1] >= 3:\n y_reshaped = y_aux0\n for i in range(1,self.v0.shape[1]):\n try:\n y_reshaped_i = y[self.v0][ponteiro,i]\n except:\n y_reshaped_i = y[:,self.v0][:,ponteiro,i]\n y_reshaped = np.concatenate((y_reshaped, y_reshaped_i), axis=-1)\n return y_reshaped\n\n def get_extrapolated_properties(self, fprop, M, Nk_face, z_face, P_face, Vp_face, v, ponteiro):\n xkj_face = np.empty((ctes.n_components, ctes.n_phases, len(P_face)))\n Csi_j_face = np.empty((1, ctes.n_phases, len(P_face)))\n rho_j_face = np.empty_like(Csi_j_face)\n\n ''' Flash calculations and properties calculations at each side of the \\\n interface '''\n if ctes.compressible_k:\n L_face, V_face, xkj_face[0:ctes.Nc,0,...], xkj_face[0:ctes.Nc,1,...], \\\n Csi_j_face[0,0,...], Csi_j_face[0,1,...], rho_j_face[0,0,...], \\\n rho_j_face[0,1,...] = StabilityCheck(P_face, fprop.T).run_init(P_face, z_face)\n\n else:\n L_face = np.ones(len(P_face)); V_face = np.zeros(len(P_face))\n xkj_face[0:ctes.Nc,0:2,:] = 1\n\n rho_j_face[0,0,:] = np.tile(fprop.rho_j[0,0,self.v0[ponteiro,0]], v)\n rho_j_face[0,1,:] = np.tile(fprop.rho_j[0,1,self.v0[ponteiro,0]], v) #constante, independe da pressao\n #self.reshape_constant_property(fprop.rho_j[0,0:2,:], ponteiro, v)\n Csi_j_face[0,0,:] = np.tile(fprop.Csi_j[0,0,self.v0[ponteiro,0]], v)\n Csi_j_face[0,1,:] = np.tile(fprop.Csi_j[0,1,self.v0[ponteiro,0]], v)\n #self.reshape_constant_property(fprop.Csi_j[0,0:2,:], ponteiro, v)\n\n\n if ctes.load_w:\n xkj_face[-1,-1,...] = 1\n xkj_face[-1,0:-1,...] = 0\n xkj_face[0:ctes.Nc,-1,...] = 0\n\n if data_loaded['compositional_data']['water_data']['mobility']:\n # Csi_W0 é constante independente de qualquer coisa(por teoria)\n Csi_W0_face = np.tile(fprop.Csi_W0[self.v0[ponteiro,0]], v)\n #self.reshape_constant_property(fprop.Csi_W0, ponteiro, v)\n Sw_face, Csi_j_face[0,-1,...], rho_j_face[0,-1,...] = \\\n PropertiesCalc().update_water_saturation(fprop, Nk_face[-1,...],\n P_face, Vp_face, Csi_W0_face)\n\n else:\n # se não movel, prop constante (no varia com P)\n Sw_face = np.tile(fprop.Sw[self.v0[ponteiro,0]], v)\n #self.reshape_constant_property(fprop.Sw, ponteiro, v)\n rho_j_face[0,-1] = np.tile(fprop.rho_j[0,-1,self.v0[ponteiro,0]], v)\n #self.reshape_constant_property(fprop.rho_j[0,-1], ponteiro, v)\n Csi_j_face[0,-1] = np.tile(fprop.Csi_j[0,-1,self.v0[ponteiro,0]], v)\n #self.reshape_constant_property(fprop.Csi_j[0,-1], ponteiro, v)\n else:\n Sw_face = np.tile(fprop.Sw[self.v0[ponteiro,0]],v)\n\n So_face, Sg_face = PropertiesCalc().update_saturations(Sw_face,\n Csi_j_face, L_face, V_face)\n\n mobilities_face = PropertiesCalc().update_mobilities(fprop, So_face,\n Sg_face, Sw_face, Csi_j_face, xkj_face)\n return mobilities_face, rho_j_face, Csi_j_face, xkj_face\n\n def Fk_from_Nk(self, fprop, M, Nk, P_face, Vp_face, ftotal, ponteiro):\n ''' Function to compute component flux based on a given composition (Nk) '''\n v = int(len(Nk[0,:])/len(ponteiro[ponteiro]))\n z = Nk[0:ctes.Nc] / np.sum(Nk[0:ctes.Nc], axis = 0)\n\n mobilities, rho_j, Csi_j, xkj = self.get_extrapolated_properties(fprop, M, Nk, z,\n np.tile(P_face,v), Vp_face, v, ponteiro)\n\n f = Flux()\n\n Pcap_reshaped = np.concatenate(np.dsplit(np.tile(fprop.Pcap[:,self.v0][:,ponteiro],v),v),axis=1)\n z_reshaped = np.concatenate(np.hsplit(np.tile(ctes.z[self.v0][ponteiro],v),v),axis=0)\n Fj = f.update_Fj_internal_faces(ftotal, rho_j, mobilities, Pcap_reshaped,\n z_reshaped, np.tile(self.pretransmissibility[ponteiro],v))\n\n Fk = f.update_Fk_internal_faces(xkj, Csi_j, Fj)\n return Fk\n\n def get_Fk_face(self, fprop, M, Nk_face, P_face, ftotal):\n ft_Nks = np.tile(ftotal,2)\n Nks = np.concatenate((Nk_face[:,:,0], Nk_face[:,:,1]), axis=1)\n Vp_face = np.concatenate((fprop.Vp[ctes.v0[:,0]], fprop.Vp[ctes.v0[:,1]]), axis=0)\n Fk_faces = self.Fk_from_Nk(fprop, M, Nks, P_face, Vp_face, ft_Nks, np.ones_like(ftotal[0], dtype=bool))\n Fk_faceL, Fk_faceR = np.hsplit(Fk_faces, 2)\n Fk_face = np.concatenate((Fk_faceL[:,:,np.newaxis], Fk_faceR[:,:,np.newaxis]), axis=-1)\n return Fk_face\n\n def medium_wave_velocity(self, M, fprop, Nk, P_face, Vp, ftotal, ponteiro):\n delta = 0.001\n Nk_aux_matrix = np.ones([ctes.n_components, ctes.n_components, len(ponteiro[ponteiro]),2])\n matrix_deltas = np.identity(ctes.n_components)[:,:,np.newaxis, np.newaxis] * Nk_aux_matrix\n delta_05 = delta * 0.5 * matrix_deltas\n #Nkm = (Nk_face[:,ponteiro,1] + Nk_face[:,ponteiro,0])/2\n\n Nk_aux = Nk[np.newaxis,:,:] * Nk_aux_matrix[...,0]\n Nk_plus = np.copy(Nk_aux)\n Nk_minus = np.copy(Nk_aux)\n Nk_plus += delta_05[...,0]\n Nk_minus -= delta_05[...,0]\n Nk_plus[Nk_minus<0] = 2 * Nk_plus[Nk_minus < 0]\n Nk_minus[Nk_minus<0] = 0\n Nks = np.concatenate((Nk_plus[...,np.newaxis], Nk_minus[...,np.newaxis]),axis=-1)\n Nks = np.concatenate(np.split(Nks, ctes.n_components),axis=2)[0,...]\n Nks = np.concatenate(np.dsplit(Nks, 2),axis=1)[...,0]\n Nk_plus, Nk_minus = np.hsplit(Nks,2)\n\n ft_Nks = np.tile(ftotal[:,ponteiro],ctes.n_components*2)\n Vps = np.tile(Vp, ctes.n_components*2)\n\n Fks = self.Fk_from_Nk(fprop, M, Nks, P_face[ponteiro], Vps, ft_Nks, ponteiro)\n\n Fk_plus, Fk_minus = np.hsplit(Fks,2)\n dFkdNk = (Fk_plus - Fk_minus)/ (Nk_plus - Nk_minus).sum(axis=0)\n dFkdNk = np.concatenate(np.hsplit(dFkdNk[:,:,np.newaxis],ctes.n_components),axis = 2)\n dFkdNk = dFkdNk.transpose(1,0,2)\n\n eigval1, v = np.linalg.eig(dFkdNk)\n dFkdNk_eigvalue = eigval1.T\n return dFkdNk_eigvalue\n\n def wave_velocity_LLF(self, M, fprop, Nk_face, P_face, ftotal, ponteiro):\n delta = 0.001\n\n Nk_aux_matrix = np.ones([ctes.n_components, ctes.n_components, len(ponteiro[ponteiro]), 2])\n matrix_deltas = np.identity(ctes.n_components)[:,:,np.newaxis, np.newaxis] * Nk_aux_matrix\n delta_05 = delta * 0.5 * matrix_deltas\n Nkm = (Nk_face[:,ponteiro,1] + Nk_face[:,ponteiro,0])/2\n\n Nkg = Nkm[:,:,np.newaxis] + (Nk_face[:,ponteiro] - Nkm[:,:,np.newaxis])/(3**(1/2))\n Nkg_aux = Nkg[np.newaxis,...] * Nk_aux_matrix\n Nkg_plus = np.copy(Nkg_aux)\n Nkg_minus = np.copy(Nkg_aux)\n Nkg_plus += delta_05\n Nkg_minus -= delta_05\n Nkg_plus[Nkg_minus<0] = 2*Nkg_plus[Nkg_minus<0]\n Nkg_minus[Nkg_minus<0] = 0\n Nkgs = np.concatenate((Nkg_plus,Nkg_minus),axis=-1)\n #Nkgs = np.concatenate(np.split(Nkgs, ctes.n_components),axis=2)[0,...]\n #Nkgs = np.concatenate(np.dsplit(Nkgs, 4),axis=1)[...,0]\n\n Nk_face_aux = Nk_face[np.newaxis,:,ponteiro,:] * Nk_aux_matrix\n Nk_face_plus = np.copy(Nk_face_aux)\n Nk_face_minus = np.copy(Nk_face_aux)\n Nk_face_plus += delta_05\n Nk_face_minus -= delta_05\n Nk_face_plus[Nk_face_minus<0] = 2 * Nk_face_plus[Nk_face_minus < 0]\n Nk_face_minus[Nk_face_minus<0] = 0\n Nk_faces = np.concatenate((Nk_face_plus,Nk_face_minus),axis=-1)\n Nks = np.concatenate((Nkgs, Nk_faces), axis=-1)\n Nks = np.concatenate(np.split(Nks, ctes.n_components),axis=2)[0,...]\n Nks = np.concatenate(np.dsplit(Nks, 8),axis=1)[...,0]\n\n Nkg_plus, Nkg_minus, Nk_face_plus, Nk_face_minus = np.hsplit(Nks,4)\n\n Nkm_aux = Nkm[np.newaxis,:,:] * Nk_aux_matrix[...,0]\n Nkm_plus = np.copy(Nkm_aux)\n Nkm_minus = np.copy(Nkm_aux)\n Nkm_plus += delta_05[...,0]\n Nkm_minus -= delta_05[...,0]\n Nkm_plus[Nkm_minus<0] = 2 * Nkm_plus[Nkm_minus < 0]\n Nkm_minus[Nkm_minus<0] = 0\n Nkms = np.concatenate((Nkm_plus[...,np.newaxis], Nkm_minus[...,np.newaxis]),axis=-1)\n Nkms = np.concatenate(np.split(Nkms, ctes.n_components),axis=2)[0,...]\n Nkms = np.concatenate(np.dsplit(Nkms, 2),axis=1)[...,0]\n Nkm_plus, Nkm_minus = np.hsplit(Nkms,2)\n Nks = np.concatenate((Nks, Nkms),axis=-1)\n\n ft_Nks = np.tile(ftotal[:,ponteiro],ctes.n_components*10)\n Vp_faceL = np.tile(fprop.Vp[self.v0[ponteiro,0]], ctes.n_components)\n Vp_faceR = np.tile(fprop.Vp[self.v0[ponteiro,1]], ctes.n_components)\n Vp_plus = np.concatenate((Vp_faceL, Vp_faceR), axis=0)\n Vp_faces = np.tile(Vp_plus, 4)\n Vpm = fprop.Vp[self.v0[ponteiro]].sum(axis=-1)*0.5\n Vpms = np.tile(Vpm, ctes.n_components*2)\n Vps = np.concatenate((Vp_faces, Vpms), axis=0)\n\n Fks = self.Fk_from_Nk(fprop, M, Nks, P_face[ponteiro], Vps, ft_Nks, ponteiro)\n\n Fk_Nkg_plus, Fk_Nkg_minus, Fk_faces_plus, Fk_faces_minus, Fkms = np.hsplit(Fks,5)\n\n Fkm_plus, Fkm_minus = np.hsplit(Fkms,2)\n dFkdNk_m = (Fkm_plus - Fkm_minus)/ (Nkm_plus - Nkm_minus).sum(axis=0)\n dFkdNk_m = np.concatenate(np.hsplit(dFkdNk_m[:,:,np.newaxis],ctes.n_components),axis = 2)\n dFkdNk_m = dFkdNk_m.transpose(1,0,2)\n\n dFkdNk = ((Fk_faces_plus - Fk_faces_minus)/(Nk_face_plus - Nk_face_minus).sum(axis=0))\n dFkdNk = np.concatenate(np.hsplit(dFkdNk[:,:,np.newaxis],2),axis=2)\n dFkdNk = np.concatenate(np.hsplit(dFkdNk[:,:,:,np.newaxis],ctes.n_components),axis=3)\n dFkdNk = dFkdNk.transpose(2,1,0,3)\n\n dFkdNk_gauss = (Fk_Nkg_plus - Fk_Nkg_minus)/(Nkg_plus - Nkg_minus).sum(axis=0)\n dFkdNk_gauss = np.concatenate(np.hsplit(dFkdNk_gauss[:,:,np.newaxis],2),axis=2)\n dFkdNk_gauss = np.concatenate(np.hsplit(dFkdNk_gauss[:,:,:,np.newaxis],ctes.n_components),axis=3)\n dFkdNk_gauss = dFkdNk_gauss.transpose(2,1,0,3)\n\n\n eigval1, v = np.linalg.eig(dFkdNk)\n dFkdNk_eigvalue = eigval1.T\n eigval2, v = np.linalg.eig(dFkdNk_gauss)\n dFkdNk_gauss_eigvalue = eigval2.transpose(2,1,0)\n eigval3, v = np.linalg.eig(dFkdNk_m)\n dFkdNk_m_eigvalue = eigval3.T\n\n alpha = np.concatenate((dFkdNk_eigvalue, dFkdNk_gauss_eigvalue), axis=-1)\n alpha = np.concatenate((alpha, dFkdNk_m_eigvalue[:,:,np.newaxis]), axis=-1)\n return alpha\n\n def update_flux_LLF(self, Fk_face_LLF_all, Nk_face_LLF, alpha_LLF):\n #alpha2 = np.concatenate((alpha_LLF, alpha_RH[:,:,np.newaxis]),axis=-1)\n alpha_RH = (Fk_face_LLF_all[:,:,1] - Fk_face_LLF_all[:,:,0]) / \\\n (Nk_face_LLF[:,:,1] - Nk_face_LLF[:,:,0])\n alpha_LLF[abs(Nk_face_LLF[:,:,1] - Nk_face_LLF[:,:,0])>1e-3] = alpha_RH[abs(Nk_face_LLF[:,:,1] -\n Nk_face_LLF[:,:,0])>1e-3][:,np.newaxis]\n alpha = np.max(abs(alpha_LLF),axis = 0)\n Fk_face_LLF = 0.5*(Fk_face_LLF_all.sum(axis=-1) - np.max(abs(alpha),axis=-1) * \\\n (Nk_face_LLF[:,:,1] - Nk_face_LLF[:,:,0]))\n\n return Fk_face_LLF, alpha\n\n def update_flux_MDW(self, Fk_face, Nk_face, alpha_MDW):\n Fk_face_MDW = 0.5*(Fk_face.sum(axis=-1) - np.max(abs(alpha_MDW),axis=-1) * \\\n (Nk_face[:,:,1] - Nk_face[:,:,0]))\n return Fk_face_MDW\n\n def wave_velocity_MDW(self, M, fprop, Nk_face, P_face, ftotal, Fk_face, ponteiro):\n Nk_aux_matrix = np.ones([ctes.n_components, ctes.n_components, len(ponteiro[ponteiro]), 2])\n dNk_face = (Nk_face[:,ponteiro,1] - Nk_face[:,ponteiro,0])\n Nkm = (Nk_face[:,ponteiro,1] + Nk_face[:,ponteiro,0])/2\n\n Nkg = Nkm[:,:,np.newaxis] + (Nk_face[:,ponteiro] - Nkm[:,:,np.newaxis])/(3**(1/2))\n\n Nkgs = np.concatenate((Nkg[:,:,0], Nkg[:,:,1]), axis=1)\n Nks = np.concatenate((Nkgs, Nkm), axis=1)\n\n ft_Nks = np.tile(ftotal[:,ponteiro],3)\n\n Vp_face = np.concatenate((fprop.Vp[ctes.v0[ponteiro,0]], fprop.Vp[ctes.v0[ponteiro,1]]), axis=0)\n Vpm = np.sum(fprop.Vp[ctes.v0[ponteiro]], axis=-1) * 0.5\n Vps = np.concatenate((Vp_face, Vpm), axis=-1)\n Fks = self.Fk_from_Nk(fprop, M, Nks, P_face[ponteiro], Vps, ft_Nks, ponteiro)\n\n Fk_NkgL, Fk_NkgR, Fk_Nkm = np.hsplit(Fks,3)\n\n dNkg_Nkface = Nkg - Nk_face[:,ponteiro]\n\n dNkm_Nkg = Nkm[:,:,np.newaxis] - Nkg\n\n alpha_L_GL = ((dNkg_Nkface[:,:,0]) * (Fk_NkgL - Fk_face[:,ponteiro,0])) / \\\n ((dNkg_Nkface[:,:,0]) * (dNkg_Nkface[:,:,0]))\n alpha_L_GL[(dNkg_Nkface[:,:,0])**2==0] = 0\n\n alpha_GL_M = ((dNkm_Nkg[:,:,0]) * (Fk_Nkm - Fk_NkgL)) / \\\n ((dNkm_Nkg[:,:,0]) * (dNkm_Nkg[:,:,0]))\n alpha_GL_M[(dNkm_Nkg[:,:,0])**2==0] = 0\n\n alpha_M_GR = ((-dNkm_Nkg[:,:,1]) * (Fk_NkgR - Fk_Nkm)) / \\\n ((-dNkm_Nkg[:,:,1]) * (-dNkm_Nkg[:,:,1]))\n alpha_M_GR[(dNkm_Nkg[:,:,1])**2==0] = 0\n\n alpha_GR_R = ((-dNkg_Nkface[:,:,1]) * (Fk_face[:,ponteiro,1] - Fk_NkgR)) / \\\n ((-dNkg_Nkface[:,:,1]) * (-dNkg_Nkface[:,:,1]))\n alpha_GR_R[(dNkg_Nkface[:,:,1])**2==0] = 0\n\n alpha_MDW = np.concatenate((alpha_L_GL[...,np.newaxis], alpha_GL_M[...,np.newaxis]), axis=-1)\n alpha_MDW = np.concatenate((alpha_MDW, alpha_M_GR[...,np.newaxis]), axis=-1)\n alpha_MDW = np.concatenate((alpha_MDW, alpha_GR_R[...,np.newaxis]), axis=-1)\n if any(np.isnan(alpha_MDW).flatten()): import pdb; pdb.set_trace()\n return alpha_MDW\n\nclass MUSCL:\n\n \"\"\" Class created for the second order MUSCL implementation for the \\\n calculation of the advective terms \"\"\"\n\n def run(self, M, fprop, wells, P_old, ftot, Pot_hid):\n\n ''' Global function that calls others '''\n self.P_face = np.sum(P_old[ctes.v0], axis=1) * 0.5\n dNk_vols = self.volume_gradient_reconstruction(M, fprop, wells)\n dNk_face, dNk_face_neig = self.get_faces_gradient(M, fprop, dNk_vols)\n\n Phi = self.Van_Leer_slope_limiter(dNk_face, dNk_face_neig)\n Nk_face, z_face = self.get_extrapolated_compositions(fprop, Phi, dNk_face_neig)\n\n #G = self.update_gravity_term() # for now, it has no gravity\n alpha = self.update_flux(M, wells, fprop, Nk_face, ftot, Pot_hid)\n #alpha = fprop.Fk_vols_total/fprop.Nk\n return alpha\n\n def volume_gradient_reconstruction(self, M, fprop, wells):\n neig_vols = M.volumes.bridge_adjacencies(M.volumes.all,2,3)\n matriz = np.zeros((ctes.n_volumes,ctes.n_volumes))\n\n lines = np.array([ctes.v0[:, 0], ctes.v0[:, 1], ctes.v0[:, 0], ctes.v0[:, 1]]).flatten()\n cols = np.array([ctes.v0[:, 1], ctes.v0[:, 0], ctes.v0[:, 0], ctes.v0[:, 1]]).flatten()\n data = np.array([np.ones(len(ctes.v0[:, 0])), np.ones(len(ctes.v0[:, 0])),\n np.zeros(len(ctes.v0[:, 0])), np.zeros(len(ctes.v0[:, 0]))]).flatten()\n all_neig = sp.csc_matrix((data, (lines, cols)), shape = (ctes.n_volumes, ctes.n_volumes)).toarray()\n all_neig = all_neig.astype(int)\n all_neig2 = all_neig + np.identity(ctes.n_volumes)\n allneig2 = all_neig2.astype(int)\n\n Nk_neig = fprop.Nk[:,np.newaxis,:] * allneig2[np.newaxis,:,:]\n Nk = Nk_neig.transpose(0,2,1)\n pos_neig = M.data['centroid_volumes'].T[:,np.newaxis,:] * allneig2[np.newaxis,:,:]\n\n pos = pos_neig.transpose(0,2,1)\n\n ds = pos_neig - pos\n ds_norm = np.linalg.norm(ds, axis=0)\n versor_ds = np.empty(ds.shape)\n versor_ds[:,ds_norm==0] = 0\n versor_ds[:,ds_norm!=0] = ds[:,ds_norm!=0] / ds_norm[ds_norm!=0]\n dNk = Nk_neig - Nk\n\n dNk_by_axes = np.repeat(dNk[:,np.newaxis,:,:],3,axis=1)\n dNk_by_axes = dNk_by_axes * versor_ds\n dNk_vols = dNk_by_axes.sum(axis = 3)\n\n ds_vols = ds * versor_ds\n ds_vols = ds_vols.sum(axis = 2)\n dNkds_vols = np.copy(dNk_vols)\n dNkds_vols[:,ds_vols!=0] = dNk_vols[:,ds_vols != 0] / ds_vols[ds_vols != 0][np.newaxis,:]\n all_neig = all_neig.sum(axis=1)\n self.faces_contour = self.identify_contour_faces(all_neig)\n #import pdb; pdb.set_trace()\n #dNkds_vols[:,:,all_neig==1] = 0 #*dNkds_vols[:,:,all_neig.sum(axis=1)==1]\n dNkds_vols[:,:,ctes.v0[self.faces_contour].flatten()] = 0 # zero in the contour volumes\n return dNkds_vols\n\n def get_faces_gradient(self, M, fprop, dNkds_vols):\n dNk_face = fprop.Nk[:,ctes.v0[:,1]] - fprop.Nk[:,ctes.v0[:,0]]\n ds_face = M.data['centroid_volumes'][ctes.v0[:,1],:] - M.data['centroid_volumes'][ctes.v0[:,0],:]\n dNk_face_vols = 2. * (dNkds_vols[:,:,ctes.v0] * ds_face.T[np.newaxis,:,:,np.newaxis]).sum(axis=1)\n dNk_face_neig = dNk_face_vols - dNk_face[:,:,np.newaxis]\n dNk_face_neig[abs(dNk_face_neig)<1e-25] = 0\n return dNk_face, dNk_face_neig\n\n def Van_Leer_slope_limiter(self, dNk_face, dNk_face_neig):\n np.seterr(divide='ignore', invalid='ignore')\n r_face = dNk_face[:,:,np.newaxis] / dNk_face_neig\n r_face[dNk_face_neig==0] = 0\n phi = (r_face + abs(r_face)) / (r_face + 1)\n phi[r_face<0] = 0 #so botei pra caso r==-1\n Phi = phi\n Phi[:,:,1] = -Phi[:,:,1]\n return Phi\n\n def Van_Albada1_slope_limiter(self, dNk_face, dNk_face_neig):\n np.seterr(divide='ignore', invalid='ignore')\n r_face = dNk_face[:,:,np.newaxis] / dNk_face_neig\n r_face[dNk_face_neig==0] = 0\n phi = (r_face**2 + abs(r_face)) / (r_face**2 + 1)\n phi[r_face<0]=0 #so botei pra caso r==-1\n Phi = phi\n Phi[:,:,1] = -Phi[:,:,1]\n return Phi\n\n def get_extrapolated_compositions(self, fprop, Phi, dNk_face_neig):\n Nk_face = fprop.Nk[:,ctes.v0] + Phi / 2 * dNk_face_neig\n if any(Nk_face.flatten()<0): import pdb; pdb.set_trace()\n #Nk_face[Nk_face<0] = fprop.Nk[:,ctes.v0][Nk_face<0]\n z_face = Nk_face[0:ctes.Nc] / np.sum(Nk_face[0:ctes.Nc], axis = 0)\n return Nk_face, z_face\n\n def update_gravity_term(self):\n G = ctes.g * self.rho_j_face * ctes.z[ctes.v0]\n return G\n\n '''def flux_calculation_conditions_Serna(self, alpha, d2FkdNk):\n #ponteiro_LLF = np.ones(ctes.n_internal_faces,dtype=bool)\n #import pdb; pdb.set_trace()\n ponteiro_LLF = np.ones((ctes.n_components,ctes.n_internal_faces),dtype=bool)\n ponteiro_LLF[alpha[:,:,0] * alpha[:,:,1] <= 0] = False\n ponteiro_LLF[d2FkdNk[:,:,0] * d2FkdNk[:,:,0] <= 0] = False\n ponteiro_LLF = ponteiro_LLF.sum(axis=0,dtype=bool)\n return ponteiro_LLF'''\n\n def identify_contour_faces(self, all_neig):\n vols_contour = np.argwhere(all_neig==1).flatten()\n faces_contour = np.empty_like(vols_contour)\n\n for i in range(len(vols_contour)):\n try: faces_contour[i] = np.argwhere(ctes.v0[:,0] == vols_contour[i]).flatten()\n except: faces_contour[i] = np.argwhere(ctes.v0[:,1] == vols_contour[i]).flatten()\n return faces_contour\n\n def update_flux(self, M, wells, fprop, Nk_face, ftotal, Pot_hid):\n Fk_internal_faces = np.empty((ctes.n_components,ctes.n_internal_faces))\n alpha_wv = np.empty((ctes.n_components,ctes.n_internal_faces, 4))\n RS = RiemannSolvers(ctes.v0, ctes.pretransmissibility_internal_faces)\n\n Fk_face = RS.get_Fk_face(fprop, M, Nk_face, self.P_face, ftotal)\n ponteiro = np.zeros(ctes.n_internal_faces,dtype=bool)\n\n Fk_internal_faces[:,~ponteiro], alpha_wv[:,~ponteiro,:] = RS.MDW(M, fprop, Nk_face, self.P_face,\n ftotal, Fk_face, ~ponteiro)\n #ponteiro[self.faces_contour] = True\n #Fk_internal_faces[:,ponteiro] = self.update_flux_upwind(fprop, Fk_face[:,ponteiro], ponteiro)\n\n '-------- Perform volume balance to obtain flux through volumes -------'\n fprop.Fk_vols_total = Flux().update_flux_volumes(Fk_internal_faces)\n if any(np.isnan(fprop.Fk_vols_total).flatten()): import pdb; pdb.set_trace()\n if any(fprop.Fk_vols_total[:-1][fprop.z==0]<0): import pdb; pdb.set_trace()\n return alpha_wv\n\n def get_LR_eigenvalues(self, M, fprop, Nk_face, ponteiro):\n\n delta = 0.001\n Nk_face_plus = Nk_face[np.newaxis,:,ponteiro,:] * np.ones([ctes.n_components, ctes.n_components, len(ponteiro[ponteiro]), 2])\n Nk_face_minus = Nk_face[np.newaxis,:,ponteiro,:] * np.ones([ctes.n_components, ctes.n_components, len(ponteiro[ponteiro]), 2])\n matrix_deltas = np.identity(ctes.n_components)[:,:,np.newaxis, np.newaxis] * np.ones([ctes.n_components, ctes.n_components, len(ponteiro[ponteiro]),2])\n Nk_face_plus += delta * 0.5 * matrix_deltas\n Nk_face_minus -= delta * 0.5 * matrix_deltas\n Nk_face_plus = np.concatenate(np.split(Nk_face_plus, ctes.n_components),axis=2)[0,...]\n Nk_face_minus = np.concatenate(np.split(Nk_face_minus, ctes.n_components),axis=2)[0,...]\n Nk_face_plus = np.concatenate(np.dsplit(Nk_face_plus, 2),axis=1)[:,:,0]\n Nk_face_minus = np.concatenate(np.dsplit(Nk_face_minus, 2),axis=1)[:,:,0]\n dFkdNk = ((self.Fk_from_Nk(fprop, M, Nk_face_plus, ponteiro) -\n self.Fk_from_Nk(fprop, M, Nk_face_minus, ponteiro))/(Nk_face_plus - Nk_face_minus).sum(axis=0))\n dFkdNk = np.concatenate(np.hsplit(dFkdNk[:,:,np.newaxis],2),axis=2)\n dFkdNk = np.concatenate(np.hsplit(dFkdNk[:,:,:,np.newaxis],ctes.n_components),axis=3)\n dFkdNk = dFkdNk.transpose(2,1,0,3)\n\n eigval1, v = np.linalg.eig(dFkdNk)\n dFkdNk_eigvalue = eigval1.T\n\n return dFkdNk_eigvalue\n\n def update_flux_upwind(self, fprop, Fk_face_upwind_all, ponteiro):\n Fk_face_upwind = np.empty_like(Fk_face_upwind_all[:,:,0])\n\n Pot_hid = fprop.P #+ fprop.Pcap\n Pot_hidj = Pot_hid[ctes.v0[:,0]][ponteiro] #- G[0,:,:,0]\n Pot_hidj_up = Pot_hid[ctes.v0[:,1]][ponteiro] #- G[0,:,:,1]\n\n Fk_face_upwind[:,Pot_hidj_up <= Pot_hidj] = \\\n Fk_face_upwind_all[:,Pot_hidj_up <= Pot_hidj, 0]\n Fk_face_upwind[:,Pot_hidj_up > Pot_hidj] = \\\n Fk_face_upwind_all[:,Pot_hidj_up > Pot_hidj, 1]\n\n return Fk_face_upwind\n\nclass FR:\n\n def __init__(self):\n 'Enviroment for the FR/CPR method - vai ser 1D por enquanto'\n 'OBS: O Fk que vai entrar aqui provavelmente, se não interpretei errado \\\n tem que ser em mol*m/s, ou seja, a pretransmissibilidade n pode ter dx \\\n dividindo'\n '1. Obtain Nk at the SP'\n '2. Compute Fk with the mobility, xkj, rho and csi approximation from \\\n volume-weigthed arithmetic average'\n '3. Transform Fk for the SP by using RTo'\n '4. Use a Riemann Solver for computing flux at the interfaces, and it will \\\n be used for the continuous flux approximation (This can be done previously'\n '5. Approximate Fk and Nk in the reference domain by using Lagranges \\\n polynomial. Where Fk = Fk^D + Fk^C, where Fk^D and Fk^C are also obtained \\\n by using Lagranges polynomial with its value from the SP.'\n '6. Obtain Nk for the next time step by the third order RungeKutta'\n '7. Project the Nk solution at the Pspace back to the CV using Gaussian \\\n integration'\n 'Legend: n_points - number of SP per control volume'\n\n def run(self, M, fprop, wells, Ft_internal_faces, Nk_SP_old, P_old, q, delta_t, t):\n self.t = t\n Nk_SP = np.copy(Nk_SP_old)\n\n q_SP = q[:,:,np.newaxis] * np.ones_like(Nk_SP)\n\n dFk_SP, wave_velocity = self.dFk_SP_from_Pspace(M, fprop, wells, Ft_internal_faces, np.copy(Nk_SP), q_SP, P_old)\n Nk_SP, z_SP = Euler.update_composition(np.copy(Nk_SP_old), q_SP, dFk_SP, delta_t)\n Nk_SP = self.MLP_slope_limiter(M, fprop, Nk_SP)\n\n '''dFk_SP, wave_velocity = self.dFk_SP_from_Pspace(M, fprop, wells, Ft_internal_faces, np.copy(Nk_SP), q_SP, P_old)\n Nk_SP = RK3.update_composition_RK3_2(np.copy(Nk_SP_old), q_SP, np.copy(Nk_SP), dFk_SP, delta_t)\n Nk_SP = self.MLP_slope_limiter(M, fprop, Nk_SP)\n\n dFk_SP, wave_velocity = self.dFk_SP_from_Pspace(M, fprop, wells, Ft_internal_faces, Nk_SP, q_SP, P_old)\n Nk_SP = RK3.update_composition_RK3_3(np.copy(Nk_SP_old), q_SP, np.copy(Nk_SP), dFk_SP, delta_t)\n Nk_SP = self.MLP_slope_limiter(M, fprop, Nk_SP)'''\n fprop.Fk_vols_total = np.min(abs(dFk_SP),axis=2)\n\n Nk = 1 / sum(ctes_FR.weights) * np.sum(ctes_FR.weights * Nk_SP,axis=2)\n\n z = Nk[0:ctes.Nc,:] / np.sum(Nk[0:ctes.Nc,:], axis = 0)\n\n if any(abs(Nk[Nk<-1e-20])):\n import pdb; pdb.set_trace()\n return wave_velocity, Nk, z, Nk_SP\n\n def dFk_SP_from_Pspace(self, M, fprop, wells, Ft_internal_faces, Nk_SP, q_SP, P_old):\n\n Ft_SP = self.total_flux_SP(fprop, wells, M, Ft_internal_faces)\n Fk_SP = self.component_flux_SP(fprop, M, Nk_SP, P_old, Ft_SP)\n\n Fk_faces, Fk_vols_RS_neig, wave_velocity = self.Riemann_Solver(M, fprop, Nk_SP, Fk_SP, P_old, Ft_internal_faces)\n Fk_D = np.sum(Fk_SP[:,:,:,np.newaxis] * ctes_FR.L[np.newaxis,np.newaxis,:], axis=2)\n dFk_D = np.sum(Fk_SP[:,:,:,np.newaxis] * ctes_FR.dL[np.newaxis,np.newaxis,:], axis=2)\n dFk_C = self.dFlux_Continuous(Fk_D, Fk_vols_RS_neig)\n dFk_Pspace = (dFk_C + dFk_D)\n\n #Fk_vols_RS_neig[:,wells['all_wells'],0] = -Fk_vols_RS_neig[:,wells['all_wells'],0]\n if not data_loaded['compositional_data']['water_data']['mobility']:\n dFk_Pspace[-1,:] = 0\n\n #dFk_Pspace[:,wells['all_wells'],1:] = 0\n #dFk_Pspace[:,wells['all_wells'],0] = (Fk_vols_RS_neig[:,wells['all_wells']]).sum(axis=2)/2\n dFk_SP = dFk_Pspace @ ctes_FR.x_points\n dFk_SP = - 2 * dFk_SP #this way only works for uniform mesh\n #import pdb; pdb.set_trace()\n #up! transforming from local space to original global space (this could be done to the g and L functions\n #only, however, I rather do like this, so it's done just once)\n\n #dFk_SP [:,wells['all_wells'],[0,-1]] = -Fk_vols_RS_neig[:,wells['all_wells'], [0,1]]#.sum(axis=2)\n\n #dFk_SP = np.empty_like(Fk_SP[:,ctes.vols_no_wells])\n #for i in range(ctes_FR.n_points):\n # dFk_SP[:,:,i] = np.array(dFk_func(ctes_FR.points[i]))\n return dFk_SP, wave_velocity\n\n def total_flux_SP(self, fprop, wells, M, Ft_internal_faces):\n 'RTo'\n phi = np.empty((len(ctes_FR.points),2))\n phi[:,0] = 1 / 4 * (1 + ctes_FR.points)\n phi[:,1] = 1 / 4 * (1 - ctes_FR.points)\n\n Ft_face_phi = (Ft_internal_faces[:,:,np.newaxis,np.newaxis] * phi[np.newaxis,np.newaxis,:])\n #Fk_face_phi_reshaped = np.concatenate(np.split(Fk_face_phi, ctes_FR.n_points,axis=3),axis=1)[:,:,:,0]\n\n 'Look for a faster way to do that'\n Ft_SP_reshaped = np.empty((1,ctes.n_volumes,ctes_FR.n_points))\n contours = np.array([0,ctes_FR.n_points-1])\n for i in range(ctes_FR.n_points):\n lines = np.array([np.zeros_like(ctes_FR.v0[:,0]), np.zeros_like(ctes_FR.v0[:,1])]).astype(int).flatten()\n cols = np.array([ctes_FR.v0[:,0], ctes_FR.v0[:,1]]).flatten()\n data = np.array([Ft_face_phi[:,:,i,0], Ft_face_phi[:,:,i,1]]).flatten()\n Ft_SP_reshaped[:,:,i] = sp.csc_matrix((data, (lines, cols)), shape = (1, ctes.n_volumes)).toarray()\n Ft_SP = 2 * np.concatenate(np.dsplit(Ft_SP_reshaped, ctes_FR.n_points), axis = 2)\n #Fk_SP[:,wells['all_wells']] = Fk_face[:,wells['all_wells'],1][:,:,np.newaxis]/2\n return Ft_SP\n\n def component_flux_SP(self, fprop, M, Nk_SP, P, Ft_SP):\n P_SP = P[:,np.newaxis] * np.ones_like(Ft_SP[0])\n ponteiro = np.ones(ctes.n_volumes,dtype=bool)\n v0 = np.arange(ctes.n_volumes)[:,np.newaxis] * np.ones((ctes.n_volumes,ctes_FR.n_points))\n Nk_SP_flatt = np.concatenate(np.dsplit(Nk_SP, ctes_FR.n_points),axis=1)[:,:,0]\n Ft_SP_flatt = np.concatenate(np.dsplit(Ft_SP, ctes_FR.n_points),axis=1)[:,:,0]\n pretr = ctes.pretransmissibility_internal_faces[ctes_FR.vols_vec][:,0]\n Vp_SP = np.tile(fprop.Vp, ctes_FR.n_points)\n Fk_SP = RiemannSolvers(v0.astype(int), pretr).Fk_from_Nk(fprop, M, Nk_SP_flatt, P, Vp_SP,\n Ft_SP_flatt, ponteiro)\n Fk_SP = np.concatenate(np.hsplit(Fk_SP[:,:,np.newaxis], ctes_FR.n_points), axis = 2)\n return Fk_SP\n\n def Riemann_Solver(self, M, fprop, Nk_SP, Fk_SP, P_old, Ft_internal_faces):\n\n Nk_faces = np.empty((ctes.n_components, ctes.n_internal_faces, 2))\n Nk_faces[:,:,1] = Nk_SP[:,ctes_FR.v0[:,1],0] #Nk faces a esquerda dos volumes\n Nk_faces[:,:,0] = Nk_SP[:,ctes_FR.v0[:,0],-1] #Nk nas faces a direita\n P_face = np.sum(P_old[ctes_FR.v0],axis=1) * 0.5\n\n Fk_faces = np.empty_like(Nk_faces)\n Fk_faces[:,:,1] = Fk_SP[:,ctes_FR.v0[:,1],0]\n Fk_faces[:,:,0] = Fk_SP[:,ctes_FR.v0[:,0],-1]\n '''Nk_face_contour = np.empty((ctes.n_components,1,2))\n Nk_face_contour[:,0,1] = Nk_SP[:,0,0]\n Nk_face_contour[:,0,0] = Nk_SP[:,-1,-1]\n Nk_face_contour[-1,0,0] = 1*fprop.Csi_j[0,-1,0]*fprop.Vp[0]\n\n Fk_faces_contour = RiemannSolvers(np.array([0,ctes.n_volumes-1])[np.newaxis]).get_Fk_face(fprop, M,\n Nk_face_contour, P_face[np.newaxis,0], Ft_internal_faces[:,0][:,np.newaxis])\n Fk_face_contour_RS, alpha_wv = RiemannSolvers(np.array([0,ctes.n_volumes-1])[np.newaxis]).LLF(M, fprop, Nk_face_contour, P_face[np.newaxis,0],\n Ft_internal_faces[:,0][:,np.newaxis], Fk_faces_contour, np.zeros(1,dtype=bool))'''\n Fk_face_RS, alpha_wv = RiemannSolvers(ctes_FR.v0, ctes.pretransmissibility_internal_faces).LLF(M, fprop, Nk_faces, P_face,\n Ft_internal_faces, Fk_faces, np.ones(ctes.n_internal_faces,dtype=bool))\n\n #Fk_face_RS, alpha_wv = RiemannSolvers(ctes_FR.v0, ctes.pretransmissibility_internal_faces).MDW(M, fprop, Nk_faces, P_face,\n # Ft_internal_faces, Fk_faces, np.ones(ctes.n_internal_faces,dtype=bool))\n 'Obtaining Flux at each CV side - by finding faces that compounds the CV \\\n this only works for 1D problems'\n vols_vec = -np.ones((ctes.n_volumes,2),dtype=int)\n lines = np.arange(ctes.n_internal_faces)\n vols_vec[ctes_FR.v0[:,0],1] = lines\n vols_vec[ctes_FR.v0[:,1],0] = lines\n\n Fk_vols_RS_neig = Fk_face_RS[:,ctes_FR.vols_vec]\n\n Fk_vols_RS_neig[:,vols_vec<0] = 0 #Fk_face_contour_RS\n #import pdb; pdb.set_trace()\n return Fk_faces, Fk_vols_RS_neig, alpha_wv\n\n def dFlux_Continuous(self, Fk_D, Fk_vols_RS_neig):\n #norm_point_coords = np.array([(x,y,z) for x in coords for y in coords for z in coords])\n x_left = np.array([(-1)**i for i in range(ctes_FR.n_points)])\n x_right = np.ones(ctes_FR.n_points)\n Fk_D_l = Fk_D @ x_left\n Fk_D_r = Fk_D @ x_right\n dFk_C = (Fk_vols_RS_neig[:,:,0] - Fk_D_l)[:,:,np.newaxis] * ctes_FR.dgLB[np.newaxis,:] + \\\n (Fk_vols_RS_neig[:,:,1] - Fk_D_r)[:,:,np.newaxis] * ctes_FR.dgRB[np.newaxis,:]\n #import pdb; pdb.set_trace()\n return dFk_C\n\n def MLP_slope_limiter(self, M, fprop, Nk_SP_in):\n\n inds = np.array([0,-1])\n\n Nk = (np.linalg.inv(ctes_FR.V)[np.newaxis,] @ Nk_SP_in[:,:,:, np.newaxis])[:,:,:,0]\n Nk_SP = self.projections(Nk, ctes_FR.n_points-1)\n\n #machine_error = np.max(abs(Nk_SP - Nk_SP_in))\n #if machine_error 2:\n '---------------Hierarchical MLP limiting procedure----------------'\n\n #axis=1 due to reshaping of the argument [~phi_Pn.astype(bool)]\n phi_Pn = self.troubled_cell_marker(M, fprop, Nk_P1_vertex, Nk_P0_vertex, Nk_SP, machine_error)\n phi_P2 = phi_Pn\n\n if ctes_FR.n_points==4:\n\n 'Projected n=2'\n Nk2 = np.zeros_like(Nk)\n Nk2[:,:,0:3] = Nk[:,:,0:3]\n Nk_P2 = self.projections(Nk, 2)\n Nk_P2_vertex = Nk_P2[:,:,inds]\n\n 'Projected P2 into n=1'\n Nk_P12 = self.projections(Nk2, 1)\n Nk_P1_vertex2 = Nk_P12[:,:,inds]\n\n 'Projected P2 into n=0'\n Nk_P02 = self.projections(Nk2, 0)\n Nk_P0_vertex2 = Nk_P02[:,:,inds]\n\n phi_P2 = self.troubled_cell_marker(M, fprop, Nk_P1_vertex2, Nk_P0_vertex2, Nk_P2, machine_error)\n\n phi_P2[phi_Pn==1] = 1\n Phi_P1[phi_P2==1] = 1\n\n phi_Pn[np.sum(Nk_SP<0,axis=-1,dtype=bool)] = 0\n phi_P2[np.sum(Nk_P2<0,axis=-1, dtype=bool)*np.sum(Nk_SP<0,axis=-1, dtype=bool)] = 0\n #Phi_P1[np.sum(Nk_P1<0,axis=-1, dtype=bool)*(phi_P2==0)] = 0\n\n\n Nk_SPlim = (Nk_P0 + Phi_P1[:,:,np.newaxis] * (Nk_P1 - Nk_P0) + \\\n phi_P2[:,:,np.newaxis] * ((Nk_P2 - Nk_P1) + phi_Pn[:,:,np.newaxis] * (Nk_SP - Nk_P2)))\n import pdb; pdb.set_trace()\n '''C_high_order_check1 = (Nk_SPlim[:,:,inds] <= np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec]) #<= machine_error\n C_high_order_check2 = (Nk_SPlim[:,:,inds] >= np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec]) #>= -machine_error\n C_high_order_check1[abs((Nk_SPlim[:,:,inds] - np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])) <= machine_error] = True\n C_high_order_check2[abs((Nk_SPlim[:,:,inds] - np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])) <= machine_error] = True\n\n high_order_check = C_high_order_check1 * C_high_order_check2\n #if any(np.min(1 * high_order_troubled_cells,axis=2)[phi_Pn==1]==0):import pdb; pdb.set_trace()\n phi_Pn_check = np.min(1 * high_order_check,axis = 2)#[phi_Pn==1]\n if len(phi_Pn_check[phi_Pn_check==0])>0: import pdb; pdb.set_trace()\n #import pdb; pdb.set_trace()'''\n #if self.t>0.8: import pdb; pdb.set_trace()\n\n return Nk_SPlim\n\n def projections(self, Nk, m):\n Nkm = np.zeros_like(Nk)\n Nkm[:,:,0:m+1] = Nk[:,:,0:m+1]\n Nk_Pm = (ctes_FR.V[np.newaxis,] @ Nkm[:,:,:,np.newaxis])[:,:,:,0]\n return Nk_Pm\n\n def P1_limiter(self, M, Nk, Nk_Pm, Nk_P0_vertex, Nk_P1_vertex, machine_error):\n Linear_term = Nk_P1_vertex - Nk_P0_vertex\n\n 'Neigboring vertex points values'\n Nk_faces = np.empty((ctes.n_components,ctes.n_internal_faces,2))\n Nk_neig = np.copy(Nk_faces)\n Nk_faces[:,:,1] = Nk_Pm[:,:,0][:,ctes_FR.v0[:,1]]\n Nk_faces[:,:,0] = Nk_Pm[:,:,-1][:,ctes_FR.v0[:,0]]\n Nk_neig[:,:,0] = Nk_P0_vertex[:,ctes_FR.v0[:,0],0]\n Nk_neig[:,:,1] = Nk_P0_vertex[:,ctes_FR.v0[:,1],0]\n\n #Phi_r = self.MLP_u1_mod(Nk_neig, Nk_P0_vertex, Linear_term)\n #Phi_r = self.MLP_u1(Nk_neig, Nk_P0_vertex, Linear_term)\n Phi_r = self.MLP_u2_mod(M, Nk_neig, Nk_P0_vertex, Linear_term)\n\n Phi_P1 = np.ones_like(Phi_r)\n Phi_P1[abs(Nk_P1_vertex - Nk_P0_vertex) >= machine_error] = Phi_r[abs(Nk_P1_vertex - Nk_P0_vertex) >= machine_error]\n Phi_P1 = np.min(Phi_P1, axis = 2)\n #Phi_P1[:,-1] = 1\n #Phi_P1[:,0] = 1\n return Phi_P1\n\n def MLP_u1_mod(self, Nk_neig, Nk_P0_vertex, Linear_term):\n Nk_avg_vertex = Nk_P0_vertex[:,ctes_FR.v0,0].sum(axis=-1)/2\n Nk_avg_vertex_vols = Nk_avg_vertex[:,ctes_FR.vols_vec]\n f_min = Nk_avg_vertex_vols + np.heaviside(Nk_avg_vertex_vols - Nk_P0_vertex, np.ones_like(Nk_P0_vertex)) * \\\n (np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec] - Nk_avg_vertex_vols)\n f_max = Nk_avg_vertex_vols + np.heaviside(Nk_avg_vertex_vols - Nk_P0_vertex, np.ones_like(Nk_P0_vertex)) * \\\n (np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec] - Nk_avg_vertex_vols)\n\n r1 = (f_min - Nk_P0_vertex) / Linear_term\n r2 = (f_max - Nk_P0_vertex) / Linear_term\n rs = np.concatenate((r1[...,np.newaxis], r2[...,np.newaxis]),axis = -1)\n rs[Linear_term == 0] = 1\n r = np.max(rs, axis = -1)\n Phi_r_u1 = r\n Phi_r_u1[Phi_r_u1>1] = 1\n #Phi_r_u1[Phi_r_u1<0] = 0\n return Phi_r_u1\n\n def MLP_u1(self, Nk_neig, Nk_P0_vertex, Linear_term):\n f_min = np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec]\n f_max = np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec]\n r1 = (f_min - Nk_P0_vertex) / Linear_term\n r2 = (f_max - Nk_P0_vertex) / Linear_term\n rs = np.concatenate((r1[...,np.newaxis], r2[...,np.newaxis]),axis = -1)\n rs[Linear_term == 0] = 1\n r = np.max(rs, axis = -1)\n Phi_r_u1 = r\n Phi_r_u1[Phi_r_u1>1] = 1\n Phi_r_u1[Phi_r_u1<0] = 0\n return Phi_r_u1\n\n def MLP_u2_mod(self, M, Nk_neig, Nk_P0_vertex, Linear_term):\n delta_minus = Linear_term\n Nk_neig_max = np.max(Nk_neig,axis=2)[:,ctes_FR.vols_vec]\n Nk_neig_max[Nk_neig_max < Nk_P0_vertex] = Nk_P0_vertex[Nk_neig_max0] = delta_plus2[delta_minus>0]\n\n x_vols = M.data['centroid_volumes'][0,0]\n dx_vols = x_vols*2\n K1 = 1e-2\n #K2 = 1e-14\n e2 = (K1 * dx_vols)**3\n\n #dNk_max_min = (np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec] - np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])\n #theta = dNk_max_min/(K2*dx_vols**1.5)\n #e2 = K1/(1+theta) * dNk_max_min**2\n\n Phi_r_u2 = 1/delta_minus * ((delta_plus**2 + e2)*delta_minus + 2*delta_minus**2*delta_plus) / \\\n (delta_plus**2 + 2*delta_minus**2 + delta_minus*delta_plus + e2)\n\n\n Phi_r_u2[delta_minus==0] = 1\n\n Phi_r_u2[Phi_r_u2>1] = 1\n Phi_r_u2[Phi_r_u2<0] = 0\n import pdb; pdb.set_trace()\n return Phi_r_u2\n\n def Phi_r_u2(self, M, r, machine_error):\n Phi_r_u2 = (r**2 + 2*r + machine_error) / (r**2 + r + 2 + machine_error)\n return Phi_r_u2\n\n def troubled_cell_marker(self, M, fprop, Nk_P1_vertex, Nk_P0_vertex, Nk_Pm, machine_error):\n Linear_term = Nk_P1_vertex - Nk_P0_vertex\n\n 'Neigboring vertex points values'\n Nk_faces = np.empty((ctes.n_components,ctes.n_internal_faces,2))\n Nk_neig = np.empty((ctes.n_components,ctes.n_internal_faces,2))\n\n Nk_faces[:,:,1] = Nk_Pm[:,ctes_FR.v0[:,1], 0]\n Nk_faces[:,:,0] = Nk_Pm[:,ctes_FR.v0[:,0], -1]\n #Nk_faces_avg = 1/2 * np.sum(ctes_FR.weights[np.newaxis,np.newaxis,:,np.newaxis] * Nk_faces, axis=2)\n Nk_avg = Nk_P0_vertex[:,:,0]\n\n Nk_neig[:,:,0] = Nk_avg[:,ctes_FR.v0[:,0]]\n Nk_neig[:,:,1] = Nk_avg[:,ctes_FR.v0[:,1]]\n inds = np.array([0,-1])\n Nk_Pmvertex = Nk_Pm[:,:,inds]\n\n 'P1-projected MLP condition - troubled-cell marker'\n\n C_troubled1 = (Nk_P1_vertex <= np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])\n C_troubled2 = (Nk_P1_vertex >= np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])\n C_troubled1[abs((Nk_P1_vertex - np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])) <= machine_error] = True\n C_troubled2[abs((Nk_P1_vertex - np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])) <= machine_error] = True\n troubled_cells = (C_troubled1 * C_troubled2)\n phi_Pm = np.min(1 * troubled_cells, axis = 2)\n\n 'Smooth extrema detector'\n '''High_order_term = Nk_Pmvertex - Nk_P1_vertex\n Nk_less_max = (Nk_Pmvertex < np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])\n Nk_big_min = (Nk_Pmvertex > np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec])\n #Nk_less_max[abs(Nk_Pmvertex - np.max(Nk_neig, axis = 2)[:,ctes_FR.vols_vec]) < machine_error] = True\n #Nk_big_min[abs(Nk_Pmvertex - np.min(Nk_neig, axis = 2)[:,ctes_FR.vols_vec]) < machine_error] = True\n C1 = (Linear_term > 0) * (High_order_term < 0) * \\\n (Nk_big_min)\n C2 = (Linear_term < 0) * (High_order_term > 0) * \\\n (Nk_less_max)\n cC3 = np.concatenate((1e-3*abs(Nk_P0_vertex), fprop.Vp[np.newaxis,:,np.newaxis]*\\\n np.ones_like(Nk_P0_vertex)),axis=-1)\n C3 = (abs(Nk_Pmvertex - Nk_P0_vertex) <= np.max(cC3,axis=-1)[:,:,np.newaxis])\n smooth_extrema = (C1 + C2) + C3\n smooth_extrema_cell = np.min(1*smooth_extrema,axis=-1)\n\n #jump = Nk_faces[:,:,:,1] - Nk_faces[:,:,:,0]\n\n jump = Nk_faces[:,:,1] - Nk_faces[:,:,0]\n c_vols = M.data['centroid_volumes'][:,1]\n c_faces = c_vols[ctes.v0]\n hf = c_vols[0]*2 #abs(c_faces[:,1] - c_faces[:,0])\n\n smooth_bound_indicator = abs(jump)/(abs(Nk_faces[:,:,1] + Nk_faces[:,:,0])/2) #em 1D apenas !!\n theta_f = smooth_bound_indicator/(hf**((ctes_FR.n_points)/2))\n trbl_bound_detector = np.empty_like(theta_f)\n\n trbl_bound_detector[theta_f<1] = 0 #normal bound\n trbl_bound_detector[theta_f>=1] = 1 #troubled bound\n trbl_bound_detector_vols = np.empty_like(ctes_FR.vols_vec)\n trbl_bound_detector_vols = trbl_bound_detector[:,ctes_FR.vols_vec]\n Nf = np.sum(trbl_bound_detector_vols, axis = -1)\n\n\n 'Type I trouble'\n\n aux_I = phi_Pm[phi_Pm==1]\n aux_Nf_I = Nf[phi_Pm==1]\n aux_I[aux_Nf_I>=1] = 0\n phi_Pm[phi_Pm==1] = aux_I\n\n 'Type II trouble'\n\n aux_II = smooth_extrema_cell[smooth_extrema_cell==1]\n aux_Nf_II = Nf[smooth_extrema_cell==1]\n aux_II[aux_Nf_II>=1] = 0\n smooth_extrema_cell[smooth_extrema_cell==1] = aux_II\n phi_Pm[~phi_Pm.astype(bool)] = smooth_extrema_cell[~phi_Pm.astype(bool)]'''\n return phi_Pm\n","sub_path":"adm_impec-00/packs/compositional/IMPEC/flux_calculation.py","file_name":"flux_calculation.py","file_ext":"py","file_size_in_byte":50809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463219583","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('courses', '0001_initial'),\n ('users', '0017_auto_20151102_1612'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='team',\n name='course',\n field=models.ForeignKey(null=True, related_name='teams', to='courses.Course', blank=True),\n ),\n ]\n","sub_path":"apps/users/migrations/0018_team_course.py","file_name":"0018_team_course.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356869918","text":"#Complete the function to print the tens digit and the ones digit of any interger.\n# def two_digits(digit):\n# return digit\nn = 79\ndigits = [int(x) for x in str(n)]\nprint(digits)\n \n\n\n#Invoke the function with any interger as its argument.\n# two_digits()","sub_path":"exercises/10-Two_digits/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611816748","text":"import logging\nimport random\nfrom typing import Any, List, Union\n\nimport discord\nfrom discord.ext import commands\n\nfrom config import ADMIN_USER_IDS, BANNED_GUILD_IDS, DM_LOG_CHANNEL_ID, LEARNER_CHANNEL_IDS, LEARNER_USER_IDS\nfrom crimsobot import db\nfrom crimsobot.models.ban import Ban\nfrom crimsobot.utils import markov as m, tools as c\n\n\nclass CrimsoBOT(commands.Bot):\n def __init__(self, **kwargs: Any) -> None:\n command_prefix = '>'\n owner_ids = set(ADMIN_USER_IDS)\n super().__init__(command_prefix, owner_ids=owner_ids, **kwargs)\n\n self.banned_user_ids = [] # type: List[int]\n\n self.log = logging.getLogger(__name__)\n self._extensions_to_load = [\n 'crimsobot.extensions.presence', # 'crimsobot.extensions.reminder',\n 'crimsobot.cogs.admin',\n 'crimsobot.cogs.chat',\n 'crimsobot.cogs.cringo',\n 'crimsobot.cogs.games',\n 'crimsobot.cogs.image',\n 'crimsobot.cogs.mystery',\n 'crimsobot.cogs.text',\n 'crimsobot.cogs.utilities',\n ]\n\n def load_extensions(self) -> None:\n for name in self._extensions_to_load:\n try:\n self.load_extension(name)\n except Exception as error:\n self.log.error('%s cannot be loaded: %s', name, error)\n\n def reload_extensions(self) -> None:\n for name in self._extensions_to_load:\n try:\n self.reload_extension(name)\n except Exception as error:\n self.log.error('%s cannot be reloaded: %s', name, error)\n\n async def start(self, *args: Any, **kwargs: Any) -> None:\n await db.connect()\n\n banned_user_ids = await Ban.filter(active=True).values_list(\n 'target__discord_user_id',\n flat=True\n ) # type: List[int]\n self.banned_user_ids = banned_user_ids\n\n await super().start(*args, **kwargs)\n\n async def close(self) -> None:\n await super().close()\n await db.close()\n\n def is_banned(self, discord_user: Union[discord.User, discord.Member]) -> bool:\n return discord_user.id in self.banned_user_ids\n\n async def on_ready(self) -> None:\n self.log.info('crimsoBOT is online')\n\n async def on_resumed(self) -> None:\n self.log.warning('crimsoBOT RECONNECT')\n\n async def on_command_error(self, ctx: commands.Context, error: Exception) -> None:\n \"\"\"For known exceptions, displays error message to user and suppresses verbose traceback in console.\"\"\"\n\n if isinstance(error, commands.MaxConcurrencyReached):\n self.log.error('MaxConcurrency: {} // {}: {}'.format(ctx.author, ctx.message.content, error))\n await ctx.send('`Already running in this channel!`', delete_after=7)\n\n elif isinstance(error, commands.CommandOnCooldown):\n self.log.error('Cooldown: %s // %s: %s', ctx.author, ctx.message.content, error)\n\n await ctx.send('**eat glass.** %.0fs cooldown.' % error.retry_after, delete_after=7)\n\n elif isinstance(error, commands.CommandInvokeError):\n self.log.error('Invoke: %s // %s: %s', ctx.author, ctx.message.content, error, exc_info=error)\n\n try:\n await ctx.send(':poop: `E R R O R` :poop:', delete_after=7)\n\n except discord.errors.Forbidden:\n self.log.error('Forbidden: %s // %s: %s', ctx.guild, ctx.channel.id, error)\n\n elif isinstance(error, commands.MissingRequiredArgument):\n self.log.error('MissingArgument: %s // %s: %s', ctx.author, ctx.message.content, error)\n\n await ctx.send(\n f'*this command requires more arguments. try `>help {ctx.command.qualified_name}`*',\n delete_after=7\n )\n\n elif isinstance(error, commands.BadArgument):\n self.log.error('BadArgument: %s // %s: %s', ctx.author, ctx.message.content, error)\n\n await ctx.send(\n f\"*that's not a valid argument value! try `>help {ctx.command.qualified_name}`*\",\n delete_after=7\n )\n\n elif isinstance(error, commands.NotOwner):\n self.log.error('NotOwner: %s // %s: %s', ctx.author, ctx.message.content, error)\n\n await ctx.send(':rotating_light: not crimso! :rotating_light:', delete_after=7)\n\n elif isinstance(error, commands.CommandNotFound):\n self.log.error(\n 'NotFound/Forbidden: %s/%s // %s: %s',\n ctx.message.guild.id, ctx.message.channel, ctx.message.content, error\n )\n else:\n self.log.error('Uncaught exception', exc_info=error)\n\n async def on_message(self, message: discord.Message) -> None:\n if self.is_banned(message.author):\n return\n\n # DM self.logger\n is_dm = isinstance(message.channel, discord.DMChannel)\n if is_dm and message.author.id != self.user.id and not message.content.startswith(('>', '.')):\n try:\n link = message.attachments[0].url\n except IndexError:\n link = ''\n\n dms_channel = self.get_channel(DM_LOG_CHANNEL_ID)\n await dms_channel.send(\n '`{}\\nuid:{}\\ncid:{}`\\n{} {}'.format(\n message.channel, message.author.id, message.channel.id, message.content, link\n )\n )\n\n # process commands\n await self.process_commands(message)\n\n # learn from crimso\n if message.author.id in LEARNER_USER_IDS and message.channel.id in LEARNER_CHANNEL_IDS:\n m.learner(message.content)\n\n # this little piggy cleans pings from crimsonic messages\n cleaner = commands.clean_content(use_nicknames=False)\n\n # respond to ping or randomly talk\n if self.user in message.mentions or (random.random() < 0.002 and not is_dm):\n # make it look like bot is typing\n await message.channel.trigger_typing()\n crimsonic = await m.async_wrap(self, m.crimso)\n\n # no more pings!\n try:\n ctx = await self.get_context(message)\n cleaned_output = await cleaner.convert(ctx, crimsonic)\n except commands.errors.BadArgument:\n cleaned_output = crimsonic\n\n await message.channel.send(cleaned_output)\n\n async def on_guild_join(self, guild: discord.Guild) -> None:\n \"\"\"Notify me when added to guild\"\"\"\n\n if guild.id in BANNED_GUILD_IDS:\n await guild.leave()\n self.log.warning('Banned guild %s attempted to add crimsoBOT.', guild.id)\n return\n\n self.log.info(\"Joined %s's %s [%s]\", guild.owner, guild, guild.id)\n\n embed = c.get_guild_info_embed(guild)\n\n # ...and send\n for user_id in ADMIN_USER_IDS:\n user = await self.get_user(user_id)\n try:\n await user.send('Added to {guild}'.format(guild=guild), embed=embed)\n except Exception:\n await user.send('Added to {guild}'.format(guild=guild))\n\n def add_command(self, command: commands.Command) -> None:\n command.cooldown_after_parsing = True\n\n super().add_command(command)\n","sub_path":"crimsobot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117832480","text":"# SAME FOR AGGRESSIVE COWS PROBLEM\n\n# In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. \n# Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such \n# that the minimum magnetic force between any two balls is maximum.\n\n# Rick stated that magnetic force between two different balls at positions x and y is |x - y|.\n\n# Given the integer array position and the integer m. Return the required force.\n\n# Example 1:\n# Input: position = [1,2,3,4,7], m = 3\n# Output: 3\n# Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\n\n# Example 2:\n# Input: position = [5,4,3,2,1,1000000000], m = 2\n# Output: 999999999\n# Explanation: We can use baskets 1 and 1000000000.\n \n# Constraints:\n# n == position.length\n# 2 <= n <= 10^5\n# 1 <= position[i] <= 10^9\n# All integers in position are distinct.\n# 2 <= m <= position.length\n\ndef maxDistance(position, m):\n\tdef check(x):\n\t\tlast_pos = position[0]\n\t\tcount = 1\n\t\tfor i in range(1, len(position)):\n\t\t\tif position[i] - last_pos >= x:\n\t\t\t\tcount += 1\n\t\t\t\tif count == m:\n\t\t\t\t\treturn True\n\t\t\t\tlast_pos = position[i]\n\t\treturn False\n\n\tposition.sort()\n\tleft = 1\n\tright = position[-1]\n\twhile left < right:\n\t\tmid = left + (right - left + 1)//2\n\t\tif check(mid):\n\t\t\tleft = mid\n\t\telse:\n\t\t\tright = mid - 1\n\treturn left\n","sub_path":"random/solutions/q18_MagneticForceBetweenTwoBalls.py","file_name":"q18_MagneticForceBetweenTwoBalls.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432774359","text":"from artiq.experiment import *\n\nclass SAWGTest(EnvExperiment):\n \"\"\"test_upconvert2\n purpose: test two-tone up-conversion feature of sawg3\n test: mix LO = 150 MHz, IF1 = 25-75 MHz, IF2 = 25-75 MHz\n expectation:\n RF: LO+IF1 and LO+IF2 are the desired features\n RF: LO-IF1 and LO-IF2\n setup: spectrum analyzer with range set to 100 kHz to 500 MHz\n \"\"\"\n def build(self):\n print(self.__doc__)\n self.setattr_device(\"core\")\n self.setattr_device(\"sawg3\")\n\n @kernel\n def run(self):\n self.core.reset()\n delay(300*us)\n self.sawg3.reset()\n\n f0 = 150\n fmin = 25\n fmax = 75\n a = 0.50\n\n self.sawg3.frequency0.set(f0*MHz)\n self.sawg3.amplitude1.set(a)\n self.sawg3.amplitude2.set(a)\n\n for f1 in range(fmin, fmax, 5):\n self.sawg3.frequency1.set(f1 * MHz)\n for f2 in range(fmin, fmax, 5):\n self.sawg3.frequency2.set(f2 * MHz)\n delay(500 * ms)\n","sub_path":"sayma/repository/sawg-tests/test_upconvert2.py","file_name":"test_upconvert2.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"528417126","text":"from django.urls import path\n\nfrom news_aggregator import views\n\napp_name = 'news_aggregator'\nurlpatterns = [\n path('news_add/', views.NewsCreateApiView.as_view(), name='news_add'),\n path('all_news/', views.NewsListApiView.as_view(), name='all_news'),\n path('news_by_genre//', views.NewsByGenreApiView.as_view(), name='news_by_genre'),\n\n]\n","sub_path":"news_aggregator/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"437947530","text":"\"\"\"\nThis module implements the TextResponse class which adds encoding handling and\ndiscovering (through HTTP headers) to base Response class.\n\nSee documentation in docs/topics/request-response.rst\n\"\"\"\n\nimport six\nfrom six.moves.urllib.parse import urljoin\n\nfrom w3lib.encoding import html_to_unicode, \\\n resolve_encoding, \\\n html_body_declared_encoding, \\\n http_content_type_encoding\n\nfrom .utils import get_base_url, \\\n memoizemethod_noargs, \\\n to_native_str, \\\n object_ref, \\\n obsolete_setter\n\nfrom .headers import Headers\n\n\nclass Response(object_ref):\n\n def __init__(self, url, status=200, headers=None, body=b'', flags=None, request=None):\n self.headers = Headers(headers or {})\n self.status = int(status)\n self._set_body(body)\n self._set_url(url)\n self.request = request\n self.flags = [] if flags is None else list(flags)\n\n @property\n def meta(self):\n try:\n return self.request.meta\n except AttributeError:\n raise AttributeError(\n \"Response.meta not available, this response \"\n \"is not tied to any request\"\n )\n\n def _get_url(self):\n return self._url\n\n def _set_url(self, url):\n if isinstance(url, str):\n self._url = url\n else:\n raise TypeError('%s url must be str, got %s:' % (type(self).__name__,\n type(url).__name__))\n\n url = property(_get_url, obsolete_setter(_set_url, 'url'))\n\n def _get_body(self):\n return self._body\n\n def _set_body(self, body):\n if body is None:\n self._body = b''\n elif not isinstance(body, bytes):\n raise TypeError(\n \"Response body must be bytes. \"\n \"If you want to pass unicode body use TextResponse \"\n \"or HtmlResponse.\")\n else:\n self._body = body\n\n body = property(_get_body, obsolete_setter(_set_body, 'body'))\n\n def __str__(self):\n return \"<%d %s>\" % (self.status, self.url)\n\n __repr__ = __str__\n\n def urljoin(self, url):\n return urljoin(self.url, url)\n\n\nclass TextResponse(Response):\n\n _DEFAULT_ENCODING = 'ascii'\n\n def __init__(self, *args, **kwargs):\n self._encoding = kwargs.pop('encoding', None)\n self._cached_benc = None\n self._cached_ubody = None\n self._cached_selector = None\n super(TextResponse, self).__init__(*args, **kwargs)\n\n def _set_url(self, url):\n if isinstance(url, six.text_type):\n if six.PY2 and self.encoding is None:\n raise TypeError(\"Cannot convert unicode url - %s \"\n \"has no encoding\" % type(self).__name__)\n self._url = to_native_str(url, self.encoding)\n else:\n super(TextResponse, self)._set_url(url)\n\n def _set_body(self, body):\n self._body = b'' # used by encoding detection\n if isinstance(body, six.text_type):\n if self._encoding is None:\n raise TypeError('Cannot convert unicode body - %s has no encoding' %\n type(self).__name__)\n self._body = body.encode(self._encoding)\n else:\n super(TextResponse, self)._set_body(body)\n\n def replace(self, *args, **kwargs):\n kwargs.setdefault('encoding', self.encoding)\n return Response.replace(self, *args, **kwargs)\n\n @property\n def encoding(self):\n return self._declared_encoding() or self._body_inferred_encoding()\n\n def _declared_encoding(self):\n return self._encoding or self._headers_encoding() \\\n or self._body_declared_encoding()\n\n def body_as_unicode(self):\n \"\"\"Return body as unicode\"\"\"\n return self.text\n\n @property\n def text(self):\n \"\"\" Body as unicode \"\"\"\n # access self.encoding before _cached_ubody to make sure\n # _body_inferred_encoding is called\n benc = self.encoding\n if self._cached_ubody is None:\n charset = 'charset=%s' % benc\n self._cached_ubody = html_to_unicode(charset, self.body)[1]\n return self._cached_ubody\n\n def urljoin(self, url):\n \"\"\"Join this Response's url with a possible relative url to form an\n absolute interpretation of the latter.\"\"\"\n return urljoin((self), url)\n\n @memoizemethod_noargs\n def _headers_encoding(self):\n content_type = self.headers.get(b'Content-Type', b'')\n return http_content_type_encoding(to_native_str(content_type))\n\n def _body_inferred_encoding(self):\n if self._cached_benc is None:\n content_type = to_native_str(self.headers.get(b'Content-Type', b''))\n benc, ubody = html_to_unicode(content_type, self.body,\n auto_detect_fun=self._auto_detect_fun,\n default_encoding=self._DEFAULT_ENCODING)\n self._cached_benc = benc\n self._cached_ubody = ubody\n return self._cached_benc\n\n def _auto_detect_fun(self, text):\n for enc in (self._DEFAULT_ENCODING, 'utf-8', 'cp1252'):\n try:\n text.decode(enc)\n except UnicodeError:\n continue\n return resolve_encoding(enc)\n\n @memoizemethod_noargs\n def _body_declared_encoding(self):\n return html_body_declared_encoding(self.body)\n\n @property\n def selector(self):\n from .selector import Selector\n if self._cached_selector is None:\n self._cached_selector = Selector(self)\n return self._cached_selector\n\n def xpath(self, query, **kwargs):\n return self.selector.xpath(query, **kwargs)\n\n","sub_path":"response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":5797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166352032","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport pexpect\nfrom utils import Log\nfrom time import sleep\nfrom reset import FactoryReset\nfrom testcase import TestCase\nfrom Client import LogCapture\nfrom sysresource import Filesystem\n\nclass TestResetClean(TestCase):\n \"\"\"docstring for TestResetClean\"\"\"\n def __init__(self, doc, level, owner):\n super(TestResetClean, self).__init__(doc, level, owner)\n self.jar_name = \"TvUiTools.jar\"\n self.tmp_path = \"/data/local/tmp/\"\n self.load_path = os.path.join(self.tmp_path, self.jar_name)\n self.load_file = \"http://172.16.117.1:8000/resource/TvUiTools.jar\"\n self.client = LogCapture(self.connection)\n\n def prepare(self):\n self.start_log()\n self.client.open_log()\n cmd2 = 'for usb in `ls /mnt/usb`; do echo $usb; busybox wget -O /data/app/%s %s ; done' % \\\n (self.jar_name, self.load_file)\n cmd1 = 'for usb in `ls /mnt/usb`; do echo $usb; busybox wget -O /mnt/usb/$usb/%s %s ; done' % \\\n (self.jar_name, self.load_file)\n self.connection.sendline(\"su\")\n self.connection.sendline(cmd2)\n sleep(8)\n self.connection.empty_buffer()\n self.connection.sendline(\"su\")\n sleep(2)\n self.connection.sendline(\"ls /data/app/\")\n index = self.connection.expect([\"TvUiTools.jar\", pexpect.TIMEOUT], timeout=10)\n if index == 0:\n Log().debug(\"download jar successful\")\n else:\n Log().error(\"download jar fail!\")\n self.connection.sendline(cmd1)\n sleep(10)\n\n def execute(self):\n self.prepare()\n fr = FactoryReset(self.connection)\n self._status, self._msg = fr.run_without_clean()\n if not Filesystem(self.platform,self.connection,self.plan.image).health_check():\n self._status = \"FAIL\"\n self._msg = \"filesystem check fail!\"\n self.reset()\n\n def push_jar(self):\n cmd = 'for usb in `ls /mnt/usb`; do echo $usb; busybox wget -O %s %s ; done' % (self.load_path, self.load_file)\n self.connection.sendline(cmd)\n for i in range(5):\n self.connection.sendline(\"ls \" + self.tmp_path)\n index = self.connection.expect([\"TvUiTools.jar\", pexpect.TIMEOUT], timeout=10)\n if index == 0:\n Log().debug(\"push jar successful!\")\n break\n else:\n sleep(5)\n\n def reset(self):\n self.connection.empty_buffer()\n self.connection.sendline(\"su\")\n sleep(2)\n self.connection.sendline(\"ls /data/app/\")\n index = self.connection.expect([\"TvUiTools.jar\", pexpect.TIMEOUT], timeout=10)\n if index == 0:\n self._status = \"PASS\"\n else:\n self._status = \"FAIL\"\n self._msg = \"/data/app/ has been cleaned\"\n self.push_jar()\n self.client.pull_log()\n self.client.pull_recovery_log()\n self.stop_log()\n\n# must add execute() here\nif __name__ == \"__main__\":\n TestResetClean('reset device without cleaning user data', 'p3', 'qiwj').run()\n","sub_path":"Python_Java_UIautomator/case/platform/system/test_reset_clean.py","file_name":"test_reset_clean.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"396899338","text":"from pieces import Character, FriendEnemyMarker\nfrom const import *\n\n\nclass Player(Character):\n def __init__(self, x, y):\n super().__init__(x, y, 'P', 1)\n self.hp = 100\n\n def is_alive(self):\n return self.hp > 0\n\nclass FriendEnemy(Character):\n def __init__(self, x, y, friend=False, direction=NORTH):\n self.is_friend = friend\n self.direction = direction\n# self.face_direction(self.direction)\n if self.is_friend:\n super().__init__(x, y, 'F')\n self.follower_sign = 'o'\n else:\n super().__init__(x, y, 'E')\n self.follower_sign = 'x'\n\n def make_friend(self):\n self.is_friend = True\n self.update_signs()\n\n def make_enemy(self):\n self.is_friend = False\n self.update_signs()\n\n def update_signs(self):\n if self.is_friend:\n self.follower_sign = 'o'\n self.sign = 'F'\n else:\n self.follower_sign = 'x'\n self.sign = 'E'\n\n def add_marker(self, direction):\n # todo: this can be done better...smarter constants?\n d_x = 0\n d_y = 0\n if direction == NORTH:\n d_y = -1\n elif direction == SOUTH:\n d_y = 1\n elif direction == EAST:\n d_x = 1\n elif direction == WEST:\n d_x = -1\n elif direction == NORTHEAST:\n d_x = 1\n d_y = -1\n elif direction == NORTHWEST:\n d_x = -1\n d_y = -1\n elif direction == SOUTHEAST:\n d_x = 1\n d_y = 1\n elif direction == SOUTHWEST:\n d_x = -1\n d_y = 1\n marker = FriendEnemyMarker(self.x + d_x, self.y + d_y, self.follower_sign)\n self.attached_pieces.append(marker)\n\n def turn_clockwise(self):\n if self.direction == NORTHWEST:\n self.direction = NORTH\n else:\n self.direction += 1\n self.face_direction(self.direction)\n\n def turn_counterclockwise(self):\n if self.direction == NORTH:\n self.direction = NORTHWEST\n else:\n self.direction -= 1\n self.face_direction(self.direction)\n\n def face_direction(self, direction):\n if direction == NORTH:\n self.face_north()\n elif direction == NORTHEAST:\n self.face_northeast()\n elif direction == EAST:\n self.face_east()\n elif direction == SOUTHEAST:\n self.face_southeast()\n elif direction == SOUTH:\n self.face_south()\n elif direction == SOUTHWEST:\n self.face_southwest()\n elif direction == WEST:\n self.face_west()\n elif direction == NORTHWEST:\n self.face_northwest()\n\n def face_north(self):\n self.attached_pieces = []\n self.add_marker(NORTHWEST)\n self.add_marker(NORTH)\n self.add_marker(NORTHEAST)\n\n def face_northeast(self):\n self.attached_pieces = []\n self.add_marker(NORTH)\n self.add_marker(NORTHEAST)\n self.add_marker(EAST)\n\n def face_east(self):\n self.attached_pieces = []\n self.add_marker(NORTHEAST)\n self.add_marker(EAST)\n self.add_marker(SOUTHEAST)\n\n def face_southeast(self):\n self.attached_pieces = []\n self.add_marker(SOUTH)\n self.add_marker(SOUTHEAST)\n self.add_marker(EAST)\n\n def face_south(self):\n self.attached_pieces = []\n self.add_marker(SOUTHEAST)\n self.add_marker(SOUTH)\n self.add_marker(SOUTHWEST)\n\n def face_southwest(self):\n self.attached_pieces = []\n self.add_marker(SOUTH)\n self.add_marker(SOUTHWEST)\n self.add_marker(WEST)\n\n def face_west(self):\n self.attached_pieces = []\n self.add_marker(SOUTHWEST)\n self.add_marker(WEST)\n self.add_marker(NORTHWEST)\n\n def face_northwest(self):\n self.attached_pieces = []\n self.add_marker(NORTH)\n self.add_marker(NORTHWEST)\n self.add_marker(WEST)\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"516108695","text":"\"\"\"YOLO configuration definition.\"\"\"\n\nfrom typing import List, Optional, Union\nimport dataclasses\n\nfrom official.core import exp_factory\nfrom official.modeling import hyperparams\nfrom official.modeling import optimization\nfrom official.modeling.hyperparams import config_definitions as cfg\nfrom official.vision.beta.configs import common\nfrom official.vision.beta.configs import decoders\nfrom official.vision.beta.configs import backbones\n\n\n@dataclasses.dataclass\nclass DataConfig(cfg.DataConfig):\n \"\"\"Input config for training.\"\"\"\n output_size: List[int] = dataclasses.field(default_factory=list)\n input_path: str = ''\n global_batch_size: int = 0\n is_training: bool = True\n dtype: str = 'float32'\n shuffle_buffer_size: int = 1000\n cycle_length: int = 10\n aug_rand_hflip: bool = True\n aug_scale_min: float = 1.0\n aug_scale_max: float = 1.0\n preserve_aspect_ratio: bool = True\n aug_jitter_im: float = 0.1\n aug_jitter_boxes: float = 0.025\n aug_policy: Optional[str] = None # None, 'autoaug', or 'randaug'\n randaug_magnitude: Optional[int] = 10\n\n # visual randaugment only, since bbox augmentation ops not implemented well ye\n randaug_available_ops: Optional[List[str]] = dataclasses.field(default_factory=lambda:\n ['AutoContrast', 'Equalize', 'Invert', 'Posterize', \n 'Solarize', 'Color', 'Contrast', 'Brightness', 'Sharpness', \n 'Cutout', 'SolarizeAdd'])\n drop_remainder: bool = True\n file_type: str = 'tfrecord'\n\n max_bbox_per_scale: int = 150\n is_bbox_in_pixels: bool = True\n is_xywh: bool = False\n\n\n@dataclasses.dataclass\nclass YoloHead(hyperparams.Config):\n anchor_per_scale: int = 3\n strides: List[int] = dataclasses.field(default_factory=list)\n anchors: List[int] = dataclasses.field(default_factory=list)\n xy_scale: List[int] = dataclasses.field(default_factory=list)\n freeze: bool = False\n\n\n@dataclasses.dataclass\nclass YoloModel(hyperparams.Config):\n num_classes: int = 0\n input_size: List[int] = dataclasses.field(default_factory=list)\n min_level: int = 3 # only for FPN or NASFPN\n max_level: int = 6 # only for FPN or NASFPN\n head: hyperparams.Config = YoloHead()\n backbone: backbones.Backbone = backbones.Backbone(\n type='resnet', resnet=backbones.ResNet())\n decoder: decoders.Decoder = decoders.Decoder(type='identity')\n norm_activation: common.NormActivation = common.NormActivation()\n\n\n@dataclasses.dataclass\nclass YoloLosses(hyperparams.Config):\n label_smoothing: float = 0.0\n class_weights: List[float] = dataclasses.field(default_factory=list)\n l2_weight_decay: float = 0.0\n iou_loss_thres: float = 0.5\n\n\n@dataclasses.dataclass\nclass YoloEvaluation(hyperparams.Config):\n report_classwise: bool = True\n precision_conf_thres: float = 0.3\n recall_conf_thres: float = 0.3\n\n\n@dataclasses.dataclass\nclass YoloTask(cfg.TaskConfig):\n \"\"\"The model config.\"\"\"\n model: YoloModel = YoloModel()\n train_data: DataConfig = DataConfig(is_training=True)\n validation_data: DataConfig = DataConfig(is_training=False)\n losses: YoloLosses = YoloLosses()\n evaluation: YoloEvaluation = YoloEvaluation()\n train_input_partition_dims: List[int] = dataclasses.field(\n default_factory=list)\n eval_input_partition_dims: List[int] = dataclasses.field(\n default_factory=list)\n init_checkpoint: Optional[str] = None\n init_checkpoint_modules: Union[\n str, List[str]] = 'all' # all, backbone, and/or decoder\n\n\n@exp_factory.register_config_factory('yolo')\ndef detector_yolo() -> cfg.ExperimentConfig:\n \"\"\"YOLO on custom datasets\"\"\"\n \n config = cfg.ExperimentConfig(\n task=YoloTask(\n model=YoloModel(\n num_classes=6,\n input_size=[256, 256, 3],\n backbone=backbones.Backbone(\n type='hardnet', hardnet=backbones.HardNet(model_id=70)),\n decoder=decoders.Decoder(\n type='pan', pan=decoders.PAN(levels=3)),\n head=YoloHead(\n anchor_per_scale=3,\n strides=[16, 32, 64],\n anchors=[12,16, 19,36, 40,28, 36,75, 76,55, 72,146, 142,110, 192,243, 459,401],\n xy_scale=[1.2, 1.1, 1.05]\n ),\n norm_activation=common.NormActivation(\n activation='relu',\n norm_momentum=0.9997,\n norm_epsilon=0.001,\n use_sync_bn=True)),\n losses=YoloLosses(l2_weight_decay=1e-4,\n iou_loss_thres=0.5),\n train_data=DataConfig(\n input_path='D:/data/whizz_tf/detect_env*',\n output_size=[256, 256],\n is_training=True,\n global_batch_size=1),\n validation_data=DataConfig(\n input_path='D:/data/whizz_tf/detect_env*',\n output_size=[256, 256],\n is_training=False,\n global_batch_size=1,\n drop_remainder=False),\n # init_checkpoint=None\n init_checkpoint_modules='backbone'),\n trainer=cfg.TrainerConfig(\n steps_per_loop=2,\n summary_interval=2,\n checkpoint_interval=2,\n train_steps=20,\n validation_steps=20,\n validation_interval=2,\n optimizer_config=optimization.OptimizationConfig({\n 'optimizer': {\n 'type': 'sgd',\n 'sgd': {\n 'momentum': 0.9\n }\n },\n 'learning_rate': {\n 'type': 'polynomial',\n 'polynomial': {\n 'initial_learning_rate': 0.007,\n 'decay_steps': 20,\n 'end_learning_rate': 0.0,\n 'power': 0.9\n }\n },\n 'warmup': {\n 'type': 'linear',\n 'linear': {\n 'warmup_steps': 2,\n 'warmup_learning_rate': 0\n }\n }\n })),\n restrictions=[\n 'task.train_data.is_training != None',\n 'task.validation_data.is_training != None'\n ])\n\n return config\n","sub_path":"official/vision/beta/configs/yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128176779","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Karesansui.\n#\n# Copyright (C) 2009-2012 HDE, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport web\n\nfrom karesansui.lib.rest import Rest, auth\nfrom karesansui.lib.checker import Checker, \\\n CHECK_EMPTY, CHECK_VALID, CHECK_LENGTH, CHECK_CHAR\nfrom karesansui.lib.utils import is_param, json_dumps\nfrom karesansui.db.access.tag import findbyhost1guestall\n\nclass GuestTag(Rest):\n @auth\n def _GET(self, *param, **params):\n host_id = self.chk_hostby1(param)\n if host_id is None: return web.notfound()\n\n tags = findbyhost1guestall(self.orm, host_id)\n if not tags:\n self.logger.debug(\"No tags is found.\")\n return web.notfound()\n\n if self.is_part() is True:\n self.view.tags = tags\n\n machine_ids = {}\n for tag in tags:\n tag_id = str(tag.id)\n\n machine_ids[tag_id] = []\n for machine in tag.machine:\n if not machine.is_deleted:\n machine_ids[tag_id].append(\"tag_machine%s\"% machine.id)\n\n machine_ids[tag_id] = \" \".join(machine_ids[tag_id])\n\n self.view.machine_ids = machine_ids\n\n return True\n\n elif self.is_json() is True:\n tags_json = []\n for tag in tags:\n tags_json.append(tag.get_json(self.me.languages))\n\n self.view.tags = json_dumps(tags_json)\n\n return True\n \n else:\n return web.nomethod()\nurls = (\n '/host/(\\d+)/guest/tag/?(\\.part|\\.json)$', GuestTag,\n )\n","sub_path":"karesansui/gadget/guesttag.py","file_name":"guesttag.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"436445783","text":"import heapq\n\ndef get_maximum_cost(problems):\n max_alp = -1\n max_cop = -1\n \n for problem in problems:\n alp_req, cop_req, _, _, _ = problem\n \n max_alp = max(max_alp, alp_req)\n max_cop = max(max_cop, cop_req)\n \n return max_alp, max_cop\n\ndef change_value(v):\n return min(150, v)\n\ndef get_out_range(x, y):\n if x >= 151 or y >= 151:\n return 1\n \n return \n\ndef bfs(alp_init, cop_init, problems):\n ans = -1\n \n max_alp, max_cop = get_maximum_cost(problems)\n \n pq = []\n heapq.heappush(pq, [0, alp_init, cop_init])\n \n max_len = 151\n cache = [[987654321] * max_len for _ in range(max_len)]\n cache[alp_init][cop_init] = 0\n \n while pq:\n time, alp, cop = heapq.heappop(pq)\n \n if max_alp <= alp and max_cop <= cop:\n return time\n \n if cache[alp][cop] < time:\n continue\n \n alp = change_value(alp)\n cop = change_value(cop)\n \n if alp + 1 < max_len and time + 1 < cache[alp + 1][cop]:\n cache[alp + 1][cop] = time + 1\n heapq.heappush(pq, [time + 1, alp + 1, cop])\n \n if cop + 1 < max_len and time + 1 < cache[alp][cop + 1]:\n cache[alp][cop + 1] = time + 1\n heapq.heappush(pq, [time + 1, alp, cop + 1])\n \n for idx in range(len(problems)):\n algo, codeing, algo_rwd, codeing_rwd, need_time = problems[idx]\n \n if algo <= alp and codeing <= cop:\n cost = time + need_time\n \n total_alp = alp + algo_rwd\n total_cop = cop + codeing_rwd\n \n \n total_alp = change_value(total_alp)\n total_cop = change_value(total_cop)\n\n if cost < cache[total_alp][total_cop]:\n cache[total_alp][total_cop] = cost\n heapq.heappush(pq, [cost, total_alp, total_cop])\n \n return -1\n\ndef solution(alp, cop, problems):\n answer = 0\n \n answer = bfs(alp, cop, problems)\n return answer","sub_path":"kakao_codeing_study.py","file_name":"kakao_codeing_study.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62440775","text":"from selenium import webdriver\nimport re\nimport csv\nimport sys\nimport time\n\ndef invoke_chrome_driver():\n options = webdriver.ChromeOptions()\n ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X)'\n ua += ' AppleWebKit/602.3.12 (KHTML, like Gecko)'\n ua += ' Version/10.0 Mobile/14C92 Safari/602.1'\n options.add_argument('--user-agent=%s' % ua) \n chromedriver = \"/Applications/chromedriver\"\n # chromedriver = \"C:\\chromedriver\\chromedriver.exe\"\n driver = webdriver.Chrome(chrome_options=options,executable_path=chromedriver)\n return driver\n\nif __name__ == \"__main__\":\n print('start!!!')\n driver = invoke_chrome_driver()\n result_lists = []\n # スクレイピングするURLを記載する\n url = 'http://12.xmbs.jp/LACOWEGOUNI-44112-d2.php?guid=on'\n # どこまでのページを取得するか記載する\n page_num = 51\n \n for i in range(0, 51):\n # 日記一覧ページ取得\n if i == 0:\n driver.get(url)\n else:\n driver.get(url + '&page2=' + str(i))\n\n # 各日記のURLを取得する\n daily_url_list = []\n daily_url_elements = driver.find_elements_by_xpath('//font/a')\n for url_elem in daily_url_elements:\n daily_url = url_elem.get_attribute('href')\n daily_url_list.append(daily_url)\n # print(daily_url)\n \n for daily_url in daily_url_list:\n # daily_url_list.append(url_elem.get_attribute('href'))\n if daily_url is None:\n continue\n if 'action' in daily_url:\n continue\n # 日記ページにアクセス\n driver.get(daily_url)\n result_list = []\n try:\n html = driver.page_source\n html = html.replace('\\n', '')\n\n # 投稿日時\n m_date = re.search(\n r'
    (.*?)
    ', \n html)\n daily_date = m_date.group(1)\n daily_date = daily_date.replace('
    ', '')\n result_list.append(daily_date)\n\n # 日記タイトル\n m_title = re.search(r'(.*?)<\\/font>', html)\n daily_title = m_title.group(1)\n result_list.append(daily_title)\n\n # 投稿\n m_post = re.search(r'>編<\\/a>\\]
    (.*?)コメントする', html)\n daily_post_text = m_post.group(1)\n daily_post_text = daily_post_text.replace('
    ', '')\n daily_post_text = daily_post_text.replace('[', '\\n')\n\n result_list.append(daily_post_text)\n\n result_lists.append(result_list)\n # print(daily_post_text)\n # sys.exit()\n except Exception as e:\n print(e)\n print('取得できませんでした')\n pass\n\n path_w = './post_daily_data.csv'\n with open(path_w, mode='w') as f:\n writer = csv.writer(f)\n for result_list in result_lists:\n writer.writerow(result_list)\n","sub_path":"mobile_space_daily_scraping.py","file_name":"mobile_space_daily_scraping.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"225287411","text":"from keras.models import model_from_json\nfrom keras.preprocessing import sequence\nimport pickle\nfrom string import punctuation\nimport numpy as np\nfrom sklearn.manifold import TSNE\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\n\nfrom nltk.stem.porter import *\n\nimport os\nimport sys\nstderr = sys.stderr\nsys.stderr = open(os.devnull, 'w')\nimport keras\nsys.stderr = stderr\n\ndef load_model(model_fname, weights_fname):\n\tjson_file = open(model_fname, 'r')\n\tloaded_model_json = json_file.read()\n\tjson_file.close()\n\tloaded_model = model_from_json(loaded_model_json)\n\tloaded_model.load_weights(weights_fname)\n\tloaded_model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n\treturn loaded_model\n\ndef load_tokenizer(fname):\n\twith open(fname, 'rb') as handle:\n\t\ttokenizer = pickle.load(handle)\n\treturn tokenizer\n\ndef safe_search(word):\n\ttry:\n\t\tidx = vocab_to_int[word]\n\texcept KeyError:\n\t\t#print('Not in vocabulary')\n\t\tidx = 0\n\treturn idx\n\ndef find_closest(word, num = 10):\n\t#w1idx = vocab_to_int[word]\n\tw1idx = safe_search(word)\n\tsims = enumerate(cosines[w1idx,:])\n\tsorted_sims = sorted(sims, key = lambda x: x[1], reverse = True)\n\tsorted_sims = [sim for sim in sorted_sims if sim[0] != w1idx]\n\twords = []\n\n\twords = [int_to_vocab[sim[0]] for sim in sorted_sims][:num]\n\treturn words\n\nmodel = load_model('model.json', 'model.h5')\ntokenizer = load_tokenizer('tokenizer.pickle')\n\nvocab_to_int = tokenizer.word_index\nvocab_to_int['__PADDING__'] = 0\n\nint_to_vocab = dict(zip(vocab_to_int.values(), vocab_to_int.keys()))\n\nvecs = model.layers[0].get_weights()[0]\nword_embeds = {w:vecs[idx] for w, idx in vocab_to_int.items()}\n\nfrom sklearn.metrics import pairwise_distances\nfrom scipy.spatial.distance import cosine\nimport numpy as np\n\ncosines = 1 - pairwise_distances(vecs, metric = 'cosine')\n\ndef find_furthest(word, num = 10):\n\t#w1idx = vocab_to_int[word]\n\tw1idx = safe_search(word)\n\tsims = enumerate(cosines[w1idx,:])\n\tsorted_sims = sorted(sims, key = lambda x: x[1])\n\tsorted_sims = [sim for sim in sorted_sims if sim[0] != w1idx]\n\twords = []\n\twords = [int_to_vocab[sim[0]] for sim in sorted_sims][:num]\n\treturn words\n\nhate_words = ['nigger', 'queer', 'fag', 'raghead', 'wetback', 'chink', 'bean', 'coon', 'negro']\n\ndef generate_clusters(keys):\n\tfar_words = []\n\tfor key in keys:\n\t\tfar_words += find_furthest(key, 3)\n\tsample = np.random.choice(far_words, size = len(keys))\n\t#keys = keys + list(set(sample))\n\t#print(keys)\n\tembedding_clusters = []\n\tword_clusters = []\n\t#keys = keys + \n\tunique_words = set()\n\tfor word in keys:\n\t\tmost_similar_words = find_closest(word, 100)\n\t\twords_no_dups = [word for word in most_similar_words if word not in unique_words]\n\t\tunique_words = unique_words.union(set(words_no_dups))\n\t\tembeddings = np.array([word_embeds[w2] for w2 in most_similar_words])\n\t\tembedding_clusters.append(embeddings)\n\t\tword_clusters.append(most_similar_words)\n\n\tembedding_clusters = np.array(embedding_clusters)\n\n\tn, m, k = embedding_clusters.shape\n\ttsne_model_2d = TSNE(perplexity = 30, n_components = 2, init = 'pca', n_iter = 3500)\n\tembeddings_2d = np.array(tsne_model_2d.fit_transform(embedding_clusters.reshape(n * m, k))).reshape(n, m, 2)\n\t\n\treturn embeddings_2d, word_clusters\n\ndef tsne_plot_similar_words(labels, embedding_clusters, word_clusters, a):\n\n\tplt.figure(figsize = (16,9))\n\tcolors = cm.PuBuGn(np.linspace(0,1,len(labels)))\n\tunique_words = set()\n\tfor label, embeddings, words, color in zip(labels, embedding_clusters, word_clusters, colors):\n\t\tx = embeddings[:,0]\n\t\ty = embeddings[:,1]\n\t\tif label in hate_words:\n\t\t\tlabel = label[0] + '*'*(len(label) - 1)\n\t\t\tplt.scatter(x,y, c = 'r', alpha = a, label = label)\n\n\t\t\tfor i, word in enumerate(words):\n\t\t\t\tif word in unique_words:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tif prof_pred([word]) == 1 or word in hate_words:\n\t\t\t\t\t word = word[0] + '*'*(len(word) - 1)\n\t\t\t\t\tplt.annotate(word, alpha = 0.5, xy = (x[i], y[i]), xytext = (5,2),\n\t\t\t\t\t\t\t\ttextcoords = 'offset points', ha = 'right', va = 'bottom', size = 8)\n\t\t\t\tunique_words.add(word)\n\t\t\telse:\n\t\t\t\tplt.scatter(x,y, c = [color], alpha = a, label = label)\n\t\t\tfor i, word in enumerate(words):\n\t\t\t\tif word in unique_words:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tif prof_pred([word]) == 1 or word in hate_words:\n\t\t\t\t\t\tword = word[0] + '*'*(len(word) - 1)\n\t\t\t\t\tplt.annotate(word, alpha = 0.5, xy = (x[i], y[i]), xytext = (5,2),\n\t\t\t\t\t\t\t\ttextcoords = 'offset points', ha = 'right', va = 'bottom', size = 8)\n\t\t\t\t\tunique_words.add(word)\n\tplt.legend(loc = 4)\n #plt.title(title)\n\tplt.grid(True)\n\tplt.show()\n\ndef run():\n\n\n\tstemmer = PorterStemmer()\n\n\tcont = True\n\n\t#ax = plt.axes()\n\n\tprint(\"\\n\\n-----This is a tool for visualizing how the model builds relationships between words.\\n\")\n\tprint(\"-----Word clusters corresponding to hate speech words should be geometrically different than those of neutral words.\\n\\n\")\n\tprint(\"-----NOTE: Similar words are stemmed.\")\n\n\tprint('\\n---Instructions---')\n\tprint('------Type Words to Generate Clusters.')\n\tprint('------Make sure words are separated by a single space')\n\tprint('------Example: \"We are going to be alright\"')\n\tprint('------If you type in a hate word, all words similar to this will be red')\n\tprint('------Note: Not all possible hate words will be recognized at this step.')\n\tprint('------Resulting plot will be clusters of words most similar to your inputted words.')\n\n\t\n\n\twhile cont == True:\n\n\t\ttxt = input('\\n\\nType words: ')\n\n\t\tkeys = txt.split()\n\t\t#print(keys)\n\t\tkeys_stem = [stemmer.stem(w) for w in txt.split()]\n\n\t\tprint('\\n Generating Clusters')\n\t\tembedding_clusters, word_clusters = generate_clusters(keys_stem)\n\t\t#tsne_plot_similar_words(keys, embedding_clusters, word_clusters, 0.7)\n\t\tcolors = cm.PuBuGn(np.linspace(0,1,len(keys)))\n\t\t\n\t\tplt.figure(figsize = (16,9))\n\n\t\tfor cluster, word, color, close_words in zip(embedding_clusters, keys, colors, word_clusters):\n\t\t\t\n\t\t\tif stemmer.stem(word) in hate_words:\n\t\t\t\tc = ['r']\n\t\t\telse: c = [color]\n\n\t\t\tx = cluster[:,0]\n\t\t\ty = cluster[:,1]\n\t\t\t\n\t\t\tplt.scatter(x,y, c = c, label = word, s = 8)\n\n\t\t\tfor i, close_word in enumerate(close_words):\n\t\t\t\tif len(close_word) > 15:\n\t\t\t\t\tclose_word = close_word[:15]\n\t\t\t\tplt.annotate(close_word, xy = (x[i], y[i]), xytext = (5,2), alpha = 0.5,\n\t\t\t\t\t\t\t\ttextcoords = 'offset points', ha = 'right', va = 'bottom', size = 8)\n\n\t\tplt.legend()\n\t\tplt.grid(True)\n\t\tplt.title('Most Similar Words')\n\t\tplt.show()\n\nif __name__ == '__main__':\n\n\trun()","sub_path":"generate_plots.py","file_name":"generate_plots.py","file_ext":"py","file_size_in_byte":6403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"256384552","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 16 19:34:34 2017\n\n@author: darragh\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport math\nfrom sklearn import mixture\nfrom sklearn.utils import shuffle\nfrom skimage import measure\nfrom glob import glob\nimport os\nfrom PIL import Image\n\n\nos.chdir('/home/darragh/Dropbox/cervical/feat')\nTRAIN_DATA = \"../data/train\"\nTEST_DATA = \"../data/test\"\nADDITIONAL_DATA = \"../data\"\ntrain_files = glob(os.path.join(TRAIN_DATA, \"*\", \"*.jpg\"))\ntest_files = glob(os.path.join(TEST_DATA, \"*.jpg\"))\nadditional_files = glob(os.path.join(ADDITIONAL_DATA, 'Type_*', \"*.jpg\"))\nROWS = 224\nCOLS = 224\n\n# Create directories\nif not os.path.exists('../data/original'):\n os.mkdir('../data/original')\n os.mkdir('../data/original/test')\n os.mkdir('../data/original/train')\n for i in range(3) : \n os.mkdir('../data/original/Type_' + str(i+1))\n os.mkdir('../data/original/train/Type_' + str(i+1))\n\n# Write images\ni = 0 \nall_paths = train_files + test_files + additional_files\nfor f in sorted(all_paths):\n if i % 50 == 0 : print('Processing image {} out of {}'.format(i, len(all_paths)))\n fpath = f.replace('../data', '../data/original')\n img = Image.open(f)\n try:\n img = img.convert('RGB')\n except:\n print('Failed to read {}'.format(fpath))\n continue\n img = img.resize((COLS * 2, ROWS * 2))\n img.save(fpath)\n i += 1","sub_path":"feat/0_save_original_small.py","file_name":"0_save_original_small.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"521837097","text":"#!/usr/bin/env python3\nimport pickle\nimport os\nfrom os import walk\nimport cv2\n\n\n\ndef log_error(msg, _quit=True):\n print(\"-- PARAMETER ERROR --\\n\"*5)\n print(\" %s \\n\" % msg)\n print(\"-- PARAMETER ERROR --\\n\"*5)\n if _quit:\n quit()\n else:\n return False\n\n\ndef file_exists(file_name):\n try:\n with open(file_name) as f:\n return file_name\n except OSError as e:\n return False\n\n\ndef file_exists_and_not_empty(file_name):\n if file_exists(file_name) and os.stat(file_name).st_size > 0:\n return True\n return False\n\n\ndef file_exists_and_empty(file_name):\n if file_exists(file_name) and os.stat(file_name).st_size == 0:\n return True\n return False\n\n\ndef read_images_in_dir(path_to_read):\n dir_name, subdir_name, file_names = next(walk(path_to_read))\n images = [item for item in file_names if '.jpeg' in item[-5:] or '.jpg' in item[-4:] or 'png' in item[-4:] ]\n\n\ndef delete_pickle(data_file):\n os.remove(data_file)\n if file_exists(data_file):\n raise Exception('unable to delete file: %s' % file_name)\n\n\ndef write_to_pickle(data, data_file):\n with open(data_file, mode='ab') as f:\n pickle.dump(data, f)\n print(\"saving into file...\", data_file)\n\n\ndef read_pickle_2(pickle_file, exception=True):\n data = []\n try:\n with open(pickle_file, 'rb') as f:\n while True:\n try:\n d = pickle.load(f)\n data.append(d)\n except Exception as e:\n break\n return len(data), data\n except OSError as e:\n if exception:\n com.log_error(\"Unable to open pickle_file: {}, original exception {}\".format(pickle_file, str(e)))\n else:\n return 0, []\n\n\ndef read_pickle(pickle_file, exception=True):\n try:\n with open(pickle_file, 'rb') as f:\n known_face_encodings, known_face_metadata = pickle.load(f)\n return len(known_face_metadata), known_face_encodings, known_face_metadata\n except OSError as e:\n if exception:\n com.log_error(\"Unable to open pickle_file: {}, original exception {}\".format(pickle_file, str(e)))\n else:\n return 0, [], []\n\n\npwd = os.getcwd()\nmetadata_file = 'data/video_encoded_faces/test_video_default_metadata.dat'\nencodings_file = 'data/video_encoded_faces/test_video_default_encodings.dat'\ntest = pwd + '/data/video_encoded_faces/test_video_default.data'\ntest = '/tmp/read_from_directory/read_from_directory.dat'\ntest = 'data/encoded_known_faces/knownFaces.dat'\ntest = 'data/video_encoded_faces/test_video_default.data'\ntest = 'data/found_faces/found_faces_db.dat'\nprint(test)\nt, datos, meta = read_pickle(test)\n#datos = read_pickle(encodings_file)\nnumero = len(meta)\nprint('numero:',numero)\n#quit()\n#print('numero:',numero,'\\ndatos:\\n', datos, 'meta', meta)\n#print('numero:',numero,'\\nmetadatos:\\n', meta)\n#print('numero:',numero)\n#print('meta 1:', meta[0]['face_image'])\n#quit()\n \ni = 0\nfor m in meta:\n print('name', m['name'], m['seen_count'], m['seen_frames'])\n #img = m['face_image']\n #cv2.imwrite(\"/tmp/stream_9/frame_\" + str(i) + \".jpg\", img)\n i += 1\nquit()\n\nfor m in meta:\n i = 0 \n for img in m['face_image']:\n cv2.imwrite(\"/tmp/stream_99/frame_\" + m['name'] + '_' + str(i) + \".jpg\", img)\n print(m['name'],' confidence:', m['confidence'], ' difference ', m['difference'] )\n i += 1\n\n","sub_path":"apps/deepstream-imagedata-multistream/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"118417635","text":"flag: bool = True\nwhile flag:\n try:\n list1 = ['Red', 'yop', 'der', 'poy', 'op', 'edr']\n print(\"l1 is \", list1)\n list2 = ['pop', 'poy', 'Red']\n print('l2 is ', list2)\n list3 = []\n for string in list1:\n # storing just the common elements in the list1 and list2\n if list2.__contains__(string):\n list3.append(string)\n print(\"Common items in l1 and l2 are \", list3)\n except IndexError:\n print(list1)\n except Exception as exep:\n print(\"Process stopped because %s\" % exep)\n print(\"To exit press 0 else press any other number\")\n if input() == 0:\n flag = False\n","sub_path":"Week2/ListQ15.py","file_name":"ListQ15.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"495289410","text":"import random\n#A script that creates a new reference with the multimapped reads \nwith open(\"shortReads.fq\",'r') as f:\n lines = f.readlines()\n\nbasepairs = \"ATCG\"\nreferenceSequence=\"\"\n#testSequence=\"\"\n#Loop through each read\nfor i in range(1,len(lines),4):\n numLoops = (i-1)/4+1\n readLength = len(lines[i])\n #Add each read to referenceSequence depending on read number\n #ie Read 4 will be in the reference sequence 4 times\n for j in range(int(numLoops)):\n #Create random filler sequence (50 bps long)\n randomFiller=\"\"\n for k in range(1,50):\n randomFiller+= random.choice(basepairs)\n referenceSequence+= lines[i][:readLength-1] + randomFiller\n# testSequence+= \"A\"\nwith open(\"multimapped.reference.short.fa\",'w+') as f:\n f.writelines(\">Reference\\n\")\n f.writelines(referenceSequence)\n \n","sub_path":"compare.tools.simulated.data/multimapped/scripts.simulate.data/buildMultiRef.short.py","file_name":"buildMultiRef.short.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180197692","text":"from django.shortcuts import render, redirect\nfrom selenium import webdriver\nimport os\nfrom iotd.models import Item\nimport re\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\n\ndef detail(request):\n pass\n\ndef crawling(request):\n if request.method == \"POST\":\n\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n modelnum = request.POST.get('modelnum')\n prdlink = request.POST.get('prdlink')\n\n # 링크\n link = prdlink\n\n # 사이트명\n if prdlink.split(\"/\")[2].split(\".\")[1] == '11st':\n retailer = \"11번가\"\n elif prdlink.split(\"/\")[2].split(\".\")[1] == 'coupang':\n retailer = \"Coupang\"\n else:\n return render(request, 'crawling.html')\n\n # 현재 크롬 드라이버\n driver_path = os.path.join(BASE_DIR, 'selenium_drivers', 'chromedriver', 'chromedriver.exe')\n \n driver = webdriver.Chrome(driver_path)\n driver.get(prdlink)\n\n # 11번가 크롤링\n if retailer == \"11번가\":\n\n # 제품명\n productName = driver.find_element_by_class_name('heading').find_element_by_tag_name('h2').text\n\n # 썸네일\n thumbnail_url = driver.find_element_by_id('thumb').find_element_by_tag_name('img').get_attribute('src')\n\n # 가격\n price = driver.find_element_by_class_name('sale_price').text + '원'\n\n # 리뷰 개수\n reviewnum_origin = driver.find_element_by_id('reviewTo').find_element_by_class_name('notice_count').text\n reviewnum0 = re.sub('[ ,\\(\\)]', '', reviewnum_origin)\n reviewnum = '리뷰 ' + reviewnum0 + '건'\n\n # 별점\n try:\n rating5 = driver.find_element_by_id('prdRating').find_element_by_class_name('num').text\n rating = '판매자 평점 별5개 중 ' + rating5 + '개'\n except:\n rating = '판매자 평점 별5개 중 0.0개'\n\n # 쿠팡 크롤링\n elif retailer == \"Coupang\":\n\n # 제품명\n productName = driver.find_element_by_class_name('prod-buy-header__title').text\n\n # 썸네일\n thumbnail_url = driver.find_element_by_class_name('prod-image__detail').get_attribute('src')\n\n # 가격\n price = driver.find_element_by_class_name('prod-coupon-price').find_element_by_class_name('total-price').text\n if price == \"\":\n price = driver.find_element_by_class_name('prod-sale-price').find_element_by_class_name('total-price').text\n\n # 리뷰 개수\n reviewnum_origin = driver.find_element_by_class_name('prod-buy-header__productreview').find_element_by_class_name('count').text\n if reviewnum_origin == \"\":\n reviewnum = '리뷰 0건'\n else:\n reviewnum0 = re.sub('[^0-9]', '', reviewnum_origin)\n reviewnum = '리뷰 ' + reviewnum0 + '건'\n\n # 별점\n rating_origin = driver.find_element_by_class_name('rating-star-num').get_attribute('style')\n rating100 = re.sub('[^0-9]', '', rating_origin)\n rating = '판매자 평점 별5개 중 ' + str(int(rating100)/100*5) + '개'\n\n else:\n return render(request, 'crawling.html')\n\n product = Item(\n modelnum = modelnum,\n productName = productName,\n retailer = retailer,\n link = link,\n thumbnail_url = thumbnail_url,\n price = price,\n reviewnum = reviewnum,\n rating = rating\n )\n\n product.save()\n\n driver.close()\n\n return render(request, 'crawling.html')\n else:\n return render(request, 'crawling.html')","sub_path":"final_pjt/iotd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34438054","text":"# -*- coding: utf-8 -*-\n\n# Redistribution and use in source and binary forms of this file,\n# with or without modification, are permitted. See the Creative\n# Commons Zero (CC0 1.0) License for more details.\n\n# Industrial Analog Out Bricklet communication config\n\ncom = {\n 'author': 'Olaf Lüke ',\n 'api_version': [2, 0, 0],\n 'category': 'Bricklet',\n 'device_identifier': 258,\n 'name': ('IndustrialAnalogOut', 'industrial_analog_out', 'Industrial Analog Out', 'Industrial Analog Out Bricklet'),\n 'manufacturer': 'Tinkerforge',\n 'description': 'Device for output of voltage between 0 and 10V and current between 4 and 20mA',\n 'released': False,\n 'packets': []\n}\n\ncom['packets'].append({\n'type': 'function',\n'name': ('Enable', 'enable'), \n'elements': [],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\n\"\"\",\n'de':\n\"\"\"\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('Disable', 'disable'), \n'elements': [],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\n\"\"\",\n'de':\n\"\"\"\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('IsEnabled', 'is_enabled'), \n'elements': [('enabled', 'bool', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\n\"\"\",\n'de':\n\"\"\"\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetVoltage', 'set_voltage'), \n'elements': [('voltage', 'uint16', 1, 'in')],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\nSets the voltage in mV.\n\"\"\",\n'de':\n\"\"\"\nSetzt die Spannung in mV.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetVoltage', 'get_voltage'), \n'elements': [('voltage', 'uint16', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\nReturns the voltage as set by :func:`SetVoltage`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Spannung zurück, wie von :func:`SetVoltage`\ngesetzt.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetCurrent', 'set_current'), \n'elements': [('current', 'uint16', 1, 'in')],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\nSets the current in µA.\n\"\"\",\n'de':\n\"\"\"\nSetzt den Strom in µA.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetCurrent', 'get_current'), \n'elements': [('current', 'uint16', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\nReturns the current as set by :func:`SetCurrent`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Spannung zurück, wie von :func:`SetCurrent`\ngesetzt.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetConfiguration', 'set_configuration'), \n'elements': [('voltage_range', 'uint8', 1, 'in', ('VoltageRange', 'voltage_range', [('0To5V', '0_to_5v', 0),\n ('0To10V', '0_to_10v', 1)])),\n ('current_range', 'uint8', 1, 'in', ('CurrentRange', 'current_range', [('4To20mA', '4_to_20ma', 0),\n ('0To20mA', '0_to_20ma', 1),\n ('0To24mA', '0_to_24ma', 2)]))],\n'since_firmware': [1, 0, 0],\n'doc': ['af', {\n'en':\n\"\"\"\nTODO\n\"\"\",\n'de':\n\"\"\"\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetConfiguration', 'get_configuration'), \n'elements': [('voltage_range', 'uint8', 1, 'out', ('VoltageRange', 'voltage_range', [('0To5V', '0_to_5v', 0),\n ('0To10V', '0_to_10v', 1)])),\n ('current_range', 'uint8', 1, 'out', ('CurrentRange', 'current_range', [('4To20mA', '4_to_20ma', 0),\n ('0To20mA', '0_to_20ma', 1),\n ('0To24mA', '0_to_24ma', 2)]))],\n'since_firmware': [1, 0, 0],\n'doc': ['af', {\n'en':\n\"\"\"\nReturns the configuration as set by :func:`SetConfiguration`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Konfiguration zurück, wie von :func:`SetConfiguration`\ngesetzt.\n\"\"\"\n}]\n})\n","sub_path":"configs/bricklet_industrial_analog_out_config.py","file_name":"bricklet_industrial_analog_out_config.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180262845","text":"from ala import bla\n\nfrom tkinter import *\nimport random\nimport tkinter.messagebox\nfrom tkinter import ttk\n\na=1\nb=\"Leszek Zukowski\"\n\nroot=Tk()\ndef delete():\n print(entry.delete(0,2))\n return\n\nroot=Tk()\n\ndef los():\n a=random.randint(1,100)\n return\n\ndef function1():\n a = random.randint(1, 100)\n print(entry.insert(1,a))\n return\n\n\nlink=\"/home/dominik/Pobrane/\"\nfile=\"x.svg\"\nlinkandfile=link+file\n\nlabel=Label(root, width=100,bg=\"#3f4a5b\")\nlabel.pack()\nbtn=ttk.Button(text=\"KLIK\",command=function1,width=20)\nimage=PhotoImage(file=\"Button-Previous-icon.png\")\nbtn.config(image=image,width=20)\nbtn.pack()\nbtn1=Button(text='Delete',bg=\"#4286f4\", command=delete)\nbtn1.pack()\nentry=Entry(root)\nentry.pack()\nentry.get()\nroot.mainloop()","sub_path":"ma.py","file_name":"ma.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"322388249","text":"\nUP = lambda x : (max(x[0] - 1, 0), x[1])\nDOWN = lambda x : (min(x[0] + 1, 2), x[1])\nLEFT = lambda x : (x[0], max(x[1] - 1, 0))\nRIGHT = lambda x : (x[0], min(x[1] + 1, 2))\n\ndef main():\n position = (1, 1)\n\n input_lines = open(\"input.txt\").readlines()\n\n code = []\n\n for line in input_lines:\n for char in line:\n if char == \"U\":\n position = UP(position)\n elif char == \"D\":\n position = DOWN(position)\n elif char == \"R\":\n position = RIGHT(position)\n elif char == \"L\":\n position = LEFT(position)\n\n code.append(position[0] * 3 + position[1] + 1)\n\n print(code)\n\nif __name__ == \"__main__\":\n main();\n","sub_path":"2016/day-2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"632531033","text":"import argparse\nimport os\nimport log\nimport sys\nimport itertools\n\nimport torch\nfrom torch.utils.data import DataLoader, ConcatDataset\nfrom torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR\n\nfrom vision.utils.misc import str2bool, Timer, freeze_net_layers, store_labels\nfrom vision.ssd.ssd import MatchPrior\nfrom vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd\nfrom vision.datasets.open_images import OpenImagesDataset\nfrom vision.nn.multibox_loss import MultiboxLoss\nfrom vision.ssd.config import mobilenetv1_ssd_config\nfrom vision.ssd.data_preprocessing import TrainAugmentation, TestTransform\n\nparser = argparse.ArgumentParser(\n description='Single Shot MultiBox Detector Training With Pytorch')\n\n# Continous training ...\nparser.add_argument('--resume', default=None, type=str,\n help='Checkpoint state_dict file to resume training from')\n# training data\nparser.add_argument('--datasets', nargs='+', help='Dataset directory path')\nparser.add_argument('--validation_dataset', help='Dataset directory path')\nparser.add_argument('--balance_data', action='store_true',\n help=\"Balance training data by down-sampling more frequent labels.\")\n# Frequently modified training params\nparser.add_argument('--num_epochs', default=120, type=int,\n help='the number epochs')\nparser.add_argument('--use_cuda', default=True, type=str2bool,\n help='Use CUDA to train model')\nparser.add_argument('--labelInModelOut_folder', default='./models/',\n help='Directory for input classification labels and output checkpoint models')\nargs = parser.parse_args()\n\n# hardcoded params for training\nargs.freeze_base_net = True\nlog.info(\"freeze_base_net : {}\".format(args.freeze_base_net))\nargs.pretrained_ssd = \"models/pretrained-ssdv1.pth\"\nlog.info(\"Using pretrained model: {}\".format(args.pretrained_ssd))\nargs.batch_size = 5\nlog.info(\"mini-batch size: {}\".format(args.batch_size))\n#args.num_workers = 4\nargs.num_workers = 1\nlog.info(\"num_workers used in dataloading: {}\".format(args.num_workers))\nargs.validation_epochs = 5\nlog.info(\"the number epochs before each validation: {}\".format(args.validation_epochs))\nargs.debug_steps = 100\nlog.info(\"debug log output frequency : one debug log per {} training samples\".format(args.debug_steps))\nargs.labelInModelOut_folder = 'models/'\nlog.info(\"Output directory for classification labels and checkpoint models : {}\".format(args.labelInModelOut_folder))\n# hardcoded params for SGD\nargs.lr = 1e-2\nlog.info(\"initial learning rate : {}\".format(args.lr)) \nargs.extra_layers_lr = args.lr\nlog.info(\"initial learning rate for the layers not in base net and prediction heads. : {}\".format(args.extra_layers_lr)) \nargs.momentum = 0.9\nlog.info(\"Momentum value for optim : {}\".format(args.momentum)) \nargs.weight_decay = 5e-4\nlog.info(\"Weight decay for SGD : {}\".format(args.weight_decay))\nargs.gamma = 0.1\nlog.info(\"Gamma update for SGD : {}\".format(args.gamma))\nargs.scheduler = 'cosine'\nlog.info(\"Scheduler for SGD. It can one of multi-step and cosine : {}\".format(args.scheduler))\nargs.t_max = 100\nlog.info(\"T_max value for Cosine Annealing Scheduler : {}\".format(args.t_max))\n\nif args.use_cuda and torch.cuda.is_available():\n torch.backends.cudnn.benchmark = True\n DEVICE = torch.device(\"cuda:0\")\n log.info(\"Use Cuda {}\".format(DEVICE))\nelse:\n DEVICE = torch.device(\"cpu\")\n log.info(\"Use CPU {}\".format(DEVICE))\n\ndef train(loader, net, criterion, optimizer, device, debug_steps=100, epoch=-1):\n net.train(True)\n running_loss = 0.0\n running_regression_loss = 0.0\n running_classification_loss = 0.0\n for i, data in enumerate(loader):\n images, boxes, labels = data\n # log.once('images.shape={}, boxes.shape={}, labels.shape={}'.format( images.shape, boxes.shape, labels.shape))\n # - train_weed1.py:88 images.shape=torch.Size([5, 3, 300, 300]), boxes.shape=torch.Size([5, 3000, 4]), labels.shape=torch.Size([5, 3000])\n images = images.to(device)\n boxes = boxes.to(device)\n labels = labels.to(device)\n\n optimizer.zero_grad()\n confidence, locations = net(images)\n # log.once('confidence.shape={}, locations.shape={}'.format( confidence.shape, locations.shape))\n # confidence.shape=torch.Size([5, 3000, 2]), locations.shape=torch.Size([5, 3000, 4])\n regression_loss, classification_loss = criterion(confidence, locations, labels, boxes) # TODO CHANGE BOXES\n loss = regression_loss + classification_loss\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n running_regression_loss += regression_loss.item()\n running_classification_loss += classification_loss.item()\n if i and i % debug_steps == 0:\n avg_loss = running_loss / debug_steps\n avg_reg_loss = running_regression_loss / debug_steps\n avg_clf_loss = running_classification_loss / debug_steps\n log.info(\n \"Epoch: {}, example: {}, \"\n \"Average all Loss: {}, \"\n \"Average Regression Loss {}, \"\n \"Average Classification Loss: {}\"\n .format(epoch,i,avg_loss,avg_reg_loss,avg_clf_loss)\n )\n running_loss = 0.0\n running_regression_loss = 0.0\n running_classification_loss = 0.0\n\n\ndef test(loader, net, criterion, device):\n net.eval()\n running_loss = 0.0\n running_regression_loss = 0.0\n running_classification_loss = 0.0\n num = 0\n for _, data in enumerate(loader):\n images, boxes, labels = data\n images = images.to(device)\n boxes = boxes.to(device)\n labels = labels.to(device)\n num += 1\n\n with torch.no_grad():\n confidence, locations = net(images)\n regression_loss, classification_loss = criterion(confidence, locations, labels, boxes)\n loss = regression_loss + classification_loss\n\n running_loss += loss.item()\n running_regression_loss += regression_loss.item()\n running_classification_loss += classification_loss.item()\n return running_loss / num, running_regression_loss / num, running_classification_loss / num\n\n\nif __name__ == '__main__':\n timer = Timer()\n\n log.info(args)\n\n create_net = create_mobilenetv1_ssd\n config = mobilenetv1_ssd_config\n \n train_transform = TrainAugmentation(config.image_size, config.image_mean, config.image_std)\n target_transform = MatchPrior(config.priors, config.center_variance,\n config.size_variance, 0.5)\n\n test_transform = TestTransform(config.image_size, config.image_mean, config.image_std)\n\n log.info(\"Prepare training datasets.\")\n datasets = []\n for dataset_path in args.datasets:\n\n dataset = OpenImagesDataset(dataset_path,\n transform=train_transform, target_transform=target_transform,\n dataset_type=\"train\", balance_data=args.balance_data)\n label_file = os.path.join(args.labelInModelOut_folder, \"outModel-labels.txt\")\n store_labels(label_file, dataset.class_names)\n log.info(dataset)\n num_classes = len(dataset.class_names)\n\n datasets.append(dataset)\n log.info(\"Stored labels into file \"+label_file)\n train_dataset = ConcatDataset(datasets)\n log.info(\"Train dataset size: {}\".format(len(train_dataset)))\n train_loader = DataLoader(train_dataset, args.batch_size,\n num_workers=args.num_workers,\n shuffle=True)\n log.info(\"Prepare Validation datasets.\")\n val_dataset = OpenImagesDataset(dataset_path,\n transform=test_transform, target_transform=target_transform,\n dataset_type=\"test\")\n log.info(val_dataset)\n log.info(\"validation dataset size: {}\".format(len(val_dataset)))\n\n val_loader = DataLoader(val_dataset, args.batch_size,\n num_workers=args.num_workers,\n shuffle=False)\n log.info(\"Build network.\")\n net = create_net(num_classes)\n min_loss = -10000.0\n last_epoch = -1\n\n # freeze_base_net:\n log.info(\"Freeze base net..\")\n freeze_net_layers(net.base_net)\n params = itertools.chain(net.source_layer_add_ons.parameters(), net.extras.parameters(),\n net.regression_headers.parameters(), net.classification_headers.parameters())\n # log.info(\"params 1 = \"+str(params)) \n params = [\n {'params': itertools.chain(\n net.source_layer_add_ons.parameters(),\n net.extras.parameters()\n ), 'lr': args.extra_layers_lr},\n {'params': itertools.chain(\n net.regression_headers.parameters(),\n net.classification_headers.parameters()\n )}\n ]\n # log.info(\"params 2 = \"+str(params)) \n\n timer.start(\"Load Model\")\n if args.resume:\n log.info(\"Resume from the model \"+args.resume)\n net.load(args.resume)\n else:\n log.info(\"Init from pretrained ssd \"+args.pretrained_ssd)\n net.init_from_pretrained_ssd(args.pretrained_ssd)\n log.info('Took '+str(timer.end(\"Load Model\"))+' seconds to load the model.')\n\n net.to(DEVICE)\n\n criterion = MultiboxLoss(config.priors, iou_threshold=0.5, neg_pos_ratio=3,\n center_variance=0.1, size_variance=0.2, device=DEVICE)\n optimizer = torch.optim.SGD(params, lr=args.lr, momentum=args.momentum,\n weight_decay=args.weight_decay)\n log.info(\"Learning rate: \"+str(args.lr) + \", Extra Layers learning rate: \"+str(args.extra_layers_lr))\n\n log.info(\"Uses CosineAnnealingLR scheduler.\")\n scheduler = CosineAnnealingLR(optimizer, args.t_max, last_epoch=last_epoch)\n \n log.info(\"Start training from epoch \"+str(last_epoch + 1))\n for epoch in range(last_epoch + 1, args.num_epochs):\n train(train_loader, net, criterion, optimizer,\n device=DEVICE, debug_steps=args.debug_steps, epoch=epoch)\n scheduler.step() # place scheduler.step() after training torch 1.1.0\n \n if epoch % args.validation_epochs == 0 or epoch == args.num_epochs - 1:\n val_loss, val_regression_loss, val_classification_loss = test(val_loader, net, criterion, DEVICE)\n log.info(\n \"Epoch: {},\"\n \"Validation Loss: {}, \"\n \"Validation Regression Loss {}, \"\n \"Validation Classification Loss: {}\"\n .format(epoch,val_loss,val_regression_loss,val_classification_loss)\n )\n model_path = os.path.join(args.labelInModelOut_folder, \"outModel.pth\")\n net.save(model_path)\n log.info(\"Saved model \"+model_path)\n","sub_path":"py/train_recycle.py","file_name":"train_recycle.py","file_ext":"py","file_size_in_byte":10838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"309883830","text":"\r\nfrom PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt\r\n\r\nfrom src.Model.TreeItem import TreeItem\r\n\r\nclass TreeModel(QAbstractItemModel):\r\n\tdef __init__(self, npy_tree, row, parent = None):\r\n\t\tsuper().__init__(parent)\r\n\t\tself._npy_tree = npy_tree\r\n\t\tself._row = row\r\n\r\n\t\tself.root_item = self._npy_tree['structure']\r\n\r\n\tdef getItem(self, index):\r\n\t\tif index.isValid():\r\n\t\t\titem = index.internalPointer()\r\n\t\t\tif item:\r\n\t\t\t\treturn item\r\n\r\n\t\treturn self.root_item\r\n\r\n\tdef index(self, row, column, parent = QModelIndex()):\r\n\t\tif parent.isValid() and parent.column() != 0:\r\n\t\t\treturn QModelIndex()\r\n\r\n\t\tparent_item = self.getItem(parent)\r\n\t\tchild_item = self._npy_tree.tree_child(parent_item, row)\r\n\t\tif child_item:\r\n\t\t\treturn self.createIndex(row, column, child_item)\r\n\t\telse:\r\n\t\t\treturn QModelIndex()\r\n\r\n\tdef parent(self, index):\r\n\t\tif not index.isValid():\r\n\t\t\treturn QModelIndex()\r\n\r\n\t\tchild_item = self.getItem(index)\r\n\t\tparent_item = self._npy_tree.tree_parent(child_item)\r\n\r\n\t\tif parent_item == self.root_item:\r\n\t\t\treturn QModelIndex()\r\n\r\n\t\tchild_number = self._npy_tree.tree_child_number(parent_item)\r\n\t\treturn self.createIndex(child_number, 0, parent_item)\r\n\r\n\tdef rowCount(self, parent = QModelIndex()):\r\n\t\tparent_item = self.getItem(parent)\r\n\r\n\t\treturn len(parent_item['children'])\r\n\r\n\tdef insertRows(self, row, count, parent = QModelIndex()):\r\n\t\tparent_item = self.getItem(parent)\r\n\t\tself.beginInsertRows(parent, row, row + count - 1)\r\n\t\tsuccess = parent_item.insertChildren(row, count, self._npy_tree.tree_column_count())\r\n\t\tself.endInsertRows()\r\n\r\n\t\treturn success\r\n\r\n\tdef removeRows(self, row, count, parent = QModelIndex()):\r\n\t\tparent_item = self.getItem(parent)\r\n\t\tself.beginRemoveRows(parent, row, row + count - 1)\r\n\t\tsuccess = parent_item.removeChildren(row, count)\r\n\t\tself.endRemoveRows()\r\n\r\n\t\treturn success\r\n\r\n\tdef data(self, index, role):\r\n\t\tif not index.isValid():\r\n\t\t\treturn None\r\n\r\n\t\tif role != Qt.DisplayRole and role != Qt.EditRole:\r\n\t\t\treturn None\r\n\r\n\t\titem = self.getItem(index)\r\n\t\treturn self._npy_tree.tree_data(item, self._row, index.column())\r\n\r\n\tdef setData(self, index, value, role = Qt.EditRole):\r\n\t\tif role != Qt.EditRole:\r\n\t\t\treturn False\r\n\r\n\t\titem = self.getItem(index)\r\n\t\tresult = self._npy_tree.tree_setData(item, self._row, index.column(), value)\r\n\r\n\t\tif result:\r\n\t\t\tself.dataChanged.emit(index, index)\r\n\r\n\t\treturn result\r\n\r\n\tdef flags(self, index):\r\n\t\tif not index.isValid():\r\n\t\t\treturn 0\r\n\r\n\t\treturn Qt.ItemIsEditable | super().flags(index)\r\n\r\n\tdef columnCount(self, parent = QModelIndex()):\r\n\t\treturn self._npy_tree.tree_column_count()\r\n\r\n\tdef headerData(self, section, orientation, role = Qt.DisplayRole):\r\n\t\tif orientation == Qt.Horizontal and role == Qt.DisplayRole:\r\n\t\t\treturn self._npy_tree.tree_column(section)\r\n\t\treturn None\r\n","sub_path":"src/Model/TreeModel.py","file_name":"TreeModel.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60006382","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 5 13:59:58 2020\n\n@author: farhan\n\"\"\"\n#this script runs the heterodimer feature generation pipeline\n#Usage: python pipeline.py \n#1. \n\n\nimport os, sys, shutil\nfrom readFastaFile import readFastaFile\n\nfasta_file_A=os.path.abspath(sys.argv[1])\nfasta_file_B=os.path.abspath(sys.argv[2])\noutdir=os.path.abspath(sys.argv[3])+\"/\"\npaths_file=os.path.abspath(sys.argv[4])\ndir_A=outdir+\"A/\"\ndir_B=outdir+\"B/\"\npackage_dir=os.path.dirname(os.path.abspath(sys.argv[0]))+\"/\"\nprint (\"Current package directory: \"+package_dir)\n#sys.exit()\nif not (os.path.exists(fasta_file_A)): sys.exit (\"Fasta file \"+fasta_file_A+\" not found! Quitting!\")\nif not (os.path.exists(fasta_file_B)): sys.exit (\"Fasta file \"+fasta_file_B+\" not found! Quitting!\")\nif not (os.path.exists(paths_file)): sys.exit (\"Paths file \"+paths_file+\" not found! Quitting!\")\nif not (os.path.isdir(outdir)): os.makedirs(outdir)\n\nif not os.path.isdir(dir_A):os.makedirs(dir_A)\nif not os.path.isdir(dir_B):os.makedirs(dir_B)\nname_A=os.path.basename(fasta_file_A).split(\".\")[0]\nname_B=os.path.basename(fasta_file_B).split(\".\")[0]\n\n#Copy the individual fasta files to respective directories\nos.system(\"scp \"+fasta_file_A+\" \"+dir_A)\nos.system(\"scp \"+fasta_file_B+\" \"+dir_B)\n\n#print (dir_A)\n#print (dir_B)\n#print (name_A)\n#print (name_B)\n\n#create combined fasta file\nprint (\"Creating folder \"+outdir+\"AB/ for combined features...\")\ndir_AB=outdir+\"AB/\"\nif not os.path.isdir(dir_AB):os.makedirs(dir_AB)\nprint (\"Done!\")\nprint (\"Creating combined fasta file... \")\nheader_A,fasta_A=readFastaFile(fasta_file_A)\nheader_B,fasta_B=readFastaFile(fasta_file_B)\nfasta_AB=fasta_A.strip()+fasta_B.strip()\nname_AB=name_A.split(\"_\")[0]+\"_\"+name_B.split(\"_\")[0]\n#header_AB=header_A.split(\",\")[0].split()[0]+\" , Chain AB;\"\nif header_A==header_B:\n header_AB=\">\"+name_AB+\" , Chain AB;\"\nelse:\n header_AB=header_A.split(\",\")[0].split()[0]+\"_\"+header_B.split(\",\")[0].split()[0].replace(\">\",\"\")+\" , Chain AB;\"\n#Resolve the name. Best to create name_A+\"_\"+name_B\n#name_AB=name_A.split(\"_\")[0]+\"_AB\"\n\n\n#print (name_AB)\n#print(dir_AB)\nwith open (dir_AB+name_AB+\".fasta\",\"w\") as f:\n f.write(header_AB+\"\\n\")\n f.write(fasta_AB)\nprint (\"Done! Combined fasta file called \"+dir_AB+name_AB+\".fasta created...\")\n#1. generate PSSM for combined fasta\nprint (\"Generating PSSM for combined fasta...\")\n#exitcode=os.system(\"python generatePSSM.py paths.txt \"+dir_AB+name_AB+\".fasta \"+dir_AB)\nexitcode=os.system(\"python \"+package_dir+\"generatePSSM.py \"+paths_file+\" \"+dir_AB+name_AB+\".fasta \"+dir_AB)\nif (exitcode==0):\n print (\"PSSM successfully created! \")\nelse:\n print (\"Failure! Could not generate PSSM\")\n sys.exit(1)\n#os.system(\"python generatePSSM.py paths.txt \"+dir_B+name_B+\".fasta \"+dir_B)\n\n#2. generate psipred\nprint (\"Generating PSIPRED\")\n#exitcode=os.system(\"python generatePSIPRED.py paths.txt \"+dir_A+name_A+\".fasta \"+dir_A+\" & \"+\"python generatePSIPRED.py paths.txt \"+dir_B+name_B+\".fasta \"+dir_B)\n##### separate the above code into two commands:\n#exitcode_A=os.system(\"python generatePSIPRED.py paths.txt \"+dir_A+name_A+\".fasta \"+dir_A)\n#exitcode_B=os.system(\"python generatePSIPRED.py paths.txt \"+dir_B+name_B+\".fasta \"+dir_B)\nexitcode_A=os.system(\"python \"+package_dir+\"generatePSIPRED.py \"+paths_file+\" \"+dir_A+name_A+\".fasta \"+dir_A)\nexitcode_B=os.system(\"python \"+package_dir+\"generatePSIPRED.py \"+paths_file+\" \"+dir_B+name_B+\".fasta \"+dir_B)\nif (exitcode_A==0 and exitcode_B==0):\n print (\"PSIPRED successfully created! \")\nelse:\n print (\"Failure! Could not generate PSIPRED\")\n sys.exit(2)\n#combine psipred features\nprint (\"Concatenating PSIPRED features into one file\")\nif not (os.path.isdir(dir_AB+\"psipred\")): os.makedirs(dir_AB+\"psipred\")\nexitcode=os.system(\"python \"+package_dir+\"combineSolv.py \"+dir_A+\"psipred/\"+name_A+\".solv \"+dir_B+\"psipred/\"+name_B+\".solv \"+dir_AB+\"psipred/\"+name_AB+\".solv \")\nexitcode=os.system(\"python \"+package_dir+\"combineSS1.py \"+dir_A+\"psipred/\"+name_A+\".ss \"+dir_B+\"psipred/\"+name_B+\".ss \"+dir_AB+\"psipred/\"+name_AB+\".ss \")\nexitcode=os.system(\"python \"+package_dir+\"combineSS2.py \"+dir_A+\"psipred/\"+name_A+\".ss2 \"+dir_B+\"psipred/\"+name_B+\".ss2 \"+dir_AB+\"psipred/\"+name_AB+\".ss2 \")\nif exitcode==0:\n print(\"PSIPRED features successfully concatenated into one file\")\nelse:\n print(\"Failure to concatenate PSIPRED features!\")\n sys.exit(3)\nprint (\"Generating SCRATCH features for both chains...\")\n#exitcode_A=os.system(\"python generateSS_SA.py paths.txt \"+dir_A+name_A+\".fasta \"+dir_A)\n#exitcode_B=os.system(\"python generateSS_SA.py paths.txt \"+dir_B+name_B+\".fasta \"+dir_B)\nexitcode_A=os.system(\"python \"+package_dir+\"generateSS_SA.py \"+paths_file+\" \"+dir_A+name_A+\".fasta \"+dir_A)\nexitcode_B=os.system(\"python \"+package_dir+\"generateSS_SA.py \"+paths_file+\" \"+dir_B+name_B+\".fasta \"+dir_B)\n\nif (exitcode_A==0 and exitcode_B==0):\n print (\"SCRATCH successfully done! \")\nelse:\n print (\"Failure! Could not generate SCRATCH\")\n sys.exit(4)\n\nprint (\"Concatenating SCRATCH features for both chains...\")\n\nif not (os.path.exists(dir_AB+\"ss_sa\")):os.makedirs(dir_AB+\"ss_sa\")\n\nexitcode=os.system(\"python \"+package_dir+\"combineSS_SA.py \"+dir_A+\"ss_sa/\"+name_A+\".ss_sa \"+dir_B+\"ss_sa/\"+name_B+\".ss_sa \"+dir_AB+\"ss_sa/\"+name_AB+\".ss_sa \")\nif exitcode==0:\n print(\"SCRATCH features successfully concatenated into one file\")\nelse:\n print(\"Failure to concatenate SCRATCH features!\")\n sys.exit(5)\nprint (\"All features successfully generated...\")\n#os.system(\"mv \"+dir_AB+\" \"+outdir[0:-1]+\"_AB\")\nprint (\"Moving output to directory \"+outdir)\nprint (\"Running command...\")\nprint(\"mv \"+dir_AB+\"* \"+outdir)\nos.system(\"mv \"+dir_AB+\"* \"+outdir)\n\n#print (\"Output saved in \"+outdir[0:-1]+\"_AB\")\nprint (\"Output saved in \"+outdir)\nprint (\"All alignment independent feature creation completed.\")\n#3. Now run dncon2 feature generation code. \nprint (\"Generating alignment dependent (co-evolutionary) features for the concatenated fasta file...\")\n#os.system(\"perl feature_gen_hetero.pl \"+outdir[0:-1]+\"_AB/\"+name_AB+\".fasta \"+outdir[0:-1]+\"_AB\")\n#os.system(\"perl feature_gen_hetero.pl \"+outdir+\"/\"+name_AB+\".fasta \"+outdir)\nprint (\"Running command...\")\nprint(\"perl \"+package_dir+\"feature_gen_hetero.pl \"+outdir+\"/\"+name_AB+\".fasta \"+outdir)\nos.system(\"perl \"+package_dir+\"feature_gen_hetero.pl \"+outdir+\"/\"+name_AB+\".fasta \"+outdir)\nprint (\"Removing any temporary files and folders...\")\n#os.remove(dir_A)\n#os.remove(dir_B)\n\nshutil.rmtree(dir_A)\nshutil.rmtree(dir_B)\nshutil.rmtree(dir_AB)\nprint (\"All features successfully generated and save in \"+outdir)\n","sub_path":"libs/scripts/feature_gen_hetero/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264855324","text":"\"\"\"Module with classes to work with autostorage internals.\"\"\"\n\nfrom contextlib import contextmanager\n\nfrom sqlalchemy.orm import sessionmaker\n\nfrom autostorage.database.common import get_engine\n\n\nclass _Base(object):\n \"\"\"Class to work with API internals.\"\"\"\n\n def __init__(self, database_config):\n engine = get_engine(database_config)\n self.__session_maker = sessionmaker(bind=engine)\n\n @contextmanager\n def get_session(self):\n \"\"\"Get session to commit to the database.\n\n :returns: sqlalchemy session instance.\n \"\"\"\n session = self.__session_maker()\n try:\n yield session\n except:\n session.rollback()\n raise\n finally:\n session.close()\n\n\nclass _BaseClient(object):\n \"\"\"Base class for client of internals.\"\"\"\n\n def __init__(self, base):\n self.__base = base\n\n @property\n def base(self):\n \"\"\"Property to obtain base object.\n\n :returns: instance of :class:`_Base`.\n \"\"\"\n return self.__base\n","sub_path":"src/autostorage/core/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192595102","text":"#!/usr/bin/env python\n\"\"\"\n===============================================================================\nBackground changer\n\nBasic tool which allows you to load image,\nsegment image using grabcut algorithm, extract specific object from picture.\nAfter image segmentation, you can put your segmented image on any background.\n\nSteps:\n1. Load image you want to segment/extract object e.g. face.\n2. Load image you wish to be background of segmented image.\n3. Apply GrabCut on first image a.k.a \"foreground image\"\nwith \"GrabCut\" dropdown menu.\n4. Put extracted foreground image on loaded background image\nwith \"Change Back\" dropdown menu.\n\nResult is saved as output.png in current working directory.\n\n===============================================================================\n\"\"\"\n\nfrom tkinter import Frame, Tk, BOTH, Text, Menu, END\nfrom tkinter import filedialog, messagebox\nimport os\nimport grabcut\nimport changebackground\n\n\n# flags\nfg_loaded = False\nbg_loaded = False\n\n\nclass Base(Frame):\n\n text_initialized = False\n\n def __init__(self):\n super().__init__()\n self.initialize()\n\n def initialize(self):\n\n self.master.title(\"Background changer\")\n self.pack(fill=BOTH, expand=1)\n # create menu\n menubar = Menu(self.master)\n self.master.config(menu=menubar)\n\n # add menu widgets\n file_menu = Menu(menubar)\n grabcut_menu = Menu(menubar)\n change_menu = Menu(menubar)\n\n # add file menu object\n menubar.add_cascade(label=\"File\", menu=file_menu)\n file_menu.add_command(label=\"Load foreground image\",\n command=self.on_open_fg)\n file_menu.add_command(label=\"Load background image\",\n command=self.on_open_bg)\n\n # add menu object but only if image for method is loaded\n if fg_loaded:\n menubar.add_cascade(label=\"GrabCut\", menu=grabcut_menu)\n # add command depend on flag (e.g. image_loaded = True)\n\n grabcut_menu.add_command(label='Extract object from image',\n command=self.on_grab)\n\n if bg_loaded and os.path.exists('grabcut_output.png'):\n menubar.add_cascade(label=\"Change Back\", menu=change_menu)\n change_menu.add_command(label=\"Apply extracted foreground\\\n image on loaded background image\", command=self.on_background)\n\n def on_open_fg(self):\n\n global fg_loaded, image_fg_path\n\n ftypes = [('JPG files', '*.jpg'), ('PNG files', '*.png'),\n ('All files', '*')]\n dlg = filedialog.Open(self, title=\"Select image file\",\n filetypes=ftypes)\n\n image_fg_path = dlg.show()\n # make sure user loaded something\n if len(image_fg_path) > 0:\n fg_loaded = True\n messagebox.showinfo(\"Success!\", \"Foreground image loaded\\\n successfully! You can now use use image segmentation with Grabcut!\")\n # initialize again to access grabcut\n self.initialize()\n\n def on_open_bg(self):\n\n global bg_loaded, image_bg_path\n\n ftypes = [('JPG files', '*.jpg'), ('PNG files', '*.png'),\n ('All files', '*')]\n dlg = filedialog.Open(self, title=\"Select image file\",\n filetypes=ftypes)\n\n image_bg_path = dlg.show()\n # make sure user loaded something\n if len(image_bg_path) > 0:\n bg_loaded = True\n messagebox.showinfo(\"Success\",\n \"Background image loaded successfully\")\n # initialize again to access background menu\n self.initialize()\n\n def on_grab(self):\n self.display_text(grabcut.__doc__)\n # init grabcut\n grabcut.init_grab(image_fg_path)\n self.txt.forget()\n Base.text_initialized = False\n # initialize again to access background menu\n self.initialize()\n\n def display_text(self, text):\n if not Base.text_initialized:\n # first create text\n self.txt = Text(self)\n self.txt.pack(fill=BOTH, expand=1)\n self.txt.insert(END, text)\n Base.text_initialized = True\n\n def on_background(self):\n self.display_text(changebackground.__doc__)\n ###\n changebackground.background_change('grabcut_output.png', image_bg_path)\n self.txt.forget()\n Base.text_initialized = False\n\n\ndef main():\n\n root = Tk()\n run = Base()\n root.geometry(\"700x450+300+300\")\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"background-changer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"25833030","text":"from flask_restful import Resource, reqparse\nimport jwt\nfrom application.models.models import UserModel, UserAppCode\nfrom datetime import datetime, timedelta\nfrom random import randint\nfrom flask import current_app, request\n\nclass UserLogin(Resource): \n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('login', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('password', required=True, location='json',\n help='This field cannot be blank')\n super(UserLogin, self).__init__()\n\n def post(self):\n\n args = self.parser.parse_args()\n\n current_user = UserModel.find_by_login(args['login'])\n\n if not current_user:\n return {'message': 'user not found'}, 404\n\n if UserModel.verify_hash(args['password'], current_user.password):\n access_token = jwt.encode({'sub': current_user.id,\n 'iat': datetime.utcnow(),\n 'exp': datetime.utcnow() +\n timedelta(minutes=1)},\n current_app.config['JWT_ACCESS_SECRET'])\n\n refresh_token = jwt.encode({'sub': current_user.id},\n current_app.config['JWT_REFRESH_SECRET'])\n\n return {\n 'message': 'OK',\n 'access_token': access_token.decode(),\n 'refresh_token': refresh_token.decode(),\n 'role': current_user.role\n }, 200\n else:\n return {'message': 'wrong credentials'}, 401\n\n\nclass TokenRefresh(Resource):\n\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('refresh_token', required=True,\n help='This field cannot be blank')\n super(TokenRefresh, self).__init__()\n\n def post(self):\n args = self.parser.parse_args()\n\n refresh_token = args['refresh_token']\n\n try:\n data = jwt.decode(refresh_token, verify=False)\n except (jwt.InvalidTokenError, Exception):\n return {'message': 'Invalid refresh token'}, 401\n\n app_id = data.get('app', None)\n if app_id:\n try:\n secret = current_app.config['APPS'][app_id][0]\n data = jwt.decode(refresh_token, secret + '_refresh')\n user_id = data['sub']\n access_token = jwt.encode({'sub': user_id,\n 'app': app_id,\n 'iat': datetime.utcnow(),\n 'exp': datetime.utcnow() +\n timedelta(minutes=1)},\n secret)\n\n return {'message': 'OK', 'access_token': access_token.decode()}, 200\n except (jwt.InvalidTokenError, Exception):\n current_app.logger.error('Invalid refresh token')\n return {'message': 'Invalid refresh token'}, 401\n\n try:\n data = jwt.decode(refresh_token, current_app.config['JWT_REFRESH_SECRET'])\n id = data['sub']\n\n access_token = jwt.encode({'sub': id,\n 'iat': datetime.utcnow(),\n 'exp': datetime.utcnow() +\n timedelta(minutes=1)},\n current_app.config['JWT_ACCESS_SECRET'])\n\n return {'message': 'OK', 'access_token': access_token.decode()}, 200\n\n except (jwt.InvalidTokenError, Exception):\n current_app.logger.error('Invalid refresh token')\n return {'message': 'Invalid refresh token'}, 401\n\n\nclass TokenCheck(Resource):\n\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('token', required=True,\n help='This field cannot be blank')\n super(TokenCheck, self).__init__()\n\n def get(self):\n\n args = self.parser.parse_args()\n\n token = args['token']\n\n try:\n data = jwt.decode(token, verify=False)\n except (jwt.InvalidTokenError, Exception):\n return {'message': 'Invalid refresh token'}, 401\n\n app_id = data.get('app', None)\n\n if app_id:\n secret = current_app.config['APPS'][app_id][0]\n else:\n secret = current_app.config['JWT_ACCESS_SECRET']\n\n try:\n data = jwt.decode(token, secret)\n return {'message': 'OK', 'user_id': data['sub']}, 200\n\n except jwt.ExpiredSignatureError:\n current_app.logger.error('Token Expired')\n return {'message': 'Token expired', 'expired': True}, 401\n except (jwt.InvalidTokenError, Exception):\n current_app.logger.error('Invalid token')\n return {'message': 'Invalid access token', 'expired': False}, 401\n\n\nclass AppCode(Resource):\n\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('client_id', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('redirect_uri', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('response_type', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('login', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('password', required=True, location='json',\n help='This field cannot be blank')\n super(AppCode, self).__init__()\n\n def post(self):\n current_app.logger.info(\"POST: {}\".format(request.full_path))\n\n args = self.parser.parse_args()\n if args['response_type'] != 'code':\n return {'message': 'Only code auth allowed'}, 400\n\n client_id = args['client_id']\n login = args['login']\n password = args['password']\n \n current_user = UserModel.find_by_login(login)\n if not current_user:\n return {'message': 'wrong credentials'}, 401\n\n if UserModel.verify_hash(password, current_user.password):\n client_info = current_app.config['APPS'].get(client_id, None)\n if not client_info:\n return {'message': 'application is not registred'}, 404\n\n code = randint(100, 100000)\n client_info[1] = code\n\n record = UserAppCode.find(current_user.id, client_id)\n if not record:\n UserAppCode.create_code_record(code=code,\n user_id=current_user.id,\n app_id=client_id)\n else:\n UserAppCode.update_code(current_user.id, client_id, code)\n\n return {'message': 'OK'}, 302, {'Location': 'http://{}/?code={}'.format(\n args['redirect_uri'], code)}\n # return {'message': 'OK', 'code': code}, 200\n else:\n return {'message': 'wrong credentials password'}, 401\n\n\nclass AppToken(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('client_id', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('client_secret', required=True, location='json',\n help='This field cannot be blank')\n self.parser.add_argument('code', required=True, location='json',\n help='This field cannot be blank')\n\n super(AppToken, self).__init__()\n\n def post(self):\n \n args = self.parser.parse_args()\n\n client_id = args['client_id']\n secret = args['client_secret']\n code = args['code']\n\n client_info = current_app.config['APPS'].get(client_id, None)\n if not client_info:\n return {'message': 'application is not registred'}, 404\n\n if client_info[0] != secret:\n return {'message': 'Incorrect secret'}, 401\n\n record = UserAppCode.find_by_code(code)\n if not record:\n return {'message': 'App unauthorized'}, 401\n\n access_token = jwt.encode({'sub': record.user_id,\n 'app': client_id,\n 'iat': datetime.utcnow(),\n 'exp': datetime.utcnow() +\n timedelta(minutes=1)},\n client_info[0])\n\n refresh_token = jwt.encode({'sub': record.user_id, 'app': client_id},\n client_info[0]+'_refresh')\n\n return {\n 'message': 'OK',\n 'access_token': access_token.decode(),\n 'refresh_token': refresh_token.decode()\n }, 200\n\n","sub_path":"auth_service/application/resources/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":9338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66674411","text":"import pandas as pd\r\nimport numpy as np\r\nimport nltk\r\nfrom nltk.stem.snowball import SnowballStemmer\r\nimport re\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n\r\n'''get data'''\r\ntitles1 = open('data/key.txt').read().split('\\n')\r\ndesc1 = open('data/des.txt',encoding='utf-8').read().split('===')[:-1]\r\ndesc1.pop(397)\r\ndesc1.pop(397)\r\ntitles=[]\r\ndesc=[]\r\n\r\nfor i in range(len(desc1)):\r\n\tif desc1[i] !='doanducmanh':\r\n\t\ttitles.append(titles1[i])\r\n\t\tdesc.append(desc1[i])\r\n\r\n# desc = open('newsy.txt',encoding='utf-8').read().split('===')[:-1]\r\n\r\n'''Process text'''\r\nstemmer = SnowballStemmer(\"english\")\r\n\r\n\r\ndef tokenize_and_stem(text):\r\n tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]\r\n filtered_tokens = []\r\n for token in tokens:\r\n if re.search('[a-zA-Z]', token):\r\n filtered_tokens.append(token)\r\n stems = [stemmer.stem(t) for t in filtered_tokens]\r\n return filtered_tokens\r\n return stems\r\n\r\ndef tokenize_only(text):\r\n tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]\r\n filtered_tokens = []\r\n for token in tokens:\r\n if re.search('[a-zA-Z]', token):\r\n filtered_tokens.append(token)\r\n return filtered_tokens\r\n\r\ntotalvocab_stemmed = []\r\ntotalvocab_tokenized = []\r\nfor i in desc:\r\n allwords_stemmed = tokenize_and_stem(i)\r\n totalvocab_stemmed.extend(allwords_stemmed)\r\n \r\n allwords_tokenized = tokenize_only(i)\r\n totalvocab_tokenized.extend(allwords_tokenized)\r\n\r\nvocab_frame = pd.DataFrame({'words': totalvocab_tokenized}, index = totalvocab_stemmed)\r\n\r\n\r\n\r\n'''TF-IDF'''\r\ntfidf_vectorizer = TfidfVectorizer(max_df=0.8,\r\n min_df=0.1, stop_words='english', ngram_range=(1,2))\r\ntfidf_matrix = tfidf_vectorizer.fit_transform(desc)\r\nterms = tfidf_vectorizer.get_feature_names()\r\n\r\n\r\n'''elbow'''\r\n# sumdn= []\r\n# K= range(1,30)\r\n# for k in K:\r\n# \tkm= KMeans(n_clusters=k)\r\n# \tkm.fit(tfidf_matrix)\r\n# \tsumdn.append(km.inertia_)\r\n\r\n# plt.plot(K, sumdn,'bx-')\r\n# plt.show()\r\n\r\n\r\n\r\n'''Kmean'''\r\nnum_clusters = 17\r\nkm = KMeans(n_clusters=num_clusters)\r\nkm.fit(tfidf_matrix)\r\nclusters = km.labels_.tolist()\r\n\r\n\r\nfilms = { 'title': titles, 'synopsis': desc, 'cluster': clusters }\r\n\r\nframe = pd.DataFrame(films, index = [clusters] , columns = ['title', 'cluster'])\r\n\r\n\r\n# '''Result'''\r\nprint(\"Top terms per cluster:\")\r\norder_centroids = km.cluster_centers_.argsort()[:, ::-1]\r\nfor i in range(num_clusters):\r\n \r\n \r\n print(\"Cluster %d:\" % i, end='')\r\n for title in frame.loc[i]['title'].values.tolist():\r\n print(' %s,' % title, end='')\r\n print()\r\n print()","sub_path":"SearchKey Clustering using Kmean/Kmean.py","file_name":"Kmean.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115399529","text":"from DataBase.access_model import DBAccessModel\nfrom Modules.Notes.BaseClases.data_structure import Structure\n\n\n\n\n\nclass Model(DBAccessModel):\n def __init__(self, data_base):\n super(Model, self).__init__(\n table=DBAccessModel.TableNotes,\n app_db=data_base\n )\n self.setHeaders(['Тема', 'Описание', 'Дата'])\n def getStructure(self, row):\n attrs = self.getRecord(row=row, record_type=self.PyDictRecord)\n struct = Structure(\n theme=attrs['theme'],\n description=attrs['descript'],\n db_datetime=attrs['datetime']\n )\n return struct\n\n def addRecord(self, data_structure, row=0):\n values = data_structure.asFieldsForRecord\n super(Model, self).addRecord(fields=values, row=row)\n\n def editRecord(self, data_structure, row):\n values = data_structure.asFieldsForRecord\n super(Model, self).editRecord(row=row, fields=values)\n","sub_path":"Modules/Notes/BaseClases/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561613071","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\nfrom tests import base\n\n\n# boiler plate to start and stop the server if needed\ndef setUpModule():\n base.enabledPlugins.append('slicer_cli_web')\n base.startServer()\n\n\ndef tearDownModule():\n base.stopServer()\n\n\nclass RestSlicerCLITest(base.TestCase):\n def setUp(self):\n import datetime\n\n from girder.api import rest\n from girder.plugins import worker\n from girder.plugins.worker import utils as worker_utils\n from girder.models.file import File\n from girder.models.folder import Folder\n from girder.models.item import Item\n from girder.models.user import User\n\n base.TestCase.setUp(self)\n\n self.admin = User().createUser('admin', 'passwd', 'admin', 'admin', 'a@d.min')\n self.folder = Folder().createFolder(self.admin, 'folder', parentType='user')\n self.item = Item().createItem('item', self.admin, self.folder)\n self.file = File().createFile(self.admin, self.item, 'file', 7, self.assetstore)\n\n # Mock several functions so we can fake creating jobs\n def getCurrentToken():\n return {\n '_id': str(self.admin['_id']),\n 'expires': datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n }\n\n def getWorkerApiUrl():\n return '/api/v1'\n\n self._origRestGetCurrentToken = rest.getCurrentToken\n self._origRestGetApiUrl = rest.getApiUrl\n self._origWorkerGetWorkerApiUrl = worker.getWorkerApiUrl\n\n rest.getCurrentToken = getCurrentToken\n rest.getApiUrl = lambda x: '/api/v1'\n rest.setCurrentUser(self.admin)\n worker.getWorkerApiUrl = worker_utils.getWorkerApiUrl = getWorkerApiUrl\n\n def tearDown(self):\n from girder.api import rest\n from girder.plugins import worker\n from girder.plugins.worker import utils as worker_utils\n\n rest.getCurrentToken = self._origRestGetCurrentToken\n rest.getApiUrl = self._origRestGetApiUrl\n worker.getWorkerApiUrl = worker_utils.getWorkerApiUrl = self._origWorkerGetWorkerApiUrl\n base.TestCase.tearDown(self)\n\n def test_genHandlerToRunDockerCLI(self):\n from girder.plugins.slicer_cli_web import docker_resource\n from girder.plugins.slicer_cli_web import rest_slicer_cli\n\n xmlpath = os.path.join(os.path.dirname(__file__), 'data', 'ExampleSpec.xml')\n cliXML = open(xmlpath, 'rb').read()\n resource = docker_resource.DockerResource('test')\n handlerFunc = rest_slicer_cli.genHandlerToRunDockerCLI(\n 'dockerImage', 'data', cliXML, resource)\n self.assertIsNotNone(handlerFunc)\n\n job = handlerFunc(params={\n 'inputImageFile_girderFileId': str(self.file['_id']),\n 'secondImageFile_girderFileId': str(self.file['_id']),\n 'outputStainImageFile_1_girderFolderId': str(self.folder['_id']),\n 'outputStainImageFile_1_name': 'sample1.png',\n 'outputStainImageFile_2_girderFolderId': str(self.folder['_id']),\n 'outputStainImageFile_2_name': 'sample2.png',\n 'stainColor_1': '[0.5, 0.5, 0.5]',\n 'stainColor_2': '[0.2, 0.3, 0.4]',\n 'returnparameterfile_girderFolderId': str(self.folder['_id']),\n 'returnparameterfile_name': 'output.data',\n })\n self.assertHasKeys(\n job['kwargs']['inputs'],\n ['inputImageFile', 'stainColor_1', 'stainColor_2'])\n self.assertEqual(job['kwargs']['inputs']['inputImageFile']['id'], str(self.file['_id']))\n self.assertEqual(job['kwargs']['inputs']['stainColor_1']['data'], '[0.5, 0.5, 0.5]')\n self.assertEqual(job['kwargs']['inputs']['stainColor_1']['type'], 'number_list')\n self.assertHasKeys(\n job['kwargs']['outputs'],\n ['outputStainImageFile_1', 'outputStainImageFile_2', 'returnparameterfile'])\n self.assertEqual(len(job['kwargs']['task']['inputs']), 5)\n self.assertEqual(len(job['kwargs']['task']['outputs']), 3)\n","sub_path":"packages/slicer_cli_web-pv/plugin_tests/rest_slicer_cli_test.py","file_name":"rest_slicer_cli_test.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407584429","text":"#!/usr/bin/python3\n#Aim : Splits the overall data into years and months\n#Author : Ravisutha Sakrepatna Srinivasamurthy\n#Project: Analysis of Chicago Crime Data\n\nimport os\nimport pandas as pd\n\nclass Splitter:\n \"\"\"Splits given data into seperate files\"\"\"\n\n def __init__(self, data_path, debug=False):\n \"\"\" Get data_path and output path. \"\"\"\n\n #Get the path for the dataset and list of output files\n self.dataset_path = data_path\n self.debug = debug\n self._init_df ()\n\n def _print (self, arg):#Split the data into years\n \"\"\" Print only if debug mode is ON. \"\"\"\n \n if (self.debug != False):\n print (arg)\n\n def _init_df (self):\n \"\"\" Initialize dataframe. \"\"\"\n \n df = pd.read_csv (self.dataset_path)\n \n #df['date'] = pd.to_datetime (df['Date'])\n #df['date'] = pd.to_datetime (df['CREATION DATE'])\n #df['date'] = pd.to_datetime (df['Creation Date'])\n df['date'] = pd.to_datetime (df['DATE SERVICE REQUEST WAS RECEIVED'])\n \n self.df = df\n \n print (self.df.head ())\n \n def data_split_year (self, output_path, year):\n \"\"\"Splits data according to years. \n Inputs: Ouput path and year.\"\"\"\n \n df = self.df\n \n df = df[df.date.dt.year == year]\n \n print (\"For year {}:\".format (year))\n print (df.head ())\n print (df.tail ())#Split the data into years\n \n df.to_csv (output_path)\n \n def data_split_months (self, output_path, year, month):\n \"\"\"Splits data according to months. \n Input: Ouput path and year.\"\"\"\n \n df = self.df\n \n df = df[(df.date.dt.year == year) & (df.date.dt.month == month)]\n \n print (\"For year {}:\".format (year))\n print (df.head ())\n print (df.tail ())\n \n df.to_csv (output_path, index=False)\n\n \ndef main ():\n \"\"\" Execution starts. \"\"\"\n \n #if (__name__ == '_main__'):\n \n #data_path = \"../../Data/Total_Data/total_crime.csv\"\n #data_path = \"../../Data/Total_Data/sanitation_community.csv\"\n #data_path = \"../../Data/Total_Data/vehicles.csv\"\n #data_path = \"../../Data/Total_Data/pot_holes.csv\"\n #data_path = \"../../Data/Total_Data/trees.csv\"\n data_path = \"../../Data/Total_Data/vacant.csv\"\n \n split = Splitter (data_path)\n \n for year in range (2001, 2016):\n #Create path string\n directory = \"../../Data/\" + str(year) + \"/\"\n #file = \"sanity_\" + str (year) + \".csv\"\n #file = \"vehicles_\" + str (year) + \".csv\"\n #file = \"lights_one_\" + str (year) + \".csv\"\n #file = \"pot_holes_\" + str (year) + \".csv\"\n #file = \"lights_alley_\" + str (year) + \".csv\"\n #file = \"trees_\" + str (year) + \".csv\"\n file = \"vacant_\" + str (year) + \".csv\"\n \n #Try making a directory\n try:\n os.mkdir (directory)\n except FileExistsError:\n pass\n \n output_path = directory + file\n \n #Split the data into years\n split.data_split_year (output_path, year)\n \n for month in range (1, 13):\n sub_directory = directory + str(month) + \"/\"\n \n #Try making a directory\n try:\n os.mkdir (sub_directory)\n except FileExistsError:\n pass\n \n #file = \"sanity_\" + str (year) + \"_\" + str (month) + \".csv\"\n #file = \"vehicles_\" + str (year) + \"_\" + str (month) + \".csv\"\n #file = \"lights_one_\" + str (year) + \"_\" + str (month) + \".csv\"\n #file = \"pot_holes_\" + str (year) + \"_\" + str (month) + \".csv\"\n #file = \"lights_alley_\" + str (year) + \"_\" + str (month) + \".csv\"\n #file = \"trees_\" + str (year) + \"_\" + str (month) + \".csv\"\n file = \"vacant_\" + str (year) + \"_\" + str (month) + \".csv\"\n output_path = sub_directory + file\n \n #Split the data into years\n split.data_split_months (output_path, year, month)\nmain ()\n","sub_path":"Code/PreProcess/splitter.py","file_name":"splitter.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"410491050","text":"from sqlalchemy.ext.automap import automap_base\r\nfrom adbk.database import engine, metadata\r\nfrom sqlalchemy.orm import sessionmaker\r\nimport csv\r\n\r\nmetadata.reflect(engine, only=['abonents', 'mails', 'phones'])\r\nSessionloc = sessionmaker(autocommit=True, autoflush=False, bind=engine)\r\n\r\nBase = automap_base(metadata=metadata)\r\nBase.prepare()\r\n\r\nAbonent, Phone, Mail = Base.classes.abonents, Base.classes.phones, \\\r\n Base.classes.mails\r\n\r\nwith open('99-contacts-addressees.csv', encoding='utf-8') as f:\r\n reader = csv.reader(f, delimiter=';')\r\n next(reader)\r\n s = Sessionloc()\r\n objs = []\r\n for row in reader:\r\n obj = Abonent(\r\n name=row[0],\r\n sex=row[1],\r\n live=row[2],\r\n photo=row[3],\r\n birth=row[4])\r\n objs.append(obj)\r\n s.bulk_save_objects(objs)\r\n\r\nwith open('99-contacts-phones.csv', encoding='utf-8') as f:\r\n reader = csv.reader(f, delimiter=';')\r\n next(reader)\r\n s = Sessionloc()\r\n objs = []\r\n for row in reader:\r\n obj = Phone(ab_id=row[0], number=row[1], type=row[2])\r\n objs.append(obj)\r\n s.bulk_save_objects(objs)\r\n\r\nwith open('99-contacts-mails.csv', encoding='utf-8') as f:\r\n reader = csv.reader(f, delimiter=';')\r\n next(reader)\r\n s = Sessionloc()\r\n objs = []\r\n for row in reader:\r\n obj = Mail(ab_id=row[0], address=row[1], type=row[2])\r\n objs.append(obj)\r\n s.bulk_save_objects(objs)\r\n","sub_path":"import_script.py","file_name":"import_script.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"43422215","text":"#!/usr/bin/python3\n\n# @Project = step_LeetCode\n# @File : 1024_Video_Stitching\n# @Author : TCY\n# @Time : 2019/4/24 16:09\n# @Email : tangcaiyuan@hust.edu.cn\n# @Software: PyCharm\n\n\nclass Solution(object):\n def videoStitching(self, clips, T):\n \"\"\"\n :type clips: List[List[int]]\n :type T: int\n :rtype: int\n \"\"\"\n \"\"\"贪心算法。当前覆盖了[0,now],找一个k,使得clips[k][0]<=now,并且使clips[k][1]尽可能大\"\"\"\n \"\"\"注意一点,tmp初始化为None,因此可能没有tmp[1];其次,对循环内完成查找和循环外完成查找都需要判定\"\"\"\n result = []\n now = 0\n while now < T:\n tmp = None\n for i in clips:\n if i[0] <= now:\n if tmp == None:\n tmp = i\n else:\n if tmp[1] < i[1]:\n tmp = i\n if now >= T:\n return len(result)\n else:\n if tmp == None:\n return -1\n else:\n if now < tmp[1]:\n now = tmp[1]\n result.append(tmp)\n else:\n return -1\n if now < T:\n return -1\n else:\n return len(result)\n","sub_path":"1024_Video_Stitching.py","file_name":"1024_Video_Stitching.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423386211","text":"#================================================\n# Steamworks For Python\n#================================================\nfrom ctypes import *\nimport sys, os\n\n# User status\n#------------------------------------------------\nFriendFlags = { # regular friend\n 'None': 0x00,\n 'Blocked': 0x01,\n 'FriendshipRequested': 0x02,\n 'Immediate': 0x04,\n 'ClanMember': 0x08,\n 'OnGameServer': 0x10,\n 'RequestingFriendship': 0x80,\n 'RequestingInfo': 0x100,\n 'Ignored': 0x200,\n 'IgnoredFriend': 0x400,\n 'Suggested': 0x800,\n 'All': 0xFFFF,\n }\n\n# Main Steam Class, obviously\n#------------------------------------------------\nclass Steam:\n\t# Set some basic variables for the Steam class\n\tcdll = None\n\twarn = False\n\tloaded = False\n\n\t# Initialize Steam\n\t@staticmethod\n\tdef Init():\n\t\tos.environ['LD_LIBRARY_PATH'] = os.getcwd()\n\t\t# Check system architecture\n\t\tif sys.maxsize > 2**32 is False:\n\t\t\tOS_BIT = '32bits'\n\t\telse:\n\t\t\tOS_BIT = '64bits'\n\t\t# Loading SteamPy API for Linux\n\t\tif sys.platform == 'linux' or sys.platform == 'linux2':\n\t\t\tSteam.cdll = CDLL(os.path.join(os.getcwd(), \"SteamworksPy.so\"))\n\t\t\tprint(\"SteamworksPy loaded for Linux\")\n\t\t\tSteam.loaded = True\n\t\t# Loading SteamPy API for Mac\n\t\telif sys.platform == 'darwin':\n\t\t\tSteam.cdll = CDLL(os.path.join(os.getcwd(), \"SteamworksPy.dylib\" ))\n\t\t\tprint(\"SteamworksPy loaded for Mac\")\n\t\t\tSteam.loaded = True\n\t\t# Loading Steamworks API for Windows\n\t\telif sys.platform == 'win32':\n\t\t\t# Check Windows architecture\n\t\t\tif OS_BIT == '32bits':\n\t\t\t\tSteam.cdll = CDLL(os.path.join(os.getcwd(), \"SteamworksPy.dll\"))\n\t\t\telse:\n\t\t\t\tSteam.cdll = CDLL(os.path.join(os.getcwd(), \"SteamworksPy64.dll\"))\n\t\t\tprint(\"SteamworksPy loaded for Windows\")\n\t\t\tSteam.loaded = True\n\t\t# Unrecognized platform, warn user and do not load Steam API\n\t\telse:\n\t\t\tprint(\"SteamworksPy failed to load (unsupported platform!\")\n\t\t\tSteam.warn = True\n\t\t\treturn\n\n\t\t# Set restype for initialization\n\t\tSteam.cdll.IsSteamRunning.restype = c_bool\n\t\t# Check that Steam is running\n\t\tif Steam.cdll.IsSteamRunning():\n\t\t\tprint(\"Steam is running!\")\n\t\telse:\n\t\t\tprint(\"Steam is not running!\")\n\n\t\t# Boot up the Steam API\n\t\tSteam.cdll.SteamInit()\n\t\t# Set restype for Apps functions\n\t\tSteam.cdll.GetDlcCount.restype = int\n\t\tSteam.cdll.IsDlcInstalled.restype = bool\n\t\tSteam.cdll.RequestAppProofOfPurchaseKey.restype = c_char_p\n\t\t# Set restype for Friends functions\n\t\tSteam.cdll.GetFriendCount.restype = int\n\t\tSteam.cdll.GetPersonaName.restype = c_char_p\n\t\tSteam.cdll.GetPersonaState.restype = int\n\t\tSteam.cdll.ActivateGameOverlay.restype = c_char_p\n\t\t# Set restype for Music functions\n\t\tSteam.cdll.MusicIsEnabled.restype = bool\n\t\tSteam.cdll.MusicIsPlaying.restype = bool\n\t\tSteam.cdll.MusicGetVolume.restype = c_float\n\t\tSteam.cdll.MusicPause.restype = bool\n\t\tSteam.cdll.MusicPlay.restype = bool\n\t\tSteam.cdll.MusicPlayNext.restype = bool\n\t\tSteam.cdll.MusicPlayPrev.restype = bool\n\t\tSteam.cdll.MusicSetVolume.restype = c_float\n\t\t# Set restype for User functions\t\t\n\t\tSteam.cdll.GetSteamID.restype = int\n\t\tSteam.cdll.GetPlayerSteamLevel.restype = int\n\t\t# Set restype for User Statistic functions\n\t\tSteam.cdll.GetAchievement.restype = bool\n\t\tSteam.cdll.GetStatInt.restype = int\n\t\tSteam.cdll.GetStatFloat.restype = c_float\n\t\tSteam.cdll.ResetAllStats.restype = bool\n\t\tSteam.cdll.RequestCurrentStats.restype = bool\n\t\tSteam.cdll.SetAchievement.restype = bool\n\t\tSteam.cdll.SetStatInt.restype = bool\n\t\tSteam.cdll.SetStatFloat.restype = bool\n\t\tSteam.cdll.StoreStats.restype = bool\n\t\tSteam.cdll.ClearAchievement.restype = bool\n\t\t# Set restype for Utilities functions\n\t\tSteam.cdll.GetCurrentBatteryPower.restype = int\n\t\tSteam.cdll.GetIPCountry.restype = c_char_p\n\t\tSteam.cdll.GetSecondsSinceAppActive.restype = int\n\t\tSteam.cdll.GetSecondsSinceComputerActive.restype = int\n\t\tSteam.cdll.GetServerRealTime.restype = int\n\t\tSteam.cdll.IsOverlayEnabled.restype = bool\n\t\tSteam.cdll.IsSteamRunningInVR.restype = bool\n\t\tSteam.cdll.GetSteamUILanguage.restype = c_char_p\n\t\tSteam.cdll.GetAppID.restype = int\n\n\t@staticmethod\n\tdef Call(method):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn method()\n\n# Class for Steam Apps\n#------------------------------------------------\nclass SteamApps:\n\n\t@staticmethod\n\tdef GetDlcCount():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetDlcCount()\n\n\t@staticmethod\n\tdef IsDlcInstalled():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.IsDlcInstalled()\n\n\t@staticmethod\n\tdef RequestAppProofOfPurchaseKey():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.RequestAppProofOfPurchaseKey()\n\n# Class for Steam Friends\n#------------------------------------------------\nclass SteamFriends:\n\n\t@staticmethod\n\tdef GetFriendCount(flag=FriendFlags['All']):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetFriendCount(flag)\n\n\t@staticmethod\n\tdef GetPlayerName():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetPersonaName()\n\n\t@staticmethod\n\tdef GetPlayerState():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetPersonaState()\n\n\t@staticmethod\n\tdef ActivateGameOverlay():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.ActivateGameOverlay()\t\t\t\n\n# Class for Steam Music\nclass SteamMusic:\n\n\t@staticmethod\n\tdef MusicIsEnabled():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicIsEnabled()\n\n\t@staticmethod\n\tdef MusicIsPlaying():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicIsPlaying()\n\n\t@staticmethod\n\tdef MusicGetVolume():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicGetVolume()\n\n\t@staticmethod\n\tdef MusicPause():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicPause()\n\n\t@staticmethod\n\tdef MusicPlay():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicPlay()\n\n\t@staticmethod\n\tdef MusicPlayNext():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicPlayNext()\n\n\t@staticmethod\n\tdef MusicPlayPrev():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicPlayPrev()\n\n\t@staticmethod\n\tdef MusicSetVolume(value):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.MusicSetVolume(value)\n\n# Class for Steam Users\n#------------------------------------------------\nclass SteamUser:\n\n\t@staticmethod\n\tdef GetPlayerID():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetSteamID()\n\n\t@staticmethod\n\tdef GetPlayerSteamLevel():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetPlayerSteamLevel()\n\n# Class for Steam User Statistics\n#------------------------------------------------\nclass SteamUserStats:\n\n\t@staticmethod\n\tdef GetAchievement(name):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetAchievement(name)\n\n\t@staticmethod\n\tdef GetStatFloat(name):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetStatFloat(name)\n\n\t@staticmethod\n\tdef GetStatInt(name):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetStatInt(name)\n\n\t@staticmethod\n\tdef ResetAllStats(achievesToo):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.ResetAllStats(achievesToo)\n\n\t@staticmethod\n\tdef RequestCurrentStats():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.RequestCurrentStats()\n\n\t@staticmethod\n\tdef SetAchievement(name):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.SetAchievement(name)\n\n\t@staticmethod\n\tdef SetStat(name, value):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\tif isinstance(value, float):\n\t\t\t\treturn Steam.cdll.SetStatFloat(name, value)\n\t\t\telif isinstance(value, int):\n\t\t\t\treturn Steam.cdll.SetStatInt(name, value)\n\t\t\telse:\n\t\t\t\traise Exception(\"SteamUserStats: SetStat value can be only int or float.\")\n\n\t@staticmethod\n\tdef StoreStats():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.StoreStats()\n\n\t@staticmethod\n\tdef ClearAchievement(name):\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.ClearAchievement(name)\n\n# Class for Steam Utilities\n#------------------------------------------------\nclass SteamUtilities:\n\t\n\t@staticmethod\n\tdef GetCurrentBatteryPower():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetCurrentBatteryPower()\n\n\t@staticmethod\n\tdef GetIPCountry():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetIPCountry()\n\n\t@staticmethod\n\tdef GetSecondsSinceAppActive():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetSecondsSinceAppActive()\n\n\t@staticmethod\n\tdef GetSecondsSinceComputerActive():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetSecondsSinceComputerActive()\n\n\t@staticmethod\n\tdef GetServerRealTime():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetServerRealTime()\n\n\t@staticmethod\n\tdef IsOverlayEnabled():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.IsOverlayEnabled()\n\n\t@staticmethod\n\tdef IsSteamRunningInVR():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.IsSteamRunningInVR()\n\n\t@staticmethod\n\tdef GetSteamUILanguage():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetSteamUILanguage()\n\n\t@staticmethod\n\tdef GetAppID():\n\t\tif not Steam.cdll and not Steam.warn:\n\t\t\tprint(\"Steam is not loaded\")\n\t\t\tSteam.warn = True\n\t\t\treturn False\n\t\telse:\n\t\t\treturn Steam.cdll.GetAppID()","sub_path":"Tests/steamworks.py","file_name":"steamworks.py","file_ext":"py","file_size_in_byte":11884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"271180878","text":"\n### Island: O'Reilly. Problem: Median\n\nfrom typing import List\n\ndef checkio(data: List[int]): # -> [int, float]\n def Qsort(data):\n data_copy = data\n pk = 0\n i = 1\n j = len(data) - 1\n pk_switch = 0\n # print(\"Beginning of Qsort =\", data[0])\n while(i < j and i <= len(data) and j > pk):\n while(data[i] <= data[pk] and i < len(data)-1):\n i = i+1;\n while(data[j] >= data[pk] and j > pk+1):\n j = j-1;\n if(i < j):\n data_copy[i], data_copy[j] = data[j], data[i];\n if (i >= j and data_copy[pk] > data_copy[j]):\n data_copy[pk], data_copy[j] = data_copy[j], data_copy[pk];\n pk_switch = 1\n if(j > 1):\n data_copy[:j] = Qsort(data_copy[:j])\n if(j < len(data) - 1):\n if(pk_switch == 1):\n data_copy[j+1:] = Qsort(data_copy[j+1:])\n else:\n data_copy[j:] = Qsort(data_copy[j:])\n return data_copy\n \n sorted_data = Qsort(data)\n item_num = len(sorted_data)\n index = int(item_num/2)\n if(item_num % 2 == 0):\n # print(\"even length, ans =\", (sorted_data[index - 1] + sorted_data[index]) / 2)\n # for item in sorted_data:\n # print(item, sep='', end=' ')\n return (sorted_data[index - 1] + sorted_data[index]) / 2\n else:\n return sorted_data[index]\n\n\n#These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n print(\"Example:\")\n print(checkio([1, 2, 3, 4, 5]))\n\n assert checkio([1, 2, 3, 4, 5]) == 3, \"Sorted list\"\n assert checkio([3, 1, 2, 5, 3]) == 3, \"Not sorted list\"\n assert checkio([1, 300, 2, 200, 1]) == 2, \"It's not an average\"\n assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, \"Even length\"\n print(\"Start the long test\")\n assert checkio(list(range(1000000))) == 499999.5, \"Long.\"\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")","sub_path":"find_median_using_QuickSort.py","file_name":"find_median_using_QuickSort.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423360447","text":"import pandas as pd\nimport requests\nimport json\n\n# If csv is detected, read & extract tracking id\ntry:\n df = open(\"~/Desktop/郵便追跡.csv\").read().replace('\"', '').replace(\"'\", \"\")\n tracking_ids = [t for t in df.split('\\n')]\n print(\"郵便追跡.csv を使いま���!\")\nexcept:\n print(\"郵便追跡.csv 見つかりませんでした、、\")\n # If xlsx is detected, read & extract tracking id\n try:\n df = pd.read_excel(\n \"~/Desktop/郵便追跡.xlsx\",\n sheet_name=None,\n engine='openpyxl',\n header=None,\n index_col=None\n )\n print(\"郵便追跡.xlsx を使います!\")\n df = df[list(df.keys())[0]][13]\n df = df.apply(lambda x: x.replace('\"', ''))\n df = df.apply(lambda x: x.replace(\"'\", \"\"))\n tracking_ids = df.values\n except:\n print(\"郵便追跡.xlsx 見つかりませんでした、、\")\n\n# Get data from API\nstatus = []\nprint(f\"{len(tracking_ids)}件読み込み完了!\")\nprint(\"追跡開始!\")\nprint(\"-----------------------------------------\")\nfor i in tracking_ids:\n try:\n print(f\"Tracking id: {i}\", end=\"\\t\")\n r = requests.get('http://nanoappli.com/tracking/api/{}.json?_=1615855517639'.format(i))\n status_returned = json.loads(r.text)[\"status\"]\n print(f\"status: {status_returned}\")\n except:\n print(\" Failed!!\")\n status_returned = \"\"\n finally:\n status.append(status_returned)\n\n# Output to 郵便追跡_結果.csv\nprint(\"-----------------------------------------\")\noutput_df = pd.DataFrame({\"追跡ID\": tracking_ids, \"追跡結果\": status})\noutput_df.to_csv(\"~/Desktop/郵便追跡_結果.csv\", index=False)\nprint(\"追跡終了!「郵便追跡_結果.csv」をご確認ください!\")\n","sub_path":"start_track.py","file_name":"start_track.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"23114994","text":"import numpy as np\nimport re \ndelim=[',',';','(',')','{','}','[',']','#','<','>',' ']\noper=['+','-','*','/','%','=','!']\ndefkey=[\"int\",\"float\",\"char\",\"double\",\"bool\"]\nothkey=[\"void\",\"extern\",\"unsigned\",\"goto\",\"static\",\"class\",\"struct\",\"for\",\"if\",\"else\",\"return\",\"register\",\"long\",\"while\",\"do\",\"main\"]\npredirect=[\"include\",\"define\",\"getch\"]\nheader=[\"stdio.h\",\"conio.h\",\"malloc.h\",\"process.h\",\"string.h\",\"ctype.h\"]\ndef ishd(w):\n for h in header:\n if h in w:\n wf.write(h+'->Header\\n')\ndef iskey(w):\n for h in predirect:\n if h in w:\n wf.write(h+'->Keyword\\n')\n for h in othkey:\n if h in w:\n wf.write(h+'->Keyword\\n')\ndef stdt(w):\n for d in defkey:\n if d in w:\n wf.write(d+'->DataType Declaration\\n')\n for l in line.split()[1:]:\n vr='[A-Za-z_][A-Za-z0-9_]*'\n match=re.findall(vr,l)\n for m in match:\n varbls.append(m)\ndef isdt(w):\n for v in varbls:\n if v==w:\n wf.write(v+'->Variable\\n')\ndef iscon(w):\n cr='\\d+(?:\\.\\d+)?|\"[A-z0-9 ]+\"'\n match=re.findall(cr,w)\n for m in match:\n wf.write(m+'->Constant Value\\n')\nvarbls=[]\ncf=open('code.txt','r')\nwf=open('output.txt','a')\nflag=0\nfor line in cf:\n wf.write(line+'\\n')\n lxx=line.split()\n for lx in lxx:\n rest=lx[0]\n for l in lx:\n for d in delim:\n if d in l:\n iscon(rest)\n wf.write(d+'->Delimiter\\n')\n rest=''\n flag=1\n continue\n for d in oper:\n if d in l:\n iscon(rest)\n wf.write(d+'->Operator\\n')\n rest=''\n flag=1\n continue\n if flag==1:\n flag=0\n continue\n else:\n isdt(rest)\n rest=rest+l\n ishd(rest)\n iskey(rest)\n stdt(rest)\n isdt(rest)\n wf.write('------ ------ ------ ------\\n\\n')\nwf.close()\n\n","sub_path":"lextest_final-writetofile.py","file_name":"lextest_final-writetofile.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381484445","text":"from .... import utils\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, TimeDistributed\nfrom keras.utils import to_categorical\nfrom keras.callbacks import ModelCheckpoint\nimport numpy as np\nimport json\nimport requests\nimport keras\nimport os\n\nglove = utils.load_vectorizer.load_glove('tagnews/data/glove.6B.50d.txt')\nner = utils.load_data.load_ner_data('tagnews/data/')\n\nos.chdir(os.path.split(__file__)[0])\n\nwith open('training.txt', encoding='utf-8') as f:\n training_data = f.read()\n\ntraining_df = pd.DataFrame([x.split() for x in training_data.split('\\n')], columns=['word', 'tag'])\ntraining_df.iloc[:,1] = training_df.iloc[:,1].apply(int)\ntraining_df['all_tags'] = 'NA'\n\nner = training_df # pd.concat([training_df, ner]).reset_in dex(drop=True)\nner = ner[['word', 'all_tags', 'tag']]\n\nner = pd.concat([ner,\n pd.DataFrame(ner['word'].str[0].str.isupper().values),\n pd.DataFrame(glove.loc[ner['word'].str.lower()].values)],\n axis='columns')\nner.fillna(value=0.0, inplace=True)\n\ndata_dim = 51\ntimesteps = 25 # only during training, testing can take arbitrary length.\nnum_classes = 2\n\ntrain_val_split = int(19 * ner.shape[0] / 20.)\n\nner_train_idxs = range(0, train_val_split - timesteps, timesteps)\nx_train = np.array([ner.iloc[i:i+timesteps, 3:].values\n for i in ner_train_idxs])\ny_train = np.array([to_categorical(ner.iloc[i:i+timesteps, 2].values, 2)\n for i in ner_train_idxs])\n\nner_val_idxs = range(train_val_split, ner.shape[0] - timesteps, timesteps)\nx_val = np.array([ner.iloc[i:i+timesteps, 3:].values\n for i in ner_val_idxs])\ny_val = np.array([to_categorical(ner.iloc[i:i+timesteps, 2].values, 2)\n for i in ner_val_idxs])\n\nmodel = Sequential()\nmodel.add(LSTM(32, return_sequences=True, input_shape=(None, data_dim)))\nmodel.add(LSTM(8, return_sequences=True))\nmodel.add(TimeDistributed(Dense(2, activation='softmax')))\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['categorical_accuracy'])\nprint(model.summary(100))\n\ncheckpointer = ModelCheckpoint(filepath='./saved/weights-{epoch:02d}.hdf5',\n monitor='val_categorical_accuracy',\n verbose=1,\n save_best_only=True)\n\nclass OurAUC(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs={}):\n # Go to https://geo-extract-tester.herokuapp.com/ and download\n # the validation data (validation.txt).\n with open('validation.txt', encoding='utf-8') as f:\n s = f.read()\n\n gloved_data = pd.concat([pd.DataFrame([[w[0].isupper()] for w in s.split('\\n') if w]),\n glove.loc[[w for w in s.split('\\n') if w]].fillna(0).reset_index(drop=True)],\n axis='columns')\n\n glove_time_size = 100\n preds_batched = []\n i = 0\n while gloved_data[i:i+glove_time_size].size:\n preds_batched.append(model.predict(np.expand_dims(gloved_data[i:i+glove_time_size],\n axis=0))[0][:,1])\n i += glove_time_size\n\n with open('guesses-{epoch:02d}.txt'.format(epoch=epoch), 'w') as f:\n for prob in [p for pred in preds_batched for p in pred]:\n f.write(str(prob) + '\\n')\n\n with open('guesses-{epoch:02d}.txt'.format(epoch=epoch), 'rb') as f:\n url = 'https://geo-extract-tester.herokuapp.com/api/score'\n r = requests.post(url, files={'file': f})\n print('AUC: {:.5f}'.format(json.loads(r.text)['auc']))\n\n os.remove('guesses-{epoch:02d}.txt'.format(epoch=epoch))\n\nour_auc = OurAUC()\n\nmodel.fit(x_train, y_train,\n epochs=20,\n validation_data=(x_val, y_val),\n callbacks=[checkpointer, our_auc],\n verbose=2)\n\nidx = slice(501, 550)\nprint(pd.concat([ner.iloc[idx, :3].reset_index(drop=True),\n pd.DataFrame(model.predict(np.expand_dims(ner.iloc[idx, 3:].values, 0))[0][:, 1:],\n columns=['prob_geloc'])],\n axis='columns'))\n","sub_path":"lib/tagnews/geoloc/models/lstm/save_model.py","file_name":"save_model.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"253289992","text":"\"\"\"\nПолучить телефон клиента и отправить ему СМС\n\n\"\"\"\nfrom smsc_api import *\nimport time\nimport sqlite3 as s3\n\n'''\n#smsc = SMSC()\n\n#s = smsc.send_sms('7926xxx', 'test', id=12346, sender='sms')\n#print(s)\n#status = smsc.get_status(12346, '7926xxx', all=1)\n#print(status)\n\n['1', '1537938113', '0', '1537938112', '7926xxx', '2.20', 'SMSC.RU~sms', 'Доставлено', 'test,0']\n'''\n\n# db_path = './project_files/gp10mo.db'\n\n\ndef put_data_to_db(number, name):\n \"\"\"\n Добавление имени и номера в БД\n :param number:\n :param name:\n :return:\n \"\"\"\n db_path = './project_files/gp10mo.db'\n con = s3.connect(db_path)\n\n input_query = 'INSERT INTO clients(phone_number, name) VALUES (?, ?)' # добавление данных\n verifying_query = 'SELECT EXISTS(SELECT phone_number FROM clients WHERE phone_number=? )' # проверка присутствия\n cur = con.cursor()\n verify_db_presence = cur.execute(verifying_query, (number,)) # наличие номера в БД\n verify_db_presence = verify_db_presence.fetchone()[0]\n # Если номера нет в базе добавляем его\n if not verify_db_presence:\n cur.execute(input_query, (number, name))\n con.commit()\n client_id = con.execute('SELECT LAST_INSERT_ROWID()')\n # получаем номер последней записи\n client_id = client_id.fetchone()[0]\n # добавляем id клиента в Статус\n cur.execute('INSERT INTO client_status(client_status, client_id) VALUES (?, ?)', ('New', client_id))\n print('number {} was added'.format(number))\n con.commit()\n else:\n print('Number exist')\n con.close()\n\n\ndef get_number_from_db():\n \"\"\"\n получить номер из БД со статусом New\n :return: список кортежей номер, имя\n \"\"\"\n # запрос к БД\n con = s3.connect('./project_files/gp10mo.db')\n cur = con.cursor()\n numbers = cur.execute('select phone_number, name from clients as c left join client_status as s on c.id = s.client_id where s.client_status = \"New\"')\n numbers = numbers.fetchall()\n print(numbers)\n con.close()\n return numbers\n\n\ndef check_status():\n \"\"\"\n Проверка статуса\n :return:\n \"\"\"\n db_path = './project_files/gp10mo.db'\n con = s3.connect(db_path)\n c = con.cursor()\n n = c.execute('select exists(select status from status where status=\"New\" )')\n m = n.fetchone()[0]\n if m:\n for i in get_number_from_db():\n print(i)\n else:\n print('not found')\n\n\ndef send_sms(num):\n \"\"\"\n\n :param num:\n :return:\n \"\"\"\n sms = SMSC()\n message = sms_message('ask_email')\n # number = get_number_from_db() uncomment this\n number = num # comment this\n sms_id = 'id' + number\n sms.send_sms(number, message, id=sms_id, sender='sms')\n #print(s)\n time.sleep(5)\n status = sms.get_status(sms_id, number)\n print(status)\n #full_status = sms.get_status(sms_id, number, all=1)\n #print(full_status)\n\n# передаваемые параметры: phone, mes, id, to для входящих sms и phone,\n# status, time, ts, id для статусов, метод POST\n#send_sms('79268401046')\n\n\ndef sms_message(key):\n \"\"\"\n Возаращает один из ответов в диалоге с клиентом\n :param key: str dict key\n :return: str dict value\n \"\"\"\n messages = {\n 'welcome': '1',\n 'order_1': 'Город',\n 'order_2': 'Ф1 Ю2',\n 'erunda_1': 'ерунда1',\n 'erunda_2': 'ерунда2',\n 'msk_order': 'Мск 1 или 2',\n 'nn_order': 'НН 1 или 2',\n 'ask_city': 'Город -> 79037676877',\n 'ask_full_address': 'Адр',\n 'ask_email': 'Email',\n 'ask_full_name': 'ФИО -> 79037676877',\n 'aks_company_details': 'Рекв -> 79037676877',\n 'thnks_1': 'Thnks!-1',\n 'thnks_2': 'Thnks!-2',\n 'shipping_to_N': 'N -> 79037676877',\n 'no_cdek_in_city': 'СДЭК нет'\n }\n\n return messages.get(key)\n\n\ndef get_answer(id, sms_id, number, mes):\n pass\n\n\n#put_data_to_db('79268401046', 'dk')\n#num = get_number_from_db()\nsend_sms('79268401046')\n\n\n\n","sub_path":"send_sms.py","file_name":"send_sms.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68957940","text":"# Example that shows how to draw very large number of \n# spheres (same for points, lines) with different colors\n# or different radius. Resolution (res) can be specified.\n# (vtk versions<8.0 might be slow)\n#\nfrom vtkplotter import Plotter\nfrom random import gauss\n\nN = 100000\n\nvp = Plotter(N=2, axes=3, interactive=0)\n\nprint('calculating..')\ncols = range(N) #color numbers\npts = [(gauss(0,1), gauss(0,2), gauss(0,1)) for i in cols]\nrads = [abs(pts[i][1])/10 for i in cols] # radius=0 for y=0\n\n# all have same radius but different colors:\ns0 = vp.spheres(pts, c=cols, r=0.1, res=3) # res=resolution\n\n# all have same color (texture) but different radius along y:\ns1 = vp.spheres(pts, r=rads, res=10, texture='gold1') \n\nvp.show(s0, at=0)\nprint('..rendering spheres:', N*2)\nvp.show(s1, at=1, legend='N='+str(N), interactive=1)\n\n","sub_path":"examples/basic/manyspheres.py","file_name":"manyspheres.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179517177","text":"import pytest\n\nfrom factories import PlayerFactory, SportFactory, GameFactory\n\n@pytest.mark.django_db\nclass TestGames:\n\n def test_about_view(self, client):\n response = client.get('/about/')\n assert response.status_code == 200\n\n def test_home_view(self, client):\n soccer = SportFactory()\n basketball = SportFactory()\n volleyball = SportFactory()\n hockey = SportFactory()\n baseball = SportFactory()\n\n player1 = PlayerFactory()\n player2 = PlayerFactory()\n player = PlayerFactory.create(sports=(basketball, soccer))\n\n game = GameFactory(owner=player.user, players=(player1, player2), sport=basketball)\n response = client.get('/')\n assert len(response.context['basketball']) == 1","sub_path":"game/test_games.py","file_name":"test_games.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"342558372","text":"from DAO.generic import DAO_generic\n\nfrom lib import gen_json\n\nfrom lib.validator import REG_UPDATE_COMMAND, REG_UPDATE_PARAM, REG_NUM, REG_LIST_NUM, checkParam\nfrom model import Update, User\n\nclass DAO_update(DAO_generic):\n def __init__(self):\n super(DAO_update, self).__init__() \n\n def add_update_devices(self, user_id, user_session, device_list_id, command, params):\n if not (checkParam(device_list_id, 250, REG_LIST_NUM)\n \tand checkParam(command, 40, REG_UPDATE_COMMAND)\n \tand checkParam(params, 255, REG_UPDATE_PARAM)):\n return gen_json.error(\"add_update_devices, invalid params\")\n\n #Check user param\n user = User(id=2)\n try:\n for device_id in device_list_id.split(\"|\"):\n update = Update(deviceId=device_id, command=command, params=params)\n self.session.add(update)\n self.session.commit()\n except:\n self.session.rollback()\n return gen_json.error(\"add_update_devices, DataBase error\")\n\n\n","sub_path":"DAO/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66026142","text":"import requests\nimport json as json\nfrom datetime import datetime\nimport alpaca_trade_api as t\nimport logging\nimport pandas as pd\nimport pytz\nimport time\n\n\nendpoint = \"https://data.alpaca.markets/v1\"\n\nheaders = json.loads(open(\"account.json\", 'r').read())\n\n\ndef hist_data(symbol, dataframe, timeframe=\"15Min\", limit=200, start=\"\", end=\"\", after=\"\", until=\"\"):\n '''Returns the historical bar data for a group of stocks '''\n df_data = {}\n # Get Requests for Bar Data\n bar_url = endpoint + \"/bars/{}\".format(timeframe)\n\n params = {\n \"symbols\": symbol,\n \"limit\": limit,\n \"start\": start,\n \"end\": end,\n \"after\": after,\n \"until\": until\n }\n\n r = requests.get(bar_url, headers=headers, params=params)\n\n json_dump = r.json()\n # loop through stock data\n for symbol in json_dump:\n # convert json into pandas dataframe\n temp = pd.DataFrame(json_dump[symbol])\n temp.rename({\"t\":\"time\", \"o\": \"open\", 'h':'high', 'l':'low', \"c\":\"close\", 'v':'volume'}, axis=1, inplace=True)\n # temp['time'] = pd.to_datetime(temp['time'], unit='s')\n # temp.set_index(\"time\", inplace=True)\n # eastern = pytz.timezone('US/Eastern')\n # temp.index = temp.index.tz_localize(pytz.utc).tz_convert(eastern)\n\n # append data to df data\n # df_data[symbol] = temp\n # global df\n # df = pd.concat([df[symbol], temp[\"close\"]])\n # dataframe = pd.concat([dataframe, temp.rename(columns={'close':symbol})[symbol]])\n # dataframe = dataframe.drop([symbol], axis=1)\n # datagrame = dataframe.rename(index={1: symbol})\n\n # print(dataframe)\n temp = temp.drop([\"time\", \"open\", \"high\", \"low\", \"volume\",], axis=1).rename(columns={\"close\":symbol})\n dataframe = pd.concat([dataframe, temp])\n print(dataframe)\n\n # return temp #df_data\n return dataframe\n\n\n\ntickers = [\"NIO\", \"PLTR\", \"AAPL\", \"AMZN\", \"FB\"]\n\n# df = pd.DataFrame(columns = tickers)\ndataframes = dict()\nfor symbol in tickers:\n dataframes[symbol] = pd.DataFrame(columns = [symbol])\n\n# time is in seconds\n\nstarttime = time.time()\n# will go for 8 hours\n# timeout = starttime + 60 * 5 # 8 hrs 60 * 8\ntimeout = starttime + 1\n\nwhile time.time() <= timeout:\n print(\"****************************************************\")\n for company in tickers:\n print(\"printing data for {} at {}\".format(company, time.time()))\n # print(hist_data(company, dataframes[company], timeframe=\"5Min\"))\n dataframes[company] = hist_data(company, dataframes[company], timeframe=\"5Min\")\n\n # after all ticker, take a break\n # time.sleep(60 - ((time.time() - starttime) % 60)) # the execution of the program will pause (rest)\n\n\n# data_dump = hist_data(\"NIO,AAPL,PLTR\", timeframe=\"5Min\", limit=200)\n# print(data_dump)\n\nfinal_prices = dataframes[tickers[0]]\nprint(final_prices)\n\nfor key, value in dataframes.items():\n final_prices = pd.concat([final_prices, value], axis=1)\n # final_prices = final_prices.join(value, how='outer')\n\nprint(final_prices.to_csv(index=False))\n","sub_path":"alpaca-api/hist_data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"214751722","text":"import random\n\npb = []\npb_particles = []\n\ndef best(ptls):\n\tglobal pb\n\tglobal particles\n\tupdatedPB = []\n\tupdatedParticles = []\n\tnewPB = [sum(particle) for particle in ptls]\n\tn1 = [abs(i - 0) for i in newPB] #because subset sum has to be zero\n\tn2 = [abs(i - 0) for i in pb]\n\tfor index, a in enumerate(zip(n1, n2)):\n\t\tif a[0] < a[1]:\n\t\t\tupdatedPB.append(n1[index])\n\t\t\tupdatedParticles.append(ptls[index])\n\t\telse:\n\t\t\tupdatedPB.append(n2[index])\n\t\t\tupdatedParticles.append(particles[index])\n\tfor index, i in enumerate(updatedPB):\n\t\tpb[index] = i\n\tfor index, i in enumerate(updatedParticles):\n\t\tparticles[index] = i\n\tgbest = max(pb)\n\ndef pso(particles, velocities):\n\tgbest, pbest = best(particles)\n\treturn []\n\ndef optimize(A, subSize):\n\tglobal pb\n\tglobal pb_particles\n\tpopulationSize = 10\n\tparticles = [random.sample(A, subSize) for i in range(populationSize)]\n\tvelocities = [[0]*5 for _ in range(populationSize)]\n\tfor particle in particles:\n\t\tpb.append(sum(particle))\n\tfor particle in particles:\n\t\tpb_particles.append(particle)\n\tlst = pso(particles, velocities)\n\treturn lst\n\nif __name__ == '__main__':\n\tA = [-12, -3, -6, 7, 2, -2, 6, 3, 9, -7, -5, -8, 1, 11, -9, -4]\n\tsubSize = 5\n\tlst = optimize(A, subSize)\n\tprint('Total subsets: {}'.format(len(lst)))\n\tfor subset in lst:\n\t\tprint(subset)","sub_path":"pso.py","file_name":"pso.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"614732560","text":"#!/usr/bin/env python3\n\"\"\"\nSetup the development environment.\n\nRuns the following commands:\n {}\n\"\"\"\nimport argparse\nimport os\nimport shlex\nimport subprocess\n\n__commands_to_run = [\n \"poetry run pip install --upgrade pip<19\",\n \"poetry install\",\n \"poetry run pre-commit install\",\n]\n\n__doc__ = __doc__.format(\"\\n \".join(__commands_to_run))\n\n\ndef execute_command_list(commands_to_run, verbose=True):\n \"\"\"\n Execute each command in the list.\n\n If any command fails, print a helpful message and exit with that status.\n \"\"\"\n for command in commands_to_run:\n if verbose:\n print(f\"+{command}\")\n subprocess.run(shlex.split(command), check=True)\n\n\ndef env_setup(verbose):\n \"\"\"Prepare environment for running.\"\"\"\n print(f\"In: {os.getcwd()}\")\n if os.getenv(\"VIRTUAL_ENV\"):\n print(f\"Setting up Virtual Environment: {os.environ['VIRTUAL_ENV']}\")\n print()\n execute_command_list(__commands_to_run, verbose=verbose)\n\n\ndef main():\n \"\"\"Execute env_setup using command line args.\"\"\"\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"store_true\",\n help=\"show each command before it is executed\",\n )\n args = parser.parse_args()\n env_setup(args.verbose)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"env_setup.py","file_name":"env_setup.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333456320","text":"from gi.repository import Gtk\nclass mynote:\n def __init__(self):\n self.builder = Gtk.Builder() # create an instance of the gtk.Builder\n self.builder.add_from_file('tut02.glade') # add the xml file to the Builder\n self.builder.connect_signals(self)\n self.window = self.builder.get_object(\"window1\") # This gets the 'window1' object\n #print '.......'\n self.window.show_all()\n def on_window1_destroy(self, object, data=None):\n Gtk.main_quit()\n\nnoteb = mynote()\nGtk.main()\n\n","sub_path":"pygtk/charter1.py","file_name":"charter1.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165797772","text":"\"\"\"Utilities for EMTF++.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport six\nfrom six.moves import range, zip, map, filter\n\n# ______________________________________________________________________________\n# Utilities\n\n# Enums\nkDT, kCSC, kRPC, kGEM, kME0 = 0, 1, 2, 3, 4\n\nkDEBUG, kINFO, kWARNING, kERROR, kFATAL = 0, 1, 2, 3, 4\n\n# Functions\ndef wrap_phi_rad(rad):\n while rad < -np.pi:\n rad += np.pi*2\n while rad >= +np.pi:\n rad -= np.pi*2\n return rad\n\ndef wrap_phi_deg(deg):\n while deg < -180.:\n deg += 360.\n while deg >= +180.:\n deg -= 360.\n return deg\n\ndef wrap_theta_rad(rad):\n rad = np.abs(rad)\n while rad >= np.pi:\n rad -= np.pi\n if rad >= np.pi/2:\n rad = np.pi - rad\n return rad\n\ndef wrap_theta_deg(deg):\n deg = np.abs(deg)\n while deg >= 180.:\n deg -= 180.\n if deg >= 180./2:\n deg = 180. - deg\n return deg\n\ndef delta_phi(lhs, rhs): # in radians\n rad = lhs - rhs\n rad = wrap_phi_rad(rad)\n return rad\n\ndef delta_theta(lhs, rhs): # in radians\n rad = lhs - rhs\n return rad\n\ndef calc_phi_loc_deg_from_glob(glob, sector):\n # glob in deg, sector [1-6]\n glob = wrap_phi_deg(glob)\n loc = glob - 15. - (60. * (sector-1))\n return loc\n\ndef calc_phi_loc_int(glob, sector):\n # glob in deg, sector [1-6]\n loc = calc_phi_loc_deg_from_glob(glob, sector)\n if (loc + 22.) < 0.:\n loc += 360.\n loc = (loc + 22.) * 60.\n phi_int = int(round(loc))\n return phi_int\n\ndef calc_phi_loc_deg(bits):\n loc = float(bits) / 60. - 22.\n return loc\n\ndef calc_phi_glob_deg(loc, sector):\n # loc in deg, sector [1-6]\n glob = loc + 15. + (60. * (sector-1))\n if glob >= 180.:\n glob -= 360.\n return glob\n\ndef calc_theta_int(theta, endcap):\n # theta in deg, endcap [-1,+1]\n if endcap == -1:\n theta = 180. - theta\n theta = (theta - 8.5) * 128. / (45.0-8.5)\n theta_int = int(round(theta))\n return theta_int\n\ndef calc_theta_rad_from_eta(eta):\n # returns theta in [0-pi] rad\n theta = np.arctan2(1.0, np.sinh(eta))\n return theta\n\ndef calc_theta_deg_from_eta(eta):\n # returns theta in [0-180] deg\n return np.rad2deg(calc_theta_rad_from_eta(eta))\n\ndef calc_theta_deg_from_int(theta_int):\n theta_deg = float(theta_int) * (45.0-8.5) / 128. + 8.5;\n return theta_deg\n\ndef calc_eta_from_theta_rad(theta_rad):\n eta = -1. * np.log(np.tan(theta_rad/2.))\n return eta\n\ndef calc_eta_from_theta_deg(theta_deg, endcap):\n # theta in deg, endcap [-1,+1]\n theta_deg = wrap_theta_deg(theta_deg)\n theta_rad = np.deg2rad(theta_deg)\n eta = calc_eta_from_theta_rad(theta_rad)\n if endcap == -1:\n eta = -eta\n return eta\n\ndef calc_simple_d0(phi, xv, yv):\n d0 = xv * np.sin(phi) - yv * np.cos(phi)\n return d0\n\ndef calc_d0(invpt, phi, xv, yv, B=3.811):\n R = -1.0 / (0.003 * B * invpt) # R = -pT/(0.003 q B) [cm]\n xc = xv - (R * np.sin(phi)) # xc = xv - R sin(phi)\n yc = yv + (R * np.cos(phi)) # yc = yv + R cos(phi)\n d0 = R - (np.sign(R) * np.hypot(xc, yc)) # d0 = R - sign(R) * sqrt(xc^2 + yc^2)\n return d0\n\ndef calc_etastar_from_eta(eta, phi, x0, y0, z0):\n # Propagate to station 2 (z = 850 cm)\n # Note: x0, y0, z0 in cm. Assume pT -> inf.\n zstar = 850.\n if eta < 0:\n zstar *= -1\n cot = np.sinh(eta)\n delta_r = np.abs((zstar - z0)/cot)\n xstar = x0 + np.cos(phi) * delta_r\n ystar = y0 + np.sin(phi) * delta_r\n rstar = np.hypot(xstar, ystar)\n cotstar = zstar/rstar\n etastar = np.arcsinh(cotstar)\n return etastar\n\ndef calc_signed_rvtx(eta, phi, x0, y0, z0):\n # Propagate to station 2 (z = 850 cm)\n # Note: x0, y0, z0 in cm. Assume pT -> inf.\n zstar = 850.\n if eta < 0:\n zstar *= -1\n cot = np.sinh(eta)\n delta_r = np.abs((zstar - z0)/cot)\n xstar = x0 + np.cos(phi) * delta_r\n ystar = y0 + np.sin(phi) * delta_r\n rstar = np.hypot(xstar, ystar)\n rvtx = np.hypot(x0, y0)\n if (rstar - delta_r) <= 0.:\n rvtx *= -1\n return rvtx\n\ndef find_endsec(endcap, sector):\n endsec = (sector - 1) if endcap == 1 else (sector - 1 + 6)\n return endsec\n\ndef pick_the_median(lst): # assume sorted list\n middle = 0 if len(lst) == 0 else (len(lst)-1)//2\n return lst[middle]\n\ndef save_np_arrays(outfile, outdict):\n from numpy.compat import contextlib_nullcontext\n with contextlib_nullcontext(outfile) as f:\n np.savez_compressed(f, **outdict)\n\ndef save_root_histograms(outfile, histograms):\n from rootpy.io import root_open\n with root_open(outfile, 'recreate') as f:\n for (k, v) in six.iteritems(histograms):\n v.Write()\n\n# Copied from https://github.com/keras-team/keras/blob/master/keras/engine/training_utils.py\ndef make_batches(size, batch_size):\n \"\"\"Returns a list of batch indices (tuples of indices).\n # Arguments\n size: Integer, total size of the data to slice into batches.\n batch_size: Integer, batch size.\n # Returns\n A list of tuples of array indices.\n \"\"\"\n num_batches = (size + batch_size - 1) // batch_size # round up\n return [(i * batch_size, min(size, (i + 1) * batch_size))\n for i in range(num_batches)]\n\n# Copied from https://github.com/keras-team/keras/blob/master/keras/utils/generic_utils.py\ndef to_list(x, allow_tuple=False):\n \"\"\"Normalizes a list/tensor into a list.\n If a tensor is passed, we return\n a list of size 1 containing the tensor.\n # Arguments\n x: target object to be normalized.\n allow_tuple: If False and x is a tuple,\n it will be converted into a list\n with a single element (the tuple).\n Else converts the tuple to a list.\n # Returns\n A list.\n \"\"\"\n if isinstance(x, list):\n return x\n if allow_tuple and isinstance(x, tuple):\n return list(x)\n return [x]\n\n# Copied from https://github.com/keras-team/keras/blob/master/keras/utils/generic_utils.py\ndef unpack_singleton(x):\n \"\"\"Gets the first element if the iterable has only one value.\n Otherwise return the iterable.\n # Argument\n x: A list or tuple.\n # Returns\n The same iterable or the first element.\n \"\"\"\n if len(x) == 1:\n return x[0]\n return x\n\n# Copied from https://github.com/keras-team/keras/blob/master/keras/utils/generic_utils.py\ndef slice_arrays(arrays, start=None, stop=None):\n \"\"\"Slices an array or list of arrays.\n This takes an array-like, or a list of\n array-likes, and outputs:\n - arrays[start:stop] if `arrays` is an array-like\n - [x[start:stop] for x in arrays] if `arrays` is a list\n Can also work on list/array of indices: `_slice_arrays(x, indices)`\n # Arguments\n arrays: Single array or list of arrays.\n start: can be an integer index (start index)\n or a list/array of indices\n stop: integer (stop index); should be None if\n `start` was a list.\n # Returns\n A slice of the array(s).\n \"\"\"\n if arrays is None:\n return [None]\n elif isinstance(arrays, list):\n # integer array indexing\n if hasattr(start, '__len__'):\n # hdf5 datasets only support list objects as indices\n if hasattr(start, 'shape'):\n start = start.tolist()\n return [None if x is None else x[start] for x in arrays]\n # slicing\n else:\n return [None if x is None else x[start:stop] for x in arrays]\n else:\n if hasattr(start, '__len__'):\n if hasattr(start, 'shape'):\n start = start.tolist()\n return arrays[start]\n elif hasattr(start, '__getitem__'):\n return arrays[start:stop]\n else:\n return [None]\n\n# Based on\n# https://www.tensorflow.org/guide/ragged_tensor\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/ragged/ragged_tensor_value.py\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/ragged/ragged_getitem.py\n# Example\n# ragged = RaggedTensorValue(values=np.array([3, 1, 4, 1, 5, 9, 2]), row_splits=np.array([0, 4, 4, 6, 7]))\nclass RaggedTensorValue(object):\n \"\"\"Represents the value of a `RaggedTensor`.\"\"\"\n\n def __init__(self, values, row_splits):\n \"\"\"Creates a `RaggedTensorValue`.\n Args:\n values: A numpy array of any type and shape; or a RaggedTensorValue.\n row_splits: A 1-D int32 or int64 numpy array.\n \"\"\"\n if not (isinstance(row_splits, (np.ndarray, np.generic)) and\n row_splits.dtype in (np.int64, np.int32) and row_splits.ndim == 1):\n raise TypeError(\"row_splits must be a 1D int32 or int64 numpy array\")\n if not isinstance(values, (np.ndarray, np.generic, RaggedTensorValue)):\n raise TypeError(\"values must be a numpy array or a RaggedTensorValue\")\n if (isinstance(values, RaggedTensorValue) and\n row_splits.dtype != values.row_splits.dtype):\n raise ValueError(\"row_splits and values.row_splits must have \"\n \"the same dtype\")\n self._values = values\n self._row_splits = row_splits\n\n row_splits = property(\n lambda self: self._row_splits,\n doc=\"\"\"The split indices for the ragged tensor value.\"\"\")\n values = property(\n lambda self: self._values,\n doc=\"\"\"The concatenated values for all rows in this tensor.\"\"\")\n dtype = property(\n lambda self: self._values.dtype,\n doc=\"\"\"The numpy dtype of values in this tensor.\"\"\")\n\n @property\n def shape(self):\n \"\"\"A tuple indicating the shape of this RaggedTensorValue.\"\"\"\n return (self._row_splits.shape[0] - 1,) + (None,) + self._values.shape[1:]\n\n def __repr__(self):\n return \"RaggedTensorValue(values=%r, row_splits=%r)\" % (\n self._values, self._row_splits)\n\n def __len__(self):\n return len(self.row_splits[:-1])\n\n def __getitem__(self, row_key):\n if isinstance(row_key, slice):\n raise ValueError(\"slicing is not supported\")\n starts = self.row_splits[:-1]\n limits = self.row_splits[1:]\n row = self.values[starts[row_key]:limits[row_key]]\n return row\n\n def __iter__(self):\n for i in range(len(self)):\n yield self[i]\n\n def to_list(self):\n \"\"\"Returns this ragged tensor value as a nested Python list.\"\"\"\n if isinstance(self._values, RaggedTensorValue):\n values_as_list = self._values.to_list()\n else:\n values_as_list = self._values.tolist()\n return [\n values_as_list[self._row_splits[i]:self._row_splits[i + 1]]\n for i in range(self._row_splits.shape[0] - 1)\n ]\n\n def to_array(self):\n \"\"\"Returns this ragged tensor value as a nested Numpy array.\"\"\"\n arr = np.empty((self._row_splits.shape[0] - 1,), dtype=np.object)\n for i in range(self._row_splits.shape[0] - 1):\n arr[i] = self._values[self._row_splits[i]:self._row_splits[i + 1]]\n return arr\n\n# Based on\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/ragged/ragged_factory_ops.py\ndef create_ragged_array(pylist):\n \"\"\"Construct a constant RaggedTensorValue from a nested list.\"\"\"\n\n # Ragged rank for returned value\n ragged_rank = 1\n\n # Build the splits for each ragged rank, and concatenate the inner values\n # into a single list.\n nested_splits = []\n values = pylist\n for dim in range(ragged_rank):\n nested_splits.append([0])\n concatenated_values = []\n for row in values:\n nested_splits[dim].append(nested_splits[dim][-1] + len(row))\n concatenated_values.extend(row)\n values = concatenated_values\n\n values = np.asarray(values)\n for row_splits in reversed(nested_splits):\n row_splits = np.asarray(row_splits, dtype=np.int32)\n values = RaggedTensorValue(values, row_splits)\n return values\n\n# Based on\n# https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/sparse_tensor.py\n# Example\n# sparse = SparseTensorValue(indices=np.array([[0, 0], [1, 2], [2, 3]]), values=np.array([1, 2, 3]), dense_shape=(3, 4))\nclass SparseTensorValue(object):\n \"\"\"Represents the value of a `SparseTensor`.\"\"\"\n\n def __init__(self, indices, values, dense_shape):\n \"\"\"Creates a `SparseTensor`.\n Args:\n indices: A 2-D int64 tensor of shape `[N, ndims]`.\n values: A 1-D tensor of any type and shape `[N]`.\n dense_shape: A 1-D int64 tensor of shape `[ndims]`.\n \"\"\"\n if not (isinstance(indices, (np.ndarray, np.generic)) and\n indices.dtype in (np.int64, np.int32) and indices.ndim == 2):\n raise TypeError(\"indices must be a 2D int32 or int64 numpy array\")\n if not isinstance(values, (np.ndarray, np.generic)):\n raise TypeError(\"values must be a numpy array\")\n self._indices = indices\n self._values = values\n self._dense_shape = dense_shape\n\n indices = property(\n lambda self: self._indices,\n doc=\"\"\"The indices of non-zero values in the represented dense tensor.\"\"\")\n values = property(\n lambda self: self._values,\n doc=\"\"\"The non-zero values in the represented dense tensor.\"\"\")\n dtype = property(\n lambda self: self._values.dtype,\n doc=\"\"\"The numpy dtype of values in this tensor.\"\"\")\n dense_shape = property(\n lambda self: self._dense_shape,\n doc=\"\"\"A tuple representing the shape of the dense tensor.\"\"\")\n shape = property(\n lambda self: self._dense_shape,\n doc=\"\"\"A tuple representing the shape of the dense tensor.\"\"\")\n\n def __repr__(self):\n return \"SparseTensorValue(indices=%r, values=%r, dense_shape=%r)\" % (\n self._indices, self._values, self._dense_shape)\n\ndef dense_to_sparse(dense):\n dense = np.asarray(dense)\n indices = np.argwhere(dense)\n values = dense[dense.nonzero()]\n dense_shape = dense.shape\n return SparseTensorValue(indices=indices, values=values, dense_shape=dense_shape)\n\ndef sparse_to_dense(sparse):\n dense = np.zeros(sparse.dense_shape, dtype=sparse.dtype)\n for i in range(len(sparse.indices)):\n dense[tuple(sparse.indices[i])] = sparse.values[i]\n return dense\n\n# Copied from https://docs.python.org/2/howto/logging.html\ndef get_logger():\n import logging\n\n # create logger\n logger = logging.getLogger('test9')\n logger.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n fh = logging.FileHandler('test9.log')\n fh.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n\n # create formatter and add it to the handlers\n #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n formatter = logging.Formatter('%(asctime)s [%(levelname)-8s] %(message)s')\n fh.setFormatter(formatter)\n formatter = logging.Formatter('[%(levelname)-8s] %(message)s')\n ch.setFormatter(formatter)\n\n # add the handlers to the logger\n if not len(logger.handlers):\n logger.addHandler(fh)\n logger.addHandler(ch)\n return logger\n\n\n# ______________________________________________________________________________\n# Models\n\n\n\n# ______________________________________________________________________________\n# Datasets\n\ndef load_tree(infiles):\n from rootpy.tree import TreeChain\n from rootpy.ROOT import gROOT\n gROOT.SetBatch(True)\n\n print('[INFO] Opening files: {0}'.format(infiles))\n tree = TreeChain('ntupler/tree', infiles)\n tree.define_collection(name='hits', prefix='vh_', size='vh_size')\n tree.define_collection(name='simhits', prefix='vc_', size='vc_size')\n tree.define_collection(name='tracks', prefix='vt_', size='vt_size')\n tree.define_collection(name='particles', prefix='vp_', size='vp_size')\n return tree\n\neos_prefix = 'root://cmsxrootd-site.fnal.gov//store/group/l1upgrades/L1MuonTrigger/P2_10_6_3/'\n\ndef load_pgun_test():\n #infile = '../test7/ntuple_SingleMuon_Endcap_2GeV_add.6.root'\n infile = '../test7/ntuple_SingleMuon_Displaced_2GeV_PhaseIITDRSpring19_add.8.root'\n return load_tree(infile)\n\ndef load_pgun_batch(k):\n my_range = np.split(np.arange(1000), 100)[k]\n infiles = []\n #for i in my_range:\n # infiles.append(eos_prefix + 'SingleMuon_Endcap_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/190923_203236/%04i/ntuple_SingleMuon_Endcap_%i.root' % ((i+1)//1000, (i+1)))\n # infiles.append(eos_prefix + 'SingleMuon_Endcap2_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/190923_203346/%04i/ntuple_SingleMuon_Endcap2_%i.root' % ((i+1)//1000, (i+1)))\n for i in my_range:\n infiles.append(eos_prefix + 'SingleMuon_Endcap_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/191115_161447/%04i/ntuple_%i.root' % ((i+1)//1000, (i+1)))\n infiles.append(eos_prefix + 'SingleMuon_Endcap2_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/191115_172000/%04i/ntuple_%i.root' % ((i+1)//1000, (i+1)))\n tree = load_tree(infiles)\n return tree\n\ndef load_pgun_displ_batch(k):\n my_range = np.split(np.arange(2000), 200)[k]\n infiles = []\n #for i in my_range:\n # infiles.append(eos_prefix + 'SingleMuon_Displaced_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/190923_212343/%04i/ntuple_SingleMuon_Displaced_%i.root' % ((i+1)//1000, (i+1)))\n # infiles.append(eos_prefix + 'SingleMuon_Displaced2_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/190923_212452/%04i/ntuple_SingleMuon_Displaced2_%i.root' % ((i+1)//1000, (i+1)))\n for i in my_range:\n if i < 1000:\n infiles.append(eos_prefix + 'SingleMuon_Displaced_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/191112_182211/%04i/ntuple_%i.root' % ((i+1)//1000, (i+1)))\n infiles.append(eos_prefix + 'SingleMuon_Displaced2_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/191112_224608/%04i/ntuple_%i.root' % ((i+1)//1000, (i+1)))\n else:\n infiles.append(eos_prefix + 'SingleMuon_Displaced_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/191120_015414/%04i/ntuple_%i.root' % ((i+1-1000)//1000, (i+1-1000)))\n infiles.append(eos_prefix + 'SingleMuon_Displaced2_2GeV_PhaseIITDRSpring19/ParticleGuns/CRAB3/191120_020405/%04i/ntuple_%i.root' % ((i+1-1000)//1000, (i+1-1000)))\n tree = load_tree(infiles)\n return tree\n\ndef load_mixing_batch(k):\n infiles = []\n #infiles += [eos_prefix + 'ntuple_SingleNeutrino_PU140_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/190926_145646/0000/ntuple_%i.root' % (i+1) for i in range(30)] # up to 30/63\n #infiles += [eos_prefix + 'ntuple_SingleNeutrino_PU200_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/190926_145529/0000/ntuple_%i.root' % (i+1) for i in range(40)] # up to 40/85\n #infiles += [eos_prefix + 'ntuple_SingleNeutrino_PU250_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/190926_145757/0000/ntuple_%i.root' % (i+1) for i in range(50)] # up to 50/125\n #infiles += [eos_prefix + 'ntuple_SingleNeutrino_PU300_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/191002_214457/0000/ntuple_%i.root' % (i+1) for i in range(50)] # up to 50/111\n infiles += [eos_prefix + 'ntuple_DoubleElectron_PU140_PhaseIITDRSpring19/DoubleElectron_FlatPt-1To100/CRAB3/190925_044352/0000/ntuple_%i.root' % (i+1) for i in range(25)]\n infiles += [eos_prefix + 'ntuple_DoubleElectron_PU200_PhaseIITDRSpring19/DoubleElectron_FlatPt-1To100/CRAB3/190925_044710/0000/ntuple_%i.root' % (i+1) for i in range(25)]\n infiles += [eos_prefix + 'ntuple_DoublePhoton_PU140_PhaseIITDRSpring19/DoublePhoton_FlatPt-1To100/CRAB3/190925_044839/0000/ntuple_%i.root' % (i+1) for i in range(25)]\n infiles += [eos_prefix + 'ntuple_DoublePhoton_PU200_PhaseIITDRSpring19/DoublePhoton_FlatPt-1To100/CRAB3/190925_044947/0000/ntuple_%i.root' % (i+1) for i in range(25)]\n infiles += [eos_prefix + 'ntuple_SingleElectron_PU200_PhaseIITDRSpring19/SingleElectron_PT2to100/CRAB3/190925_181236/0000/ntuple_%i.root' % (i+1) for i in range(15)]\n infiles += [eos_prefix + 'ntuple_SinglePhoton_PU200_PhaseIITDRSpring19/PhotonFlatPt8To150/CRAB3/190925_181357/0000/ntuple_%i.root' % (i+1) for i in range(77)]\n infile = infiles[k]\n tree = load_tree(infile)\n return tree\n\ndef load_singleneutrino_batch(k, pileup=200):\n if pileup == 140:\n infiles = [eos_prefix + 'ntuple_SingleNeutrino_PU140_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/190926_145646/0000/ntuple_%i.root' % (i+1) for i in range(63)]\n elif pileup == 200:\n infiles = [eos_prefix + 'ntuple_SingleNeutrino_PU200_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/190926_145529/0000/ntuple_%i.root' % (i+1) for i in range(85)]\n elif pileup == 250:\n infiles = [eos_prefix + 'ntuple_SingleNeutrino_PU250_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/190926_145757/0000/ntuple_%i.root' % (i+1) for i in range(125)]\n elif pileup == 300:\n infiles = [eos_prefix + 'ntuple_SingleNeutrino_PU300_PhaseIITDRSpring19/Nu_E10-pythia8-gun/CRAB3/191002_214457/0000/ntuple_%i.root' % (i+1) for i in range(111)]\n else:\n raise RuntimeError('Cannot recognize pileup: {0}'.format(pileup))\n infile = infiles[k]\n tree = load_tree(infile)\n return tree\n\ndef load_mumu_flatpt_batch(k, pileup=200):\n if pileup == 0:\n infiles = [eos_prefix + 'ntuple_MuMu_FlatPt_PU0_PhaseIITDRSpring19/Mu_FlatPt2to100-pythia8-gun/CRAB3/190925_042003/0000/ntuple_MuMu_FlatPt_PU0_%i.root' % (i+1) for i in range(5)]\n elif pileup == 200:\n infiles = [eos_prefix + 'ntuple_MuMu_FlatPt_PU200_PhaseIITDRSpring19/Mu_FlatPt2to100-pythia8-gun/CRAB3/190925_051735/0000/ntuple_%i.root' % (i+1) for i in range(33)]\n elif pileup == 300:\n infiles = [eos_prefix + 'ntuple_MuMu_FlatPt_PU300_PhaseIITDRSpring19/Mu_FlatPt2to100-pythia8-gun/CRAB3/190924_201214/0000/ntuple_MuMu_FlatPt_PU300_%i.root' % (i+1) for i in range(280)]\n else:\n raise RuntimeError('Cannot recognize pileup: {0}'.format(pileup))\n infile = infiles[k]\n tree = load_tree(infile)\n return tree\n","sub_path":"Analyzers/test9/emtf_utils.py","file_name":"emtf_utils.py","file_ext":"py","file_size_in_byte":21298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"447212846","text":"\nfrom abc import abstractmethod\n\nfrom .abstract_test import AbstractTest\nfrom munch import Munch\nfrom checklist_fork.checklist.eval_core import CoreRecord\nfrom checklist_fork.checklist.utils import DataShape, group_data\n\nfrom typing import List, Union, Dict, Any\n\n\nclass MetricTest(AbstractTest):\n def __init__(\n self,\n name: str,\n required_ds: DataShape,\n only_accumulate: bool = False\n ) -> None:\n \"\"\"\n Arguments:\n name: name of the test\n only_accumulate: Set to True if the metric doesn't support\n per-group results. In such case the get_results is given data\n for all groups (preds and confs are 2d for classification and\n 3d for sequence labeling). If False the get_results function\n gets the data for a single group (preds and confs are 1d for\n classification and 2d for sequence labeling).\n \"\"\"\n self.name: str = name\n self.only_accumulate: bool = only_accumulate\n self.required_ds: DataShape = required_ds\n\n def get_name(self) -> str:\n return self.name\n\n def get_group_names(\n self,\n core_record: CoreRecord\n ) -> List[str]:\n \"\"\"\n Returns the names of all groups, based on either\n (i) the metadata held in the core_record, as ordered in the template\n instantiations. The order is important to determine which scores belong\n to what group.\n or\n (ii) the group_names field in core_record -- this field is set only\n if the data was grouped to start with (had the #ngroups x #nexemples\n structure).\n\n IMPORTANT: In the (i) case, the implementation assumes the order is the\n same for all templated sentences!\n \"\"\"\n if core_record.group_names is not None:\n return core_record.group_names\n\n if core_record.data_structure == DataShape.GROUPED:\n n_groups = len(core_record.preds)\n else:\n n_groups = len(core_record.preds[0])\n\n if core_record.meta:\n return [core_record.meta[0][x] for x in range(n_groups)]\n else:\n return [f\"Group{x+1}\" for x in range(n_groups)]\n\n def compute(\n self,\n core_record: CoreRecord\n ) -> Munch:\n # get names first -- before the restructuring (just in case)\n self.group_names = self.get_group_names(core_record)\n\n # restructure the data -- this is dependent on the metric/test\n self.process_labels_preds_and_confs(core_record)\n n_examples = self.get_n_examples(core_record)\n\n results = {}\n # get results for each group independently and then accumulate\n if not self.only_accumulate:\n # to support single-group evaluation the data has to be\n # restructured accordingly\n assert core_record.data_structure == DataShape.GROUPED\n\n for gname, labels, preds, confs, meta in zip(\n self.group_names, core_record.labels,\n core_record.preds, core_record.confs, core_record.meta):\n\n results[gname] = self.get_results(\n labels, preds, confs, meta,\n data_structure=core_record.data_structure)\n\n results['all'] = self.get_results(\n [x for l in core_record.labels for x in l],\n [x for p in core_record.preds for x in p],\n [x for c in core_record.confs for x in c],\n [x for m in core_record.meta for x in m],\n data_structure=core_record.data_structure)\n\n results = self.cross_group_accumulation(results)\n else:\n results = self.get_results(\n core_record.labels, core_record.preds, core_record.confs,\n core_record.meta, data_structure=core_record.data_structure)\n\n return Munch({\"results\": results, \"n_examples\": n_examples})\n\n def cross_group_accumulation(self, results) -> Any:\n \"\"\"\n Accumulate the results obtained independently for each group.\n This is only called if self.only_accumulate is False.\n\n Return the *full dictionary of results* (e.g. the one that was passed\n as a parameted with some additional keys):\n The function supports complete replacement of results -- e.g. if the\n results for individual groups are calculated only in order to be\n accumulated into the final result)\n \"\"\"\n return results\n\n def process_labels_preds_and_confs(\n self,\n core_record: CoreRecord\n ) -> None:\n \"\"\"\n (Potentially) restructure the labels, preds and confs stored in the\n core_record. Note: each test gets its own CoreRecord instance, so other\n tests won't be affected by altering fields in core_record.\n\n Return the number of remaining test examples overall (int) or per\n group (dict).\n \"\"\"\n if self.required_ds == DataShape.GROUPED:\n if core_record.data_structure != DataShape.GROUPED:\n # #examples x #groups => #groups x #examples\n group_data(core_record)\n elif self.required_ds == DataShape.UNGROUPED and \\\n core_record.data_structure == DataShape.GROUPED:\n raise Exception(\n 'Cannot run a test for ungrouped/counterfatual data on ' +\n 'data split into groups!')\n elif self.required_ds != DataShape.UNGROUPED:\n raise Exception(f'Unsupported data structure: {self.required_ds}')\n\n def get_n_examples(\n self,\n core_record: CoreRecord\n ) -> Union[int, Dict[str, int]]:\n if self.required_ds == DataShape.GROUPED:\n if all([x == core_record.labels[0] for x in core_record.labels]):\n # all groups have the same number of examples\n return len(core_record.labels[0])\n else:\n # the data must have been originally 'grouped' to allow for a\n # mismatch\n return {k: len(core_record.labels[i])\n for i, k in enumerate(core_record.group_names)}\n elif self.required_ds == DataShape.UNGROUPED:\n return len(core_record.labels)\n else:\n raise Exception(f'Unsupported data structure: {self.required_ds}')\n\n @abstractmethod\n def get_results(self, labels, preds, confs, meta, **kwargs):\n \"\"\"\n Get results for one group (if self.only_accumulate is False) or for\n many groups at once (if self.only_accumulate is True).\n \"\"\"\n raise NotImplementedError\n","sub_path":"checklist_fork/checklist/tests/metric_test.py","file_name":"metric_test.py","file_ext":"py","file_size_in_byte":6666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287916214","text":"\"\"\"\n Implement pow(x, n), which calculates x raised to the power n (i.e. xn).\n\n\"\"\"\nclass Solution:\n def myPow( x: float, n: int) -> float:\n print(' Calcuating {} ^ {}'.format(x, n) )\n if x==0:\n return 0\n if n==0:\n return 1\n if abs(x) == 1.0:\n return 1 if n%2==0 else x\n num = x\n npow = abs(n)\n f_out=1\n counter=0\n while npow>0:\n if f_out==0:\n break\n tmp , tmpf_out=1, num\n while tmp+tmp < npow :\n counter+=1\n if tmp==0 or tmpf_out==1 :\n break\n tmp+=tmp\n tmpf_out*=tmpf_out\n counter+=1\n npow-=tmp\n f_out *= tmpf_out\n print(' outer loop counter = ', counter , 'f_out=', f_out,'')\n if n < 0:\n return 1/f_out\n \n return f_out\n\nclass Solution2:\n def myPow( x: float, n: int) -> float: \n print('calculate {} ^{}'.format(x,n))\n if n<0:\n x = 1/x\n n = -n\n if abs(x)==1:\n return 1 if n%2==0 else x\n res = 1\n current_product = x\n while n>0:\n if current_product==0 or current_product==1:\n res=current_product\n break\n if n%2:\n res *= current_product\n current_product *= current_product\n n=n//2 \n return res","sub_path":"LeetCode_exercises/ex0050_pow.py","file_name":"ex0050_pow.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"255348803","text":"def count_zero_neighbours(numbers):\n\n count = 0\n index = 0\n\n for number in numbers:\n if index < len(numbers)- 1:\n neighbour = numbers[index + 1]\n\n if neighbour + number == 0:\n count += 1\n index += 1\n\n return count\n\n\n","sub_path":"week 4/pairs.py","file_name":"pairs.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60455544","text":"'''\nCreated on 22/05/2013\n\n@author: Jamie Carl\n@author: Alex Ferrara\n'''\n\nclass DB:\n \n backend = None\n \n def __init__(self, db_type, config):\n \n if db_type == 'sqlite':\n self.backend = SQLite(config['file'])\n \n elif db_type == 'mongodb':\n self.backend = Mongo(config['hosts'])\n \n else:\n raise Exception('Database type is unknown.')\n \n def id_exists(self, row_id):\n return self.backend.exists(\"episodes\", row_id)\n\n def add_torrent(self, torrent):\n return self.backend.insert(\"episodes\", torrent)\n \nclass SQLite:\n '''SQLite database class'''\n\n client = None\n cursor = None\n \n def __init__(self, filename):\n '''Constructor'''\n import sqlite3\n\n self.client = sqlite3.connect(filename)\n self.cursor = self.client.cursor()\n\n create_schema = 'CREATE TABLE IF NOT EXISTS episodes (_id INTEGER PRIMARY KEY, link TEXT, pubDate TEXT, title TEXT);'\n\n self.cursor.execute(create_schema)\n\n def exists(self, table, criteria):\n '''Returns True if row with criteria exists in the database table'''\n\n where = None\n \n if type(criteria) == int:\n where = \" WHERE _id = ?\"\n \n if type(criteria) == dict:\n items = []\n \n for key in criteria:\n items.append(key + '= ?')\n \n if len(items) > 0:\n where = \" WHERE \" + ','.join(items)\n \n self.cursor.execute(\"SELECT count(*) FROM \" + table + where, (criteria,))\n\n return self.cursor.fetchone() != (0, )\n\n def insert(self, table, fields):\n '''Adds a row to the database'''\n\n cols = []\n values = []\n episode = []\n\n for i in fields:\n cols.append(i)\n values.append('?')\n episode.append(fields[i])\n \n cols = ','.join(cols) \n values = ','.join(values)\n \n self.cursor.execute(\"INSERT INTO episodes (\" + cols + \") VALUES (\" + values + \")\", episode)\n self.client.commit()\n\nclass Mongo:\n '''MongoDB database class'''\n\n def __init__(self, database):\n '''Constructor'''\n from pymongo import MongoClient\n self.client = MongoClient(database)\n\n self.db = self.client.showrss\n\n def exists(self, collection, criteria):\n '''Returns True if document with criteria exists in the collection'''\n\n if type(criteria) == int:\n criteria = { '_id' : criteria }\n \n col = self.db[collection]\n \n return col.find(criteria).count() != 0\n\n def insert(self, collection, fields):\n '''Adds a row to the database'''\n\n col = self.db[collection]\n \n return col.insert(fields)\n","sub_path":"lib/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36415700","text":"import csv\nimport os\nimport subprocess\nimport sys\nimport json\nimport time\nimport traceback\nimport urllib\nfrom urllib import parse, request\nimport logging\nimport glob\nimport re\n\nnot_geocoded_addrs = \"\"\ncounter = 0\n\nlogPath = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\", \"log\"))\n\n\ndef create_directory_if_not_exists(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n if os.path.exists(directory):\n return True\n\n\ncreate_directory_if_not_exists(logPath)\n\n# first file logger\nformatter_err = logging.Formatter(\"\\n%(asctime)s %(levelname)s %(message)s\")\nlogger_err = logging.getLogger('simple_logger')\nhdlr_err = logging.FileHandler(\"{0}{1}{2}\".format(logPath, os.sep, \"errors.log\"))\nhdlr_err.setFormatter(formatter_err)\nlogger_err.addHandler(hdlr_err)\n\n# second file logger\nformatter_info = logging.Formatter(\"\\n%(asctime)s %(levelname)s %(message)s\")\nlogger_info = logging.getLogger('simple_logger_2')\nlogger_info.setLevel(logging.INFO)\nhdlr_info = logging.FileHandler(\"{0}{1}{2}\".format(logPath, os.sep, \"info.log\"))\nhdlr_info.setFormatter(formatter_info)\nlogger_info.addHandler(hdlr_info)\n\nbase_url = \"https://geocode-maps.yandex.ru/1.x/?format=json&geocode=\"\n\n\ndef createZip(filename, zipname):\n import zipfile\n from os.path import basename\n with zipfile.ZipFile(zipname, \"w\", zipfile.ZIP_DEFLATED) as myzip:\n myzip.write(filename, basename(filename))\n return zipname\n\n\ndef get_largest_file_in_directory(dir):\n filename = sorted((os.path.getsize(s), s) for s in glob.glob(\"{}*.csv\".format(dir)))[-1][1]\n return filename\n\n\ndef buffer_encode(input_str, encoding):\n return sys.stdout.buffer.write(input_str.encode(encoding))\n\n\ndef get_keys_values_from_fieldstorage(data):\n result = {}\n for key in data.keys():\n variable = str(key)\n value = str(data.getvalue(variable))\n result[key] = value\n return result\n\n\ndef get_current_date():\n return int(time.time())\n # return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\ndef datestyle(date):\n date = date.split(\".\")\n return \"\".join([date[2], date[1], date[0]])\n\n\ndef get_config(config_file):\n return json.load(open(config_file, encoding=\"utf-8\"))\n\n\ndef return_formatted_dict(dct):\n return json.dumps(dct, indent=4, sort_keys=True, ensure_ascii=False)\n\n\ndef set_name(in_file, out_file):\n return out_file.replace(\"{}\", in_file.split(\".\")[0])\n\n\ndef zzz(t):\n time.sleep(t)\n\n\ndef write_to_file(fl, str, append=False):\n if append:\n f = open(fl, 'a', encoding=\"utf-8\")\n else:\n f = open(fl, 'w', encoding=\"utf-8\")\n f.write(str)\n\n\ndef get_json(query):\n strng = ''\n with urllib.request.urlopen(query) as f:\n strng += f.read().decode() + '\\n'\n data = json.loads(strng)\n return data\n\n\ndef prepare_str(str):\n return str.strip().lower()\n\n\ndef csv_to_json_order(fl):\n orders = []\n orders_order = \"orders_order\"\n orders_address = \"orders_address\"\n orders_metro = \"orders_metro\"\n orders_equipment = \"orders_equipment\"\n orders_job_type = \"orders_job_type\"\n orders_ultima_line = \"sources\"\n regex = re.compile(r\"(,\\s+)?$\", re.IGNORECASE)\n reader = csv.DictReader(open(fl), delimiter=';', restkey='restkey', dialect='excel')\n for line in reader:\n info = {}\n info[orders_order] = {}\n info[orders_address] = {}\n info[orders_metro] = {}\n info[orders_equipment] = {}\n info[orders_job_type] = {}\n info[orders_ultima_line] = {}\n\n try:\n info[orders_order][\"code\"] = line['Код'].strip()\n info[orders_order][\"date\"] = line['Дата проведения'].strip()\n info[orders_address][\"address_house\"] = line['Адрес'].strip()\n info[orders_metro][\"title\"] = line['Станция метро'].strip()\n info[orders_equipment][\"title\"] = line['Тип оборудования'].strip()\n info[orders_job_type][\"title\"] = line['Основной вид работ'].strip()\n info[orders_ultima_line][\"name\"] = line['Линия'].strip()\n info[orders_ultima_line][\"ultima_line\"] = info[orders_ultima_line][\"name\"]\n info[orders_ultima_line][\"display_name\"] = info[orders_ultima_line][\"name\"]\n except IndexError:\n logger_err.error(\"[ {0}{1}]\".format(traceback.format_exc(), line))\n continue\n try:\n if info[orders_address][\"address_house\"].find('пд.') != -1:\n info[orders_address][\"address_house\"], info[orders_order]['address_rest'] = info[orders_address][\n 'address_house'].split('пд.')\n info[orders_address][\"address_house\"] = regex.sub('', info[orders_address]['address_house'])\n info[orders_order][\"address_rest\"] = 'пд.' + info[orders_order]['address_rest']\n else:\n info[orders_order]['address_rest'] = None\n except AttributeError:\n logger_err.error(\"[ {0}{1}]\".format(traceback.format_exc(), line))\n continue\n orders.append(info)\n\n return orders\n\n\n# 01.09.2016;Алексея Дикого, 16А;1;36;Котов Денис;Шестаков А.Н.;Контроль;Листовки;72;\n#\ndef csv_to_json_get_unique_addrs(fl):\n json = {}\n unique_addrs = {}\n unique_addrs_l = []\n flag = True\n with open(fl) as f:\n try:\n lines = filter(None, (line.rstrip() for line in f))\n # content = f.readlines()\n for i, line in enumerate(lines):\n t = line.split(\";\")\n try:\n # если в заголовке нет колонок Консьерж и Домофон\n if i == 0:\n if line.find(\"Консьерж\") == -1:\n flag = False\n\n last_column = 10\n if not flag:\n if len(t) == last_column:\n t[last_column - 1] = \"\"\n t.append(\"\")\n\n if t[0] and t[0] != \"Дата\":\n t[0] = prepare_str(t[0])\n t[1] = prepare_str(t[1])\n t[2] = prepare_str(t[2])\n if t[1]:\n unique_addrs[t[1]] = None\n if t[0] not in json:\n json[t[0]] = {}\n if t[1] not in json[t[0]]:\n json[t[0]][t[1]] = []\n tmp = \\\n {\n t[2]:\n {\n \"flats\": t[3].strip(),\n \"foreman\": t[4].strip(),\n \"postman\": t[5].strip(),\n \"notice\": t[6].strip(),\n \"source\": t[7].strip(),\n \"items\": t[8].strip(),\n \"doorkeeper\": t[9].strip(),\n \"entryphone\": t[10].strip()\n }\n }\n json[t[0]][t[1]].append(tmp)\n except Exception as e:\n logger_err.info(\"[{0}{1}]\".format(traceback.format_exc(), line))\n except Exception as e:\n logger_err.info(\"[{0}]\".format(traceback.format_exc()))\n for i in unique_addrs:\n unique_addrs_l.append(i)\n return json, len(unique_addrs_l)\n\n\ndef get_coords_street(street):\n global not_geocoded_addrs\n global counter\n result = ''\n street_coords = {}\n try:\n urlencoded_addr = urllib.parse.quote_plus(street)\n tmp_coords = get_json(base_url + urlencoded_addr)\n path = tmp_coords[\"response\"][\"GeoObjectCollection\"][\"featureMember\"]\n\n if not path:\n street_coords[street] = \"0,0\"\n return result, street_coords\n else:\n path = path[0][\"GeoObject\"]\n kind = path[\"metaDataProperty\"][\"GeocoderMetaData\"][\"kind\"]\n precision = path[\"metaDataProperty\"][\"GeocoderMetaData\"][\"precision\"]\n nearest_house = path[\"metaDataProperty\"][\"GeocoderMetaData\"][\"text\"]\n coords = path[\"Point\"][\"pos\"].split(\" \")\n street = prepare_str(street)\n\n result = \"{lon},{lat};{street};{type_of_object};{precision};{nearest_house}{newline}\".format(\n lon=coords[1]\n , lat=coords[0]\n , street=prepare_str(street)\n , type_of_object=kind\n , precision=precision\n , nearest_house=prepare_str(nearest_house)\n , newline=\"\\n\")\n\n if precision != \"exact\":\n street_coords[street] = \"0,0\"\n # not_geocoded_addrs += result\n logger_info.info(not_geocoded_addrs)\n return result, street_coords\n else:\n street_coords[street] = coords[1] + \",\" + coords[0]\n return result, street_coords\n\n except Exception as e:\n if not_geocoded_addrs:\n logger_info.info(not_geocoded_addrs)\n not_geocoded_addrs = \"\"\n logger_err.exception(\"error\")\n finally:\n return result, street_coords\n\n\ndef sort_dict_by_date(dct):\n from datetime import datetime\n from collections import OrderedDict\n ordered = OrderedDict(sorted(dct.items(),\n key=lambda t: datetime.strptime(t[0], '%d.%m.%Y')))\n return ordered\n\n\ndef prepare_dict_from_db_query(polys):\n obj = {}\n for poly in polys:\n obj[poly[0]] = {}\n obj[poly[0]][\"coords\"] = []\n obj[poly[0]][\"name\"] = poly[2]\n obj[poly[0]][\"rooms\"] = poly[3]\n obj[poly[0]][\"area\"] = float(poly[4])\n tmp = poly[1].split(\",\")\n for i in tmp:\n tmpC = i.split(\" \")\n obj[poly[0]][\"coords\"].append([float(tmpC[1]), float(tmpC[0])])\n return obj\n\n\ndef list2dict(l):\n d = {}\n for item in l:\n si = item.split(\":\")\n d[si[0]] = si[1]\n return d\n\n\ndef getLocalIp():\n proc = subprocess.Popen('ipconfig | find /i \"ipv4\"', shell=True, stdout=subprocess.PIPE)\n ip = '127.0.0.1'\n while True:\n output = proc.stdout.readline()\n if output == b'' and proc.poll() is not None:\n break\n if output:\n ip = output.strip().decode('cp866').split(':')[1].strip()\n return ip\n\n\ndef createTotalRecord(records, search_str, search_in_elem, elem_placeholder_for_total, elem_skip):\n if records[search_in_elem] == search_str:\n for i in records:\n if i == elem_skip:\n continue\n records[i] = None\n records[elem_placeholder_for_total] = \"Итого\"\n return records\n\n\ndef set_select_all_options(obj):\n if 'select_all_this_values' in obj:\n obj['select_all_this_values'] = obj['select_all_this_values'].strip(']\"[')\n obj['select_all_this_values'] = [i.strip(\" '\")[:-4] for i in obj['select_all_this_values'].split(',')]\n for i in obj['select_all_this_values']:\n obj[i] = 'select_all_this_values'\n return obj\n else:\n return obj\n","sub_path":"src/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":11374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66889735","text":"import unittest as ut\nimport unittest.mock as mock\nfrom asyncio import new_event_loop\n\nimport pytest\n\nimport cardinal.utils as utils\nfrom cardinal.errors import PromptTimeout\n\nfrom . import CoroMock\n\n\nclass FormatMessageTestCase(ut.TestCase):\n def setUp(self):\n msg = mock.NonCallableMock()\n msg.content = 'Test message'\n msg.author.name = 'Test author name'\n msg.author.id = 123456789\n msg.guild = None\n self.msg = msg\n\n def test_dm(self):\n expected = '[DM] {0.author.name} ({0.author.id}): {0.content}'.format(self.msg)\n got = utils.format_message(self.msg)\n self.assertMultiLineEqual(expected, got)\n\n def test_guild(self):\n self.msg.guild = mock.NonCallableMock()\n self.msg.guild.name = 'Test guild'\n self.msg.guild.id = 987654321\n self.msg.channel.name = 'Test channel'\n self.msg.channel.id = 123459876\n\n expected = '[{0.guild.name} ({0.guild.id}) -> #{0.channel.name} ({0.channel.id})] {0.author.name} ({0.author.id}): {0.content}'.format(self.msg)\n got = utils.format_message(self.msg)\n self.assertMultiLineEqual(expected, got)\n\n\nclass CleanPrefixTestCase(ut.TestCase):\n def setUp(self):\n ctx = mock.NonCallableMock()\n ctx.me.mention = '<@123456789>'\n ctx.me.name = 'Test bot'\n ctx.guild = None\n self.ctx = ctx\n\n def test_regular_dm(self):\n self.ctx.prefix = '?'\n expected = '?'\n got = utils.clean_prefix(self.ctx)\n self.assertMultiLineEqual(expected, got)\n\n def test_mention_dm(self):\n self.ctx.prefix = self.ctx.me.mention\n expected = '@{}'.format(self.ctx.me.name)\n got = utils.clean_prefix(self.ctx)\n self.assertMultiLineEqual(expected, got)\n\n def test_regular_guild_no_nick(self):\n self.ctx.guild = True\n self.ctx.me.nick = None\n self.ctx.prefix = '?'\n expected = '?'\n got = utils.clean_prefix(self.ctx)\n self.assertMultiLineEqual(expected, got)\n\n def test_mention_guild_no_nick(self):\n self.ctx.guild = True\n self.ctx.me.nick = None\n self.ctx.prefix = self.ctx.me.mention\n expected = '@{}'.format(self.ctx.me.name)\n got = utils.clean_prefix(self.ctx)\n self.assertMultiLineEqual(expected, got)\n\n def test_regular_guild_nick(self):\n self.ctx.guild = True\n self.ctx.me.nick = 'Test nick'\n self.ctx.prefix = '?'\n expected = '?'\n got = utils.clean_prefix(self.ctx)\n self.assertMultiLineEqual(expected, got)\n\n def test_mention_guild_nick(self):\n self.ctx.guild = True\n self.ctx.me.nick = 'Test nick'\n self.ctx.prefix = self.ctx.me.mention\n expected = '@{}'.format(self.ctx.me.nick)\n got = utils.clean_prefix(self.ctx)\n self.assertMultiLineEqual(expected, got)\n\n\nclass TestPrompt:\n @pytest.fixture\n def loop(self):\n return new_event_loop()\n\n @pytest.fixture\n def bot(self, mocker):\n _bot = mocker.Mock()\n _bot.wait_for = CoroMock()\n\n return _bot\n\n @pytest.fixture\n def ctx(self, mocker, bot):\n ctx = mocker.Mock()\n ctx.bot = bot\n ctx.send = CoroMock()\n\n return ctx\n\n @pytest.fixture\n def msg(self, mocker):\n return mocker.Mock()\n\n def test_response(self, ctx, loop, mocker, msg):\n expected = mocker.Mock()\n ctx.bot.wait_for.coro.return_value = expected\n\n response = loop.run_until_complete(utils.prompt(msg, ctx))\n assert response is expected\n\n def test_default_timeout(self, ctx, loop, msg):\n loop.run_until_complete(utils.prompt(msg, ctx))\n\n assert ctx.bot.wait_for.call_count == 1\n\n args, kwargs = ctx.bot.wait_for.call_args\n assert args == ('message',)\n assert kwargs['timeout'] == 60.0\n\n def test_custom_timeout(self, ctx, loop, msg):\n loop.run_until_complete(utils.prompt(msg, ctx, 1234))\n\n assert ctx.bot.wait_for.call_count == 1\n\n args, kwargs = ctx.bot.wait_for.call_args\n assert args == ('message',)\n assert kwargs['timeout'] == 1234\n\n def test_pred(self, ctx, loop, msg):\n loop.run_until_complete(utils.prompt(msg, ctx))\n\n *_, kwargs = ctx.bot.wait_for.call_args\n pred = kwargs['check']\n assert callable(pred)\n\n # Two conditions => four possible combinations\n # False, False\n msg.author.id = 1\n ctx.author.id = 2\n msg.channel.id = 3\n ctx.channel.id = 4\n assert not pred(msg)\n\n # False, True\n ctx.channel.id = 3\n assert not pred(msg)\n\n # True, False\n ctx.channel.id = 4\n ctx.author.id = 1\n assert not pred(msg)\n\n # True, True\n ctx.channel.id = 3\n assert pred(msg)\n\n def test_timeout_not_triggered(self, ctx, loop, msg):\n loop.run_until_complete(utils.prompt(msg, ctx))\n ctx.send.assert_called_once_with(msg)\n\n def test_timeout_triggered(self, ctx, loop, msg):\n ctx.bot.wait_for.coro.return_value = None\n\n with pytest.raises(PromptTimeout):\n loop.run_until_complete(utils.prompt(msg, ctx))\n\n ctx.send.assert_called_once_with(msg)\n","sub_path":"tests/test_cardinal/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"171641380","text":"import sys\nimport operator\nimport binascii\n\n\ndef get_bytes(filename):\n lang = {}\n count = 0\n with open(filename, \"rb\") as f:\n bytes_read = f.read(512)\n while True:\n if not bytes_read:\n break\n bytes_read = f.read(512)\n for byte in bytes_read:\n if byte > 127:\n count += 1\n cha = bytearray([byte])\n lang[bytes(cha)] = lang.get(bytes(cha), 0) + 1\n to_ret = {n: (lang[n] * 100 / count) for n in list(lang.keys())}\n return sorted(to_ret.items(), key=operator.itemgetter(1), reverse=True)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: \" + __file__ + \" file_name\")\n else:\n try:\n print(get_bytes(sys.argv[1]))\n except OSError as e:\n print(\"Unable to read: \", e, file=sys.stderr)\n","sub_path":"problems-2/n-shashok/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188425010","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport mysql.connector\nimport random\nimport time\nimport redis\nimport sys\nimport configparser\n\nenv = 'lkker'\nbduid = 1\nbduname = 'test{}'.format(bduid)\nconf_file = './../config/sql.conf'\nconfig = configparser.ConfigParser()\n\n# 从配置文件中读取mysql和reids配置\nconfig.read(conf_file,encoding='utf-8')\n\nDATABASE_NAME = config[env]['DATABASE_NAME']\nMYSQL_HOST = config[env]['MYSQL_HOST']\nMYSQL_PORT = config[env]['MYSQL_PORT']\nUSER_NAME = config[env]['USER_NAME']\nPASSWORD = config[env]['PASSWORD']\nCHAR_SET = config[env]['CHAR_SET']\n\nREDIS_HOST = config[env]['REDIS_HOST']\nREDIS_PORT = config[env]['REDIS_PORT']\n\n#redis\ndef may_redis(bduid):\n userkey = 'may:user:%s' % bduid\n cashkey = 'may:cash:%s' % bduid\n r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT,db=0)\n r.delete(userkey)\n r.hmset(userkey,{'aiqiyi':'15','film':'15','cash_2':'15','fuel_20':'15','iphone7p':'15','mac_air':'15','travel':'15'})\n r.hmset(userkey,{'ki':1,'zn':1,'zi':1,'qn':1})\n r.delete(cashkey)\n bduname = 'test{}'.format(bduid)\n r.hmset(cashkey,{'bduname':bduname,'ki':1,'zn':1,'zi':1,'qn':1})\n print ('user %s info is:%s' % (bduid, r.hgetall(userkey)))\n print ('user %s cash is:%s' % (bduid, r.hgetall(cashkey)))\nwhile bduid < 10:\n may_redis(bduid)\n bduid +=1\n\n# mysql\nconn = mysql.connector.connect(\n host = MYSQL_HOST,\n port = MYSQL_PORT,\n user = USER_NAME,\n passwd = PASSWORD,\n db = DATABASE_NAME,\n charset = 'utf8'\n)\ncursor = conn.cursor()\n\ncategory_list = ['zhuanche','filmcoupon','scene_120','waimai_15','aiqiyi','film','cash_2','fuel_20','iphone7p','mac_air','travel','cash_5']\ncuid = ''\nmobile = ''\nnum = 1\nresult = 0\ndetail = ''\ncreate_time = int(time.time())\nconsignee = ''\naddress = ''\nis_received = 1\n\nfor i in category_list:\n # time.sleep(1)\n category = i\n if i in ['aiqiyi','film','cash_2','fuel_20','iphone7p','mac_air','travel','cash_5']:\n is_received = 0\n try:\n sql = \"INSERT INTO `test` (`bduid`,`bduname`,`cuid`,`category`,`mobile`,`num`,`result`,`detail`,`create_time`,`consignee`,`address`,`is_received`) VALUES ('%d','%s','%s','%s','%s','%d','%d','%s','%d','%s','%s','%d')\"\n cursor.execute(sql % (bduid,bduname,cuid,category,mobile,num,result,detail,create_time,consignee,address,is_received))\n print ('NO.%s insert success' % i)\n conn.commit()\n except Exception as e:\n print ('NO.%s insert failed, fail reason is %s' % (i, e))\n pass\n# print(cursor.fetchall())\ncursor.close()\nconn.close()\n\n","sub_path":"tools/mayday.py","file_name":"mayday.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68082180","text":"#!/usr/bin/env python\n# Copyright 2017 Authors of Cilium\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport logging\nimport re\nimport os\nimport shutil\nimport subprocess\nimport utils\n\n\nlog = logging.getLogger(__name__)\n\n\nclass SysdumpCollector(object):\n \"\"\"Collects logs and other useful information for debugging.\n\n Args:\n sysdump_dir_name: the sysdump file name.\n since: the relative duration duration (like 5s, 2m, or 3h) used to\n decide how old the logs can be for them to be collected.\n size_limit: size limit (MB) for the collected logs.\n \"\"\"\n\n def __init__(\n self,\n sysdump_dir_name, since, size_limit, output):\n self.sysdump_dir_name = sysdump_dir_name\n self.since = since\n self.size_limit = size_limit\n self.output = output\n\n def collect_nodes_overview(self):\n nodes_overview_file_name = \"nodes-{}.json\".format(\n utils.get_current_time())\n cmd = \"kubectl get nodes -o json > {}/{}\".format(\n self.sysdump_dir_name, nodes_overview_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect nodes overview: {}\".\n format(exc, nodes_overview_file_name))\n else:\n log.info(\"collected nodes overview: {}\"\n .format(nodes_overview_file_name))\n\n def collect_pods_overview(self):\n pods_overview_file_name = \"pods-{}.json\".format(\n utils.get_current_time())\n cmd = \"kubectl get pods -o json --all-namespaces > {}/{}\".format(\n self.sysdump_dir_name, pods_overview_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect pods overview: {}\".\n format(exc, pods_overview_file_name))\n else:\n log.info(\"collected pods overview: {}\"\n .format(pods_overview_file_name))\n\n def collect_pods_summary(self):\n pods_summary_file_name = \"pods-{}.txt\".format(\n utils.get_current_time())\n cmd = \"kubectl get pods --all-namespaces -o wide > {}/{}\".format(\n self.sysdump_dir_name, pods_summary_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect pods summary: {}\".\n format(exc, pods_summary_file_name))\n else:\n log.info(\"collected pods summary: {}\"\n .format(pods_summary_file_name))\n\n def collect_logs(self, label_selector):\n for name, _, _, _ in \\\n utils.get_pods_status_iterator_by_labels(label_selector):\n log_file_name = \"{}-{}\".format(name,\n utils.get_current_time())\n command = \"kubectl logs {} --timestamps=true --since={} \" \\\n \"--limit-bytes={} -n kube-system {} > {}/{}.log\"\n cmd = command.format(\n \"\", self.since, self.size_limit, name,\n self.sysdump_dir_name, log_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect log file: {}\"\n .format(exc, log_file_name))\n else:\n log.info(\"collected log file: {}\".format(log_file_name))\n\n # Previous containers\n log_file_name_previous = \"{0}-previous\".format(log_file_name)\n cmd = command.format(\n \"--previous\", self.since, self.size_limit, name,\n self.sysdump_dir_name, log_file_name_previous)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.debug(\n \"Debug: {}. Could not collect previous \"\n \"log for '{}': {}\"\n .format(exc, name, log_file_name))\n else:\n log.info(\"collected log file: {}\".format(\n log_file_name_previous))\n\n def collect_gops_stats(self, label_selector):\n self.collect_gops(label_selector, \"stats\")\n self.collect_gops(label_selector, \"memstats\")\n self.collect_gops(label_selector, \"stack\")\n\n def collect_gops(self, label_selector, type_of_stat):\n for name, _, _, _ in \\\n utils.get_pods_status_iterator_by_labels(label_selector):\n file_name = \"{}-{}-{}.txt\".format(name,\n utils.get_current_time(),\n type_of_stat)\n cmd = \"kubectl exec -it -n kube-system {} -- \" \\\n \"/bin/gops {} 1 > {}/{}\".format(\n name, type_of_stat, self.sysdump_dir_name, file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect gops {}: {}\"\n .format(exc, type_of_stat, file_name))\n else:\n log.info(\"collected gops {} file: {}\".format(\n type_of_stat, file_name))\n\n def collect_cnp(self):\n cnp_file_name = \"cnp-{}.yaml\".format(utils.get_current_time())\n cmd = \"kubectl get cnp -o yaml --all-namespaces > {}/{}\".format(\n self.sysdump_dir_name, cnp_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect cilium network \"\n \"policy: {}\".format(exc, cnp_file_name))\n else:\n log.info(\"collected cilium network policy: {}\"\n .format(cnp_file_name))\n\n def collect_cep(self):\n cep_file_name = \"cep-{}.yaml\".format(utils.get_current_time())\n cmd = \"kubectl get cep -o yaml --all-namespaces > {}/{}\".format(\n self.sysdump_dir_name, cep_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Could not collect cilium endpoints {}\"\n .format(exc, cep_file_name))\n else:\n log.info(\"collected cilium endpoints: {}\".format(cep_file_name))\n\n def collect_daemonset_yaml(self):\n daemonset_file_name = \"cilium-ds-{}.yaml\".format(\n utils.get_current_time())\n cmd = \"kubectl get ds cilium -n kube-system -oyaml > {}/{}\".format(\n self.sysdump_dir_name, daemonset_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Unable to get cilium daemonset yaml\"\n .format(exc))\n else:\n log.info(\"collected cilium daemonset yaml file: {}\".format(\n daemonset_file_name))\n\n def collect_cilium_configmap(self):\n configmap_file_name = \"cilium-configmap-{}.yaml\".format(\n utils.get_current_time())\n cmd = \"kubectl get configmap cilium-config -n kube-system -oyaml \" \\\n \"> {}/{}\".format(self.sysdump_dir_name, configmap_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Unable to get cilium configmap yaml\"\n .format(exc))\n else:\n log.info(\"collected cilium configmap yaml file: {}\".format(\n configmap_file_name))\n\n def collect_cilium_secret(self):\n secret_file_name = \"cilium-etcd-secrets-{}.json\".format(\n utils.get_current_time())\n cmd = \"kubectl get secret cilium-etcd-secrets -n kube-system -o json\"\n try:\n output = json.loads(subprocess.check_output(cmd, shell=True))\n data = {}\n for key, value in output.get('data').iteritems():\n data[key] = \"XXXXX\"\n output['data'] = data\n with open(\n os.path.join(self.sysdump_dir_name,\n secret_file_name), 'w') as fp:\n fp.write(json.dumps(output))\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Unable to get and redact cilium secret\"\n .format(exc))\n else:\n log.info(\"collected and redacted cilium secret file: {}\".format(\n secret_file_name))\n\n def collect_cilium_bugtool_output(self):\n for name, _, _, _ in \\\n utils.get_pods_status_iterator_by_labels(\"k8s-app=cilium\"):\n bugtool_output_file_name = \"bugtool-{}-{}.tar\".format(\n name, utils.get_current_time())\n cmd = \"kubectl exec -n kube-system -it {} cilium-bugtool\".format(\n name)\n try:\n encoded_output = subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\n \"Error: {}. Could not run cilium-bugtool on {}\"\n .format(exc, name))\n else:\n output = encoded_output.decode()\n p = re.compile(\n \"^ARCHIVE at (.*)$\")\n output_file_name = \"\"\n for line in output.splitlines():\n match = p.search(line)\n if match:\n output_file_name = match.group(1)\n if output_file_name == \"\":\n log.error(\n \"Error: {}. Could not find cilium-bugtool output\"\n \" file name\".format(exc))\n\n cmd = \"kubectl cp kube-system/{}:{} ./{}/{}\".format(\n name, output_file_name, self.sysdump_dir_name,\n bugtool_output_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\n \"Error: {} Could not collect cilium-bugtool\"\n \" output: {}\".format(\n exc, bugtool_output_file_name))\n else:\n log.info(\"collected cilium-bugtool output: {}\".format(\n bugtool_output_file_name))\n\n def collect_services_overview(self):\n svc_file_name = \"services-{}.yaml\".format(\n utils.get_current_time())\n cmd = \"kubectl get svc --all-namespaces -oyaml \" \\\n \"> {}/{}\".format(self.sysdump_dir_name, svc_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Unable to get svc overview\")\n else:\n log.info(\"collected svc overview: {}\".format(svc_file_name))\n\n def collect_k8s_version_info(self):\n version_file_name = \"k8s-version-info-{}.txt\".format(\n utils.get_current_time())\n cmd = \"kubectl version > {}/{}\".format(self.sysdump_dir_name,\n version_file_name)\n try:\n subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as exc:\n if exc.returncode != 0:\n log.error(\"Error: {}. Unable to get kubernetes version info\")\n else:\n log.info(\"collected kubernetes version info: {}\"\n .format(version_file_name))\n\n def collect(self):\n log.info(\"collecting kubernetes version info ...\")\n self.collect_k8s_version_info()\n log.info(\"collecting nodes overview ...\")\n self.collect_nodes_overview()\n log.info(\"collecting pods overview ...\")\n self.collect_pods_overview()\n log.info(\"collecting pods summary ...\")\n self.collect_pods_summary()\n log.info(\"collecting services overview ...\")\n self.collect_services_overview()\n log.info(\"collecting cilium gops stats ...\")\n self.collect_gops_stats(\"k8s-app=cilium\")\n log.info(\"collecting cilium network policy ...\")\n self.collect_cnp()\n log.info(\"collecting cilium etcd secret ...\")\n self.collect_cilium_secret()\n log.info(\"collecting cilium endpoints ...\")\n self.collect_cep()\n log.info(\"collecting cilium daemonset yaml ...\")\n self.collect_daemonset_yaml()\n log.info(\"collecting cilium configmap yaml ...\")\n self.collect_cilium_configmap()\n log.info(\"collecting cilium-bugtool output ...\")\n self.collect_cilium_bugtool_output()\n log.info(\"collecting cilium logs ...\")\n self.collect_logs(\"k8s-app=cilium\")\n\n def archive(self):\n filename = self.output or self.sysdump_dir_name\n archive_name = shutil.make_archive(filename, 'zip',\n self.sysdump_dir_name)\n log.info(\"deleting directory: {}\".format(self.sysdump_dir_name))\n shutil.rmtree(self.sysdump_dir_name)\n log.info(\"the sysdump has been saved in the file {}.\"\n .format(archive_name))\n","sub_path":"cluster-diagnosis/sysdumpcollector.py","file_name":"sysdumpcollector.py","file_ext":"py","file_size_in_byte":14663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630038872","text":"import logging\n\nfrom guardian.shortcuts import get_objects_for_user\nfrom rest_framework import serializers\n\nfrom projects import models\nfrom stolos_watchd.models import ProjectRoutingConfig\nfrom stolos_watchd.serializers import ProjectRoutingConfigSerializer\n\n\nclass ServerSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Server\n\n\nclass StackSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Stack\n\n\nclass ProjectSerializer(serializers.ModelSerializer):\n routing_config = ProjectRoutingConfigSerializer(many=False)\n server = ServerSerializer(many=False, read_only=True)\n set_stack = serializers.SlugRelatedField(\n slug_field='slug',\n queryset=models.Stack.objects.all(),\n write_only=True,\n allow_null=True,\n )\n stack = StackSerializer(many=False, read_only=True)\n owner = serializers.SlugRelatedField(\n read_only=True,\n slug_field='username',\n default=serializers.CreateOnlyDefault(\n serializers.CurrentUserDefault()),\n )\n\n def __init__(self, *args, **kwargs):\n super(ProjectSerializer, self).__init__(*args, **kwargs)\n if 'request' in self.context:\n self.fields['stack'].queryset = get_objects_for_user(\n self.context['request'].user, ['view_stack'], models.Stack)\n\n class Meta:\n model = models.Project\n fields = ('uuid', 'stack', 'set_stack', 'server', 'owner', 'created',\n 'last_update', 'routing_config')\n read_only_fields = ('uuid', 'server', 'created', 'last_update')\n\n def create(self, validated_data):\n routing_config = validated_data.pop('routing_config')\n validated_data['stack'] = validated_data.pop('set_stack')\n project = models.Project(**validated_data)\n project.save()\n ProjectRoutingConfig(project=project, **routing_config).save()\n return project\n","sub_path":"projects/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459061526","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nimport numpy as np\nfrom math import log\nimport scipy.io as scio\nimport pandas as pd\nimport operator\nfrom sklearn.model_selection import train_test_split\n\n\ndef loadData():\n data = scio.loadmat(\"Sogou_data/Sogou_webpage.mat\")\n word_mat = data['wordMat'] # 14400*1200 doc_num * keyword_num\n doc_label = data['doclabel']# 14400*1 每篇文档对应的标签\n data_frame = pd.read_excel('Sogou_data/keyword.xls')\n keyword = data_frame.values[:,1] # 1200个关键词\n # 3:1:1 train:validation:test\n X_train, X_test, y_train, y_test = train_test_split(word_mat, doc_label, test_size=0.2)\n X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25)\n return X_train, X_val,X_test, y_train, y_val, y_test, keyword\n\n\ndef GenerateTree(dataSet,labels,featLabels,thresh):\n classList=[example[-1] for example in dataSet]\n if classList.count(classList[0])/len(classList) > thresh:\n return classList[0]\n if len(dataSet[0])==1:\n major, _ = majorCnt(classList)\n return major\n bestFeat=SelectFeature(dataSet)\n bestFeatLabel=labels[bestFeat]\n featLabels.append(bestFeatLabel)\n myTree={bestFeatLabel.tolist():{}}\n del(labels[bestFeat])\n featValues = [example[bestFeat] for example in dataSet]\n uniqueVls = set(featValues)\n for value in uniqueVls:\n myTree[bestFeatLabel][value] = GenerateTree(SplitNode(dataSet, bestFeat, value),\n labels, featLabels)\n return myTree\n\n\ndef SplitNode(dataSet, axis, value): #对当前节点进行分支\n # 创建返回的数据集列表\n retDataSet = []\n # 遍历数据集\n for featVec in dataSet: #每一行\n if featVec[axis] == value:\n # 去掉axis特征\n reduceFeatVec = featVec[:axis].tolist()\n # 将符合条件的添加到返回的数据集\n reduceFeatVec.extend(featVec[axis + 1:])\n retDataSet.append(reduceFeatVec)\n # 返回划分后的数据集\n return retDataSet\n\n\ndef SelectFeature(dataSet): #对当前节点选择待分特征\n numFeatures = len(dataSet[0]) - 1\n baseEntropy = Impurity(dataSet)\n bestInfoGain = 0.0\n bestFeature = -1\n for i in range(numFeatures):\n featList = [example[i] for example in dataSet]\n uniqueVals = set(featList)\n newEntropy = 0.0\n for value in uniqueVals:\n subDataSet = SplitNode(dataSet, i, value)\n prob = len(subDataSet) / float(len(dataSet))\n newEntropy += prob * Impurity((subDataSet))\n infoGain = baseEntropy - newEntropy\n print(\"第%d个特征的增益为%.3f\" % (i, infoGain))\n if (infoGain > bestInfoGain):\n bestInfoGain = infoGain\n bestFeature = i\n return bestFeature\n\n\ndef Impurity(dataSet):\n numEntries = len(dataSet)\n labelCounts = {}\n for featVec in dataSet:\n currentLabel = featVec[-1]\n if currentLabel not in labelCounts.keys():\n labelCounts[currentLabel] = 0\n labelCounts[currentLabel] += 1\n\n shannonEnt = 0.0\n for key in labelCounts:\n prob = float(labelCounts[key]) / numEntries\n shannonEnt -= prob * log(prob, 2)\n return shannonEnt \n \n \ndef majorCnt(classList):\n classCount={}\n for vote in classList:\n if vote not in classCount.keys():\n classCount[vote]=0\n classCount[vote]+=1\n #降序\n sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n mis_impurity = 1 - sortedClassCount[0][0] / np.sum(classCount.items()) #采用错分不纯度\n return sortedClassCount[0][0], mis_impurity\n\n\n# 使用生成的树GenerateTree,对样本XToBePredicted进行预测\ndef Decision(inputTree,featLabels,testVec):\n firstStr=next(iter(inputTree))\n secondDict=inputTree[firstStr]\n featIndex=featLabels.index(firstStr)\n\n for key in secondDict.keys():\n if testVec[featIndex]==key:\n if type(secondDict[key]).__name__=='dict':\n classLabel=Decision(secondDict[key],featLabels,testVec)\n else: classLabel=secondDict[key]\n return classLabel\n\n\n# def Prune(GenerateTree, CrossValidationDataset):#对已经生成好并停止分支的树进行剪枝:\n # 考虑所有相邻的叶子节点,如果将他们消去可以增加验证集上的正确率,则减去两叶子节点,将他们的共同祖先作为新的叶子节点\n\n\ndef main():\n #import data\n X_train, X_val, X_test, y_train, y_val, y_test, propertyName = loadData()\n featLabels = []\n myTree = GenerateTree(X_train, y_train, featLabels)\n\n # 测试数据\n pre_label = Decision(myTree, featLabels, X_test)\n\n print(accuracy)\n\nif __name__ =='__main__':\n main()\n","sub_path":"11Decision Tree/code/decisionTree.py","file_name":"decisionTree.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"12076956","text":"import math\nimport sys\n#The sys.exit function was used here in order to prevent the program\n#from running when the BOND calculation was complete. Without, it would\n#give an error message with regards to the INVESTMENT option.\n\n#This is a welcome message\n\nprint('''Welcome to Second Investment Bank.\nWe are an investment bank established to cater to your investment desires.''')\n\n#The boolean variable was created to verify valid input from the user.\n\nvalid_input = True\n\n\ninv_option = str(input('''We can assist you in calculating the following:\n- Investment: The amount of interest earned on your investment\n- Bond: The amount you would need to pay on a home loan\nWhich of the aforementioned calculators would you like to access?:'''))\n\n#The characrer count helps in determining an invalid input by the user.\n#The following section will aid in validating the input of the user.\n#The numbers 4 & 10 correspond to the number of characters in bond &\n#investment respectively. The logical statement was added to further\n#validate the users input.\n\nnum_of_char = len(inv_option)\n\nif (num_of_char > 4 <= 10 and inv_option == \"investment\"):\n valid_input = True\n\nif (num_of_char > 4 <= 10 and inv_option != \"investment\"):\n valid_input = False\n print('''An error has occured in trying to identify your\nselection. Please select one of the aforementioned calculators.''')\n\n\nif (num_of_char < 4):\n valid_input = False\n print('''An error has occured in trying to identify your\nselection. Please select one of the aforementioned calculators.''')\n\n\n\n#This section will cover the investment & bond calculator\n\nif (valid_input == True and inv_option == \"investment\"):\n P = float(input(\"How much are you willing to deposit?:\"))\n r = float(input(\"What is your desired interest rate?:\"))\n t = float(input(\"How many years are you willing to invest?:\"))\n interest = str(input('''Are you willing to invest on simple interest or\ncompound interest?:'''))\n\nelif (valid_input == True and inv_option == \"bond\"):\n P = float(input(\"What is the present value of your home?:\"))\n i = float(input(\"What is your annual interest rate?:\"))\n n = float(input(\"How many months are you paying towards your bond:\"))\n bond_pay = round(((((i/100)/12))*P)/(1-(1+((i/100)/12))**(-n)), 0)\n print(f\"Your month payment towards your bond is R{bond_pay}.\")\n sys.exit()\n#See the comment above with regards to the sys.exit() function\n\n\n#This is dependent on the selection of the user, whether they choose\n#simple or compound interest.\n\nsimple = round(float(P*(1+(r/100)*t)), 0)\ncompound = round(float(P*math.pow((1+(r/100)),t)), 0)\n\nif (interest == \"simple\"):\n print(f\"Return on investment with simple interest {simple}.\")\nelif(interest == \"compound\"):\n print(f'''Your retrun on investment with compound interest\nis {compound}.''')\n","sub_path":"financial_calculators.py","file_name":"financial_calculators.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191801565","text":"# -*- coding:utf-8 -*-\r\n\r\nimport math\r\nfrom collections import Counter\r\nfrom openpyxl import load_workbook, Workbook\r\nfrom operator import itemgetter\r\nfrom numpy import *\r\n\r\nclass Dataset:\r\n\tdef __init__(self, listArray, stopWords, minimum_word_length = 3, minimum_word_count = 3):\r\n\t\tself.dataset = {}\r\n\t\tself.dataLine = {}\r\n\t\tself.wordList = []\r\n\t\tself.minLength = minimum_word_length\r\n\t\tself.minCount = minimum_word_count\r\n\t\tself.wordCount = {}\r\n\t\tself.numOfTotalWords = 0\r\n\t\tself.loadData(listArray, stopWords)\r\n\r\n\tdef __str__(self):\r\n\t\treturn repr([self.dataset, self.dataLine])\r\n\r\n\tdef loadData(self, lines, stopWords):\r\n\t\titab = '!\"#$%&()*+,./:;<=>?[\\]^_`{|}~@\\''\r\n\t\totab = ' '\r\n\t\t# itab = '!\",.:;?#$%|{}[]()-'\r\n\t\t# otab = ' '\r\n\t \r\n\t\tbuffer = []\r\n\t\tfor line in lines:\r\n\t\t\tkey = line[:9]\r\n\t\t\tdesc = line[12:]\r\n\t\t\t# values = set(desc.translate(str.maketrans(itab,otab)).lower().split())\r\n\t\t\tvalues = desc.translate(str.maketrans(itab,otab)).lower().split()\r\n\t\t\t# values = [x for x in values if len(x) >= self.minLength and not x.isdigit()]\t\r\n\t\t\tvalues = [x for x in values if not x.isdigit()]\t\r\n\t\t\tfor stopWord in stopWords:\r\n\t\t\t\twhile values.count(stopWord) > 0 : values.remove(stopWord)\r\n\t\t\tself.dataset[key] = values\r\n\t\t\tself.dataLine[key] = desc\r\n\t\t\tbuffer.extend(values)\r\n\r\n\t\tself.wordCount = Counter(buffer)\r\n\t\tfor k, v in self.wordCount.items():\r\n\t\t\tif v >= self.minCount or len(k) >= self.minLength : \r\n\t\t\t\tself.wordList.append(k)\r\n\t\t\t\tself.numOfTotalWords += v\r\n\r\ndef readFile(filename):\r\n\twith open(filename, 'rt') as f:\r\n\t\tlines = f.readlines()\r\n\treturn lines\t\t\r\n\r\ndef loadExcel(filename, worksheet=None):\r\n\twb = load_workbook(filename)\r\n\tsheetNames = []; dic = {}\r\n\tif worksheet is None: sheetNames = wb.get_sheet_names()\r\n\telse: sheetNames.append(worksheet)\r\n\tfor name in sheetNames:\r\n\t\tws = wb[name]\r\n\t\tdata = []\r\n\t\tfor row in ws.rows:\r\n\t\t\tfor cell in row:\r\n\t\t\t\tif cell.value != None: data.append(str(cell.value).strip())\r\n\t\tdic[name] = data\r\n\treturn dic\r\n\r\ndef dict2array(dic, header):\r\n\tfmt = ['f8' for i in range(len(header))]\r\n\tdata_type = dict(names = header, formats = fmt)\r\n\treturn array([[key,val] for (key,val) in array.items()], data_type)\r\n\r\ndef dict2list(dic):\r\n\tresult = []\r\n\tfor key, values in dic.items():\r\n\t\tif type(values) != list:\r\n\t\t\tresult += [[key] + [values]]\r\n\t\telse:\r\n\t\t\tresult += [[key] + values]\r\n\treturn result\r\n\r\ndef reportResult(dic, filename=\"Dataset.xlsx\"):\r\n\twb = Workbook()\r\n\tfor sheetName, dataset in dic.items():\r\n\t\tws = wb.create_sheet(title=sheetName)\r\n\t\tfor data in dataset:\r\n\t\t\tws.append(data)\r\n\ttry:\r\n\t\twb.save(filename)\r\n\texcept PermissionError as e:\r\n\t\tprint(e)\r\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432759651","text":"\"\"\"\r\nAll important imports, which are needed for running program properly\r\n\"\"\"\r\nimport csv\r\nimport os\r\nimport tkinter\r\nfrom tkinter import *\r\nfrom tkinter.ttk import *\r\nimport tkinter.messagebox\r\n\r\n\r\nclass GUI(Frame):\r\n \"\"\"\r\n Creating class, which is base of GUI\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.initUI()\r\n\r\n def initUI(self):\r\n\r\n \"\"\"\r\n Defining method where everything will be implemented\r\n :return:\r\n \"\"\"\r\n\r\n fileExist = os.path.isfile('People.csv')\r\n header = ['NAME:', 'SURNAME:', 'AGE:']\r\n addon = []\r\n\r\n def clearAction():\r\n \"\"\"\r\n Implementing button action which clears all text boxes.\r\n \"\"\"\r\n area1.delete(0, 'end')\r\n area2.delete(0, 'end')\r\n area3.delete(0, 'end')\r\n\r\n def quitAction():\r\n \"\"\"\r\n Implementing button action which disposes a program.\r\n \"\"\"\r\n quit()\r\n\r\n def helpAction():\r\n \"\"\"\r\n Implementing button action which displays message window with describes all buttons\r\n \"\"\"\r\n tkinter.messagebox.showinfo('Help', 'Add button: Adds person from text areas\\n'\r\n 'Clear button: Clears entry boxes\\n'\r\n 'Quit button: Aborts program\\n'\r\n 'Show info button: Displays file. Enables after adding person. '\r\n 'Disables after clicking')\r\n\r\n def addAction():\r\n \"\"\"\r\n Implementing button action which allows us to create and add person\r\n from text boxes to a .csv file\r\n :return:\r\n \"\"\"\r\n displayBtn['state'] = NORMAL\r\n\r\n class Data:\r\n \"\"\"\r\n Implementing bridge design pattern.\r\n It will display headers preceding information from text boxes\r\n in messagebox to avoid any mistakes.\r\n \"\"\"\r\n\r\n @staticmethod\r\n def takeName():\r\n \"\"\"\r\n Header preceding information from first text box\r\n :return:\r\n \"\"\"\r\n return 'Name: '\r\n\r\n @staticmethod\r\n def takeSurname():\r\n \"\"\"\r\n Header preceding information from second text box\r\n :return:\r\n \"\"\"\r\n return 'Surname: '\r\n\r\n @staticmethod\r\n def takeAge():\r\n \"\"\"\r\n Header preceding information from third text box\r\n :return:\r\n \"\"\"\r\n return 'Age: '\r\n\r\n class Check:\r\n \"\"\"\r\n Impossible to implement bridge pattern without this constructor in this way\r\n \"\"\"\r\n\r\n def __init__(self, bridgePerson):\r\n self.bridgePerson = bridgePerson\r\n\r\n class Product:\r\n \"\"\"\r\n Similarly to bridge, builder could not be implemented without this\r\n \"\"\"\r\n\r\n def __init__(self, buildPerson):\r\n self.buildPerson = buildPerson\r\n\r\n class infoA(Check):\r\n \"\"\"\r\n Creating class for output for user\r\n \"\"\"\r\n\r\n def __init__(self, bridgePerson, objName, objSurname, objAge):\r\n super().__init__(bridgePerson)\r\n\r\n self.objName = objName\r\n self.objSurname = objSurname\r\n self.objAge = objAge\r\n\r\n def displayName(self):\r\n \"\"\"\r\n Function which allows us to see header preceding\r\n first information from text box in messagebox\r\n \"\"\"\r\n self.bridgePerson.takeName(self.objName)\r\n\r\n def displaySurname(self):\r\n \"\"\"\r\n Function which allows us to see header preceding\r\n second information from text box in messagebox\r\n \"\"\"\r\n\r\n self.bridgePerson.takeSurname(self.objSurname)\r\n\r\n def displayAge(self):\r\n \"\"\"\r\n Function which allows us to see header preceding\r\n third information from text box in messagebox\r\n \"\"\"\r\n self.bridgePerson.takeAge(self.objAge)\r\n\r\n class infoB(Product):\r\n \"\"\"\r\n Creating class which will allow us to build person\r\n and add it to .csv file by addAction\r\n \"\"\"\r\n\r\n def __init__(self, buildPerson, bName, bSurname, bAge):\r\n super().__init__(buildPerson)\r\n\r\n self.bName = bName\r\n self.bSurname = bSurname\r\n self.bAge = bAge\r\n\r\n def buildName(self):\r\n \"\"\"\r\n Function which builds name\r\n :return:\r\n \"\"\"\r\n self.bName = area1\r\n return self.bName\r\n\r\n def buildSurname(self):\r\n \"\"\"\r\n Function which builds surname\r\n :return:\r\n \"\"\"\r\n self.bSurname = area2\r\n return self.bSurname\r\n\r\n def buildAge(self):\r\n \"\"\"\r\n Function which builds age\r\n :return:\r\n \"\"\"\r\n self.bAge = area3\r\n return self.bAge\r\n\r\n data = Data()\r\n\r\n personInformation = infoA(Data, area1, area2, area3)\r\n infoBuild = infoB(Data, area1, area2, area3)\r\n\r\n addon.append(infoBuild.buildName().get())\r\n addon.append(infoBuild.buildSurname().get())\r\n addon.append(infoBuild.buildAge().get())\r\n\r\n personInformation.displayName = data.takeName()\r\n personInformation.displaySurname = data.takeSurname()\r\n personInformation.displayAge = data.takeAge()\r\n\r\n answer = tkinter.messagebox.askyesno('Confirmation', 'Do you really want to add this person?\\n' +\r\n\r\n str(personInformation.displayName) + str(area1.get()) + '\\n' +\r\n str(personInformation.displaySurname) + str(area2.get()) + '\\n' +\r\n str(personInformation.displayAge) + str(area3.get()))\r\n\r\n if answer is True:\r\n with open('People.csv', 'a', newline='') as csvfile:\r\n writer = csv.writer(csvfile)\r\n if not fileExist:\r\n writer.writerow(header)\r\n\r\n writer.writerow(addon)\r\n csvfile.close()\r\n addon.clear()\r\n area1.delete(0, 'end')\r\n area2.delete(0, 'end')\r\n area3.delete(0, 'end')\r\n\r\n else:\r\n addon.clear()\r\n\r\n def displayAction():\r\n \"\"\"\r\n Implementing button action which displays written .csv file with informations\r\n :return:\r\n \"\"\"\r\n\r\n class Singleton(object):\r\n \"\"\"\r\n Creating Singleton\r\n \"\"\"\r\n _instance = None\r\n\r\n def __init__(self):\r\n raise RuntimeError('Call instance() instead')\r\n\r\n @classmethod\r\n def instance(cls):\r\n \"\"\"\r\n Creating function which is instance of singleton\r\n :return:\r\n \"\"\"\r\n if cls._instance is None:\r\n print('Creating new instance')\r\n cls._instance = cls.__new__(cls)\r\n\r\n return cls._instance\r\n\r\n s1 = Singleton.instance()\r\n s2 = Singleton.instance()\r\n\r\n\r\n \"\"\"\r\n Implementing window after reading file\r\n \"\"\"\r\n if s1 == s2:\r\n\r\n displayBtn['state'] = DISABLED\r\n window = tkinter.Toplevel()\r\n window.geometry('350x720')\r\n window.title('Student informations')\r\n\r\n scr = tkinter.Scrollbar(master=window)\r\n txt = tkinter.Text(master=window, height=50, width=50)\r\n scr.pack(side=tkinter.RIGHT, fill=tkinter.Y)\r\n txt.pack(side=tkinter.LEFT, fill=tkinter.Y)\r\n scr.config(command=txt.yview)\r\n txt.config(yscrollcommand=scr.set)\r\n\r\n with open('People.csv', 'r', newline='') as csvfile:\r\n reader = csv.reader(csvfile, quotechar='|')\r\n for row in reader:\r\n txt.insert(tkinter.INSERT, '\\t\\t|'.join(row).strip() + '\\n')\r\n\r\n else:\r\n tkinter.messagebox.showerror('Already open', 'This database has been already opened')\r\n\r\n\r\n \"\"\"\r\n Implementing core window. \r\n \"\"\"\r\n self.master.title('Add student')\r\n self.pack(fill=BOTH, expand=True)\r\n\r\n self.columnconfigure(1, weight=1)\r\n self.columnconfigure(3, pad=7)\r\n self.rowconfigure(3)\r\n self.rowconfigure(5, pad=5)\r\n\r\n lbl = Label(self, text='Student:')\r\n lbl.grid(sticky='w', pady=4, padx=5)\r\n\r\n lbl = Label(self, text='Name:')\r\n lbl.grid(sticky='w', pady=4, padx=5)\r\n\r\n area1 = Entry(self)\r\n area1.grid(row=2, column=0, columnspan=2, rowspan=1, padx=5, sticky='new')\r\n\r\n lbl = Label(self, text='Surname:')\r\n lbl.grid(sticky='nw', pady=4, padx=5)\r\n\r\n area2 = Entry(self)\r\n area2.grid(row=3, column=0, columnspan=2, rowspan=1, padx=5, sticky='new', pady=26)\r\n\r\n lbl = Label(self, text='Age:')\r\n lbl.grid(row=3, sticky='nw', pady=65, padx=5)\r\n\r\n area3 = Entry(self)\r\n area3.grid(row=3, column=0, columnspan=2, rowspan=1, padx=5, sticky='new', pady=85)\r\n\r\n separator = Separator(self, orient=VERTICAL)\r\n separator.grid(column=3, row=0, rowspan=8, sticky='ns')\r\n\r\n addBtn = Button(self, text='Add', command=addAction)\r\n\r\n addBtn.grid(row=1, column=4, pady=4, padx=5)\r\n\r\n clearBtn = Button(self, text='Clear', command=clearAction)\r\n clearBtn.grid(row=2, column=4, pady=4, padx=5)\r\n\r\n helpBtn = Button(self, text='Help', command=helpAction)\r\n helpBtn.grid(row=4, column=0, padx=5)\r\n\r\n quitBtn = Button(self, text='Quit', command=quitAction)\r\n quitBtn.grid(row=4, column=4, padx=5)\r\n\r\n displayBtn = Button(self, text='Show info', command=displayAction)\r\n displayBtn['state'] = DISABLED\r\n displayBtn.grid(row=3, column=4, padx=5)\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Creating main function which will display whole window\r\n and will have all implemented before methods\r\n \"\"\"\r\n root = Tk()\r\n root.geometry('350x310+300+300')\r\n root = GUI()\r\n root.mainloop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201284989","text":"from menu import *\nimport random\nfrom class_player import Player\nfrom class_border import Border\nfrom class_bullet import Bullet\n\n\nbg = [\"backgrounds/background4.jpg\",\n \"backgrounds/background1.jpg\",\n \"backgrounds/background2.jpg\",\n \"backgrounds/background3.jpg\",\n \"backgrounds/background5.jpg\"]\n\npygame.init()\ninfoObject = pygame.display.Info()\nwidth = infoObject.current_w\nheight = infoObject.current_h\nscreen = pygame.display.set_mode((width, height), pygame.FULLSCREEN)\npygame.mixer.init()\npygame.display.set_caption('Hekatonkheries')\npygame.mixer.music.load(\"sounds/introSW.ogg\")\npygame.mixer.music.play(0)\nclock = pygame.time.Clock()\ntutorial(width, height, screen)\n\n\ndef main():\n\n background_image = pygame.transform.scale(pygame.image.load(random.choice(bg)).convert(), (width, height))\n pygame.joystick.init()\n joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]\n try:\n joysticks[0].init()\n joysticks[1].init()\n player1_joystick = joysticks[0]\n player2_joystick = joysticks[1]\n except IndexError:\n player1_joystick = None\n player2_joystick = None\n\n border = Border(10, width, height)\n picture_1 = pygame.transform.scale(pygame.image.load(\"pictures/falcon.png\"), (35, 35))\n picture_2 = pygame.transform.scale(pygame.image.load(\"pictures/tief.png\"), (35, 35))\n picture_r = pygame.transform.scale(pygame.image.load(\"pictures/proj_r.png\"), (30, 30))\n picture_b = pygame.transform.scale(pygame.image.load(\"pictures/proj_b.png\"), (30, 30))\n player_1 = Player(start_x=width/5*2, start_y=height-100, speed=4, direction=\"up\", player_img=picture_1,\n buttons={\"up\": pygame.K_UP, \"down\": pygame.K_DOWN, \"left\": pygame.K_LEFT, \"right\": pygame.K_RIGHT},\n joystick=player1_joystick, player_color=(0, 0, 255), player_id=1)\n player_2 = Player(start_x=width/5*4, start_y=height-100, speed=4, direction=\"up\", player_img=picture_2,\n buttons={\"up\": pygame.K_w, \"down\": pygame.K_s, \"left\": pygame.K_a, \"right\": pygame.K_d},\n joystick=player2_joystick, player_color=(255, 0, 0), player_id=2)\n\n # bullets\n bullet_list = []\n if player_1.joystick is not None and player_2.joystick is not None:\n for element in [0, 1, 2, 3]:\n bullet_list.append(Bullet(player_2, element, player_1, picture_r, (width - 150 - element*30, 15)))\n for element in [0, 1, 2, 3]:\n bullet_list.append(Bullet(player_1, element, player_2, picture_b, (0 + 15 + element*30, 15)))\n else:\n for i, element in enumerate([pygame.K_e, pygame.K_r, pygame.K_t, pygame.K_z]):\n bullet_list.append(Bullet(player_2, element, player_1, picture_r, (width - 150 - i*30, 15)))\n for i, element in enumerate([pygame.K_h, pygame.K_j, pygame.K_k, pygame.K_l]):\n bullet_list.append(Bullet(player_1, element, player_2, picture_b, (0 + 15 + i*30, 15)))\n\n game_intro(width, height, screen, clock, player_1, player_2)\n\n while True:\n quit_game()\n for i, bullet in enumerate(bullet_list):\n bullet.movement()\n bullet_collision = bullet.collide()\n if bullet_collision == 1:\n Player.player_scores[str(bullet.player.player_id)]\n game_end(\"Player %s win!\" % bullet.player.player_id,\n width, height, screen, player_1, player_2)\n main()\n if int(bullet_collision) > 0:\n bullet.enemy.lines.insert(bullet_collision - 2,\n pygame.Rect(bullet.enemy.lines[bullet_collision - 2].midtop[0],\n bullet.enemy.lines[bullet_collision - 2].midtop[1], 1, 1))\n del bullet.enemy.lines[bullet_collision - 1]\n del bullet_list[i]\n player_1.movement(screen)\n player_2.movement(screen)\n screen.fill((0, 0, 0))\n screen.blit(background_image, [0, 0])\n border.draw(screen)\n for bullet in bullet_list:\n if not bullet.bullet_bool:\n bullet.draw(screen)\n if bullet.bullet_counter_bool:\n bullet.draw_counter(screen)\n\n player_1.draw_line(screen)\n player_1.draw(screen)\n\n player_2.draw_line(screen)\n player_2.draw(screen)\n\n if player_1.collide(border, player_2):\n Player.player_scores['2'] += 1\n game_end(\"Player 2 win!\", width, height, screen, player_1, player_2)\n main()\n if player_2.collide(border, player_1):\n Player.player_scores['1'] += 1\n game_end(\"Player 1 win!\", width, height, screen, player_1, player_2)\n main()\n pygame.display.flip()\n clock.tick(60)\n\n\nmain()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274661115","text":"#1\n\nimport turtle\nbob = turtle.Turtle()\njohn = turtle.Turtle()\nprint(bob)\nprint(john)\n\ndef square(t):\n for i in range(4):\n t.fd(100)\n t.lt(90)\n \nsquare(bob)\nsquare(john)\nturtle.mainloop()\n\n#2\n\nimport turtle\nbob = turtle.Turtle()\njohn = turtle.Turtle()\nprint(bob)\nprint(john)\n\ndef square(t, length):\n for i in range(4):\n t.fd(length)\n t.lt(90)\n \nsquare(bob, 50)\nsquare(john, 100)\nturtle.mainloop()\n\n#3\n\nimport turtle\nbob = turtle.Turtle()\njohn = turtle.Turtle()\nprint(bob)\nprint(john)\n\n# n-sided polygon\ndef polygon(t, n, length):\n for i in range(n):\n t.fd(length)\n t.lt(360 / n)\n \npolygon(bob, 4, 50)\npolygon(john, 5, 100)\nturtle.mainloop()\n\n# 4\n\nimport turtle\nimport math\nbob = turtle.Turtle()\njohn = turtle.Turtle()\nprint(bob)\nprint(john)\n\n# n-approximate polygon-circle\ndef polygon(t, r, n):\n for i in range(n):\n t.fd((2 * math.pi * r) / n)\n t.lt(360 / n)\n \npolygon(bob, 100, 50)\npolygon(john, 100, 100)\nturtle.mainloop()\n","sub_path":"Ch. 4.py","file_name":"Ch. 4.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537815316","text":"# coding = utf-8\n__author__ = 'supercore'\nimport urllib.request\nimport re\nimport pandas as pd\nimport tushare as ts\nimport math\nimport datetime as dt\nimport time\nimport logbook\nimport os\nimport json\n\ndef _code_to_symbol(ocode):\n \"\"\"\n 生成symbol代码标志\n \"\"\"\n code = str(ocode)\n if code.startswith(('5','6','9','11','13')):\n return 'sh%s'%code\n elif code.startswith(('1000')):\n return 'CON_OP_%s'%code\n else :\n return 'sz%s'%code\n\n return ''\n\nclass Option(object):\n config_path = os.path.dirname(__file__) + '/config/token.txt'\n quote_cols = ['bid_v','bid_p','price','ask_p','ask_v','pos','rise','strike',\n 'pre_settle','open','up_limit','down_limit','a5_p','a5_v',\n 'a4_p','a4_v','a3_p','a3_v','a2_p','a2_v','a1_p','a1_v',\n 'b1_p','b1_v','b2_p','b2_v','b3_p','b3_v','b4_p','b4_v',\n 'b5_p','b5_v','data_time','u33','t0','ebs','var_ticker','name','u38',\n 'high','low','vol','amount']\n list_cols = ['optID','tickerSymbol','expDate','contractType','strikePrice']\n cw_col=['optID','strikePrice','left_days','cw_year_ratio','cw_static_return_ratio','cw_downside_protection_ratio','expDate','price','b1_p','b1_v','b2_p','b2_v','target_a1_p','down_break_even_price','cw_downside_protection_point','cw_initial_investment','cw_static_return','cw_strike_return','data_time','action']\n cw_col_disp=['optID','strike','left_days','年化','静态收益率','下行保护%','expDate','price','b1_p','b1_v','b2_p','b2_v','etf卖1价','盈亏平衡价格','下跌保护点数','初始净投资','静态收益','行权收益','time','action']\n pa_col=['optID','strike','left_days','put_year_ratio','put_strike_return_ratio','put_inintial_investment','put_strike_return','expDate','price','a1_p','a1_v','a2_p','a2_v','target_a1_p','data_time','action']\n pa_col_disp=['optID','strike','left_days','年化','行权收益率','初始净投资','行权收益','expDate','price','a1_p','a1_v','a2_p','a2_v','etf卖1价','time','action']\n ca_col=['optID','strike','left_days','call_year_ratio','call_strike_return_ratio','call_inintial_investment','call_strike_return','expDate','price','a1_p','a1_v','a2_p','a2_v','target_b1_p','data_time','action']\n ca_col_disp=['optID','strike','left_days','年化','行权收益率','初始净投资','行权收益','expDate','price','a1_p','a1_v','a2_p','a2_v','etf买1价','time','action']\n\n def __init__(self,token,monitor_path,target='510050',option_fee=8,r=0.03,stock_fee_ratio=0.0003):\n\n self.monitorDir = monitor_path\n\n self.option_fee = option_fee\n self.r = r\n self.stock_fee_ratio = stock_fee_ratio\n\n self.target = target\n self.token = None\n self.lists = None\n self.contracts = None\n\n self.token = token\n ts.set_token(self.token)\n\n #get contract lists available\n self.lists = ts.Options().Opt(contractStatus='L')[self.list_cols]\n self.lists['optID'] =self.lists.optID.map(lambda x:str(x)) #确保optID类型一致,都为字符型\n\n def quotes(self,symbols = None):\n \"\"\"\n 获取期权实时交易数据 getting real time quotes data\n Parameters\n ------\n symbols : string, array-like object (list, tuple, Series).\n\n return\n -------\n DataFrame 实时交易数据\n 0: bid_v 买一量\n 1: bid_p 买一价\n 2: price 最新价\n 3: ask_p 卖一价\n 4: ask_v 卖一量\n 5: pos 持仓\n 6: rise 涨幅%\n 7: strike 行权价\n 8: pre_settle 昨日结算价?\n 9: open 今开\n 10: up_limit 涨停\n 11: down_limit 跌停\n 12: a5_p 卖五价\n 13: a5_v 卖五量\n 14: a4_p 卖四价\n 15: a4_v 卖四量\n 16: a3_p 卖三价\n 17: a3_v 卖三量\n 18: a2_p 卖二价\n 19: a2_v 卖二量\n 20: a1_p 卖一价\n 21: a1_v 卖一量\n 22: b1_p 买一价\n 23: b1_v 买一量\n 24: b2_p 买二价\n 25: b2_v 买二量\n 26: b3_p 买三价\n 27: b3_v 买三量\n 28: b4_p 买四价\n 29: b4_v 买四量\n 30: b5_p 买五价\n 31: b5_v 买五量\n 32: data_time DATE\n 33: u33 u33\n 34: t0 T0\n 35: ebs EBS\n 36: var_ticker 标的证券\n 37: name 简称\n 38: u38 U38\n 39: high 最高\n 40: low 最低\n 41: vol 总量\n 42: amount 金额\n \"\"\"\n symbols_list = ''\n if isinstance(symbols, list) or isinstance(symbols, set) or isinstance(symbols, tuple) or isinstance(symbols, pd.Series) or isinstance(symbols,pd.DataFrame):\n for code in symbols:\n symbols_list += _code_to_symbol(code) + ','\n else:\n symbols_list = _code_to_symbol(symbols)\n\n request = urllib.request.urlopen(\"http://hq.sinajs.cn/list=%s\"%symbols_list)\n text = request.read().decode(\"gb2312\")\n\n reg = re.compile(r'\\=\"(.*?)\\\";')\n data = reg.findall(text)\n regSym = re.compile(r'(?:sh|sz|OP_)(.*?)\\=')\n syms = regSym.findall(text)\n data_list = []\n syms_list = []\n for index, row in enumerate(data):\n if len(row)>1:\n data_list.append([astr for astr in row.split(',')])\n syms_list.append(syms[index])\n if len(syms_list) == 0:\n return None\n df = pd.DataFrame(data_list, columns = self.quote_cols)\n df['optID'] = syms_list\n\n return df\n\n def prepare(self):\n quotes = self.quotes(self.lists['optID'])\n contracts = pd.merge(self.lists,quotes,on='optID')\n contracts['strikePrice']=contracts['strikePrice'].map(lambda x:float(x))\n contracts['strike']=contracts['strike'].map(lambda x:float(x))\n contracts['pre_settle']=contracts['pre_settle'].map(lambda x:float(x))\n contracts['a1_p']=contracts['a1_p'].map(lambda x:float(x))\n contracts['b1_p']=contracts['b1_p'].map(lambda x:float(x))\n contracts['a1_v']=contracts['a1_v'].map(lambda x:float(x))\n contracts['b1_v']=contracts['b1_v'].map(lambda x:float(x))\n\n contracts['a2_p']=contracts['a2_p'].map(lambda x:float(x))\n contracts['b2_p']=contracts['b2_p'].map(lambda x:float(x))\n contracts['b2_v']=contracts['b2_v'].map(lambda x:float(x))\n contracts['a2_v']=contracts['a2_v'].map(lambda x:float(x))\n contracts['pos']=contracts['pos'].map(lambda x:float(x))\n contracts['rise']=contracts['rise'].map(lambda x:float(x))\n contracts['price']=contracts['price'].map(lambda x:float(x))\n\n target = ts.get_realtime_quotes('510050')\n contracts['target_pre_close']=float(target.iloc[0]['pre_close'])\n contracts['target_price']=float(target.iloc[0]['price'])\n contracts['target_b2_p']=float(target.iloc[0]['b2_p'])\n contracts['target_a2_p']=float(target.iloc[0]['a2_p'])\n contracts['target_b1_p']=float(target.iloc[0]['b1_p'])\n contracts['target_a1_p']=float(target.iloc[0]['a1_p'])\n now = dt.datetime.today()\n contracts['left_days']=contracts['expDate'].map(lambda x:(dt.datetime.strptime(x,'%Y-%m-%d')-now).days)\n contracts['action']=''\n self.__check(contracts)\n\n data=[]\n for i in range(len(contracts)):\n p = contracts.iloc[i]\n strike = p['strike']\n pre_settle = p['pre_settle']\n pre_close = p['target_pre_close']\n margin = self.calc_margin(strike,pre_settle,pre_close,p['contractType'])\n # otm = 0\n # itm = 0\n data.append((p['optID'],margin))\n margins = pd.DataFrame(data,columns=['optID','margin'])\n\n self.contracts = pd.merge(contracts,margins,on=['optID'])\n\n return self.contracts\n\n def __check(self,contracts):\n pass\n\n def calc_margin(self,strike,pre_settle,pre_close,opt_type):\n # 认沽期权义务仓开仓初始保证金 = 合约单位*min{前结算价+max(15%*标的前收盘价-认沽期权虚值,7%*行权价),行权价)}\n # 认沽期权虚值= max(合约标的前收盘价-行权价,0)*合约单位\n # 认沽期权义务仓持仓维持保证金 = 合约单位*min{结算价+max(15%*标的收盘价-认沽期权虚值,7%*行权价),行权价)}\n # 认沽期权虚值= max(合约标的收盘价-行权价,0)*合约单位\n\n # 认购期权义务仓开仓初始保证金 = 合约单位*{前结算价+max(15%*标的前收盘价-认购期权虚值,7%*行权价)}\n # 认购期权虚值= max(行权价-合约标的前收盘价,0)\n # 认购期权义务仓持仓维持保证金 = 合约单位*{结算价+max(15%*标的收盘价-认购期权虚值,7%*行权价)}\n # 认购期权虚值= max(行权价-合约标的收盘价,0)\n\n if str(opt_type).upper()=='PO':\n putOTM = max(float(pre_close)-strike,0)*10000 #虚值\n putITM = max(strike-float(pre_close),0)*10000 #实值\n putMargin = min(strike,float(pre_settle)+max(0.15*float(pre_close)-max(float(pre_close)-strike,0),0.07*strike))*10000\n return putMargin #,putOTM,putITM\n if str(opt_type).upper()=='CO':\n callOTM = max(strike-float(pre_close),0)*10000\n callITM = max(float(pre_close)-strike,0)*10000\n callMargin=(float(pre_settle)+max(0.15*float(pre_close)-max(strike-float(pre_close),0),0.07*strike))*10000\n return callMargin #,callOTM,callITM\n\n\n def covered_write(self,expected_return = 0.15,downside_protetion = 0.05,do = None):\n '''\n 卖出备兑看涨期权:买入标的现货,卖出看涨期权。\n 看涨期权权利金收入可以为组合提供下行保护,可以增厚组合的收益;\n 卖出看涨期权也限制了组合获得正股大幅上涨的收益,因为股票被卖出看涨期权行权了。\n 下行保护:权利金/股票现价 c/s\n 组合潜在最大收益:k-s+c\n 组合潜在最大收益率:(k-s+c)/(s-c)\n 组合前者最大年化收益率:(k-s+c)/(s-c)*365/left_days\n\n 组合净投资:买入股票的成本s+买入股票的手续费-卖出CALL的权利金c+卖出期权的手续费\n 行权收益:卖出股票的价格s(T)-卖出股票的手续费+到期日前收到的股息-组合净投资\n 股票不变行权收益:卖出股票的收入s+股息-卖出组合净投资 (此时看涨期权无价值到期,不需要卖出股票)\n 下行盈亏平衡点:到期时股票总成本(=净投资-股息)/股票数量 = 盈亏平衡价格\n 下行保护百分比:受保护的点数(=初始股价-盈亏平衡价格)/初始股价\n\n 计算covered_write收益和下行保护时,采用ETF的卖一价和call的买一价,实际买卖的时候期权采用卖二价,\n 标的股票价格为:s a1_p 卖一价\n 买卖股票费率: stock_fee = 0.0003\n 看涨期权权利金为: c 采用买1价 b1_p\n 卖出期权手续费:self.option_fee = 8 元 一手\n\n return: 股票年化收益率高的期权列表,下行保护比率高的期权列表,年化收益和下行保护比率高的期权列表\n '''\n\n dividen = 0 # 每股收到分红,这里要有个更新,放到df里去\n contract_unit = 10000\n\n # if do is None:\n # do = update_contracts()\n mask = (self.contracts['contractType']=='CO')\n df = self.contracts[mask].copy()\n\n #开仓初始净投资\n df['cw_initial_investment'] = df['target_a1_p']*(1+self.stock_fee_ratio)*contract_unit - df['b1_p']*contract_unit + self.option_fee\n #股价不变收益 & 行权收益 实值call两者相等\n df['cw_strike_return'] = df['strike']*contract_unit + dividen*contract_unit - df['cw_initial_investment'] - self.option_fee\n df['cw_static_return'] = df['target_a1_p']*(1-self.stock_fee_ratio)*contract_unit + dividen*contract_unit - df['cw_initial_investment']\n df.loc[(df['target_a1_p']>df['strike']),'cw_static_return'] =df.loc[(df['target_a1_p']>df['strike']),'cw_strike_return']\n\n #股价不变假设前提下的行权收益率\n df['cw_static_return_ratio'] = df['cw_static_return']/df['cw_initial_investment']\n #年化收益率\n df['cw_year_ratio'] = df['cw_static_return_ratio']*365/df['left_days']\n\n #盈亏平衡价格:标的股本下跌到此盈亏平衡价格时,盈亏为0\n df['down_break_even_price'] = (df['cw_initial_investment'] - dividen*contract_unit)/contract_unit\n #股票下跌点数,cw的下行保护点数\n df['cw_downside_protection_point'] = df['target_a1_p'] - df['down_break_even_price']\n #下行保护比例\n df['cw_downside_protection_ratio'] = df['cw_downside_protection_point']/df['target_a1_p']\n df['action'] = ''\n\n mask1 = (df['cw_year_ratio'] >= expected_return) & (df['b1_p']>0)\n mask2 = df['cw_downside_protection_ratio'] >= downside_protetion\n\n cw_open = df[mask1 & mask2][self.cw_col].sort('left_days',ascending = True).copy()\n if cw_open.empty==False:\n cw_open['action'] = cw_open['target_a1_p'].map(lambda x:'buy 510050 '+str(x)+' 10000;') + cw_open['optID'].map(lambda x:'sell '+str(x)) + cw_open['b2_p'].map(lambda x:' '+str(x)+' 1')\n tmp,cw_open.columns = cw_open.columns,self.cw_col_disp\n cw_open.to_html(self.monitorDir+'covered_write_open.html',classes='covered_write_open')\n cw_open.columns = tmp\n return cw_open,'available'\n\n cw = df[self.cw_col].sort('cw_year_ratio',ascending = False).copy()\n return cw,'none'\n\n\n def put_arbitrage(self,expected_return=0.15):\n \"\"\"\"\n 认沽期权定价错误套利 k-s-p>3% 认沽期权定价不合理,导致K-S的空间大过权利金,导致可以套利,一般在\n 市场大跌的时候s降得快,容易出现套利机会\n 操作:\n 买入1张行权价为K,到期日为T的认沽期权,其价格为p,取卖一价a1_p -p\n 买入1张合约对应数量的标的股票,其价格为s,取卖一价target_a1_p -s\n 平仓:认沽期权行权,卖出股票 +k\n \"\"\"\n\n mask = (self.contracts['contractType']=='PO')\n df = self.contracts[mask].copy()\n\n df['put_inintial_investment'] = df['target_a1_p']*10000*(1+self.stock_fee_ratio) + df['a1_p']*10000+self.option_fee\n df['put_strike_return'] = df['strike']*10000 - self.option_fee - df['put_inintial_investment']\n df['put_strike_return_ratio'] = df['put_strike_return'] / df['put_inintial_investment']\n df['put_year_ratio'] = df['put_strike_return_ratio']*365/df['left_days']\n\n mask = (df['put_year_ratio'] >= expected_return) & (df['a1_p']>0)\n pa = df[mask][self.pa_col].sort('put_year_ratio',ascending=False).copy()\n if pa.empty==False:\n pa['action'] = pa['target_a1_p'].map(lambda x:'buy 510050 '+str(x)+' 10000;') + pa['optID'].map(lambda x:'buy '+str(x)) + pa['a2_p'].map(lambda x:' '+str(x)+' 1')\n tmp,pa.columns = pa.columns,self.pa_col_disp\n pa.to_html(self.monitorDir+'put_arbitrage.html',classes='put_arbitrage')\n pa.columns = tmp\n return pa,'available'\n\n return df,'none'\n\n\n def call_arbitrage(self,expected_return=0.15):\n \"\"\"\"\n 认购期权定价错误套利 s-k-c>0 认购期权定价不合理,s-k的空间大过权利金,导致可以套利,一般在\n 市场大跌的时候s降得快,容易出现套利机会\n 操作:\n 买入1张行权价为K,到期日为T的认购期权,其价格为c,取卖一价a1_p -c\n 卖出1张合约对应数量的标的股票,其价格为s,取卖一价target_b1_p +s\n 平仓:认购期权行权,获得股票 -k\n \"\"\"\n mask = (self.contracts['contractType']=='CO')\n df = self.contracts[mask].copy()\n df['call_inintial_investment'] = df['a1_p']*10000+self.option_fee+df['target_b1_p']*10000*self.stock_fee_ratio\n df['call_strike_return'] = df['target_b1_p']*10000-df['strike']*10000-df['a1_p']*10000-self.option_fee #扣除行权费用\n df['call_strike_return_ratio'] = df['call_strike_return'] / df['call_inintial_investment']\n df['call_year_ratio'] = df['call_strike_return_ratio']*365/df['left_days']\n\n mask = (df['call_year_ratio'] >= expected_return) & (df['a1_p']>0)\n ca = df[mask][self.ca_col].sort('call_year_ratio',ascending=False).copy()\n if ca.empty == False:\n ca['action'] = ca['target_b1_p'].map(lambda x:'sell 510050 '+str(x)+' 10000;') + ca['optID'].map(lambda x:'buy '+str(x)) + ca['a1_p'].map(lambda x:' '+str(x)+' 1')\n tmp,ca.columns = ca.columns,self.ca_col_disp\n ca.to_html(self.monitorDir+'call_arbitrage.html')\n ca.columns = tmp\n return ca,'available'\n\n return df\n\n def dividen_arbitrage(self,dividen=0):\n \"\"\"\"\n 在股票除息的前一天,交易者能够通过买入股票和看跌期权锁定盈利,然后等着在将put行权前收取股息。\n k+d-p-s>0\n\n 操作:\n 买入1张行权价为K,到期日为T的认沽期权,其价格为p,取卖一价a1_p -p\n 买入1张合约对应数量的标的股票,其价格为s,取卖一价target_a1_p -s\n 持有看跌期权和股票,一直到股票除息,假设股息d\n 平仓:认沽期权行权,按行权价k行权卖出股票 +k\n \"\"\"\n\n mask = (self.contracts['contractType']=='PO')\n df = self.contracts[mask].copy()\n\n df['put_inintial_investment'] = df['target_a1_p']*10000*(1+self.stock_fee_ratio) + df['a1_p']*10000+self.option_fee\n df['put_strike_return'] = dividen + df['strike']*10000 - self.option_fee - df['put_inintial_investment']\n df['put_strike_return_ratio'] = df['put_strike_return'] / df['put_inintial_investment']\n df['put_year_ratio'] = df['put_strike_return_ratio']*365/df['left_days']\n\n mask = (df['put_year_ratio'] >= expected_return) & (df['a1_p']>0)\n pa = df[mask][self.pa_col].sort('put_year_ratio',ascending=False).copy()\n if pa.empty==False:\n pa['action'] = pa['target_a1_p'].map(lambda x:'buy 510050 '+str(x)+' 10000;') + pa['optID'].map(lambda x:'buy '+str(x)) + pa['a2_p'].map(lambda x:' '+str(x)+' 1')\n tmp,pa.columns = pa.columns,self.pa_col_disp\n pa.to_html(self.monitorDir+'股息分红套利.html')\n pa.columns = tmp\n return pa,'available'\n\n return df\n\n def conversion_arbitrage(self,expected_return=0.15):\n \"\"\"\"\n 期权转换套利 C+K*EXP(-rT)-P-S-fees > 3% 期权合成指数贵过现货,空期权多现货\n 开仓:\n 卖出1张行权价为K,到期日为T的认购期权,其价格为C,取买1价b1_p\n 买入1张行权价为K,到期日为T的认沽期权,其价格为P,取卖1价a1_p\n 买入1张合约对应数量的标的股票,其价格为S,取卖1价target_a1_p\n 平仓:行权\n \"\"\"\n\n df = self.contracts.copy()\n\n validGrp = []\n grouped = df.groupby(['strikePrice','expDate'])\n for n,g in grouped:\n k, expDate = n\n\n p = g[g['contractType']=='PO'].iloc[0]['a1_p'] #买入认沽,采用卖1价\n p_id = g[g['contractType']=='PO'].iloc[0]['optID']\n c = g[g['contractType']=='CO'].iloc[0]['b1_p'] #卖出认购,采用买二价\n c_id = g[g['contractType']=='CO'].iloc[0]['optID']\n left_days = g[g['contractType']=='CO'].iloc[0]['left_days']\n target_a1_p = g[g['contractType']=='CO'].iloc[0]['target_a1_p']\n c_margin = g[g['contractType']=='CO'].iloc[0]['margin']\n time = g[g['contractType']=='CO'].iloc[0]['data_time']\n\n initial_investment = p*10000 + target_a1_p*(1+self.stock_fee_ratio)*10000 - c*10000 + self.option_fee + c_margin\n final_capital = k*10000 - self.option_fee + c_margin\n strike_return = final_capital*math.exp(-self.r*left_days/365) - initial_investment\n strike_return_ratio = strike_return / initial_investment\n strike_year_ratio = strike_return_ratio*365/left_days\n if strike_year_ratio>=0:\n action = 'buy '+str(p_id)+' '+str(p)+'1;'+'sell '+str(c_id)+' '+ str(c)+' 1;'+'buy 510050'+str(target_a1_p)+' 10000'\n data = ('buy',p_id,p,'sell',c_id,c,'buy','510050',target_a1_p,k,expDate,left_days,\n strike_year_ratio,strike_return_ratio,strike_return,time,action)\n validGrp.append(data)\n\n col = ['onPut','putID','putPrice','onCall','callID','callPrice','onETF','ticker','price','strike','expDate','left_days','year_ratio','return_rt','return','time','action']\n ret = pd.DataFrame(validGrp,columns=col)\n mask = (ret['year_ratio']>=expected_return) & (ret['putPrice']>0) & (ret['callPrice']>0)\n if ret[mask].empty==False:\n ret[mask].sort('year_ratio',ascending=False).to_html(self.monitorDir+'转换套利.html',classes='conversion_arbitrage')\n return ret[mask].sort('year_ratio',ascending=False),'available'\n\n return ret,'none'\n\n def reverse_conversion_arbitrage(self,expected_return=0.15):\n \"\"\"\"\n 反转组合套利 delta = P+S-C-K*EXP(-rT)-fees > pl 期权合成多头比现货便宜,多期权空现货\n 开仓操作:赚取锁定的delta收益\n 卖出1张行权价为K,到期日为T的认沽期权,其价格为P,取买1价b1_p\n 买入1张行权价为K,到期日为T的认购期权,其价格为C,取卖1价a1_p\n 卖出1张合约对应数量的标的股票,其价格为S,取买1价 b1_p (融券或者自融券后者期货空单)\n 借出资金 Kexp(-rT)\n 平仓操作:平仓日无论50ETF价格是什么,现金流总为0\n 对C和P行权平仓,现金流 S(T)-K \n 借出资金回笼,现金流+K\n 买入510050或者融券平仓或者期货空单平仓,现金流-S(T)\n \"\"\"\n\n\n df = self.contracts.copy()\n\n validGrp = []\n grouped = df.groupby(['strikePrice','expDate'])\n for n,g in grouped:\n k, expDate = n\n\n p = g[g['contractType']=='PO'].iloc[0]['b1_p'] #卖出认沽,采用买1价\n p_id = g[g['contractType']=='PO'].iloc[0]['optID']\n p_margin = g[g['contractType']=='PO'].iloc[0]['margin']\n\n c = g[g['contractType']=='CO'].iloc[0]['a1_p'] #买入认购,采用卖1价\n c_id = g[g['contractType']=='CO'].iloc[0]['optID']\n \n left_days = g[g['contractType']=='CO'].iloc[0]['left_days']\n target_b1_p = g[g['contractType']=='CO'].iloc[0]['target_b1_p']\n time = g[g['contractType']=='CO'].iloc[0]['data_time']\n\n initial_investment = c*10000 + self.option_fee + p_margin \n strike_return = p*10000+target_b1_p*10000-c*10000-k*10000*math.exp(-self.r*left_days/365)-self.option_fee-target_b1_p*self.stock_fee_ratio #p+s-c-kexp(-rt)-fees\n strike_return_ratio = strike_return / initial_investment\n strike_year_ratio = strike_return_ratio*365/left_days\n\n if strike_year_ratio >=0:\n action = 'sell '+str(p_id)+' '+str(p)+'1;'+'buy '+str(c_id)+' '+ str(c)+' 1;'+ \\\n 'sell 510050'+str(target_b1_p)+' 10000'\n data = ('sell',p_id,p,'buy',c_id,c,'sell','510050',target_b1_p,k,expDate,left_days,\n strike_year_ratio,strike_return_ratio,strike_return,time,action)\n validGrp.append(data)\n\n col = ['onPut','putID','putPrice','onCall','callID','callPrice','onETF','ticker','price','strike','expDate','left_days','year_ratio','return_rt','return','time','action']\n ret = pd.DataFrame(validGrp,columns=col)\n mask = (ret['year_ratio']>=expected_return) & (ret['putPrice']>0) &(ret['callPrice']>0)\n if ret[mask].empty==False:\n ret[mask].sort('year_ratio',ascending=False).to_html(self.monitorDir+'反向转换套利.html')\n\n return ret[mask].sort('year_ratio',ascending=False),'available'\n return ret,'none'\n\n def boxsell_arbitrage(self,expected_return=0.15):\n \"\"\"\"\n 策略:盒子套利 c1-c2-(p1-p2)-(k2-k1)*exp(-rT)-fees > 1.1*成本 低行权价期权指数空头 价格高过 高行权价指数多头\n 操作:\n 卖出1张较低行权价k1,到期日为T的认购期权,其价格为c1,取买二价b2_p\n 买入一张较低行权价k1,到期日为T的认沽期权,其价格为p1,取卖二价a2_p\n 买入1张较高行权价k2,到期日为T的认购期权,其价格为c2,取卖二价a2_p\n 卖出一张较高行权价k2,到期日为T的认沽期权,其价格为p2,取买二价b2_p\n 同时贷出资金(k2-k1)exp(-rT)\n 市场利率 self.r = 0.02\n 套利空间 pl = 10%,年化\n \"\"\"\n df = self.contracts.copy()\n doc = df[df['contractType']=='CO']\n dop = df[df['contractType']=='PO']\n\n groupedc = doc.groupby(['expDate'])\n groupedp = dop.groupby(['expDate'])\n # now =dt.datetime.today()\n validGrp=[]\n for name,group in groupedc:\n expDate = name\n length = len(group)\n # T = dt.datetime.strptime(expDate,'%Y-%m-%d')-now\n pgroup = groupedp.get_group(name)\n for i in range(length):\n for j in range(i+1,length):\n k1 = group.iloc[i]['strike']\n k2 = group.iloc[j]['strike']\n\n if k1=0 and c1*c2*p1*p2>0 and left_days>4:\n validGrp.append(('buy',p1_id,p1,'sell',c1_id,c1,k1,'buy',c2_id,c2,'sell',p2_id,p2,k2,expDate,left_days,gain_year,gain,c1_margin+p2_margin,'boxsell_arbitrage'))\n\n col = ['onPut1','put1ID','put1Price','onCall1','call1ID','Call1Price','strike_L','onCall2','call2ID','call2Price','onPut2','put2ID','put2Price','strike_H',\n 'expDate','left_days','gain_year','gain','margin','time','action']\n ret = pd.DataFrame(validGrp,columns=col)\n mask = ret['gain_year']>=expected_return\n if ret[mask].empty==False:\n ret.sort('gain_year',ascending=False).to_html(monitorDir+'boxsell_arbitrage.html')\n return ret[mask],'available'\n\n return ret,'none'\n\n\n# def xsrgjctl(do = None):\n# \"\"\"\"\n# 策略3:牛市认购价差套利 C1-C2-(K2-K1)*EXP(-rT)-fees > 3%\n# 一般而言,行权价越低的CALL,价格越高,但当两个CALL的价格之差大于行权价的折现值时,就出现套利机会\n# 操作:\n# 卖出1张较低行权价为K1,到期日为T的认购期权,其价格为C1,取买二价b2_p\n# 买入1张较高行权价为K2,到期日为T的认购期权,其价格为C2,取卖二价a2_p\n# 借出资金 Kexp(-rT)\n# 市场利率 self.r = 0.02\n# 套利空间 pl = 3%\n# \"\"\"\n# s = ts.get_realtime_quotes('510050').iloc[0]['b2_p']\n# self.r = 0.02\n# pl = 0.03\n# fee = 30\n# if do is None:\n# do = update_contracts()\n# do = do[do['contractType']=='CO']\n\n# now =dt.datetime.today()\n# grouped = do.groupby(['expDate'])\n# for name,group in grouped:\n# expDate = name\n# length = len(group)\n# T = dt.datetime.strptime(expDate,'%Y-%m-%d')-now\n# for i in range(length):\n# for j in range(i+1,length):\n# k1 = group.iloc[i]['strikePrice']\n# k2 = group.iloc[j]['strikePrice']\n\n# if k1pl and T.days>1:\n# print('牛市价差套利\\n')\n# print('牛市认购价差套利:对手价买入',c2_id,\"strike=\",k2,\"对手价卖出\",c1_id,\"strike=\",k1,\"到期日期:\",expDate,\"剩余天数:\",T.days)\n# print('牛市价差套利:gain=',gain,'gain%=',gain_per,'expDate=',expDate[:-3],'还剩天数',T.days,'\\n')\n\n\n# return\n\n# def nsrgjctl(do = None):\n# \"\"\"\"\n# 策略3:牛市认购价差套利 C1-C2-(K2-K1)*EXP(-rT)-fees > 3%\n# 一般而言,行权价越低的CALL,价格越高,但当两个CALL的价格之差大于行权价的折现值时,就出现套利机会\n# 操作:\n# 卖出1张较低行权价为K1,到期日为T的认购期权,其价格为C1,取买二价b2_p\n# 买入1张较高行权价为K2,到期日为T的认购期权,其价格为C2,取卖二价a2_p\n# 借出资金 Kexp(-rT)\n# 市场利率 self.r = 0.02\n# 套利空间 pl = 3%\n# \"\"\"\n# s = ts.get_realtime_quotes('510050').iloc[0]['b2_p']\n# self.r = 0.02\n# pl = 0.03\n# fee = 30\n# if do is None:\n# do = update_contracts()\n# do = do[do['contractType']=='CO']\n\n# now =dt.datetime.today()\n# grouped = do.groupby(['expDate'])\n# for name,group in grouped:\n# expDate = name\n# length = len(group)\n# T = dt.datetime.strptime(expDate,'%Y-%m-%d')-now\n# for i in range(length):\n# for j in range(i+1,length):\n# k1 = group.iloc[i]['strikePrice']\n# k2 = group.iloc[j]['strikePrice']\n\n# if k10.03 and T.days>1:\n# print('牛市价差套利\\n')\n# print('牛市认购价差套利:对手价',c2,'买入call',c2_id,\"strike=\",k2,\";对手价\",c1,\"卖出call\",c1_id,\"strike=\",k1,\"到期日期:\",expDate,\"剩余天数:\",T.days)\n# print('牛市价差套利:gain=',gain,'gain%=',gain_per,'expDate=',expDate[:-3],'还剩天数',T.days,'\\n')\n\n\n# return\n\n\n\n\n# def boxbuy_arbitrage(do = None):\n# \"\"\"\"\n# 策略1:盒子套利 c1-c2-(p1-p2)-(k2-k1)*exp(-rT)<- 3% c2-c1+p1-p2+(k2-k1)*exp(-rT)-fee>3%\n# 策略:买入盒子套利 当高行权价\n# 操作:\n# 卖出1张较低行权价k1,到期日为T的认购期权,其价格为c1,取买二价b2_p\n# 买入1张较高行权价k2,到期日为T的认购期权,其价格为c2,取卖二价a2_p\n# 卖出一张较高行权价k2,到期日为T的认沽期权,其价格为p2,取买二价b2_p\n# 买入一张较低行权价k1,到期日为T的认沽期权,其价格为p1,取卖二价a2_p\n# 同时贷出资金(k2-k1)exp(-rT)\n# 市场利率 self.r = 0.02\n# 套利空间 pl = 3%\n# \"\"\"\n# s = ts.get_realtime_quotes('510050').iloc[0]['b2_p']\n# self.r = 0.02\n# pl = 0.03\n# fee = 30\n# if do is None:\n# do = update_contracts()\n# doc = do[do['contractType']=='CO']\n# dop = do[do['contractType']=='PO']\n\n# now =dt.datetime.today()\n# groupedc = doc.groupby(['expDate'])\n# groupedp = dop.groupby(['expDate'])\n# for name,group in groupedc:\n# expDate = name\n# length = len(group)\n# T = dt.datetime.strptime(expDate,'%Y-%m-%d')-now\n# pgroup = groupedp.get_group(name)\n# for i in range(length):\n# for j in range(i+1,length):\n# k1 = group.iloc[i]['strikePrice']\n# k2 = group.iloc[j]['strikePrice']\n\n# if k1pl and T.days>1:\n# print('买入盒子套利\\n')\n# print(\"盒子套利:对手价\",c1,\"卖出call\",c1_id,\"strike=\",k1,\";对手价\",p1,\"买入put\",p1_id,\"strike=\",k1,\";到期日期:\",expDate,\"剩余天数:\",T.days)\n# print(\"盒子套利:对手价\",p2,\"卖出put\",p2_id,\"strike=\",k2,\";对手价\",c2,\"买入call\",c2_id,\"strike=\",k2,\";到期日期:\",expDate,\"剩余天数:\",T.days)\n# print(\"c1 c2 p1 p2\",str(c1),str(c2),str(p1),str(p2),k1,k2)\n# print('盒子套利收益:gain=',gain,'gain%=',gain_per,';expDate=',expDate[:-3],'还剩天数',T.days,'\\n')\n\n# return\n\n# # def main():\n# # _login()\n# # do = update_contracts()\n# # d1 =do.copy()\n# # d2 =do.copy()\n# # d3 =do.copy()\n# # d4 =do.copy()\n# # d5 =do.copy()\n# # d6 =do.copy()\n# # d7 = do.copy()\n# # while True:\n# # time.sleep(6)\n# # sstl(d1)\n# # tstl(d2)\n# # nsrgjctl(d3)\n# # xsrgjctl(d4)\n# # put_arbitrage(d5)\n# # boxsell_arbitrage(d6)\n# # boxbuy_arbitrage(d7)\n\n# # if __name__ == '__main__':\n# # main()\n","sub_path":"option.py","file_name":"option.py","file_ext":"py","file_size_in_byte":38267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"266349997","text":"\"\"\"\r\nCreate pdf files from Tableau dashboards. Requires tabcmd.exe,\r\navailable for free download here: https://www.tableau.com/support/releases/server\r\nCreated by James D. Triveri (BSD 3-Clause)\r\n\"\"\"\r\nimport sys\r\nimport os\r\nimport os.path\r\nimport configparser\r\nimport subprocess\r\nimport itertools\r\nimport datetime\r\nimport re\r\nimport shutil\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # Read in settings from settings.cfg in same folder as\r\n config = configparser.ConfigParser()\r\n cfgdir = os.path.dirname(__file__)\r\n cfgpath = cfgdir + os.path.sep + \"settings.cfg\"\r\n config.read(cfgpath)\r\n\r\n SERVER = config[\"SETTINGS\"][\"SERVER\"]\r\n PROXY = config[\"SETTINGS\"][\"PROXY\"]\r\n USER = config[\"SETTINGS\"][\"USER\"]\r\n PASSWORD = config[\"SETTINGS\"][\"PASSWORD\"]\r\n TABCMD = config[\"SETTINGS\"][\"TABCMD\"]\r\n VIEW_URL = config[\"SETTINGS\"][\"VIEW_URL\"]\r\n PDF_DIR = config[\"SETTINGS\"][\"PDF_DIR\"]\r\n INPUTS = config[\"SETTINGS\"][\"INPUTS\"]\r\n TIMEOUT = config[\"SETTINGS\"][\"TIMEOUT\"]\r\n\r\n # Set working directory to PDF_DIR if exists.\r\n now = datetime.datetime.today().strftime(\"%Y%m%d\")\r\n pdf_dir_ = PDF_DIR.rstrip(\"/\").rstrip(\"\\\\\") if \\\r\n any(PDF_DIR.endswith(i) for i in (\"\\\\\",\"/\")) else PDF_DIR\r\n\r\n output_dir = pdf_dir_ + os.path.sep + \"Tableau_Exhibits_\" + now + os.path.sep\r\n if os.path.isdir(output_dir): shutil.rmtree()\r\n os.mkdir(output_dir, mode=770)\r\n all_specs, all_pdfs = [], []\r\n\r\n # Produce PDF for each combination of values present in `INPUTS`.\r\n # Headers in file represent Tableau exhibit elements to be filtered\r\n # (these are case sensitive). The number of PDFs generated will\r\n # exactly match the number of records present in `INPUTS`.\r\n with open(INPUTS, newline='') as f:\r\n reader = csv.DictReader(f)\r\n for row in reader:\r\n keysinit, valsinit = list(row.keys()), list(row.values())\r\n iterkeys = [re.sub(\"\\\\s{1,}\",\"%20\",i) for i in keysinit]\r\n itervals = [re.sub(\"\\\\s{1,}\",\"%20\",i) for i in valsinit]\r\n iterspec = \"&\".join(i + \"=\" + j for i,j in zip(iterkeys,itervals))\r\n pdfname = \"_\".join(re.sub(\"\\\\s{1,}\",\"_\",i) for i in valsinit).strip()\r\n iterpdf = output_dir + pdfname + \".pdf\"\r\n all_specs.append((iterspec,iterpdf))\r\n\r\n # Initialize single session - login to Tableau server.\r\n try:\r\n loginargs = [\r\n TABCMD, \"login\", \"--server\", SERVER,\"--username\", USER,\r\n \"--password\", PASSWORD, \"--proxy\", PROXY,\"--timeout\",\r\n str(TIMEOUT),\"--no-certcheck\"\r\n ]\r\n\r\n loginproc = subprocess.Popen(loginargs, shell=False)\r\n loginproc.communicate()\r\n now = datetime.datetime.today().strftime(\"%Y-%m-%d @ %H:%M:%S\")\r\n if loginproc.returncode==0:\r\n print(\" + [{}] Successfully authenticated to {}\".format(now, SERVER))\r\n else:\r\n print(\" + [{}] Unable to authenticate to {}\".format(now, SERVER))\r\n sys.exit(1)\r\n\r\n # Iterate over all_specs appending each set of specified parameters\r\n # to the specified workbook/view basename given by `VIEW_URL`.\r\n for i in all_specs:\r\n iterspec, iterpdf = i[0], i[1]\r\n iterurl = str(VIEW_URL) + \"?\" + spec + \".pdf\"\r\n\r\n # Submit arguments for pdf generation. By specifying only\r\n # password and not password, server and username, the\r\n # established session will be used instead of creating\r\n # a new one.\r\n procargs = [\r\n TABCMD, \"get\", iterurl, \"--filename\", iterpdf,\r\n \"--password\", PASSWORD, \"--proxy\", PROXY,\r\n \"--timeout\", str(TIMEOUT), \"--no-certcheck\"\r\n ]\r\n\r\n # Dispatch procargs.\r\n try:\r\n iterproc = subprocess.Popen(procargs, shell=False)\r\n iterproc.communicate()\r\n now = datetime.datetime.today().strftime(\"%Y-%m-%d @ %H:%M:%S\")\r\n if iterproc.returncode==0:\r\n print(\" + [{}] `{}` successfully created.\".format(now, iterpdf))\r\n all_pdfs.append(iterpdf)\r\n except:\r\n print(\" + [{}] An error occurred exporting {}\".format(now, iterpdf))\r\n continue\r\n\r\n finally:\r\n logoutargs = [TABCMD, \"logout\"]\r\n logoutproc = subprocess.Popen(logoutargs, shell=False)\r\n logoutproc.communicate()\r\n now = datetime.datetime.today().strftime(\"%Y-%m-%d @ %H:%M:%S\")\r\n if logoutproc.returncode==0:\r\n print(\" + [{}] Server session successfully terminated.\".format(now))\r\n\r\n\r\n # Merge PDFs and save to PDF_DIR if `--collate` present in argvs.\r\n if \"--collate\" in sys.argv[1:]:\r\n\r\n import PyPDF2\r\n\r\n merger = PyPDF2.PdfFileMerger()\r\n\r\n for i in all_pdfs:\r\n merger.append(PyPDF2.PdfFileReader(open(i, 'rb')))\r\n\r\n all_pdfs_name = output_dir + \"All_Groups.pdf\"\r\n merger.write(all_pdfs_name)\r\n merger.close()\r\n","sub_path":"tab2pdf/tab2pdf.py","file_name":"tab2pdf.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"400785839","text":"from PIL import Image\nimport io\n\ndef format(image_data, file_type):\n\twidth = 400\n\theight = int(width / 10 * 16)\n\n\t# Reading image data\n\tinput_bytes = io.BytesIO(image_data)\n\tinput_image = Image.open(input_bytes)\n\tinput_width = input_image.width\n\tinput_height = input_image.height\n\n\t# Obtaining most dominant color\n\tall_colors = input_image.getcolors(input_image.size[0] * input_image.size[1])\n\tmost_dom_color = max(all_colors)\n\n\t# Resizing image to fit layer\n\tresized_width = int(width)\n\tresized_height = int(input_height / (input_width / width))\n\tresized_image = input_image.resize((resized_width, resized_height))\n\n\t# Flatten resized image and background layer\n\toffset = (int((width - resized_width) / 2), int((height - resized_height) / 2))\n\toutput_layer = Image.new(\"RGB\", (width, height), most_dom_color[1])\n\toutput_layer.paste(resized_image, offset)\n\n\t# Output image\n\toutput_arr = io.BytesIO()\n\toutput_type = get_type(file_type)\n\toutput_layer.save(output_arr, output_type)\n\treturn output_arr.getvalue()\n\ndef get_type(file_type):\n\tif file_type in {\".jpg\", \".jpeg\"}:\n\t\treturn \"jpeg\"\n\telif file_type in {\".png\"}:\n\t\treturn \"png\"","sub_path":"Scraper/format_image.py","file_name":"format_image.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245466658","text":"\"\"\"Retrieve data from EIA Form 860 spreadsheets for analysis.\n\nThis modules pulls data from EIA's published Excel spreadsheets.\n\nThis code is for use analyzing EIA Form 860 data.\n\"\"\"\nimport pandas as pd\n\nimport pudl.logging_helpers\nfrom pudl.extract import excel\nfrom pudl.helpers import remove_leading_zeros_from_numeric_strings\nfrom pudl.settings import Eia860Settings\n\nlogger = pudl.logging_helpers.get_logger(__name__)\n\n\nclass Extractor(excel.GenericExtractor):\n \"\"\"Extractor for the excel dataset EIA860.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize the module.\n\n Args:\n ds (:class:datastore.Datastore): Initialized datastore.\n \"\"\"\n self.METADATA = excel.Metadata(\"eia860\")\n self.cols_added = []\n super().__init__(*args, **kwargs)\n\n def process_raw(self, df, page, **partition):\n \"\"\"Apply necessary pre-processing to the dataframe.\n\n * Rename columns based on our compiled spreadsheet metadata\n * Add report_year if it is missing\n * Add a flag indicating if record came from EIA 860, or EIA 860M\n * Fix any generator_id values with leading zeroes.\n \"\"\"\n df = df.rename(columns=self._metadata.get_column_map(page, **partition))\n if \"report_year\" not in df.columns:\n df[\"report_year\"] = list(partition.values())[0]\n self.cols_added = [\"report_year\"]\n # Eventually we should probably make this a transform\n if \"generator_id\" in df.columns:\n df = remove_leading_zeros_from_numeric_strings(\n df=df, col_name=\"generator_id\"\n )\n df = self.add_data_maturity(df, page, **partition)\n return df\n\n def extract(self, settings: Eia860Settings = Eia860Settings()):\n \"\"\"Extracts dataframes.\n\n Returns dict where keys are page names and values are\n DataFrames containing data across given years.\n\n Args:\n settings: Object containing validated settings\n relevant to EIA 860. Contains the tables and years to be loaded\n into PUDL.\n \"\"\"\n return super().extract(year=settings.years)\n\n @staticmethod\n def get_dtypes(page, **partition):\n \"\"\"Returns dtypes for plant id columns.\"\"\"\n return {\n \"Plant ID\": pd.Int64Dtype(),\n \"Plant Id\": pd.Int64Dtype(),\n }\n","sub_path":"src/pudl/extract/eia860.py","file_name":"eia860.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"45787244","text":"from os.path import join\n\nfrom yamltool.yamltool import read_yaml_config_string\nfrom yamltool.yamltool import preprocess_yaml_file\nfrom yamltool.yamltool import parse_configuration\nfrom yamltool.yamltool import YAMLTemplater\n\n\ndef test_preprocess_yaml_file():\n\n res = preprocess_yaml_file(join('tests', 'yaml_import', 'example.yaml'))\n\n expected = [\n '#!define variable=defined_value',\n '#aa.yaml',\n '#a.yaml',\n '#bb.yaml',\n '#b.yaml',\n '#example.yaml',\n 'from_define: {{variable}}',\n 'rootdir: {{root}}',\n 'rootappend: {{root::hello}}'\n ]\n assert res == expected\n\n\ndef test_read_yaml_config_string():\n\n res = read_yaml_config_string(\"\"\"\nkey1: value1\nkey2: value2\n \"\"\")\n\n assert res == {'key1': 'value1', 'key2': 'value2'}\n\n res = read_yaml_config_string(\"\"\"\n^key1: value1\nkey2: value2\n \"\"\")\n\n assert res == {'key2': 'value2'}\n\n res = read_yaml_config_string(\"\"\"\n^key1: &anchor_key1 value\nkey2: *anchor_key1\n \"\"\")\n\n assert res == {'key2': 'value'}\n\n\ndef test_read_yaml_config_file():\n\n yaml_templater = YAMLTemplater()\n yaml_templater.add_const_template('root', 'root_replacement')\n yaml_templater.add_function_template('root', lambda x: x)\n\n config, config_text = parse_configuration(\n join('tests', 'yaml_import', 'example.yaml'),\n yaml_templater)\n\n assert config['from_define'] == 'defined_value'\n assert config['rootdir'] == 'root_replacement'\n assert config['rootappend'] == 'hello'\n","sub_path":"tests/test_yaml_tool.py","file_name":"test_yaml_tool.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180138863","text":"#-*- coding: utf-8 -*- \nimport logging\nimport pytz\nfrom api.lib.error import *\nfrom api.lib.action import Action\nfrom api.conf.content_conf import *\nfrom api.conf.global_conf import *\n\nclass web_insert_visit_report(Action):\n\t\n\tlogger = logging.getLogger('api')\n\tparams_info = {\t\n\t\t'reporter' : ['r', 'int'],\n\t\t'member' : ['r', 'int'],\n\t\t'visitor' : ['r', 'str'],\n\t\t'visit_type' : ['r', 'str'],\n\t\t'visit_place' : ['r', 'str'],\n\t\t'visit_reason' : ['r', 'str'],\n\t\t'visit_result' : ['r', 'str'],\n\t\t'after_plan' : ['r', 'str'],\n\t\t'visit_date' : ['r', 'str']\n\t}\n\n\tdef __init__(self, request):\n\t\trequest_params = request['request']\n\t\tself.params = self.set_params_web(request_params, self.params_info)\n\n\tdef _set_ins_params(self, member):\n\t\tparams = {}\n\t\tparams['reporter'] = self.params['reporter']\n\t\tparams['member'] = member\n\t\tparams['visitor'] = self.params['visitor']\n\t\tparams['visit_type'] = self.params['visit_type']\n\t\tparams['visit_place'] = self.params['visit_place']\n\t\tparams['visit_reason'] = self.params['visit_reason']\n\t\tparams['visit_result'] = self.params['visit_result']\n\t\tparams['after_plan'] = self.params['after_plan']\n\t\tparams['visit_date'] = self.params['visit_date']\n\n\t\treturn params\n\n\tdef execute(self):\n\t\tself.member_dao = self.locator.getDAO('members')\n\t\tself.report_dao = self.locator.getDAO('visit_report')\n\t\n\t\tmember = self.member_dao.getVOfromID(self.params['member'])\n\t\tins_params = self._set_ins_params(member)\n\n\t\treport_id = self.report_dao.insert(ins_params)\n\t\tret = { 'id' : report_id }\n\t\n\t\tself.logger.debug(ret)\t\n\t\treturn ret\n","sub_path":"api/action/web_insert_visit_report.py","file_name":"web_insert_visit_report.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"63053846","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:Zhangcl\nimport re\nimport os\nstaff_table=\"staff_table.txt\"\nstaff_table_new=\"staff_table_new.txt\"\nstaff_table_tmp=\"staff_table_tmp.txt\"\npath_exis =os.path.exists(staff_table)\nif path_exis == False:\n exit('配置文件不存在,强制退出')\nthe_table_field={\n 'staff_id':0,\n 'name':1,\n 'age':2,\n 'phone':3,\n 'dept':4,\n 'enroll_date':5\n }\ndef path(): #判断临时文件是否存在\n path_exis_new=os.path.exists(staff_table_new)\n path_exis_tmp=os.path.exists(staff_table_tmp)\n if path_exis_new:\n os.remove(staff_table_new)\n if path_exis_tmp:\n os.remove(staff_table_tmp)\n\ndef file_open():#打开文件\n staff_old =open(staff_table,'r',encoding='utf-8')\n staff_new =open(staff_table_new,'w',encoding='utf-8')\n return staff_old,staff_new\n\ndef file_tmp():#替换文件\n path_exis_tmp = os.path.exists(staff_table_tmp)\n if path_exis_tmp:\n os.remove(staff_table_tmp)\n os.rename(staff_table,staff_table_tmp)\n os.rename(staff_table_new,staff_table)\n\ndef add():#添加模块\n path()\n staff_old, staff_new = file_open()\n the_file_is_null = False#设置变量用来判断文件是否为空\n the_values = re.search('\\(.*\\)',str(sql_list)).group()#匹配出values后的内容\n the_values_into = the_values.split('(')[1].split(')')[0].split(',')#将values()括号内的值取出\n file_len = open(staff_table, 'r', encoding='utf-8')\n if len(file_len.read()) == 0:#判断表内是否有记录,如无记录则默认用户ID为1\n the_num_add = '1'\n the_file_is_null = True#文件为空,变量值变为True\n file_len.close()\n num_is=True\n if the_file_is_null ==False:#如果文件不为空,就依次匹配电话号码是否重复和获取ID\n for the_phone in staff_old:\n the_phone_list = the_phone.split()\n if the_phone_list[3] == the_values_into[2]:#依次匹配电话号码\n print('\\033[1;31m电话号码重复!\\033[0m')\n num_is=False#如果号码重复,则不进行下面的代码\n break\n if num_is==True:#如果电话号码不重复,num_is就不会变成false,就执行下面的写入记录代码\n to_find_num=open(staff_table,'r',encoding='utf-8')\n for num in to_find_num:\n num_list=num.split()\n the_num_add=str(int(num_list[0]) + 1)#轮训到表的最后一条记录取ID+1,就为新加入的记录的用户ID\n staff_new.write(num)\n the_values_into.insert(0,the_num_add)#将获取的ID插入等会需要写入文本的列表中\n print(the_values_into)\n the_values_into_list=' '.join(the_values_into)+'\\n'\n staff_new.write(the_values_into_list)\n to_find_num.close()\n staff_old.close()\n staff_new.close()\n file_tmp()\n print('\\033[1;31m添加成功\\033[0m')\n else:#如果文件为空,就直接写入新文件\n the_values_into.insert(0, the_num_add)\n print(the_values_into)\n the_values_into_list = ' '.join(the_values_into) + '\\n'\n staff_new.write(the_values_into_list)\n staff_old.close()\n staff_new.close()\n file_tmp()\n print('\\033[1;31m添加成功\\033[0m')\n\ndef remove():#删除模块\n path()\n staff_old, staff_new = file_open()\n for i in staff_old:\n if i.strip().startswith(sql_list[-1]):#匹配用户ID,如果相同就跳过写入以起到删除作用\n continue\n staff_new.write(i)\n staff_old.close()\n staff_new.close()\n file_tmp()\n print('\\033[1;31m删除成功\\033[0m')\n\ndef change():#修改模块\n path()\n staff_old, staff_new = file_open()\n change_num=0\n for i in staff_old:\n a=re.split(' ',i)\n if a[the_table_field[sql_list[-3]]]== sql_list[-1]:#匹配where后面的表名数据在文本中的位置然后再与需要的筛选的内容进行对比\n a[the_table_field[sql_list[3]]]=sql_list[5]#将需要修改的内容重新赋值进去\n a_into=' '.join(a)\n staff_new.write(a_into)\n change_num = change_num+1\n continue\n staff_new.write(i)\n staff_old.close()\n staff_new.close()\n file_tmp()\n print('\\033[1;31m%s条记录已更新!\\033[0m' %change_num)\n\ndef fetch():#查询模块\n path()\n staff_old, staff_new = file_open()\n if len(sql_list)== 4:#判断sql语句是否是条件查询语句\n if sql_list[1]==\"*\":#判断是否全部字段查询\n cont=0\n with open(staff_table,'r',encoding='utf-8') as f:\n for i in f :\n print(i.replace('\\n',''))\n cont=cont+1\n print('\\033[1;31m已查询到%s条内容\\033[0m' %cont)\n if sql_list[1]!='*':#如果不是全部查询\n select_to_find=sql_list[1].split(',')\n for x in staff_old:\n find_output = []\n to_find = re.split(' ', x)\n for ff in select_to_find:\n find_output.append(to_find[the_table_field[ff]])\n print(' '.join(find_output).replace('\\n',''))\n\n def field_output():#判断是全部查询还是按表名查询\n if sql_list[1] != '*':\n select_to_find = sql_list[1].split(',')\n to_find_output = []\n for ff in select_to_find:\n to_find_output.append(to_find_where[the_table_field[ff]])\n print(' '.join(to_find_output))\n else:\n print(' '.join(to_find_where).replace('\\n',''))\n\n if re.search(\"=|>|<|like\",sql) is not None:#判断sql语句中是否有模糊查询\n change_num = 0\n num_is=False\n for i in staff_old:#以下匹配模糊查询类型\n to_find_where = re.split(' ', i)\n if sql_list[-2] == '=':\n if to_find_where[the_table_field[sql_list[-3]]] == sql_list[-1]:\n field_output()\n num_is = True\n if sql_list[-2] == '>':\n if int(to_find_where[the_table_field[sql_list[-3]]]) > int(sql_list[-1]):\n field_output()\n num_is = True\n if sql_list[-2] == '<':\n if int(to_find_where[the_table_field[sql_list[-3]]]) < int(sql_list[-1]):\n field_output()\n num_is = True\n if re.search('like',sql) is not None:\n if re.search(sql_list[-1],to_find_where[the_table_field[sql_list[-3]]]) is not None:\n field_output()\n num_is = True\n if num_is == True:#上面的代码只要匹配成功num_is=True就计数一次\n change_num = change_num + 1\n num_is = False\n print('\\033[1;31m已查询到%s条内容\\033[0m' % change_num)\n staff_old.close()\n staff_new.close()\n\nwhile True:\n sql = input(\"请输入sql语句>>:\")\n sql_list = re.split(' ', sql)\n if re.search(\"^(?i)insert into\",sql) is not None and len(sql_list) ==4:\n add()\n elif re.search(\"^(?i)delete\", sql) is not None and len(sql_list) ==7:\n remove()\n elif re.search(\"^(?i)update\", sql) is not None and len(sql_list) == 11:\n change()\n elif re.search(\"^(?i)select\",sql) is not None:\n fetch()\n elif sql=='q' or sql == 'Q':\n exit()\n else:\n print(\"输入错误!\")\n\n\n","sub_path":"day4/员工信息表/empinfo3.py","file_name":"empinfo3.py","file_ext":"py","file_size_in_byte":7515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570472894","text":"\nimport dpkt, socket, sys, geoip2.database, datetime\nfrom tkinter import *\n\nglobal tracker\ntracker = []\n\nclass pycap():\n\tdef __init__(self, capture, db_path, filter, initialize_window, all_data):\n\t\tself.capture = capture\n\t\tself.db_path = db_path\n\t\tself.filter = filter\n\t\tself.initialize_window = initialize_window\n\t\tself.all_data = all_data\n\n\t\tself.init_window(capture, db_path, filter)\n\t\n\tdef init_window(self, capture, db_path, filter):\n\t\tglobal root\n\t\tif self.initialize_window is False:\n\t\t\tself.initialize_window = True\n\t\t\troot = Tk()\n\t\t\troot.geometry(\"1000x500\")\n\t\t\troot.title(\"pycap\")\n\t\t\tval = StringVar() # value of entry is stored here\n\t\t\t\n\t\t\tstatus_bar = \"NO. SOURCE DESTINATION LOCATION (src) LOCATION (dst) \"\n\t\t\tstatus = Label(root, text = status_bar, bd = 1, relief = FLAT, anchor = W)\n\t\t\tstatus.pack(side = TOP, fill = X)\n\t\t\t\n\t\t\t# /\\ search frame /\\\n\t\t\tsearch_frame = Frame(root, relief = FLAT)\n\t\t\tsearch_frame.pack(side = BOTTOM, fill = X)\n\n\t\t\tinfo_txt = (\" {}\").format(sys.argv[1])\n\t\t\tinfo = Label(search_frame, text = info_txt)\n\t\t\tinfo.pack(side = RIGHT)\n\n\t\t\tlabel_entry = Label(search_frame, text = \"FILTER: \")\n\t\t\tlabel_entry.pack(side = LEFT)\n\n\t\t\tglobal filter_entry\n\t\t\tfilter_entry = Entry(search_frame, textvariable = val, width = 30)\n\t\t\tfilter_entry.pack(side = LEFT)\n\t\t\tfilter_entry.bind(\"\", self.apply_filter)\n\t\t\t\n\t\t\t# /\\ search frame /\\\n\n\t\t\tscroll = Scrollbar(root)\n\t\t\tscroll.pack(side = RIGHT, fill = Y)\n\t\t\t\n\t\t\tglobal listbox\n\t\t\tlistbox = Listbox(root, yscrollcommand = scroll.set)\n\t\t\tlistbox.bind('', self.more_info)\n\t\t\tlistbox.pack(expand = True, side = \"left\", fill = \"both\")\n\t\t\tscroll.config(command = listbox.yview)\n\t\t\n\t\telse: pass\n\t\tf = open(capture)\n\t\tpcap = dpkt.pcap.Reader(f)\n\t\tfor line in self.pcap_reader(pcap, filter, 100): listbox.insert(END, line)\n\n\t\troot.mainloop()\n\t\n\tdef pcap_reader(self, cap, filter, line):\n\t\tarr = []\n\n\t\tthis_ip = socket.gethostbyname(socket.gethostname())\n\n\t\tfor (ts, buf) in cap:\n\t\t\tthis_dict = {}\n\t\t\ttry:\n\t\t\t\teth = dpkt.ethernet.Ethernet(buf)\n\t\t\t\tip = eth.data\n\t\t\t\tsrc = socket.inet_ntoa(ip.src)\n\t\t\t\tdst = socket.inet_ntoa(ip.dst)\n\t\t\t\tprotocol = ip.get_proto(ip.p).__name__\n\n\t\t\t\tsrc_copy = src\n\t\t\t\tdst_copy = dst\n\n\t\t\t\tsrc_lookup = self.ip_lookup(src)\n\t\t\t\tdst_lookup = self.ip_lookup(dst)\n\n\t\t\t\tsrc_loc_copy = src_lookup\n\t\t\t\tdst_loc_copy = dst_lookup\n\n\t\t\t\tsport = ip.data.sport\n\t\t\t\tdport = ip.data.dport\n\t\t\t\t\n\t\t\t\tdo_not_fragment = bool(ip.off & dpkt.ip.IP_DF)\n\t\t\t\tmore_fragments = bool(ip.off & dpkt.ip.IP_MF)\n\t\t\t\t\n\t\t\t\tif src_copy == this_ip: \n\t\t\t\t\tsrc_lookup = \"[YOU] \"\n\t\t\t\t\tsrc_loc_copy = \"[YOU]\"\n\t\t\t\t\n\t\t\t\telif dst_copy == this_ip:\n\t\t\t\t\tdst_lookup = \"[YOU] \"\n\t\t\t\t\tdst_loc_copy = \"[YOU]\"\n\n\t\t\t\tthis_dict[\"no\"] = str(line)\n\n\t\t\t\tthis_dict[\"src\"] = src_copy\n\t\t\t\tthis_dict[\"dst\"] = dst_copy\n\n\t\t\t\tthis_dict[\"src_lookup\"] = src_loc_copy\n\t\t\t\tthis_dict[\"dst_lookup\"] = dst_loc_copy\n\n\t\t\t\tthis_dict[\"protocol\"] = protocol\n\n\t\t\t\tthis_dict[\"ts\"] = str(datetime.datetime.utcfromtimestamp(ts))\n\t\t\t\tthis_dict[\"ttl\"] = str(ip.ttl)\n\n\t\t\t\tthis_dict[\"df\"] = do_not_fragment\n\t\t\t\tthis_dict[\"mf\"] = more_fragments\n\n\t\t\t\tthis_dict[\"sport\"] = str(sport)\n\t\t\t\tthis_dict[\"dport\"] = str(dport)\n\n\t\t\t\ttcp = ip.data\n\t\t\t\tif tcp.dport == 80 and len(tcp.data) > 0:\n\t\t\t\t\thttp = dpkt.http.Request(tcp.data)\n\t\t\t\t\tthis_dict[\"http_uri\"] = http.uri\n\t\t\t\t\tthis_dict[\"user_agent\"] = http.headers['user-agent']\n\t\t\t\t\tthis_dict[\"http_method\"] = http.method\n\t\t\t\t\n\t\t\t\tself.all_data.append(this_dict)\n\n\t\t\t\tif(len(src) < 13):\n\t\t\t\t\tloops = 13 - len(src)\n\t\t\t\t\tfor i in range(loops): src += \" \"\n\t\t\t\t\n\t\t\t\tif(len(dst) < 13):\n\t\t\t\t\tloops = 13 - len(dst)\n\t\t\t\t\tfor i in range(loops): dst += \" \"\n\t\t\t\t\n\t\t\t\tif(len(src_lookup) < 10):\n\t\t\t\t\tloops = 9 - len(src_lookup)\n\t\t\t\t\tfor i in range(loops): src_lookup += \" \"\n\t\t\t\t\n\t\t\t\tif(len(dst_lookup) < 9):\n\t\t\t\t\tloops = 9 - len(dst_lookup)\n\t\t\t\t\tfor i in range(loops): dst_lookup += \" \"\n\t\t\t\tdata_line = \"\"\n\t\t\t\tdata_line = (\"{}. {} {} {} {} \").format(line, src, dst, src_lookup, dst_lookup)\n\n\t\t\t\tif len(filter) == 0:\n\t\t\t\t\t\n\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\tline +=1\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tfor f in filter:\n\t\t\t\t\t\tfv2 = f.split(\"=\")\n\t\t\t\t\t\ttarget = fv2[0]\n\t\t\t\t\t\tval = fv2[1]\n\t\t\t\t\t\t#print(\"target: {}. val: {}\").format(target, val)\n\t\t\t\t\t\t#print(\"sport: {}, dport: {}\").format(sport, dport)\n\t\t\t\t\t\tif target == \"no\" and int(val) == line:\n\t\t\t\t\t\t\tline +=1\n\t\t\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif target == \"src\" and val == src_copy:\n\t\t\t\t\t\t\tline +=1\n\t\t\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif target == \"dst\" and val == dst_copy:\n\t\t\t\t\t\t\tline +=1\n\t\t\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif target == \"src_loc\" and val == src_loc_copy:\n\t\t\t\t\t\t\tline +=1\n\t\t\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif target == \"dst_loc\" and val == dst_loc_copy:\n\t\t\t\t\t\t\tline +=1\n\t\t\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif target == \"proto\" and val == protocol:\n\t\t\t\t\t\t\tline +=1\n\t\t\t\t\t\t\tarr.append(data_line)\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tline += 1\n\t\t\t\t\t\t\t\n\n\t\t\texcept: continue\n\t\t\n\t\treturn arr\n\t\n\tdef apply_filter(self, filter):\n\t\tglobal command\n\t\tcommand = (filter_entry.get()).split(\",\")\n\t\tcommand_list = [\"no\",\"src\",\"dst\",\"src_loc\",\"dst_loc\",\"proto\"]\n\n\t\tfor filter in command:\n\t\t\tfil = filter.split(\"=\")\n\t\t\ttarget = fil[0]\n\t\t\t\n\t\t\tif target not in command_list: command.remove(filter)\n\t\t\n\t\tlistbox.delete(0, END)\n\t\tself.init_window(self.capture, self.db_path, command)\n\t\t\n\tdef ip_lookup(self, ip):\n\t\t\n\t\ttry:\n\t\t\tdb = geoip2.database.Reader(self.db_path)\n\t\t\tdb_response = db.city(ip)\n\t\t\tcountry = db_response.country.iso_code\n\t\t\tcity = db_response.city.name\n\t\t\tidentity = \"[\" + city + \"]\"\n\t\t\tdb.close()\n\t\t\treturn identity\n\n\t\texcept: return \"[Unknown]\"\n\n\tdef more_info(self, val):\n\t\ttry:\n\t\t\tselection = listbox.curselection()\n\t\t\tpos = str(list(selection)[0] + 100)\n\t\t\ttitle = (\"packet number \" + str(pos))\n\n\t\t\tif pos not in tracker:\n\t\t\t\twin = Toplevel()\n\t\t\t\ttracker.append(pos)\n\t\t\t\tinfo = []\n\n\t\t\t\tfor dict in self.all_data:\n\t\t\t\t\tif dict.get(\"no\") == pos:\n\t\t\t\t\t\tinfo.append(dict.get(\"protocol\"))\n\t\t\t\t\t\tinfo.append(dict.get(\"ts\"))\n\t\t\t\t\t\tinfo.append(dict.get(\"ttl\"))\n\t\t\t\t\t\tinfo.append(dict.get(\"df\"))\n\t\t\t\t\t\tinfo.append(dict.get(\"mf\"))\n\t\t\t\t\t\tinfo.append(dict.get(\"sport\"))\n\t\t\t\t\t\tinfo.append(dict.get(\"dport\"))\n\t\t\t\t\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tinfo.append(dict.get(\"http_uri\"))\n\t\t\t\t\t\t\tinfo.append(dict.get(\"user_method\"))\n\t\t\t\t\t\t\tinfo.append(dict.get(\"http_method\"))\n\t\t\t\t\t\texcept: pass\n\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\tcontinue\n\t\t\t\tmore_info = new_window(win, title, \"400x500\", pos, info)\n\n\t\texcept: pass\n\t\n\nclass new_window(pycap):\n\tdef __init__(self, master, title, geometry, pos, info):\n\t\tself.master = master\n\t\tself.title = title\n\t\tself.geometry = geometry\n\t\tself.pos = pos\n\t\tself.info = info\n\n\t\tself.master.title(self.title)\n\t\tself.master.geometry(self.geometry)\n\t\tself.master.resizable(width = False, height = False)\n\t\tself.master.protocol(\"WM_DELETE_WINDOW\", self.__close__)\n\n\t\tself.display_info()\n\n\t\tself.master.mainloop()\n\n\tdef __close__(self):\n\t\ttracker.remove(self.pos)\n\t\tself.master.destroy()\n\t\n\tdef display_info(self):\n\t\tts_label = Label(self.master, text = (\"Timestamp: \" + str(self.info[1])))\n\t\tts_label.place(x = 15, y = 20)\n\n\t\tttl_label = Label(self.master, text = (\"Time to live: \" + str(self.info[2])))\n\t\tttl_label.place(x = 15, y = 45)\n\n\t\tdf_label = Label(self.master, text = (\"DF flag: \" + str(self.info[3])))\n\t\tdf_label.place(x = 15, y = 70)\n\n\t\tmf_label = Label(self.master, text = (\"MF flag: \" + str(self.info[4])))\n\t\tmf_label.place(x = 15, y = 95)\n\n\t\tsport_label = Label(self.master, text = (\"Source port: \" + str(self.info[5])))\n\t\tsport_label.place(x = 15, y = 120)\n\n\t\tmf_label = Label(self.master, text = (\"Destination port: \" + str(self.info[6])))\n\t\tmf_label.place(x = 15, y = 145)\n\n\t\tproto_label = Label(self.master, text = (\"Protocol: \" + str(self.info[0])))\n\t\tproto_label.place(x = 15, y = 170)\n\n\t\tif self.info[5] == \"80\":\n\t\t\thttp_title = Label(self.master, text = \"HTTP:\")\n\t\t\thttp_title.place(x = 15, y = 200)\n\n\t\t\tmethod_label = Label(self.master, text = (\"- Method: \" + str(self.info[9])))\n\t\t\tmethod_label.place(x = 30, y = 225)\n\n\t\t\tagent_label = Label(self.master, text = (\"- User agent: \" + str(self.info[8])))\n\t\t\tagent_label.place(x = 30, y = 250)\n\n\t\t\turi_label = Label(self.master, text = (\"- URI: \" + str(self.info[7])))\n\t\t\turi_label.place(x = 30, y = 275)\n\ndef main(filter):\n\tdb_path = \"/opt/geolite-2/GeoLite2-City.mmdb\" #add path to the geolite database\n\tfilter = \"\"\n\ttry:\n\t\tpycap_obj = pycap(sys.argv[1], db_path, filter, False, [])\n\n\texcept Exception as err:\n\t\tprint(\"[+] {}\".format(err))\n\t\tsys.exit()\n\nif __name__ == \"__main__\":\n\tmain(filter)\n","sub_path":"pycap.py","file_name":"pycap.py","file_ext":"py","file_size_in_byte":8797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"502089861","text":"# -*- coding: utf-8 -*-\n# import openerp.netsvc\nimport openerp.netsvc\n# from openerp.osv import osv, fields\nfrom openerp.osv import osv, fields\n\nclass hr_leave_mass_approve(osv.osv_memory):\n _name = 'hr.leave.mass.approve'\n \n def confirm_mass_leave(self, cr, uid, ids, context=None):\n leaves_ids = context.get('active_ids', [])\n wf_service = openerp.netsvc.LocalService(\"workflow\")\n for leave_id in leaves_ids:\n wf_service.trg_validate(uid, context['active_model'], leave_id, 'confirm', cr)\n return {'type': 'ir.actions.act_window_close'}\n\n def validate_mass_leave(self, cr, uid, ids, context=None):\n leaves_ids = context.get('active_ids', [])\n wf_service = openerp.netsvc.LocalService(\"workflow\")\n for leave_id in leaves_ids:\n wf_service.trg_validate(uid, context['active_model'], leave_id, 'validate', cr)\n return {'type': 'ir.actions.act_window_close'}\n \n def cancel_mass_leave(self, cr, uid, ids, context=None):\n leaves_ids = context.get('active_ids', [])\n wf_service = openerp.netsvc.LocalService(\"workflow\")\n for leave_id in leaves_ids:\n wf_service.trg_validate(uid, context['active_model'], leave_id, 'cancel', cr)\n return {'type': 'ir.actions.act_window_close'}\n \n\nhr_leave_mass_approve()\n\nclass hr_extra_mass_compute(osv.osv_memory):\n _name = 'hr.extra.mass.compute'\n \n def compute_mass_extra_hours(self, cr, uid, ids, context=None):\n active_ids = context.get('active_ids', [])\n self.pool.get('hr.payroll.extrahours').compute_value(cr, uid, active_ids, context=context)\n return {'type': 'ir.actions.act_window_close'}\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"hr_payroll_extended/wizard/hr_leave_mass_approve.py","file_name":"hr_leave_mass_approve.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"353061366","text":"# from datetime import datetime\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom django.views.generic import CreateView, UpdateView, DeleteView\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.urls import reverse, reverse_lazy\nfrom django.db.models.functions import TruncMonth, TruncDate\nfrom django.db.models import Count\n\nfrom notifications.models import Notification\n\nfrom .decorators import restaurant_required\nfrom .models import Category, Restaurant\nfrom accounts.models import User\nfrom .forms import RestaurantProfileForm\nfrom foods.models import Food, FoodTemplate, Category as FoodCategory\nfrom foods.views import FoodListView, FoodDetailView\nfrom orders.models import Order\n\n\ndef restaurant_list(request, category_slug=None):\n category = None\n categories = Category.objects.all()\n # currentTime = datetime.now().time()\n restaurants = Restaurant.objects.all()\n # tmp_restaurant1 = tmp_restaurant.filter(Q(open_hour__lte=F('close_hour')), Q(open_hour__lte=currentTime), close_hour__gte=currentTime)\n # tmp_restaurant2 = tmp_restaurant.filter(available=True).filter(Q(open_hour__gt=F('close_hour')), Q(open_hour__lte=currentTime) | Q(close_hour__gte=currentTime))\n # restaurants = tmp_restaurant1 | tmp_restaurant2\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n restaurants = restaurants.filter(category=category)\n return render(\n request,\n 'restaurants/restaurant_list.html',\n {\n 'category': category,\n 'categories': categories,\n 'restaurants': restaurants\n }\n )\n\n\ndef restaurant_detail(request, id, slug):\n restaurant = get_object_or_404(Restaurant,\n id=id,\n slug=slug)\n\n foods_obj = Food.objects.filter(restaurant=restaurant)\n food_categories = set(map(lambda x: x.category, foods_obj))\n\n foods = {}\n\n for category in food_categories:\n foods[category.name] = []\n\n for food in foods_obj:\n foods[food.category.name].append(food)\n\n return render(request,\n 'restaurants/restaurant_detail.html',\n {'restaurant': restaurant,\n 'foods': foods,\n })\n\n\n@login_required\n@restaurant_required\ndef restaurant_dashboard(request):\n allowed_categories = ['month', 'date']\n order_category = request.GET.get('order_by', 'date')\n\n # if order_category not in allowed_categories:\n # return redirect('restaurants:restaurant_dashboard')\n\n if order_category == 'month':\n sales = Order.objects.filter(complete=True) \\\n .filter(items__food__restaurant=request.user.restaurant) \\\n .annotate(month=TruncMonth('created')) \\\n .values('month') \\\n .annotate(count=Count('id')) \\\n .order_by()\n labels = [sale['month'].strftime('%b %Y') for sale in sales]\n elif order_category == 'date':\n sales = Order.objects.filter(complete=True) \\\n .filter(items__food__restaurant=request.user.restaurant) \\\n .annotate(date=TruncDate('created')) \\\n .values('date') \\\n .annotate(count=Count('id')) \\\n .order_by()\n \n labels = [sale['date'].strftime('%d %b %Y') for sale in sales]\n \n data = [sale['count'] for sale in sales]\n\n context = {\n 'restaurant': request.user.restaurant,\n 'section': 'dashboard',\n 'labels': labels,\n 'data': data,\n 'order_parameter': order_category\n }\n return render(request, 'restaurants/dashboard.html', context)\n\n\n@login_required\n@restaurant_required\ndef update_restaurant_profile(request):\n if request.method == 'GET':\n form = RestaurantProfileForm(instance=request.user.restaurant)\n else:\n form = RestaurantProfileForm(\n data=request.POST,\n files=request.FILES,\n instance=request.user.restaurant\n )\n print(form.errors.as_data())\n if form.is_valid():\n form.save()\n messages.success(request, 'Profile sucessfully updated!')\n return redirect('restaurants:update_profile')\n else:\n messages.error(request, 'Profile Update failed!')\n return redirect('restaurants:update_profile')\n\n context = {\n 'form': form,\n 'section': 'profile',\n }\n return render(request, 'restaurants/profile_update.html', context)\n\n\nclass FoodCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView):\n model = Food\n fields = ['category', 'name', 'description', 'price', 'image', 'discount_percent','available']\n template_name = 'restaurants/food_form.html'\n success_url = reverse_lazy('restaurants:food_list')\n\n def test_func(self):\n return self.request.user.is_active and self.request.user.is_restaurant\n\n def form_valid(self, form):\n form.instance.restaurant = self.request.user.restaurant\n return super().form_valid(form)\n\n def get_context_data(self, **kwargs):\n template_slug = self.kwargs.get('slug')\n context = super().get_context_data(**kwargs)\n context['templates'] = FoodTemplate.objects.all()\n context['template_slug'] = template_slug\n context['section'] = 'foods'\n return context\n\n def get_initial(self):\n template_slug = self.kwargs.get('slug')\n data = super().get_initial()\n\n if template_slug:\n template_instance = get_object_or_404(\n FoodTemplate, slug=template_slug)\n data['category'] = template_instance.category\n data['name'] = template_instance.name\n data['description'] = template_instance.description\n data['image'] = template_instance.image\n data['price'] = template_instance.price\n data['available'] = template_instance.available\n\n return data\n\n\nclass FoodUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):\n model = Food\n fields = ['category', 'name', 'description', 'price', 'image', 'discount_percent', 'available']\n template_name = 'restaurants/food_form.html'\n success_url = reverse_lazy('restaurants:food_list')\n\n def test_func(self):\n return self.request.user.is_active and self.request.user.is_restaurant \\\n and self.get_object().restaurant == self.request.user.restaurant\n\n def form_valid(self, form):\n form.instance.restaurant = self.request.user.restaurant\n return super().form_valid(form)\n\n\nclass FoodDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):\n model = Food\n success_url = reverse_lazy('restaurants:food_list')\n context_object_name = 'food'\n template_name = 'restaurants/food_delete.html'\n\n def test_func(self):\n return self.request.user.is_active and self.request.user.is_restaurant \\\n and self.get_object().restaurant == self.request.user.restaurant\n\n\nclass RestaurantFoodListView(LoginRequiredMixin, UserPassesTestMixin, FoodListView):\n template_name = 'restaurants/food_list.html'\n\n def test_func(self):\n return self.request.user.is_active and self.request.user.is_restaurant\n\n def get_queryset(self, **kwargs):\n restaurant_foods = self.model.objects.filter(\n restaurant=self.request.user.restaurant)\n category_slug = self.kwargs.get('category_slug')\n if category_slug:\n category = get_object_or_404(FoodCategory, slug=category_slug)\n return restaurant_foods.filter(category=category)\n return restaurant_foods.all()\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n slug = self.kwargs.get('category_slug')\n restaurant_foods = self.model.objects.filter(\n restaurant=self.request.user.restaurant)\n categories = set(map(lambda x: x.category, restaurant_foods))\n context['categories'] = categories\n if slug:\n context['category'] = get_object_or_404(FoodCategory, slug=slug)\n context['section'] = 'foods'\n return context\n\n\nclass RestaurantFoodDetailView(LoginRequiredMixin, UserPassesTestMixin, FoodDetailView):\n template_name = 'restaurants/food_detail.html'\n\n def test_func(self):\n return self.request.user.is_active and self.request.user.is_restaurant \\\n and self.get_object().restaurant == self.request.user.restaurant\n\n\ndef view_new_order(request):\n user = User.objects.get(id=request.user.id)\n order_category = request.GET.get('order_by', 'unread')\n\n if order_category == 'all':\n notifications = user.notifications.all().order_by('-unread')\n\n if order_category == 'unread':\n notifications = user.notifications.unread()\n \n if order_category == 'read':\n notifications = user.notifications.read()\n\n context = {\n 'notifications': notifications,\n 'section': 'new_order',\n 'order_parameter': order_category,\n }\n\n return render(\n request,\n 'restaurants/new_order.html',\n context,\n )\n\n\ndef order_mark_as_read(request, notification_id):\n notification = get_object_or_404(Notification, id=notification_id)\n if not request.user == notification.recipient:\n messages.error(request, 'You cannot mark this order as read.')\n else:\n notification.unread = False\n notification.save()\n messages.success(request, f'{notification.action_object} was successfully marked as complete.')\n return redirect(request.META.get('HTTP_REFERER', 'redirect_if_referer_not_found'))\n\n\ndef order_mark_as_unread(request, notification_id):\n notification = get_object_or_404(Notification, id=notification_id)\n if not request.user == notification.recipient:\n messages.error(request, 'You cannot unmark this order as unread.')\n else:\n notification.unread = True\n notification.save()\n messages.success(request, f'{notification.action_object} was successfully marked as unread.')\n return redirect(request.META.get('HTTP_REFERER', 'redirect_if_referer_not_found'))\n\n\ndef order_detail(request, notification_id):\n notification = get_object_or_404(Notification, id=notification_id)\n if not request.user == notification.recipient:\n messages.error(request, 'You cannot view detail of this order.')\n return redirect(request.META.get('HTTP_REFERER', 'redirect_if_referer_not_found'))\n else:\n order = notification.action_object\n order_items = [item for item in order.items.all() if item.food.restaurant==request.user.restaurant]\n total_cost = sum(item.get_cost() for item in order_items)\n\n context = {\n 'notification': notification,\n 'order': order,\n 'order_items': order_items,\n 'total_cost': total_cost,\n }\n\n return render(request, 'restaurants/order_detail.html', context)\n\n","sub_path":"restaurants/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"182203745","text":"import xml.sax\n\ndatas=set()\n\nclass MovieHandler(xml.sax.ContentHandler):\n def __init__(self):\n self.title = \"\"\n self.ee = \"\"\n self.year=\"\"\n self.journal=\"\"\n\n # 元素开始事件处理\n def startElement(self, tag, attributes):\n self.CurrentData = tag\n if tag == \"article\":\n key = attributes[\"key\"]\n # 元素结束事件处理\n def endElement(self, tag):\n if self.CurrentData == \"title\":\n print (u'title:',self.title)\n elif self.CurrentData == \"ee\":\n print (u'ee:',self.ee)\n elif self.CurrentData == \"journal\":\n print (u'journal:',self.journal)\n if self.CurrentData == \"year\":\n print (u'year:', self.year)\n self.CurrentData = \"\"\n\n # 内容事件处理\n def characters(self, content):\n if self.CurrentData == \"title\":\n self.title = content\n elif self.CurrentData == \"ee\":\n self.ee = content\n elif self.CurrentData == \"year\":\n self.year = content\n elif self.CurrentData == \"journal\":\n self.journal = content\n\nif (__name__ == \"__main__\"):\n # 创建一个 XMLReader\n parser = xml.sax.make_parser()\n # turn off namepsaces\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\n\n # 重写 ContextHandler\n Handler = MovieHandler()\n parser.setContentHandler(Handler)\n parser.parse(\"dblp.xml\")\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"606538926","text":"############################################################\n# -*- coding: utf-8 -*-\n#\n# Python-based Tool for interaction with the 10micron mounts\n# GUI with PyQT5 for python\n# Python v3.5\n#\n# Michael Würtenberger\n# (c) 2016, 2017\n#\n# Licence APL2.0\n#\n############################################################\nimport logging\nimport math\nimport datetime\nfrom astrometry.erfa import ERFA\nimport threading\n\n\nclass Transform:\n logger = logging.getLogger(__name__)\n\n def __init__(self, app):\n self.app = app\n self.ERFA = ERFA()\n self.transformationLockERFA = threading.Lock()\n self.conversionLock = threading.Lock()\n\n def ra_dec_lst_to_az_alt(self, ra, dec):\n LAT = self.degStringToDecimal(self.app.mount.site_lat)\n ra = (ra * 360 / 24 + 360.0) % 360.0\n dec = math.radians(dec)\n ra = math.radians(ra)\n lat = math.radians(LAT)\n alt = math.asin(math.sin(dec) * math.sin(lat) + math.cos(dec) * math.cos(lat) * math.cos(ra))\n A = math.acos((math.sin(dec) - math.sin(alt) * math.sin(lat)) / (math.cos(alt) * math.cos(lat)))\n A = math.degrees(A)\n alt = math.degrees(alt)\n if math.sin(ra) >= 0.0:\n az = 360.0 - A\n else:\n az = A\n return az, alt\n\n def degStringToDecimal(self, value, splitter=':'):\n returnValue = 0\n sign = 1\n if '-' in value:\n value = value.replace('-', '')\n sign = -1\n elif '+' in value:\n value = value.replace('+', '')\n try:\n if len(value.split(splitter)) == 3:\n hour, minute, second = value.split(splitter)\n returnValue = (float(hour) + float(minute) / 60 + float(second) / 3600) * sign\n elif len(value.split(splitter)) == 2:\n hour, minute = value.split(splitter)\n returnValue = (float(hour) + float(minute) / 60) * sign\n except Exception as e:\n self.logger.error('error in conversion of:{0} with splitter:{1}, e:{2}'.format(value, splitter, e))\n returnValue = 0\n finally:\n pass\n return returnValue\n\n def decimalToDegree(self, value, with_sign=True, with_decimal=False, spl=':'):\n if value >= 0:\n sign = '+'\n else:\n sign = '-'\n value = abs(value)\n hour = int(value)\n minute = int((value - hour) * 60)\n second = int(((value - hour) * 60 - minute) * 60)\n if with_decimal:\n second_dec = '.{0:1d}'.format(int((((value - hour) * 60 - minute) * 60 - second) * 10))\n else:\n second_dec = ''\n if with_sign:\n returnValue = '{0}{1:02d}{5}{2:02d}{5}{3:02d}{4}'.format(sign, hour, minute, second, second_dec, spl)\n else:\n returnValue = '{0:02d}{4}{1:02d}{4}{2:02d}{3}'.format(hour, minute, second, second_dec, spl)\n return returnValue\n\n # ---------------------------------------------------------------------------\n # implementation ascom.transform to erfa.py\n # ---------------------------------------------------------------------------\n\n def transformERFA(self, ra, dec, transform=1):\n self.transformationLockERFA.acquire()\n SiteElevation = float(self.app.mount.site_height)\n SiteLatitude = self.degStringToDecimal(self.app.mount.site_lat)\n SiteLongitude = self.degStringToDecimal(self.app.mount.site_lon)\n if SiteLatitude == 0 or SiteLongitude == 0 or SiteElevation == 0:\n self.logger.error('not site parameters set')\n return 0, 0\n ts = datetime.datetime.utcnow()\n suc, dut1_prev = self.ERFA.eraDat(ts.year, ts.month, ts.day, 0)\n if suc != 0:\n self.logger.error('error result : {0} in eraDat year: {1}, month: {2}, day: {3}'.format(suc, ts.year, ts.month, ts.day))\n dut1 = 37 + 4023.0 / 125.0 - dut1_prev\n jd = float(self.app.mount.data['JulianDate'])\n suc, tai1, tai2 = self.ERFA.eraUtctai(jd, 0)\n if suc != 0:\n self.logger.error('error result : {0} in eraUtctai jd: {1}'.format(suc, jd))\n tt1, tt2 = self.ERFA.eraTaitt(tai1, tai2)\n jdtt = tt1 + tt2\n date1 = jd\n date2 = 0\n\n if transform == 1: # J2000 to Topo Az /Alt\n ra = ra % 24 # mount has hours\n suc, aob, zob, hob, dob, rob, eo = self.ERFA.eraAtco13(ra * self.ERFA.ERFA_D2PI / 24,\n dec * self.ERFA.ERFA_D2PI / 360,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n date1 + date2,\n 0.0,\n dut1,\n SiteLongitude * self.ERFA.ERFA_DD2R,\n SiteLatitude * self.ERFA.ERFA_DD2R,\n SiteElevation,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0)\n val1 = aob * 360 / self.ERFA.ERFA_D2PI\n val2 = 90.0 - zob * 360 / self.ERFA.ERFA_D2PI\n\n elif transform == 2: # Topo to J2000\n rc, dc, eo = self.ERFA.eraAtic13(self.ERFA.eraAnp(ra * self.ERFA.ERFA_D2PI / 24 + self.ERFA.eraEo06a(jdtt, 0.0)),\n dec * self.ERFA.ERFA_D2PI / 360,\n date1 + date2,\n 0.0)\n val1 = rc * 24.0 / self.ERFA.ERFA_D2PI\n val2 = dc * self.ERFA.ERFA_DR2D\n\n elif transform == 3: # J2000 to Topo\n ri, di, eo = self.ERFA.eraAtci13(ra * self.ERFA.ERFA_D2PI / 24,\n dec * self.ERFA.ERFA_D2PI / 360,\n 0,\n 0,\n 0,\n 0,\n date1 + date2,\n 0)\n val1 = self.ERFA.eraAnp(ri - eo) * 24 / self.ERFA.ERFA_D2PI\n val2 = di * 360 / self.ERFA.ERFA_D2PI\n else:\n val1 = ra\n val2 = dec\n self.transformationLockERFA.release()\n return val1, val2\n","sub_path":"mountwizzard/astrometry/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":7378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"313314934","text":"import argparse\nimport textwrap\nfrom typing import List\nimport itertools\nfrom bs4 import BeautifulSoup\nimport requests\nimport numpy as np\nimport pandas as pd\nfrom tabulate import tabulate\nfrom gamestonk_terminal.helper_funcs import check_positive, parse_known_args_and_warn\n\nd_open_insider = {\n \"lcb\": \"latest-cluster-buys\",\n \"lpsb\": \"latest-penny-stock-buys\",\n \"lit\": \"latest-insider-trading\",\n \"lip\": \"insider-purchases\",\n \"blip\": \"latest-insider-purchases-25k\",\n \"blop\": \"latest-officer-purchases-25k\",\n \"blcp\": \"latest-ceo-cfo-purchases-25k\",\n \"lis\": \"insider-sales\",\n \"blis\": \"latest-insider-sales-100k\",\n \"blos\": \"latest-officer-sales-100k\",\n \"blcs\": \"latest-ceo-cfo-sales-100k\",\n \"topt\": \"top-officer-purchases-of-the-day\",\n \"toppw\": \"top-officer-purchases-of-the-week\",\n \"toppm\": \"top-officer-purchases-of-the-month\",\n \"tipt\": \"top-insider-purchases-of-the-day\",\n \"tippw\": \"top-insider-purchases-of-the-week\",\n \"tippm\": \"top-insider-purchases-of-the-month\",\n \"tist\": \"top-insider-sales-of-the-day\",\n \"tispw\": \"top-insider-sales-of-the-week\",\n \"tispm\": \"top-insider-sales-of-the-month\",\n}\n\nd_notes = {\n \"A\": \"A: Amended filing\",\n \"D\": \"D: Derivative transaction in filing (usually option exercise)\",\n \"E\": \"E: Error detected in filing\",\n \"M\": \"M: Multiple transactions in filing; earliest reported transaction date and weighted average transaction price\",\n}\n\n\ndef print_insider_data(other_args: List[str], type_insider: str):\n \"\"\"Corporate lobbying details\n\n Parameters\n ----------\n other_args : List[str]\n Command line arguments to be processed with argparse\n type_insider: str\n Insider type of data\n \"\"\"\n parser = argparse.ArgumentParser(\n add_help=False,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n prog=type_insider,\n description=f\"Print {d_open_insider[type_insider].replace('-', ' ')} [Source: OpenInsider]\",\n )\n parser.add_argument(\n \"-n\",\n \"--num\",\n action=\"store\",\n dest=\"num\",\n type=check_positive,\n default=20,\n help=\"Number of datarows to display\",\n )\n\n try:\n ns_parser = parse_known_args_and_warn(parser, other_args)\n if not ns_parser:\n return\n\n response = requests.get(\n f\"http://openinsider.com/{d_open_insider[type_insider]}\"\n )\n soup = BeautifulSoup(response.text, \"html.parser\")\n table = soup.find(\"table\", {\"class\": \"tinytable\"})\n\n if not table:\n print(\"No insider information found\", \"\\n\")\n return\n\n table_rows = table.find_all(\"tr\")\n\n res = []\n for tr in table_rows:\n td = tr.find_all(\"td\")\n row = [tr.text.strip() for tr in td if tr.text.strip()]\n res.append(row)\n\n df = pd.DataFrame(res).dropna().head(n=ns_parser.num)\n\n df.columns = [\n \"X\",\n \"Filing Date\",\n \"Trade Date\",\n \"Ticker\",\n \"Company Name\",\n \"Industry\" if type_insider == \"lcb\" else \"Insider Name\",\n \"Title\",\n \"Trade Type\",\n \"Price\",\n \"Qty\",\n \"Owned\",\n \"Diff Own\",\n \"Value\",\n ]\n\n df[\"Filing Date\"] = df[\"Filing Date\"].apply(\n lambda x: \"\\n\".join(textwrap.wrap(x, width=10)) if isinstance(x, str) else x\n )\n df[\"Company Name\"] = df[\"Company Name\"].apply(\n lambda x: \"\\n\".join(textwrap.wrap(x, width=20)) if isinstance(x, str) else x\n )\n df[\"Title\"] = df[\"Title\"].apply(\n lambda x: \"\\n\".join(textwrap.wrap(x, width=10)) if isinstance(x, str) else x\n )\n if type_insider == \"lcb\":\n df[\"Industry\"] = df[\"Industry\"].apply(\n lambda x: \"\\n\".join(textwrap.wrap(x, width=20))\n if isinstance(x, str)\n else x\n )\n else:\n df[\"Insider Name\"] = df[\"Insider Name\"].apply(\n lambda x: \"\\n\".join(textwrap.wrap(x, width=20))\n if isinstance(x, str)\n else x\n )\n\n print(\n tabulate(\n df,\n headers=df.columns,\n tablefmt=\"fancy_grid\",\n stralign=\"right\",\n showindex=False,\n )\n )\n l_chars = [list(chars) for chars in df[\"X\"].values]\n l_uchars = np.unique(list(itertools.chain(*l_chars)))\n\n for char in l_uchars:\n print(d_notes[char])\n print(\"\")\n\n except Exception as e:\n print(e, \"\\n\")\n","sub_path":"gamestonk_terminal/insider/openinsider_view.py","file_name":"openinsider_view.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"477172272","text":"from flask import Flask\nfrom flask import request\nfrom firebase_admin import db\nimport base64\nimport json\n\nref = db.reference('notas')\n \napp = Flask(__name__)\n\n@app.route('/')\ndef home(): \n\treturn 'Notification service', 200\n\n@app.route('/salvar', methods=['POST'])\ndef publish():\n\tpayload = request.get_json()\n\tmessage_body = base64.b64decode(str(payload['message']['data'])).decode('utf-8').replace(\"'\", '\"')\n\tarray_notas = json.loads(message_body)\n\tsaveNotes(array_notas)\n\treturn 'OK', 200\n\ndef saveNotes(array_notas):\n\tprint('NOTAS ', array_notas)\n\n#\tfor n in array_notas:\n#\t\tkey = u'{}'.format(n['matricula'])\n#\t\tusers_ref = ref.child(key)\n#\t users_ref.set({\n#\t\t\t'matricula': key,\n#\t\t\t'nome': n['nome'],\n#\t\t\t'nota': n['nota']\n#\t\t})\n#\t\t\n#\t\tprint('Saved {}: '.format(key))\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8080, debug=True)\n\n","sub_path":"cidade-conectada/stolen-service/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570357593","text":"import socket\nimport time\nfrom multiprocessing import Process\nimport select\nimport time\nimport sys\nsys.path.append('../')\nsys.path.append('../../../')\nfrom serializator.dst import room_pb2\nfrom g.Types import Types\n\n\ndef handleData(data, addr, lastseq, needseq, unackseq, recvseq, client_socket):\n room = room_pb2.Room()\n room.ParseFromString(data)\n if room.type == Types.GAMEDATA.value:\n lastseq = max(lastseq, room.seq)\n if room.seq == needseq:\n print('send seq ' + str(lastseq) + ' ack')\n # render\n room = room_pb2.Room()\n room.type = Types.GAMEDATA.value # ack\n room.seq = needseq\n client_socket.sendto(room.SerializeToString(), addr) \n else:\n recvseq.append(room.seq)\n print('send seq ' + str(lastseq) + ' ack')\n room = room_pb2.Room()\n room.type = Types.ACK.value # ack\n client_socket.sendto(room.SerializeToString(), addr)\n elif room.type == Types.ACK.value:\n print('recv seq ' + str(room.seq) + ' ack')\n if room.seq in unackseq:\n unackseq.remove(room.seq)\n return None\n\n\ndef clientProcess():\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n epoll = select.epoll()\n client_socket.setblocking(0)\n epoll.register(client_socket.fileno(), select.EPOLLIN)\n serveraddr = ('127.0.0.1', 6666)\n lastseq = 0\n needseq = 1\n unackseq = []\n recvseq = []\n t = 0\n flag = Types.LOGIN.value\n username = 'heim'\n password = 'zeng'\n room = room_pb2.Room()\n room.type = flag\n p1 = room.persons.add()\n p1.name = username\n p1.password = password\n data = room.SerializeToString()\n client_socket.sendto(data, serveraddr)\n roomIn = room_pb2.Room()\n roomIn.id = 11\n roomIn.type = Types.JOINROOM.value\n p1 = roomIn.persons.add()\n p1.name = username\n data = roomIn.SerializeToString()\n client_socket.sendto(data, serveraddr)\n seq = 0\n try:\n while True:\n if lastseq == seq:\n t = time.clock()\n roomGame = room_pb2.Room()\n roomGame.type = Types.GAMEDATA.value\n roomGame.seq = seq + 1\n seq += 1\n # roomGame.rotation = random.random() * 360\n # roomGame.direction = int(random.random() * 3)\n data = roomGame.SerializeToString()\n client_socket.sendto(data, serveraddr)\n print('send seq: ' + str(seq) + ' len ' + str(len(data)))\n t = time.clock()\n events = epoll.poll(1)\n for fileno, event in events:\n if fileno == client_socket.fileno():\n data, addr = client_socket.recvfrom(1024)\n room = room_pb2.Room()\n room.ParseFromString(data)\n if room.type == Types.ACK.value:\n lastseq = room.seq\n response = handleData(data, addr, lastseq, needseq, unackseq, recvseq, client_socket)\n # client_socket.sendto(data, addr)\n print('ttl: ' + str(time.clock()-t) + ' secends')\n finally:\n print('error')\n epoll.unregister(client_socket.fileno())\n epoll.close()\n client_socket.close()\n\n\nif __name__ == '__main__':\n cp = Process(target=clientProcess)\n cp.start()\n cp.join()\n","sub_path":"python/modules/rudp/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"529955991","text":"import random\nimport string\nimport unittest\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\n\nimport hurraypy as hp\n\n\ndef random_name(l):\n return ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(l))\n\n\nclass IntegrationTest(unittest.TestCase):\n \"\"\"\n Make sure you have a hurray server running at localhost:2222 or a socket at /tmp/hurray.socket\n You probably want to clean the database files after testing\n \"\"\"\n\n def operations(self, conn):\n db_name = 'htest-' + random_name(5) + '.h5'\n conn.create_db(db_name)\n db = conn.connect_db(db_name)\n\n group_path = '/mygrp'\n\n db.create_group(group_path)\n grp = db[group_path]\n\n self.assertEqual(grp.path, group_path)\n\n array_name = 'myarray'\n array_path = group_path + '/' + array_name\n\n data = np.array([[1, 2, 3], [4, 5, 6]])\n ds = grp.create_dataset(array_name, data=data)\n\n self.assertEqual(ds.path, array_path)\n\n dataset = db[array_path]\n\n assert_array_equal(data, dataset[:])\n assert_array_equal(data[1], dataset[1])\n\n x = np.array([8, 9, 10])\n dataset[0, :] = x\n assert_array_equal(np.array([x, data[1]]), dataset[:])\n\n attr_key = 'foo'\n attr_value = 'bar'\n\n dataset.attrs[attr_key] = attr_value\n self.assertEqual(dataset.attrs['foo'], attr_value)\n\n self.assertTrue(attr_key in dataset.attrs)\n self.assertFalse('no' in dataset.attrs)\n\n self.assertEqual(dataset.attrs.keys(), (attr_key,))\n\n attr_value_array = np.array([0.1, 0.2, 0.5])\n\n dataset.attrs['num'] = attr_value_array\n assert_array_equal(dataset.attrs['num'], attr_value_array)\n\n def test_tcp(self):\n conn = hp.connect('localhost', '2222')\n self.operations(conn)\n\n def _test_socket(self):\n conn = hp.connect(unix_socket_path='/tmp/hurray.socket')\n self.operations(conn)\n","sub_path":"tests/integration.py","file_name":"integration.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"473438964","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport pymysql\n\n\nclass SunspiderPipeline(object):\n def __init__(self):\n try:\n self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='sundb1811',charset='utf8')\n self.cur = self.conn.cursor()\n except Exception as e:\n print(e)\n\n\n def process_item(self, item, spider):\n try:\n sql = 'insert into sun0769 VALUES (0,%s,%s,%s,%s,%s,%s)'\n params = [item['name'],item['number'],item['url'],item['content'],item['author'],item['pub_date']]\n count = self.cur.execute(sql,params)\n self.conn.commit()\n except Exception as e:\n print(e)\n return item\n\n def close_spider(self,item,spider):\n self.cur.close()\n self.conn.close()\n","sub_path":"guo_py1811code/three/20190408-CrawlSpider实现自动爬取/code/SunSpider/SunSpider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538000088","text":"import cv2\nimport numpy as np\nimport Foreground\n\ndef get_detected_soldiers(filename):\n DEFAULF = 0\n std_dir = \"C:\\\\Users\\\\t8545065\\\\Desktop\\\\Lil project\\\\procton\\\\Integration\\\\stds\"\n threshold_r = 0\n threshold_g = 6\n threshold_b = 6\n img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)\n # img = cv2.medianBlur(img,5)\n img = cv2.resize(img, (640, 360))\n cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n\n circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 15,\n param1=40, param2=13, minRadius=7, maxRadius=13)\n\n circles = np.uint16(np.around(circles))\n whiteCircles = np.ndarray(shape=circles.shape)\n blackCircles = np.ndarray(shape=circles.shape)\n\n foreground = Foreground.foreground_poc(threshold=[threshold_r, threshold_g, threshold_b],diff_path=filename,\n std_dir= std_dir)\n\n whiteCount = 0\n blackCount = 0\n for i in circles[0, :]:\n # print(i)\n if foreground[i[1]][i[0]] == 1:\n if img[i[1]][i[0]] > 100:\n whiteCircles[0][whiteCount] = i\n whiteCount += 1\n cv2.circle(cimg, (i[0], i[1]), i[2], (0, 0, 0), 2)\n else:\n blackCircles[0][blackCount] = i\n blackCount += 1\n cv2.circle(cimg, (i[0], i[1]), i[2], (255, 255, 255), 2)\n cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)\n\n\n # cv2.imshow('detected circles', cimg)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n return [whiteCircles, blackCircles]\n\nget_detected_soldiers(\"C:\\\\Users\\\\t8545065\\\\Desktop\\\\Lil project\\\\procton\\\\Board_detection_manager\\\\Soldier_Detection\"\n \"\\\\test_photos\\\\WIN_20191209_17_00_11_Pro.jpg\")\n\n","sub_path":"Integration/ImageProcessing.py","file_name":"ImageProcessing.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393199511","text":"\"\"\"\nPlot maps of PAMIP data for each month from November to April using\nthe ensemble mean (100,200,300) to calculate the signal-to-noise ratio\n\nNotes\n-----\n Author : Zachary Labe\n Date : 28 June 2019\n\"\"\"\n\n### Import modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\nimport datetime\nimport read_MonthlyData as MO\nimport calc_Utilities as UT\nimport cmocean\nimport itertools\n\n### Define directories\ndirectorydata = '/seley/zlabe/simu/'\ndirectoryfigure = '/home/zlabe/Desktop/STRATOVARI/'\n\n### Define time \nnow = datetime.datetime.now()\ncurrentmn = str(now.month)\ncurrentdy = str(now.day)\ncurrentyr = str(now.year)\ncurrenttime = currentmn + '_' + currentdy + '_' + currentyr\ntitletime = currentmn + '/' + currentdy + '/' + currentyr\nprint('\\n' '----Plotting Signal-to-Noise- %s----' % titletime)\n\n### Alott time series (300 ensemble members)\nyear1 = 1701\nyear2 = 2000\nyears = np.arange(year1,year2+1,1)\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Call arguments\nvarnames = ['U10','U300','SLP','Z500','T2M','THICK']\n\n######################\ndef readDataPeriods(varnames,sliceq):\n ### Call function for 4d variable data\n lat,lon,lev,varfuture = MO.readExperiAll(varnames,'Future','surface')\n lat,lon,lev,varpast = MO.readExperiAll(varnames,'Past','surface')\n \n ### Select ensemble mean period\n if sliceq == 'Mean':\n varfuture = varfuture[:,:,:,:]\n varpast = varpast[:,:,:,:]\n elif sliceq == 'A':\n varfuture = varfuture[:100,:,:,:]\n varpast = varpast[:100,:,:,:]\n elif sliceq == 'B':\n varfuture = varfuture[100:200,:,:,:]\n varpast = varpast[100:200,:,:,:]\n elif sliceq == 'C':\n varfuture = varfuture[200:,:,:,:]\n varpast = varpast[200:,:,:,:]\n \n ### Create 2d array of latitude and longitude\n lon2,lat2 = np.meshgrid(lon,lat)\n \n ### Remove missing data\n varfuture[np.where(varfuture <= -1e10)] = np.nan\n varpast[np.where(varpast <= -1e10)] = np.nan\n \n ### Rearrange months (N,D,J,F,M,A)\n varfuturem = np.append(varfuture[:,-2:,:,:],varfuture[:,:4,:,:],\n axis=1)\n varpastm = np.append(varpast[:,-2:,:,:],varpast[:,:4,:,:],axis=1)\n \n ### Calculate ensemble mean\n future = np.nanmean(varfuturem,axis=0)\n climo = np.nanmean(varpastm,axis=0)\n \n ### Calculate anomalies\n anomall = varfuturem - varpastm\n anomm = future - climo\n \n ### Calculate standard deviation\n anomstd = np.nanstd(anomall,axis=0)\n \n ### Calculate signal to noise (mean/std)\n sig = np.abs(anomm)/anomstd\n \n return sig,lat,lon,lev\n \n###############################################################################\n###############################################################################\n###############################################################################\n### Read in data\nfor v in range(len(varnames)):\n sigm,lat,lon,lev = readDataPeriods(varnames[v],'Mean')\n siga,lat,lon,lev= readDataPeriods(varnames[v],'A')\n sigb,lat,lon,lev = readDataPeriods(varnames[v],'B')\n sigc,lat,lon,lev = readDataPeriods(varnames[v],'C')\n\n var = list(itertools.chain(*[sigm,siga,sigb,sigc]))\n \n ### Plot Variables\n plt.rc('text',usetex=True)\n plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) \n \n ### Set limits for contours and colorbars\n if varnames[v] == 'T2M':\n limit = np.arange(0,5.1,0.25)\n barlim = np.arange(0,6,1)\n elif varnames[v] == 'THICK':\n limit = np.arange(0,2.1,0.2)\n barlim = np.arange(0,3,1)\n elif varnames[v] == 'SLP':\n limit = np.arange(0,1.1,0.1)\n barlim = np.arange(0,2,1)\n elif varnames[v] == 'Z500':\n limit = np.arange(0,1.1,0.1)\n barlim = np.arange(0,2,1)\n elif varnames[v] == 'Z30':\n limit = np.arange(0,1.1,0.1)\n barlim = np.arange(0,2,1)\n elif varnames[v] == 'U10' or varnames[v] == 'U300' or varnames[v] == 'U500':\n limit = np.arange(0,1.1,0.1)\n barlim = np.arange(0,2,1)\n \n lonq,latq = np.meshgrid(lon,lat)\n \n fig = plt.figure()\n for i in range(len(var)):\n ax1 = plt.subplot(4,6,i+1)\n \n m = Basemap(projection='ortho',lon_0=0,lat_0=89,resolution='l',\n area_thresh=10000.)\n \n varn, lons_cyclic = addcyclic(var[i], lon)\n varn, lons_cyclic = shiftgrid(180., varn, lons_cyclic, start=False)\n lon2d, lat2d = np.meshgrid(lons_cyclic, lat)\n x, y = m(lon2d, lat2d)\n \n circle = m.drawmapboundary(fill_color='white',\n color='dimgrey',linewidth=0.7)\n circle.set_clip_on(False)\n \n cs = m.contourf(x,y,varn,limit,extend='max')\n \n m.drawcoastlines(color='dimgrey',linewidth=0.6)\n \n cmap = cmocean.cm.rain\n cs.set_cmap(cmap) \n \n if any([i==0,i==6,i==12,i==18]):\n ax1.tick_params(labelleft='on') \n else:\n ax1.tick_params(labelleft='off') \n if i < 18:\n ax1.tick_params(labelbottom='off') \n if any([i==0,i==6,i==12]):\n ax1.tick_params(axis='y',direction='out',which='major',pad=3,\n width=2,color='dimgrey')\n ax1.tick_params(axis='x',direction='out',which='major',pad=3,\n width=0,color='dimgrey') \n else:\n if i < 24 and i != 18:\n ax1.tick_params(axis='y',direction='out',which='major',pad=3,\n width=0,color='dimgrey')\n if i < 18:\n ax1.tick_params(axis='y',direction='out',which='major',\n pad=3,width=0,color='dimgrey')\n ax1.tick_params(axis='x',direction='out',which='major',\n pad=3,width=0,color='dimgrey') \n \n labelmonths = [r'NOV',r'DEC',r'JAN',r'FEB',r'MAR',r'APR']\n if i < 6:\n ax1.annotate(r'\\textbf{%s}' % labelmonths[i],\n xy=(0, 0),xytext=(0.5,1.13),xycoords='axes fraction',\n fontsize=13,color='dimgrey',rotation=0,\n ha='center',va='center')\n if i==0: \n plt.annotate(r'\\textbf{Mean}',\n xy=(0, 0),xytext=(-0.3,0.5),xycoords='axes fraction',\n fontsize=15,color='k',rotation=90,\n ha='center',va='center') \n elif i==6: \n plt.annotate(r'\\textbf{A}',\n xy=(0, 0),xytext=(-0.3,0.5),xycoords='axes fraction',\n fontsize=15,color='k',rotation=90,\n ha='center',va='center') \n elif i==12: \n plt.annotate(r'\\textbf{B}',\n xy=(0, 0),xytext=(-0.3,0.5),xycoords='axes fraction',\n fontsize=15,color='k',rotation=90,\n ha='center',va='center') \n elif i==18: \n plt.annotate(r'\\textbf{C}',\n xy=(0, 0),xytext=(-0.3,0.5),xycoords='axes fraction',\n fontsize=15,color='k',rotation=90,\n ha='center',va='center') \n \n\n cbar_ax = fig.add_axes([0.312,0.09,0.4,0.02]) \n cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal',\n extend='max',extendfrac=0.07,drawedges=True)\n \n cbar.set_label(r'\\textbf{Signal-to-Noise Ratio [%s]}' % varnames[v],\n fontsize=9,color='dimgray',labelpad=0)\n \n cbar.set_ticks(barlim)\n cbar.set_ticklabels(list(map(str,barlim))) \n cbar.ax.tick_params(axis='x', size=.01)\n cbar.outline.set_edgecolor('dimgrey')\n cbar.dividers.set_color('dimgrey')\n cbar.dividers.set_linewidth(1.2)\n cbar.outline.set_linewidth(1.2)\n cbar.ax.tick_params(labelsize=8)\n\n plt.subplots_adjust(hspace=0.0,bottom=0.14,top=0.93,wspace=0.0)\n \n plt.savefig(directoryfigure + '%s_SignalToNoise_100yr.png' % varnames[v],\n dpi=300)\n print('Completed: Script done!')\n\n\n ","sub_path":"Scripts/plot_Maps_SignalToNoise_Monthly_100yrPeriods.py","file_name":"plot_Maps_SignalToNoise_Monthly_100yrPeriods.py","file_ext":"py","file_size_in_byte":8296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245296863","text":"#!/usr/bin/env python3\r\n\r\n# The time module provides useful commands for working with time\r\n# e.g. obtaining the current time. We will need it later, so we import it.\r\n# The random module provides commands for, surprise!, working with random\r\n# numbers, e.g. choosing a stimulus at random from a given list etc.\r\n# We will also need it for the experiment, so we import it.\r\nimport time\r\nimport random\r\n\r\n\r\ndef run_experiment():\r\n \"\"\"\r\n This function is the main entry for the experiment.\r\n It calls and coordinates the other helper functions we will use\r\n for the experiment.\r\n \"\"\"\r\n\r\n # Here, we initialize a dictionary to store relevant information\r\n # about our participant. In this simple experiment, we only need\r\n # four pieces of information: participant ID, age, sex, major (psychology), a list\r\n # to store the participant's reaction times, a list to store the stimulus\r\n # types, and a list to store the whether the participant responded correctly or not.\r\n # It is always a good practice to set dictionary values which\r\n # are to-be-filled later to the corresponding empty types\r\n participant_info = {\r\n \"participantID\": \"\",\r\n \"age\": \"\",\r\n \"sex\": \"\",\r\n \"major\": \"\",\r\n \"reaction_times\": [],\r\n \"stimulus_types\": [],\r\n \"correct\": []\r\n }\r\n\r\n # Call helper function collect_infos(participant_info)\r\n # to obtain biographic data\r\n # Note that the helper functions modifies the participant_info\r\n # dict, so changes will be reflected in the current function\r\n # START CODE HERE (1 line of code)\r\n collect_info(participant_info)\r\n # END CODE HERE #\r\n\r\n # Call helper function prepare_stimuli()\r\n # to obtain a list of randomly shuffled stimuli\r\n # START CODE HERE # (1 line of code)\r\n stimuli = prepare_stimuli()\r\n # END CODE HERE #\r\n\r\n # Call helper function present_instructions() to display\r\n # some text explaining the (bizarre) purpose of our experiment\r\n # START CODE HERE (1 line of code)\r\n present_instructions()\r\n # END CODE HERE #\r\n\r\n # Call helper function start_main_loop(participant_info, stimuli)\r\n # to run your first experiment!\r\n # START CODE HERE # (1 line of code)\r\n start_main_loop(participant_info, stimuli)\r\n # END CODE HERE #\r\n\r\n # Call helper function save_results(participant_info)\r\n # to save the results from the experiment\r\n # START CODE HERE # (1 line of code)\r\n save_results(participant_info)\r\n # END CODE HERE\r\n\r\n # Say goodbye to the participant\r\n goodbye()\r\n\r\n\r\ndef start_main_loop(participant_info, stimuli):\r\n \"\"\"\r\n This function starts the experiment and runs\r\n len(stimuli) number of trials. As the experiment progresses, the participants'\r\n responses are stored into the responses key of the info dict.\r\n :param participant_info: the participant info dict with filled bio data\r\n :param stimuli: a list of randomly shuffled stimuli\r\n :return: nothing, since responses are stored in participant_info dict\r\n \"\"\"\r\n\r\n # We start the experiment by looping through the list of stimuli\r\n for stimulus in stimuli:\r\n # We obtain a timestamp of when the stimulus was presented\r\n # using the time function\r\n # START CODE HERE # (1 line of code)\r\n start = time.time()\r\n # END CODE HERE #\r\n\r\n # Then, we present the word by simply printing it to the screen\r\n # The \"\\n\" * 50 part simply print 50 newlines, to that the last stimulus is hidden\r\n # form the screen\r\n print(\"\\n\" * 50, stimulus)\r\n\r\n # After that, we wait for the participant to respond\r\n response = input()\r\n\r\n # Immediately after the response, we calculate the reaction time\r\n # we use the built-in round() function to round down the rt to\r\n # 4 decimal places\r\n rt = round(time.time() - start, 4)\r\n # ...we evaluate the response\r\n response_correct = evaluate_response(stimulus, response)\r\n # ...and add all the information to the participant info dict\r\n # START CODE HERE # (3 lines of code)\r\n participant_info['reaction_times'].append(rt)\r\n participant_info['stimulus_types'].append(stimulus)\r\n participant_info['correct'].append(response_correct)\r\n # END CODE HERE #\r\n\r\ndef evaluate_response(stimulus, response):\r\n \"\"\"\r\n This function evaluates a response as correct (1) or wrong (0)\r\n :param stimulus: a string (GO, or NO-GO)\r\n :param response: the participant's response, should be empty string,\r\n if stimulus were GO, otherwise an 'a'\r\n :return: 1, if response correct, 0, if incorrect\r\n \"\"\"\r\n\r\n if stimulus == \"GO\" and response == \"\":\r\n return True\r\n elif stimulus == \"NO-GO\" and response == \"a\":\r\n return True\r\n else:\r\n # The only two correct responses are exhausted, so if we reach\r\n # this block, then the participant responded incorrectly\r\n return False\r\n\r\n\r\ndef present_instructions():\r\n \"\"\"\r\n This function simply presents the instructions\r\n and waits for the participant to respond with any key.\r\n \"\"\"\r\n\r\n # Prepare text as multi-line string\r\n instructions = \"\"\"\r\n Welcome to our Go/No-Go experiment!\\n\r\n In the following, You are going to see a sequence of words.\\n\r\n The words can be of two types: GO and NO-GO. As You expect,\\n\r\n You are supposed to respond with the enter key as fast as possible\\n\r\n upon seeing the word GO. If the word is NO-GO, you should first type\\n\r\n the letter 'a', and then press enter, thus indicating that you did not\\n\r\n trigger a false alarm.\\n\\n\\n\r\n Press Enter to continue with the experiment...\\n\r\n \"\"\"\r\n\r\n # Print on screen and wait for response (collect input with input())\r\n # START CODE HERE # (2 lines of code)\r\n print(instructions)\r\n input()\r\n # END CODE HERE #\r\n\r\ndef prepare_stimuli():\r\n \"\"\"\r\n This function initializes a list with 20 randomly shuffled stimuli\r\n for our reaction time experiment. The stimuli comprise only two types: GO, NO-GO\r\n Later, these stimuli will be presented in the console window.\r\n :return: a list with 20 stimuli in a shuffled order.\r\n \"\"\"\r\n\r\n # This line initializes a list with 10 'GO' and 10 'NO-GO' stimuli (you can confirm that\r\n # by printing the list after creation.\r\n stimuli = [\"GO\", \"NO-GO\"] * 10\r\n\r\n # We have initialized our stimuli. The problem is, that they now follow the same\r\n # pattern: GO, NO-GO, GO,... This is boring and kinda deterministic. Your goal is\r\n # to look up the online documentation of the random module and find a proper function\r\n # to randomly shuffle the elements of the list (hint: shuffle)\r\n # https://docs.python.org/3/library/random.html\r\n\r\n # shuffle the stimuli\r\n # START CODE HERE # (1 line of code)\r\n random.shuffle(stimuli)\r\n # END CODE HERE #\r\n\r\n # Finaly, we return the randomly shuffled sequence\r\n return stimuli\r\n\r\n\r\ndef collect_info(participant_info):\r\n \"\"\"\r\n This function collects demographical data from the participant\r\n and writes it into the participant_info dictionary\r\n :param participant_info: a dictionary containing keys with empty value\r\n :return: nothing, since it modified the participant_info dict\r\n \"\"\"\r\n\r\n # Collect all data sequentially using the input() function\r\n # START CODE HERE # (4 lines of code)\r\n partID = input(\"Enter a participant ID: \")\r\n age = input(\"Enter your age: \")\r\n sex = input(\"Enter your gender(m\\w\\o): \")\r\n major = input(\"Enter your subject of study: \")\r\n # END CODE HERE #\r\n\r\n # Store input data into the dictionary\r\n # Note, that we could have performed the collection\r\n # and the storing in a single step, e.g. p_info['age'] = input(...)\r\n # Here we will do it in two steps. So next, store the collected info in the\r\n # participant_info dict:\r\n\r\n # STAR CODE HERE # (4 lines of code)\r\n participant_info['participantID'] = partID\r\n participant_info['age'] = age\r\n participant_info['sex'] = sex\r\n participant_info['major'] = major\r\n # END CODE HERE #\r\n\r\ndef goodbye():\r\n \"\"\"Be nice to the participant and thank her or him for participation.\"\"\"\r\n\r\n # Define text as a multi-line string\r\n goodbye_text = \"\"\"\r\n Thank you for participating in the experiment!\\n\r\n Your participation means a lot to us. You really\\n\r\n helped pushing science to the next level!\\n\\n\\n\r\n See you next time!\r\n \"\"\"\r\n\r\n # \"Clear screen\" and present text\r\n print(\"\\n\" * 50, goodbye_text)\r\n\r\n\r\ndef save_results(participant_info):\r\n \"\"\"\r\n This functions saves the participant infos to the disk.\r\n :param participant_info: the full dictionary\r\n :return: None\r\n \"\"\"\r\n\r\n # Construct a filename from ID and age\r\n file_name = participant_info[\"participantID\"] + \"_\" + \\\r\n str(participant_info['age']) + \".txt\"\r\n\r\n # Open the file as we already learned\r\n with open(file_name, \"w\") as outfile:\r\n # Write dict to file: note that you cannot\r\n # simply write the dict itself, as you can\r\n # normally print it to the screen, but first\r\n # we have to convert it to a string, since\r\n # the write() function only accepts a string\r\n\r\n # STAR CODE HERE # (1 line of code)\r\n outfile.write(str(participant_info))\r\n # END CODE HERE #\r\n\r\n # btw., you usually want to save your data in such a\r\n # format, so that you can easily read it with a statistical\r\n # program like SPSS (if SPSS can be called a program) or R\r\n # can you come up with a better formatting?\r\n\r\nif __name__ == \"__main__\":\r\n run_experiment()\r\n","sub_path":"labsolutions/lab5Solution.py","file_name":"lab5Solution.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335022877","text":"# 34. 名詞の連接Permalink\n# 名詞の連接(連続して出現する名詞)を最長一致で抽出せよ.\nimport re\n\n\ndef parse(block):\n ret = []\n for row in block.split('\\n'):\n rowlist = re.split(r'\\t', row)\n if len(rowlist) == 2:\n rowarry = rowlist[1].split(',')\n lineDic = {\n 'surface': rowlist[0],\n 'base': rowarry[6],\n 'pos': rowarry[0],\n 'pos1': rowarry[1]\n }\n ret.append(lineDic)\n return ret\n\n\ndef getLongestNoun(x):\n ret = []\n noun = []\n for y in x:\n if y['pos'] == '名詞':\n noun.append(y['surface'])\n elif len(noun) > 1:\n ret.append(''.join(noun))\n noun = []\n else:\n noun = []\n return ret\n\n\nfilepath = 'neko.txt.mecab'\nwith open(filepath, encoding='utf-8') as f:\n block = f.read().split('EOS\\n')\nblock = list(filter(lambda x: x != '', block))\nresult30 = [parse(y) for y in block]\nresult = [getLongestNoun(x) for x in result30]\nprint(result)\n","sub_path":"chapter4/34.py","file_name":"34.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546103907","text":"import botocore\nimport click\n\nfrom newrelic_lambda_cli import utils\n\n\ndef list_functions(session, filter_choice):\n client = session.client(\"lambda\")\n\n # set all if the filter_choice is \"all\" or there is no filter_choice active.\n all = filter_choice == \"all\" or not filter_choice\n\n pager = client.get_paginator(\"list_functions\")\n for func_resp in pager.paginate():\n funcs = func_resp.get(\"Functions\", [])\n\n for f in funcs:\n f.setdefault(\"x-new-relic-enabled\", False)\n for layer in f.get(\"Layers\", []):\n if layer.get(\"Arn\", \"\").startswith(\n utils.get_arn_prefix(session.region_name)\n ):\n f[\"x-new-relic-enabled\"] = True\n if all:\n yield f\n elif filter_choice == \"installed\" and f[\"x-new-relic-enabled\"]:\n yield f\n elif filter_choice == \"not_installed\" and not f[\"x-new-relic-enabled\"]:\n yield f\n\n\ndef get_function(session, function_name):\n \"\"\"Returns details about an AWS lambda function\"\"\"\n try:\n return session.client(\"lambda\").get_function(FunctionName=function_name)\n except botocore.exceptions.ClientError as e:\n if (\n e.response\n and \"ResponseMetadata\" in e.response\n and \"HTTPStatusCode\" in e.response[\"ResponseMetadata\"]\n and e.response[\"ResponseMetadata\"][\"HTTPStatusCode\"] == 404\n ):\n return None\n raise click.UsageError(str(e))\n","sub_path":"newrelic_lambda_cli/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"633944470","text":"def stupid(i, j):\n if dp[i][j] >= 0:\n return dp[i][j]\n dp[i][j] = 0\n if i > 1 and j > 0:\n dp[i][j] += stupid(i - 2, j - 1)\n if i > 1 and j < m - 1:\n dp[i][j] += stupid(i - 2,j + 1)\n if i > 0 and j > 1:\n dp[i][j] += stupid(i - 1, j - 2)\n if i < n - 1 and j > 1:\n dp[i][j] += stupid(i + 1, j - 2)\n return dp[i][j]\n\nINF = 10 ** 9 + 7\n\nfin = open(\"knight2.in\", 'r')\nfout = open(\"knight2.out\", 'w')\n\nn, m = map(int, fin.readline().split())\n\ndp = [[-1] * m for i in range(n)]\ndp[0][0] = 1\nprint(stupid(n-1, m-1), file=fout)\n\nfin.close()\nfout.close()\n","sub_path":"anichkov-camp-2018/DAY05/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"548657961","text":"from django.urls import path, include\nfrom rest_framework import routers\nfrom . import views as forum_views\n\n\nrouter = routers.SimpleRouter()\n\nrouter.register(r'post',\n\tforum_views.PostView, basename='post')\n\nrouter.register(r'discussion',\n\tforum_views.DiscussionView, basename='discussion')\n\nurlpatterns = [\n\n] + router.urls","sub_path":"websocketaspire/forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140392489","text":"from unittest import TestCase\n\nfrom cryptochallenge import decryptors\nfrom cryptochallenge.tools.bytearrays import hex_to_bytearray, bytearray_to_utf8, single_byte_xor\nfrom cryptochallenge.tools.strings import english_rank\nfrom tests.set1 import get_test_resource\n\n\n# Challenge 4 - Detect single-character XOR\nclass Challenge4(TestCase):\n def test_detect_single_character_xor(self):\n file = get_test_resource('ch4.txt')\n expected_result = 'Now that the party is jumping\\n'\n\n with open(file) as f:\n lines = map(lambda l: l.strip(), f.readlines())\n\n decrypted_strings = []\n\n for l in lines:\n byte_array = hex_to_bytearray(l)\n key = decryptors.single_byte_xor_decryptor(byte_array)\n if key != '':\n de_string = bytearray_to_utf8(single_byte_xor(byte_array, key))\n decrypted_strings.append((english_rank(de_string), key, de_string))\n\n decrypted_strings.sort(key=lambda tup: tup[0], reverse=True)\n actual_result = decrypted_strings[0][2]\n\n self.assertEqual(expected_result, actual_result)\n","sub_path":"tests/set1/challenge4.py","file_name":"challenge4.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264864459","text":"# !/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport wave\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nfrom sklearn import preprocessing\n\n# i=1\n# filepath = \"./audio_train/\" # 添加路径\n# filename = os.listdir(filepath) # 得到文件夹下的所有文件名称\n# print(filepath + filename[i])\n# f = wave.open(filepath + filename[i], 'rb')\n# params = f.getparams()\n# nchannels, sampwidth, framerate, nframes = params[:4]\n# strData = f.readframes(nframes) # 读取音频,字符串格式\n# waveData = np.fromstring(strData, dtype=np.int16) # 将字符串转化为int\n# # waveData = waveData * 1.0 / (max(abs(waveData))) # wave幅值归一化\n# # plot the wave\n# # time = np.arange(0, nframes) * (1.0 / framerate)\n# x = np.arange(0,nframes)\n# plt.plot(x, waveData)\n# plt.xlabel(\"nframes\")\n# plt.ylabel(\"Amplitude\")\n# plt.title(\"Single channel wavedata-filename[%d]\" % i)\n# plt.grid('on') # 标尺,on:有,off:无。\n# plt.savefig(filename[i].split('.')[0])\n\n\n\ndef padding(data,input_length):\n if len(data) > input_length:\n max_offset = len(data) - input_length\n offset = np.random.randint(max_offset)\n data = data[offset:(input_length + offset)]\n else:\n if input_length > len(data):\n max_offset = input_length - len(data)\n offset = np.random.randint(max_offset)\n else:\n offset = 0\n data = np.pad(data, (offset, input_length - len(data) - offset), \"constant\")\n return data\n\ntrain_path = './audio_train/'\ntest_path = './audio_test/'\naudio_train_files = os.listdir('./audio_train')\naudio_test_files = os.listdir('./audio_test')\n\ntrain = pd.read_csv('./train.csv')\nsubmission = pd.read_csv('./sample_submission.csv')\n\ninput_length = 600000\n\ndata=[]\ntrain_label = []\n# 读取训练数据\ntrain_names,train_labels = train['fname'],train['label']\nprint(train_labels)\nlabels = train_labels.values # labels:ndarray\nLABELS = list(np.unique(labels))\nlabel_idx = {label: i for i, label in enumerate(LABELS)}\nprint(label_idx)\nmax_len = 0\n\nfor i in range(3000,4000):\n # print(train_names[i],train_labels[i])\n f = wave.open(train_path + train_names[i], 'rb')\n params = f.getparams()\n nchannels, sampwidth, framerate, nframes = params[:4]\n strData = f.readframes(nframes) # 读取音频,字符串格式\n waveData = np.fromstring(strData, dtype=np.int16) # 将字符串转化为int\n if len(waveData) > max_len:\n max_len = len(waveData)\n waveData = preprocessing.scale(waveData) # wave幅值归一化\n waveData = padding(waveData,input_length=input_length)\n data.append(waveData)\n label = label_idx[labels[i]]\n train_label.append(label)\nprint(len(data))\nprint(train_label)\n# 1.将较长数据切割成几份等长度数据,扩充训练数据\n\n# 2.将所有数据padding成一样长度\n\n# np.save('train',data)\n# np.save('label',train_label)\nnp.save('eval',data)\nnp.save('eval_label',train_label)\n\n","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"358274543","text":"from appium import webdriver\nfrom appium.webdriver.extensions.android.nativekey import AndroidKey\n\n# com.ss.android.ugc.aweme/.main.MainActivity\ndesired_caps = {\n 'platformName': 'Android', # 被测手机是安卓\n 'platformVersion': '7.0', # 手机安卓版本\n 'deviceName': 'xxx', # 设备名,安卓手机可以随意填写\n 'appPackage': 'com.zhihu.android', # 启动APP Package名称\n 'appActivity': '.app.ui.activity.LauncherActivity', # 启动Activity名称\n 'unicodeKeyboard': True, # 使用自带输入法,输入中文时填True\n 'resetKeyboard': True, # 执行完程序恢复原来输入法\n 'noReset': True, # 不要重置App\n 'newCommandTimeout': 6000,\n 'automationName': 'UiAutomator2'\n # 'app': r'd:\\apk\\bili.apk',\n}\n\n# 连接Appium Server,初始化自动化环境\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n# 设置缺省等待时间\ndriver.implicitly_wait(5)\n\n\n","sub_path":"爬虫APP端/zhihu.py","file_name":"zhihu.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368789201","text":"import gfw\nfrom pico2d import *\nfrom gobj import *\n\nclass Background:\n def __init__(self, imageName):\n self.imageName = imageName\n self.image = gfw.image.load(res(imageName))\n self.target = None\n self.cw, self.ch = get_canvas_width(), get_canvas_height()\n self.win_rect = 0, 0, self.cw, self.ch\n #self.center = self.image.w // 2, self.image.h // 2\n #self.center = 400, 300\n self.center = get_canvas_width() // 2 , get_canvas_height() // 2\n hw, hh = self.cw // 2, self. ch // 2\n self.boundary = hw, hh, self.image.w - hw, self.image.h - hh\n def set_target(self, target):\n self.target = target\n self.update()\n def draw(self):\n self.image.clip_draw_to_origin(*self.win_rect, 0, 0)\n def update(self):\n if self.target is None:\n return\n tx, ty = self.target.pos\n sl = round(tx - self.cw / 2)\n sb = round(ty - self.ch / 2)\n self.win_rect = sl, sb, self.cw, self.ch\n def get_boundary(self):\n return self.boundary\n def translate(self, point):\n x, y = point\n l, b, r, t = self.win_rect\n return l + x, b + y\n def to_screen(self, point):\n # return self.cw // 2, self.ch // 2\n x, y = point\n l, b, r, t = self.win_rect\n return x - l, y - b\n\n # def to_screen(self, point):\n # hw, hh = self.cw // 2, self.ch // 2\n # x, y = point\n\n # if x > self.image.w - hw:\n # x = self.cw - (self.image.w - x)\n # elif x > hw:\n # x = self.cw // 2\n\n # if y > self.image.h - hh:\n # y = self.ch - (self.image.h - y)\n # elif y > hh:\n # y = self.ch // 2\n\n # return x, y\n\nclass FixedBackground(Background):\n MARGIN_L, MARGIN_B, MARGIN_R, MARGIN_T = 20, 40, 20, 40\n def __init__(self, imageName):\n super().__init__(imageName)\n self.boundary = (\n FixedBackground.MARGIN_L, \n FixedBackground.MARGIN_B,\n self.image.w - FixedBackground.MARGIN_R, \n self.image.h - FixedBackground.MARGIN_T\n )\n def update(self):\n if self.target is None:\n return\n tx, ty = self.target.pos\n sl = clamp(0, round(tx - self.cw / 2), self.image.w - self.cw)\n sb = clamp(0, round(ty - self.ch / 2), self.image.h - self.ch)\n self.win_rect = sl, sb, self.cw, self.ch\n\nclass InfiniteBackground(Background):\n def __init__(self, imageName, width=0, height=0):\n super().__init__(imageName)\n self.boundary = (-sys.maxsize, -sys.maxsize, sys.maxsize, sys.maxsize)\n self.fix_x, self.fix_y = self.cw // 2, self.ch // 2\n if width == 0:\n width = self.image.w\n if height == 0:\n height = self.image.h\n self.w, self.h = width, height\n def set_fixed_pos(self, x, y):\n self.fix_x, self.fix_y = x, y\n def update(self):\n if self.target is None:\n return\n tx, ty = self.target.pos\n\n # quadrant 3\n q3l = round(tx - self.fix_x) % self.image.w\n q3b = round(ty - self.fix_y) % self.image.h\n q3w = clamp(0, self.image.w - q3l, self.image.w)\n q3h = clamp(0, self.image.h - q3b, self.image.h)\n self.q3rect = q3l, q3b, q3w, q3h\n # quadrant 2\n self.q2rect = q3l, 0, q3w, self.ch - q3h\n self.q2origin = 0, q3h\n # quadrant 4\n self.q4rect = 0, q3b, self.cw - q3w, q3h\n self.q4origin = q3w, 0\n # quadrant 1\n self.q1rect = 0, 0, self.cw - q3w, self.ch - q3h\n self.q1origin = q3w, q3h\n\n def draw(self):\n self.image.clip_draw_to_origin(*self.q3rect, 0, 0)\n self.image.clip_draw_to_origin(*self.q2rect, *self.q2origin)\n self.image.clip_draw_to_origin(*self.q4rect, *self.q4origin)\n self.image.clip_draw_to_origin(*self.q1rect, *self.q1origin)\n\n def to_screen(self, point):\n x, y = point\n tx, ty = self.target.pos\n return self.fix_x + x - tx, self.fix_y + y - ty\n\n def translate(self, point):\n x, y = point\n tx, ty = self.target.pos\n dx, dy = x - self.fix_x, y - self.fix_y\n return tx + dx, ty + dy\n\nclass HorzScrollBackground:\n def __init__(self, imageName):\n self.imageName = imageName\n self.image = gfw.image.load(res(imageName))\n self.cw, self.ch = get_canvas_width(), get_canvas_height()\n self.scroll = 0\n self.speed = 0\n\n def update(self):\n self.scroll += self.speed * gfw.delta_time\n\n def set_scroll(self, scroll):\n self.scroll = scroll\n\n def draw(self):\n left, bottom = 0, 0\n page = self.image.w * self.ch // self.image.h\n curr = int(-self.scroll) % page\n if curr > 0:\n sw = int(1 + self.image.h * curr / self.ch)\n sl = self.image.w - sw\n src = sl, 0, sw, self.image.h\n dw = int(sw * self.ch / self.image.h)\n dst = curr - dw, 0, dw, self.ch\n self.image.clip_draw_to_origin(*src, *dst)\n dst_width = round(self.image.w * self.ch / self.image.h)\n while curr + dst_width < self.cw:\n dst = curr, 0, dst_width, self.ch\n self.image.draw_to_origin(*dst)\n curr += dst_width\n if curr < self.cw:\n dw = self.cw - curr\n sw = int(1 + self.image.h * dw / self.ch)\n src = 0, 0, sw, self.image.h\n dw = int(sw * self.ch / self.image.h)\n dst = curr, 0, dw, self.ch\n self.image.clip_draw_to_origin(*src, *dst)\n\n def to_screen(self, point):\n x, y = point\n return x - self.scroll, y\n\n def translate(self, point):\n x, y = point\n return x + self.scroll, y\n\n def get_boundary(self):\n return (-sys.maxsize, -sys.maxsize, sys.maxsize, sys.maxsize)\n\n # self.image.clip_draw_to_origin(*self.src_rect_1, *self.dst_rect_1)\n # self.image.clip_draw_to_origin(*self.src_rect_2, *self.dst_rect_2)\n\n # private void drawHorizontal(Canvas canvas) {\n # int left = 0;\n # int top = 0;\n # int right = UiBridge.metrics.size.x;\n # int bottom = UiBridge.metrics.size.y;\n # int pageSize = sbmp.getWidth() * (bottom - top) / sbmp.getHeight();\n\n # canvas.save();\n # canvas.clipRect(left, top, right, bottom);\n\n # float curr = scrollX % pageSize;\n # if (curr > 0) curr -= pageSize;\n # curr += left;\n # while (curr < right) {\n # dstRect.set(curr, top, curr + pageSize, bottom);\n # curr += pageSize;\n # canvas.drawBitmap(sbmp.getBitmap(), srcRect, dstRect, null);\n # }\n # canvas.restore();\n # }\n\n","sub_path":"DOOM_2D/background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":6737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361158180","text":"import random\nfrom battleship.players import Human, Computer\nfrom battleship.config import PROMPT\nfrom battleship.ui import show_game, convert, flip\n\n\nclass Engine(object):\n\n def __init__(self):\n \"\"\"Engine has a list of players.\n \"\"\"\n self.opponent = Computer()\n self.home = Human()\n self.players = self.opponent, self.home\n\n def start(self):\n \"\"\"Starts the game with some instructions.\n \"\"\"\n print(PROMPT['title'])\n print(PROMPT['explain'])\n\n self._example_setup()\n\n eg_ship = random.choice(list(self.opponent.brd.fleet.values()))\n\n print(self.opponent.brd)\n\n print(PROMPT['example'].format(eg_ship, convert(eg_ship.pos[0]),\n convert(eg_ship.pos[-1])))\n\n self.opponent.brd.remove_fleet()\n\n input(PROMPT['ready'])\n\n def set(self):\n \"\"\"Set up each player's board, and decides who goes first with flip().\n \"\"\"\n for player in self.players:\n player.set_up()\n\n if flip():\n self.current_player = self.home\n self.next_player = self.opponent\n else:\n self.current_player = self.opponent\n self.next_player = self.home\n\n input(PROMPT['comprehend'])\n\n def play(self):\n \"\"\"Rolls out the turns, determines who wins.\n \"\"\"\n turn = 0\n first2go = self.current_player\n\n print(PROMPT['turn_line'].format(turn))\n\n show_game(self.home.brd, self.opponent.brd)\n\n while True:\n if self.current_player == first2go:\n turn += 1\n print(PROMPT['turn_line'].format(turn))\n\n point = self.current_player.where2bomb()\n self.next_player.receive_shot(point)\n\n if self.current_player != first2go:\n show_game(self.home.brd, self.opponent.brd)\n input(PROMPT['comprehend'])\n\n if self.next_player.sunk == 5:\n return self.current_player.win()\n\n self.current_player, self.next_player =\\\n self.next_player, self.current_player\n\n def end(self):\n \"\"\"Asks whether to play again or not.\n \"\"\"\n again = input(PROMPT['play_again']).lower()\n\n if again == 'n' or again == 'no':\n return None\n else:\n return True\n\n def _example_setup(self):\n \"\"\"Setup to show an example of the board and game.\n \"\"\"\n fleet = self.opponent.brd.fleet\n fleet_lst = [fleet[ship] for ship in fleet]\n random.shuffle(fleet_lst)\n\n for ship in fleet_lst:\n self.opponent.auto_hide_ships(ship, 2)\n","sub_path":"battleship/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462948455","text":"import warnings\nfrom dataclasses import dataclass\nfrom brownie import interface\nfrom brownie.network.contract import InterfaceContainer\nfrom rich.console import Console\nimport logging\nimport json\nimport requests\nfrom rich.logging import RichHandler\nfrom web3 import Web3\n\n\nwarnings.simplefilter( \"ignore\" )\n\nconsole = Console()\nlogging.basicConfig( level=\"ERROR\", format=\"%(message)s\", datefmt=\"[%X]\",\n handlers=[RichHandler( rich_tracebacks=True )] )\nlog = logging.getLogger( \"rich\" )\n\nZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\"\nnetwork = \"bsc\"\n@dataclass\nclass lpToken:\n name: str\n token: InterfaceContainer\n\n def describe(self):\n scale = 10 ** self.token.decimals()\n try:\n info = {\n \"token0\": self.token.token0(),\n \"token1\": self.token.token1(),\n \"token0_reserve\": self.token.getReserves()[0],\n \"token1_reserve\": self.token.getReserves()[1],\n \"totalSupply\": self.token.totalSupply(),\n \"decimals\": self.token.decimals()\n }\n\n #console.print(f'token0:{token0_name}, token1: {token1_name}, getReserves:{reserves}')\n\n #info = {\n # \"token0Name\": self.token.token0.key('token0')\n # \"token1Name\": self.token.token1.key('token1')\n # \"token0Reserve\": self.sett.getReserves()['_reserve0'] / scale,\n # \"token1Reserve\": self.sett.getReserves()['_reserve1'] / token1_scale,\n # \"totalSupply\" : self.sett.totalSupply() / scale,\n #}\n except ValueError as e:\n info = {}\n log.exception( str( e ) )\n\n return info\n\n@dataclass\nclass Sett:\n name: str\n sett: InterfaceContainer\n\n def describe(self):\n scale = 10 ** self.sett.decimals()\n try:\n info = {\n \"pricePerShare\": self.sett.getPricePerFullShare() / scale,\n \"totalSupply\" : self.sett.totalSupply() / scale,\n \"balance\": self.sett.balance() / scale,\n \"available\" : self.sett.available() / scale,\n }\n except ValueError as e:\n info = {}\n log.exception( str( e ) )\n\n return info\n\n@dataclass\nclass TokenBalance:\n wallets: dict\n token: InterfaceContainer\n tokenName: str\n\n def describe(self):\n info = []\n for name, address in self.wallets.items():\n scale = 10 ** self.token.decimals()\n try:\n info.append({\n \"balance\": self.token.balanceOf( address ) / scale,\n \"tokenName\": self.tokenName,\n \"tokenAddress\": self.token,\n \"walletAddress\": address,\n \"walletName\": name\n })\n except ValueError as e:\n log.exception( str( e ) )\n return info\n\nbadger_wallets_input = {\n \"deployer\": \"0xDA25ee226E534d868f0Dd8a459536b03fEE9079b\",\n \"guardian\": \"0x29F7F8896Fb913CF7f9949C623F896a154727919\",\n \"keeper\": \"0x872213E29C85d7e30F1C8202FC47eD1Ec124BB1D\",\n \"devMultisig\": \"0x6DA4c138Dd178F6179091C260de643529A2dAcfe\",\n \"opsMultisig\": \"0x7c7054bd87431378C837B2679f223f6d6aa602C1\",\n \"devProxyAdmin\": \"0x6354e79f21b56c11f48bcd7c451be456d7102a36\",\n}\nbadger_wallets = {}\nfor name, address in badger_wallets_input.items():\n badger_wallets[name] = Web3.toChecksumAddress(address)\n\n\nsett_vault_input = {\n \"bcakeBnbBtcb\": \"0xaf4B9C4b545D5324904bAa15e29796D2E2f90813\",\n \"bcakebBadgerBtcb\": \"0x857F91f735f4B03b19D2b5c6E476C73DB8241F55\",\n \"bcakebDiggBtcb\": \"0xa861Ba302674b08f7F2F24381b705870521DDfed\"\n }\nsett_vaults = {}\nfor name, address in sett_vault_input.items():\n sett_vaults[name] = Web3.toChecksumAddress(address)\n\ncoingecko_tokens_input = {\n \"0x753fbc5800a8C8e3Fb6DC6415810d627A387Dfc9\" : 'badger-dao',\n \"0x1F7216fdB338247512Ec99715587bb97BBf96eae\" :'badger-sett-badger',\n \"0x5986D5c77c65e5801a5cAa4fAE80089f870A71dA\" : 'badger-sett-digg',\n \"0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c\" : 'binance-bitcoin',\n \"0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c\": 'binancecoin',\n \"0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82\" : 'pancakeswap-token',\n}\ncoingecko_tokens = {}\nfor address, id in coingecko_tokens_input.items():\n coingecko_tokens[Web3.toChecksumAddress(address)] = id\n\ntreasury_tokens_input = {\n \"BADGER\" : '0x753fbc5800a8C8e3Fb6DC6415810d627A387Dfc9',\n \"bBADGER\" :'0x1F7216fdB338247512Ec99715587bb97BBf96eae', \n \"bDIGG\" : '0x5986D5c77c65e5801a5cAa4fAE80089f870A71dA',\n \"BTCb\" : '0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c',\n \"WBNB\": '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c',\n \"CAKE\" : '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82',\n \"cakebBadgerBtcb\" : '0x10F461CEAC7A17F59e249954Db0784d42EfF5DB5',\n \"cakebDiggBtcb\" : '0xE1E33459505bB3763843a426F7Fd9933418184ae',\n \"cakeBnbBtcb\" : '0x7561EEe90e24F3b348E1087A005F78B4c8453524',\n}\ntreasury_tokens = {}\nfor name, address in treasury_tokens_input.items():\n treasury_tokens[name] = Web3.toChecksumAddress(address)\n\nlp_tokens_input = {\n \"cakebBadgerBtcb\" : '0x10F461CEAC7A17F59e249954Db0784d42EfF5DB5',\n \"cakebDiggBtcb\" : '0xE1E33459505bB3763843a426F7Fd9933418184ae',\n \"cakeBnbBtcb\": '0x7561eee90e24f3b348e1087a005f78b4c8453524'\n }\nlp_tokens = {}\nfor name,address in lp_tokens_input.items():\n lp_tokens[name] = Web3.toChecksumAddress(address)\n\noracle = Web3.toChecksumAddress('0x058ec2Bf15011095a25670b618A129c043e2162E')\noracle_provider = Web3.toChecksumAddress('0x72dc16CFa95beB42aeebD2B10F22E55bD17Ce976')\nbadgertree = Web3.toChecksumAddress('0x660802Fc641b154aBA66a62137e71f331B6d787A')\n\ndef treasury_tokes():\n return treasury_tokens\ndef get_lp_data():\n return [lpToken( name=f'{name}', token=interface.lpToken(token)) for name, token in lp_tokens.items()]\n\ndef get_sett_data():\n return [Sett( name=f'{name}', sett=interface.Sett( sett ) ) for name, sett in sett_vaults.items()]\n\n\ndef get_token_balance_data(wallets, tokenAddress, tokenName):\n return TokenBalance(wallets=wallets, token=interface.ERC20(tokenAddress), tokenName=tokenName)\n\ndef get_json_request(request_type, url, request_data=None):\n # Take a request object and request type, then return the response in JSON format\n json_request = json.dumps(request_data)\n if(request_type == 'get'):\n r = requests.get(f'{url}', data=json_request)\n elif(request_type == 'post'):\n r = requests.post(f'{url}', data=json_request)\n else:\n return None\n return r.json()\n","sub_path":"docker/scout/scripts/data_bsc.py","file_name":"data_bsc.py","file_ext":"py","file_size_in_byte":6638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635041043","text":"from mmsdk.mmdatasdk import log, computational_sequence\nimport sys\nimport numpy\nimport time\nfrom tqdm import tqdm\nimport os\n\n#specified for numerical inconsistencies within floating points - if abs l1 distance two numbers is less than this, then they are the same. \n#only use for interval comparison.\nepsilon=10e-6\n\nclass mmdataset:\n\n\tdef __init__(self,recipe,destination=None):\n\t\tself.computational_sequences={}\n\n\t\tif type(recipe) is str:\n\t\t\tif os.path.isdir(recipe) is False:\n\t\t\t\tlog.error(\"Dataset folder does not exist ...\",error=True)\n\n\t\t\tfrom os import listdir\n\t\t\tfrom os.path import isfile, join\n\t\t\tcomputational_sequence_list = [f for f in listdir(recipe) if isfile(join(recipe, f)) and f[-4:]=='.csd']\n\t\t\tfor computational_sequence_fname in computational_sequence_list:\n\t\t\t\tthis_sequence=computational_sequence(join(recipe,computational_sequence_fname))\n\t\t\t\tself.computational_sequences[this_sequence.metadata[\"root name\"]]=this_sequence\n\n\t\telif type(recipe) is dict:\n\t\t\tfor entry, address in recipe.items():\n\t\t\t\tself.computational_sequences[entry]=computational_sequence(address,destination)\n\n\t\telif type(recipe) is list:\n\t\t\t#TODO: computational sequence with uuid\n\t\t\tpass\n\n\t\telse:\n\t\t\tlog.error(\"Cannot create a dataset with the given recipe. Exiting ...!\",error=True)\n\n\t\tif len(self.computational_sequences.keys())==0:\n\t\t\tlog.error(\"Dataset failed to initialize ...\", error=True)\n\n\t\tlog.success(\"Dataset initialized successfully ... \")\n\n\tdef __getitem__(self,key):\n\t\tif key not in list(self.computational_sequences.keys()):\n\t\t\tlog.error(\"Computational sequence does not exist ...\",error=True)\n\t\treturn self.computational_sequences[key]\n\n\tdef keys(self):\n\t\treturn self.computational_sequences.keys()\n\n\tdef add_computational_sequences(self,recipe,destination):\n\t\tfor entry, address in recipe.items():\n\t\t\tif entry in self.computational_sequences:\n\t\t\t\tlog.error(\"Dataset already contains <%s> computational sequence ...\"%entry)\n\t\t\tself.computational_sequences[entry]=computational_sequence(address,destination)\n\n\tdef bib_citations(self,outfile=None):\n\t\toutfile=sys.stdout if outfile is None else outfile\n\t\tsdkbib='@article{zadeh2018multi, title={Multi-attention recurrent network for human communication comprehension}, author={Zadeh, Amir and Liang, Paul Pu and Poria, Soujanya and Vij, Prateek and Cambria, Erik and Morency, Louis-Philippe}, journal={arXiv preprint arXiv:1802.00923}, year={2018}}'\n\t\toutfile.write('mmsdk bib: '+sdkbib+'\\n\\n')\n\t\tfor entry,compseq in self.computational_sequences.items():\n\t\t\tcompseq.bib_citations(outfile)\n\n\tdef unify(self,active=True):\n\t\tlog.status(\"Unify was called ...\")\n\n\t\tall_vidids={}\n\t\tviolators=[]\n\t\t\n\t\tall_keys={}\n\t\tfor seq_key in list(self.computational_sequences.keys()):\n\t\t\tall_keys[seq_key]=[vidid.split(\"[\")[0] for vidid in self.computational_sequences[seq_key].data.keys()]\n\t\t\n\t\tvalids=set.intersection(*[set(all_keys[x]) for x in all_keys])\n\t\tviolators=set()\n\t\tfor seq_key in list(self.computational_sequences.keys()):\n\t\t\tviolators=violators.union(set([vidid.split(\"[\")[0] for vidid in self.computational_sequences[seq_key].data.keys()])-valids)\n\t\t\n\t\tif len(violators) >0 :\n\t\t\tfor violator in violators:\n\t\t\t\tlog.error(\"%s entry is not shared among all sequences, removing it ...\"%violator,error=False)\n\t\t\t\tif active==True:\n\t\t\t\t\tself.remove_id(violator,purge=True)\n\t\tif active==False and len(violators)>0:\n\t\t\tlog.error(\"%d violators remain, alignment will fail if called ...\"%len(violators),error=True)\n\n\t\tlog.success(\"Unify completed ...\")\n\n\tdef hard_unify(self,active=True):\n\t\tlog.status(\"Hard unify was called ...\")\n\n\t\tall_vidids={}\n\t\tviolators=[]\n\t\t\n\t\tall_keys={}\n\t\tfor seq_key in list(self.computational_sequences.keys()):\n\t\t\tall_keys[seq_key]=[vidid for vidid in self.computational_sequences[seq_key].data.keys()]\n\t\t\n\t\tvalids=set.intersection(*[set(all_keys[x]) for x in all_keys])\n\t\tfor seq_key in list(self.computational_sequences.keys()):\n\t\t\thard_unify_compatible=all([\"[\" in vidid for vidid in self.computational_sequences[seq_key].data.keys()])\n\t\t\tif hard_unify_compatible is False:\n\t\t\t\tlog.error(\"Hard unify can only be done on aligned computational sequences, %s violated this ... Exiting ...\"%seq_key)\n\t\t\tviolators=set([vidid for vidid in self.computational_sequences[seq_key].data.keys()])-valids\n\t\t\tfor violator in violators:\n\t\t\t\tif active==True:\n\t\t\t\t\tlog.error(\"%s entry is not shared among all sequences, removing it ...\"%violator,error=False)\n\t\t\t\t\tself[seq_key]._remove_id(violator,purge=False)\n\n\t\t\tif active==False and len(violators)>0:\n\t\t\t\tlog.error(\"%d violators remain, alignment will fail if called ...\"%len(violators),error=True)\n\t\t\n\t\tlog.success(\"Hard unify completed ...\")\n\n\n\t\n\tdef remove_id(self,entry_id,purge=False):\n\t\tfor key,compseq in self.computational_sequences.items():\n\t\t\tcompseq._remove_id(entry_id,purge=purge)\n\n\tdef align(self,reference,collapse_functions=None,replace=True):\n\t\taligned_output={}\n\n\t\tfor sequence_name in self.computational_sequences.keys():\n\t\t\taligned_output[sequence_name]={}\n\t\tif reference not in self.computational_sequences.keys():\n\t\t\tlog.error(\"Computational sequence <%s> does not exist in dataset\"%reference,error=True)\n\t\trefseq=self.computational_sequences[reference].data\n\t\t#unifying the dataset, removing any entries that are not in the reference computational sequence\n\t\tself.unify()\n\n\t\t#building the relevant entries to the reference - what we do in this section is simply removing all the [] from the entry ids and populating them into a new dictionary\n\t\tlog.status(\"Pre-alignment based on <%s> computational sequence started ...\"%reference)\n\t\trelevant_entries=self.__get_relevant_entries(reference)\n\t\tlog.status(\"Alignment starting ...\")\n\n\t\tpbar = log.progress_bar(total=len(refseq.keys()),unit=\" Computational Sequence Entries\",leave=False)\n\t\tpbar.set_description(\"Overall Progress\")\n\t\tfor entry_key in list(refseq.keys()):\n\t\t\tpbar_small=log.progress_bar(total=refseq[entry_key]['intervals'].shape[0],unit=\" Segments\",leave=False)\n\t\t\tpbar_small.set_description(\"Aligning %s\"%entry_key)\n\t\t\tfor i in range(refseq[entry_key]['intervals'].shape[0]):\n\t\t\t\t#interval for the reference sequence\n\t\t\t\tref_time=refseq[entry_key]['intervals'][i,:]\n\t\t\t\t#we drop zero or very small sequence lengths - no align for those\n\t\t\t\tif (abs(ref_time[0]-ref_time[1]) computational sequences to <%s> computational sequence\"%(otherseq_key,reference),error=True)\n\t\t\t\t\taligned_output[otherseq_key][entry_key+\"[%d]\"%i]={}\n\t\t\t\t\taligned_output[otherseq_key][entry_key+\"[%d]\"%i][\"intervals\"]=intersects\n\t\t\t\t\taligned_output[otherseq_key][entry_key+\"[%d]\"%i][\"features\"]=intersects_features\n\t\t\t\tpbar_small.update(1)\n\t\t\tpbar_small.close()\n\t\t\tpbar.update(1)\n\t\tpbar.close()\n\t\tlog.success(\"Alignment to <%s> complete.\"%reference)\n\t\tif replace is True:\n\t\t\tlog.status(\"Replacing dataset content with aligned computational sequences\")\n\t\t\tself.__set_computational_sequences(aligned_output)\n\t\t\treturn None\n\t\telse:\n\t\t\tlog.status(\"Creating new dataset with aligned computational sequences\")\n\t\t\tnewdataset=mmdataset({})\n\t\t\tnewdataset.__set_computational_sequences(aligned_output,metadata_copy=False)\n\t\t\treturn newdataset\n\n\tdef __collapse(self,intervals,features,functions):\n\t\t#we simply collapse the intervals to (1,2) matrix\n\t\tnew_interval=numpy.array([[intervals.min(),intervals.max()]])\n\t\ttry:\n\t\t\tnew_features=numpy.concatenate([function(intervals,features) for function in functions],axis=0)\n\t\t\tif len(new_features.shape)==1:\n\t\t\t\tnew_features=new_features[None,:]\n\t\texcept:\n\t\t\tlog.error(\"Cannot collapse given the set of functions. Please check for exceptions in your functions ...\", error=True)\n\t\treturn new_interval,new_features\n\n\t#TODO: This is not passive-align safe\n\tdef revert(self,replace=True):\n\t\treverted_dataset={x:{} for x in self.keys()}\n\t\tlog.status(\"Revert was called ...\")\n\t\tif len(self.keys())==0:\n\t\t\tlog.error(\"The dataset contains no computational sequences ... Exiting!\",error=True)\n\n\t\tself.hard_unify()\n\t\tall_keys=list(self[list(self.keys())[0]].keys())\n\n\t\tif len(all_keys)==0:\n\t\t\tlog.error(\"No entries in computational sequences or removed during unify ... Exiting!\")\n\n\t\tunique_unnumbered_entries={}\n\n\t\tfor key in all_keys:\n\t\t\tif key.split('[')[0] not in unique_unnumbered_entries:\n\t\t\t\tunique_unnumbered_entries[key.split('[')[0]]=[]\n\t\t\tunique_unnumbered_entries[key.split('[')[0]].append(int(key.split('[')[1][:-1]))\n\n\t\tpbar = tqdm(total=len(unique_unnumbered_entries.keys()),unit=\" Unique Sequence Entries\",leave=False)\n\t\tpbar.set_description(\"Reversion Progress\")\n\t\tfor key in unique_unnumbered_entries.keys():\n\t\t\tunique_unnumbered_entries[key].sort()\n\t\t\tfor cs_key in reverted_dataset.keys():\n\t\t\t\tintervals=numpy.concatenate([self[cs_key][str('%s[%d]'%(key,i))][\"intervals\"] for i in unique_unnumbered_entries[key]],axis=0)\n\t\t\t\tfeatures=numpy.concatenate([self[cs_key][str('%s[%d]'%(key,i))][\"features\"] for i in unique_unnumbered_entries[key]],axis=0)\n\t\t\t\treverted_dataset[cs_key][key]={\"intervals\":intervals,\"features\":features}\n\t\t\tpbar.update(1)\n\t\tpbar.close()\n\t\tlog.success(\"Reversion completed ...\")\n\t\tif replace is True:\n\t\t\tlog.status(\"Replacing dataset content with reverted computational sequences\")\n\t\t\tself.__set_computational_sequences(reverted_dataset)\n\t\t\treturn None\n\t\telse:\n\t\t\tlog.status(\"Creating new dataset with reverted computational sequences\")\n\t\t\tnewdataset=mmdataset({})\n\t\t\tnewdataset.__set_computational_sequences(reverted_dataset,metadata_copy=False)\n\t\t\treturn newdataset\t\n\n\tdef impute(self,ref_key,imputation_fn=numpy.zeros):\n\t\tlog.status(\"Imputation called with function: %s ...\"%str(imputation_fn.__name__))\n\t\tother_keys=list(self.keys())\n\t\tother_keys.remove(ref_key)\n\t\tother_keys_dims={x:list(self[x][list(self[x].keys())[0]][\"features\"].shape[1:]) for x in other_keys}\n\t\tpbar = tqdm(total=len(self[ref_key].keys()),unit=\" Reference Computational Sequence Entries\",leave=False)\n\t\tpbar.set_description(\"Imputation Progress\")\n\t\tfor seg_key in self[ref_key].keys():\n\t\t\tfor other_key in other_keys:\n\t\t\t\ttry:\n\t\t\t\t\tself[other_key][seg_key]\n\t\t\t\texcept:\n\t\t\t\t\tnum_entries=self[ref_key][seg_key][\"intervals\"].shape[0]\n\t\t\t\t\tself[other_key][seg_key]={\"intervals\":self[ref_key][seg_key][\"intervals\"],\"features\":imputation_fn([num_entries]+other_keys_dims[other_key])}\n\t\t\t\t\t#log.status(\"Imputing %s,%s with function %s\"%(other_key,seg_key,str(imputation_fn.__name__)))\n\t\t\tpbar.update(1)\n\t\tpbar.close()\n\t\tlog.success(\"Imputation completed ...\")\n\n\n\t#setting the computational sequences in the dataset based on a given new_computational_sequence_data - may copy the metadata if there is already one\n\tdef __set_computational_sequences(self,new_computational_sequences_data,metadata_copy=True):\n\n\t\t#getting the old metadata from the sequence before replacing it. Even if this is a new computational sequence this will not cause an issue since old_metadat will just be empty\n\t\told_metadata={m:self.computational_sequences[m].metadata for m in list(self.computational_sequences.keys())}\n\t\tself.computational_sequences={}\n\t\tfor sequence_name in list(new_computational_sequences_data.keys()):\n\t\t\tself.computational_sequences[sequence_name]=computational_sequence(sequence_name)\n\t\t\tself.computational_sequences[sequence_name].setData(new_computational_sequences_data[sequence_name],sequence_name)\n\t\t\tif metadata_copy:\n\t\t\t\t#if there is no metadata for this computational sequences from the previous one or no previous computational sequenece\n\t\t\t\tif sequence_name not in list(old_metadata.keys()):\n\t\t\t\t\tlog.error (\"Metadata not available to copy ..., please provide metadata before writing to disk later\", error =False)\n\t\t\t\tself.computational_sequences[sequence_name].setMetadata(old_metadata[sequence_name],sequence_name)\n\t\t\tself.computational_sequences[sequence_name].rootName=sequence_name\n\n\tdef deploy(self,destination,filenames):\n\t\tif os.path.isdir(destination) is False:\n\t\t\tos.mkdir(destination)\n\t\tfor seq_key in list(self.computational_sequences.keys()):\n\t\t\tif seq_key not in list(filenames.keys()):\n\t\t\t\tlog.error(\"Filename for %s computational sequences not specified\"%seq_key)\n\t\t\tfilename=filenames[seq_key]\n\t\t\tif filename [:-4] != '.csd':\n\t\t\t\tfilename+='.csd'\n\t\t\tself.computational_sequences[seq_key].deploy(os.path.join(destination,filename))\n\n\tdef sort(self,sort_function=sorted):\n\t\t\"\"\" Sorts the computational sequence data based on the start time in intervals \n\n\t\t#Arguments\n\t\t\tself: The dataset object.\n\t\t\tsort_function: The function passed for sorting. This function will receive the intervals one by one for each key \n\n\t\t#Returns\n\t\t\tDoes not return any values - replaces in place\n\n\t\t\"\"\"\n\n\n\t\tfor key in list(self.keys()):\n\t\t\tfor csd in list(self[key].keys()):\n\t\t\t\tthis_intervals_np=numpy.array(self[key][csd][\"intervals\"])\n\t\t\t\tthis_features_np=numpy.array(self[key][csd][\"features\"])\n\t\t\t\tsorted_indices=sort_function(range(this_intervals_np.shape[0]),key=lambda x: this_intervals_np[x,0])\n\t\t\t\tsorted_this_intervals_np=this_intervals_np[sorted_indices,:]\n\t\t\t\tsorted_this_features_np=this_features_np[sorted_indices,:]\n\t\t\t\tself[key][csd][\"intervals\"]=sorted_this_intervals_np\n\t\t\t\tself[key][csd][\"features\"]=sorted_this_features_np\n\n\t#TODO: Add folds to this function\n\tdef get_tensors(self,seq_len,non_sequences=[],direction=False,folds=None):\n\t\t\"\"\" Returns trainable tensor from computational sequence data\n\n\t\t#Arguments\n\t\t\tself: The dataset object.\n\t\t\tseq_len: The maximum sequence length for the computational sequence entries, e.g. sentence length in words.\n\t\t\tdirection: True for right padding and False for left padding.\n\t\t\tfolds: The folds in which the dataset should be split.\n\t\t#Returns\n\t\t\tDictionary of numpy arrays with the same data type as computational sequences. Dictionaries include the same keys as the dataset\n\n\t\t\"\"\"\n\n\t\tcsds=list(self.keys())\n\n\t\tdef handle_none_folds():\n\t\t\treturn_folds={}\n\t\t\tfor key in list(self[csds[0]].keys()):\n\t\t\t\treturn_folds[key.split(\"[\")[0]]=None\n\t\t\treturn [list(return_folds.keys())]\n\t\n\t\tif folds==None:\n\t\t\tlog.error(\"No fold specified for get_tensors, defaulting to the first computational sequence ids\",error=False)\n\t\t\tfolds=handle_none_folds()\n\n\t\tself.hard_unify()\n\n\t\tdata=[]\n\t\toutput=[]\n\t\n\t\tfor i in range (len(folds)):\n\t\t\tdata.append({})\n\t\t\toutput.append({})\n\t\t\n\t\tdef lpad(this_array,direction):\n\t\t\tif direction==False:\n\t\t\t\ttemp_array=numpy.concatenate([numpy.zeros([seq_len]+list(this_array.shape[1:])),this_array],axis=0)[-seq_len:,...]\n\t\t\telse:\n\t\t\t\ttemp_array=numpy.concatenate([this_array,numpy.zeros([seq_len]+list(this_array.shape[1:]))],axis=0)[:seq_len,...]\n\t\t\treturn temp_array\n\n\t\tdef detect_entry_fold(entry,folds):\n\t\t\tentry_id=entry.split(\"[\")[0]\n\t\t\tfor i in range(len(folds)):\n\t\t\t\tif entry_id in folds[i]: return i\n\t\t\treturn None\n\t\t\t\n\n\t\tif len(csds)==0:\n\t\t\tlog.error(\"Dataset is empty, cannot get tensors. Exiting ...!\",error=True)\n\n\t\tfor i in range (len(folds)):\n\t\t\tfor csd in csds:\n\t\t\t\tdata[i][csd]=[]\n\n\t\tfor key in list(self[csds[0]].keys()):\n\t\t\twhich_fold=detect_entry_fold(key,folds)\n\t\t\tif which_fold==None:\n\t\t\t\tlog.error(\"Key %s doesn't belong to any fold ... \"%str(key),error=False)\n\t\t\t\tcontinue\n\t\t\tfor csd in list(self.keys()):\n\t\t\t\tthis_array=self[csd][key][\"features\"]\n\t\t\t\tif csd in non_sequences:\n\t\t\t\t\tdata[which_fold][csd].append(this_array)\n\t\t\t\telse:\n\t\t\t\t\tdata[which_fold][csd].append(lpad(this_array,direction))\n\n\t\tfor i in range(len(folds)):\n\t\t\tfor csd in csds:\n\t\t\t\toutput[i][csd]=numpy.array(data[i][csd])\n\n\t\treturn output\n\n\tdef __intersect_and_copy(self,ref,relevant_entry,epsilon):\n\n\t\tsub=relevant_entry[\"intervals\"]\n\t\tfeatures=relevant_entry[\"features\"]\n\n\t\t#copying and inverting the ref\n\t\tref_copy=ref.copy()\n\t\tref_copy[1]=-ref_copy[1]\n\t\tref_copy=ref_copy[::-1]\n\t\tsub_copy=sub.copy()\n\t\tsub_copy[:,0]=-sub_copy[:,0]\n\t\t#finding where intersect happens\n\t\twhere_intersect=(numpy.all((sub_copy-ref_copy)>(-epsilon),axis=1)==True)\n\t\tintersectors=sub[where_intersect,:]\n\t\tintersectors=numpy.concatenate([numpy.maximum(intersectors[:,0],ref[0])[:,None],numpy.minimum(intersectors[:,1],ref[1])[:,None]],axis=1)\n\t\tintersectors_features=features[where_intersect,:]\n\t\t#checking for boundary cases and also zero length\n\t\twhere_nonzero_len=numpy.where(abs(intersectors[:,0]-intersectors[:,1])>epsilon)\n\t\tintersectors_final=intersectors[where_nonzero_len]\n\t\tintersectors_features_final=intersectors_features[where_nonzero_len]\n\t\treturn intersectors_final,intersectors_features_final\n\n\t#TODO: Need tqdm bar for this as well\n\tdef __get_relevant_entries(self,reference):\n\t\trelevant_entries={}\n\t\trelevant_entries_np={}\n\n\t\t#pbar = tqdm(total=count,unit=\" Computational Sequence Entries\",leave=False)\n\n\n\t\tfor otherseq_key in set(list(self.computational_sequences.keys()))-set([reference]):\n\t\t\trelevant_entries[otherseq_key]={}\n\t\t\trelevant_entries_np[otherseq_key]={}\n\t\t\tsub_compseq=self.computational_sequences[otherseq_key] \n\t\t\tfor key in list(sub_compseq.data.keys()): \n\t\t\t\tkeystripped=key.split('[')[0] \n\t\t\t\tif keystripped not in relevant_entries[otherseq_key]: \n\t\t\t\t\trelevant_entries[otherseq_key][keystripped]={}\n\t\t\t\t\trelevant_entries[otherseq_key][keystripped][\"intervals\"]=[] \n\t\t\t\t\trelevant_entries[otherseq_key][keystripped][\"features\"]=[] \n\t\t \n\t\t\t\trelev_intervals=self.computational_sequences[otherseq_key].data[key][\"intervals\"] \n\t\t\t\trelev_features=self.computational_sequences[otherseq_key].data[key][\"features\"] \n\t\t\t\tif len(relev_intervals.shape)<2:\n\t\t\t\t\trelev_intervals=relev_intervals[None,:]\n\t\t\t\t\trelev_features=relev_features[None,:]\n\n\t\t\t\trelevant_entries[otherseq_key][keystripped][\"intervals\"].append(relev_intervals)\n\t\t\t\trelevant_entries[otherseq_key][keystripped][\"features\"].append(relev_features)\n\t\t \n\t\t\tfor key in list(relevant_entries[otherseq_key].keys()):\n\t\t\t\trelev_intervals_np=numpy.concatenate(relevant_entries[otherseq_key][key][\"intervals\"],axis=0) \n\t\t\t\trelev_features_np=numpy.concatenate(relevant_entries[otherseq_key][key][\"features\"],axis=0)\n\t\t\t\tsorted_indices=sorted(range(relev_intervals_np.shape[0]),key=lambda x: relev_intervals_np[x,0]) \n\t\t\t\trelev_intervals_np=relev_intervals_np[sorted_indices,:] \n\t\t\t\trelev_features_np=relev_features_np[sorted_indices,:]\n\n\t\t\t\trelevant_entries_np[otherseq_key][key]={}\n\t\t\t\trelevant_entries_np[otherseq_key][key][\"intervals\"]=relev_intervals_np\n\t\t\t\trelevant_entries_np[otherseq_key][key][\"features\"]=relev_features_np\n\t\t\tlog.status(\"Pre-alignment done for <%s> ...\"%otherseq_key)\n\t\treturn relevant_entries_np\n","sub_path":"mmsdk/mmdatasdk/dataset/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":19546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"599239734","text":"from analizer_pl.abstract.instruction import Instruction\nfrom analizer_pl.statement.expressions import code\nfrom analizer_pl.reports.Nodo import Nodo\nfrom analizer_pl.abstract.environment import Environment\nfrom analizer_pl import grammar\n\n\nclass Return(Instruction):\n def __init__(self, exp, row, column) -> None:\n super().__init__(row, column)\n self.exp = exp\n\n def execute(self, environment):\n try:\n tab = \"\"\n cd = \"\"\n tab1 = False\n if isinstance(environment, Environment):\n tab += \"\\t\"\n tab1 = True\n if self.exp:\n e = self.exp.execute(environment)\n cd += tab + \"stack.append(\" + e.temp + \")\\n\"\n grammar.optimizer_.addIgnoreString(\n str(\"stack.append(\" + e.temp + \")\"), self.row, tab1\n )\n cd += tab + \"goto .endLabel\\n\"\n grammar.optimizer_.addGoto(str(\"endLabel\"), self.row, tab1)\n return code.C3D(e.value + cd, \"return\", self.row, self.column)\n cd = tab + \"stack.append(None)\\n\"\n grammar.optimizer_.addIgnoreString(\n str(\"stack.append(None)\"), self.row, tab1\n )\n cd += tab + \"goto .endLabel\\n\"\n grammar.optimizer_.addGoto(str(\"endLabel\"), self.row, tab1)\n return code.C3D(cd, \"return\", self.row, self.column)\n except:\n grammar.PL_errors.append(\n \"Error P0000: plpgsql fatal error \\n Hint---> Return Expresion\"\n )\n\n def dot(self):\n\n new = Nodo(\"RETURN\")\n new.addNode(self.exp.dot())\n return new\n","sub_path":"parser/fase2/team29/analizer_pl/C3D/operations/return_.py","file_name":"return_.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"149384315","text":"import wikipedia\n\n\ndef get_page_sumarries(page_name):\n wikipedia.set_lang('fa')\n try:\n return [[page_name, wikipedia.page(page_name).summary.replace('\\u200c', ' ')]]\n except wikipedia.exceptions.DisambiguationError as e:\n return [[p, wikipedia.page(p).summary.replace('\\u200c', ' ')] for p in e.options]\n\n\ndef get_random_pages_summary(pages=1):\n ret = []\n wikipedia.set_lang('fa')\n page_names = [wikipedia.random(1) for i in range(pages)]\n for p in page_names:\n for page_summary in get_page_sumarries(p):\n ret.append(page_summary.replace('\\u200c', ' '))\n return ret\n\n\ndef random_title():\n wikipedia.set_lang('fa')\n return wikipedia.random(1).replace('\\u200c', ' ')\n\n\n","sub_path":"func/wikipedia_crawler.py","file_name":"wikipedia_crawler.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392341097","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n 学生出勤记录\n\"\"\"\n\n\n# 简单思路\nclass Solution:\n def checkRecord(self, s: str) -> bool:\n a_count = 0\n l_state = 0\n for x in s:\n if x == \"A\":\n a_count += 1\n l_state = 0\n elif x == \"L\":\n l_state += 1\n if l_state > 2:\n return False\n else:\n l_state = 0\n if a_count > 1:\n return False\n\n return True\n\n\n# 简介代码\nclass Solution2:\n def checkRecord(self, s: str) -> bool:\n return s.count(\"A\") < 2 and s.count(\"LLL\") < 1\n","sub_path":"src/leetcode/python3/leetcode551.py","file_name":"leetcode551.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"363912761","text":"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"\nEstimating the susceptibility distortions without fieldmaps.\n\n.. testsetup::\n\n >>> tmpdir = getfixture('tmpdir')\n >>> tmp = tmpdir.chdir() # changing to a temporary directory\n >>> data = np.zeros((10, 10, 10, 1, 3))\n >>> data[..., 1] = 1\n >>> nb.Nifti1Image(data, None, None).to_filename(\n ... tmpdir.join('field.nii.gz').strpath)\n\n.. _sdc_fieldmapless :\n\nFieldmap-less approaches\n~~~~~~~~~~~~~~~~~~~~~~~~\nMany studies acquired (especially with legacy MRI protocols) do not have any\ninformation to estimate susceptibility-derived distortions.\nIn the absence of data with the specific purpose of estimating the :math:`B_0`\ninhomogeneity map, researchers resort to nonlinear registration to an\n«*anatomically correct*» map of the same individual (normally acquired with\n:abbr:`T1w (T1-weighted)`, or :abbr:`T2w (T2-weighted)` sequences).\nOne of the most prominent proposals of this approach is found in [Studholme2000]_.\n\n*SDCFlows* includes an (experimental) procedure (see :py:func:`init_syn_sdc_wf` below),\nbased on nonlinear image registration with ANTs' symmetric normalization (SyN) technique.\nThis workflow takes a skull-stripped :abbr:`T1w (T1-weighted)` image and\na reference :abbr:`EPI (Echo-Planar Imaging)` image, and estimates a field of nonlinear\ndisplacements that accounts for susceptibility-derived distortions.\nTo more accurately estimate the warping on typically distorted regions, this\nimplementation uses an average :math:`B_0` mapping described in [Treiber2016]_.\nThe implementation is a variation on those developed in [Huntenburg2014]_ and\n[Wang2017]_.\nFeedback will be enthusiastically received.\n\nReferences\n----------\n.. [Studholme2000] Studholme et al. (2000) Accurate alignment of functional EPI data to\n anatomical MRI using a physics-based distortion model,\n IEEE Trans Med Imag 19(11):1115-1127, 2000, doi: `10.1109/42.896788\n `__.\n.. [Treiber2016] Treiber, J. M. et al. (2016) Characterization and Correction\n of Geometric Distortions in 814 Diffusion Weighted Images,\n PLoS ONE 11(3): e0152472. doi:`10.1371/journal.pone.0152472\n `_.\n.. [Wang2017] Wang S, et al. (2017) Evaluation of Field Map and Nonlinear\n Registration Methods for Correction of Susceptibility Artifacts\n in Diffusion MRI. Front. Neuroinform. 11:17.\n doi:`10.3389/fninf.2017.00017\n `_.\n.. [Huntenburg2014] Huntenburg, J. M. (2014) `Evaluating Nonlinear\n Coregistration of BOLD EPI and T1w Images\n `__,\n Berlin: Master Thesis, Freie Universität.\n\n\"\"\"\nfrom nipype.pipeline import engine as pe\nfrom nipype.interfaces import utility as niu\nfrom niworkflows.engine.workflows import LiterateWorkflow as Workflow\n\nDEFAULT_MEMORY_MIN_GB = 0.01\nINPUT_FIELDS = (\n \"epi_ref\",\n \"epi_mask\",\n \"anat_brain\",\n \"std2anat_xfm\",\n \"anat2epi_xfm\",\n)\n\n\ndef init_syn_sdc_wf(\n *,\n atlas_threshold=3,\n debug=False,\n name=\"syn_sdc_wf\",\n omp_nthreads=1,\n):\n \"\"\"\n Build the *fieldmap-less* susceptibility-distortion estimation workflow.\n\n SyN deformation is restricted to the phase-encoding (PE) direction.\n If no PE direction is specified, anterior-posterior PE is assumed.\n\n SyN deformation is also restricted to regions that are expected to have a\n >3mm (approximately 1 voxel) warp, based on the fieldmap atlas.\n\n\n Workflow Graph\n .. workflow ::\n :graph2use: orig\n :simple_form: yes\n\n from sdcflows.workflows.fit.syn import init_syn_sdc_wf\n wf = init_syn_sdc_wf(omp_nthreads=8)\n\n Parameters\n ----------\n atlas_threshold : :obj:`float`\n Exclude from the registration metric computation areas with average distortions\n below this threshold (in mm).\n debug : :obj:`bool`\n Whether a fast (less accurate) configuration of the workflow should be applied.\n name : :obj:`str`\n Name for this workflow\n omp_nthreads : :obj:`int`\n Parallelize internal tasks across the number of CPUs given by this option.\n\n Inputs\n ------\n epi_ref : :obj:`tuple` (:obj:`str`, :obj:`dict`)\n A tuple, where the first element is the path of the distorted EPI\n reference map (e.g., an average of *b=0* volumes), and the second\n element is a dictionary of associated metadata.\n epi_mask : :obj:`str`\n A path to a brain mask corresponding to ``epi_ref``.\n anat_brain : :obj:`str`\n A preprocessed, skull-stripped anatomical (T1w or T2w) image.\n std2anat_xfm : :obj:`str`\n inverse registration transform of T1w image to MNI template\n anat2epi_xfm : :obj:`str`\n transform mapping coordinates from the EPI space to the anatomical\n space (i.e., the transform to resample anatomical info into EPI space.)\n\n Outputs\n -------\n fmap : :obj:`str`\n The path of the estimated fieldmap.\n fmap_ref : :obj:`str`\n The path of an unwarped conversion of files in ``epi_ref``.\n fmap_coeff : :obj:`str` or :obj:`list` of :obj:`str`\n The path(s) of the B-Spline coefficients supporting the fieldmap.\n\n \"\"\"\n from pkg_resources import resource_filename as pkgrf\n from packaging.version import parse as parseversion, Version\n from nipype.interfaces.image import Rescale\n from niworkflows.interfaces.fixes import (\n FixHeaderApplyTransforms as ApplyTransforms,\n FixHeaderRegistration as Registration,\n )\n from niworkflows.interfaces.nibabel import Binarize\n from ...utils.misc import front as _pop\n from ...interfaces.utils import Deoblique, Reoblique\n from ...interfaces.bspline import (\n BSplineApprox,\n DEFAULT_LF_ZOOMS_MM,\n DEFAULT_HF_ZOOMS_MM,\n DEFAULT_ZOOMS_MM,\n )\n from ..ancillary import init_brainextraction_wf\n\n ants_version = Registration().version\n if ants_version and parseversion(ants_version) < Version(\"2.2.0\"):\n raise RuntimeError(\n f\"Please upgrade ANTs to 2.2 or older ({ants_version} found).\"\n )\n\n workflow = Workflow(name=name)\n workflow.__desc__ = f\"\"\"\\\nA deformation field to correct for susceptibility distortions was estimated\nbased on *fMRIPrep*'s *fieldmap-less* approach.\nThe deformation field is that resulting from co-registering the EPI reference\nto the same-subject T1w-reference with its intensity inverted [@fieldmapless1;\n@fieldmapless2].\nRegistration is performed with `antsRegistration`\n(ANTs {ants_version or \"-- version unknown\"}), and\nthe process regularized by constraining deformation to be nonzero only\nalong the phase-encoding direction, and modulated with an average fieldmap\ntemplate [@fieldmapless3].\n\"\"\"\n inputnode = pe.Node(niu.IdentityInterface(INPUT_FIELDS), name=\"inputnode\")\n outputnode = pe.Node(\n niu.IdentityInterface([\"fmap\", \"fmap_ref\", \"fmap_coeff\", \"fmap_mask\"]),\n name=\"outputnode\",\n )\n\n invert_t1w = pe.Node(Rescale(invert=True), name=\"invert_t1w\", mem_gb=0.3)\n anat2epi = pe.Node(\n ApplyTransforms(interpolation=\"BSpline\"), name=\"anat2epi\", n_procs=omp_nthreads\n )\n\n # Mapping & preparing prior knowledge\n # Concatenate transform files:\n # 1) anat -> EPI; 2) MNI -> anat; 3) ATLAS -> MNI\n transform_list = pe.Node(\n niu.Merge(3), name=\"transform_list\", mem_gb=DEFAULT_MEMORY_MIN_GB\n )\n transform_list.inputs.in3 = pkgrf(\n \"sdcflows\", \"data/fmap_atlas_2_MNI152NLin2009cAsym_affine.mat\"\n )\n prior2epi = pe.Node(\n ApplyTransforms(input_image=pkgrf(\"sdcflows\", \"data/fmap_atlas.nii.gz\")),\n name=\"prior2epi\",\n n_procs=omp_nthreads,\n mem_gb=0.3,\n )\n atlas_msk = pe.Node(Binarize(thresh_low=atlas_threshold), name=\"atlas_msk\")\n\n deoblique = pe.Node(Deoblique(), name=\"deoblique\")\n reoblique = pe.Node(Reoblique(), name=\"reoblique\")\n\n # SyN Registration Core\n syn = pe.Node(\n Registration(from_file=pkgrf(\"sdcflows\", \"data/susceptibility_syn.json\")),\n name=\"syn\",\n n_procs=omp_nthreads,\n )\n\n unwarp_ref = pe.Node(\n ApplyTransforms(interpolation=\"BSpline\"),\n name=\"unwarp_ref\",\n )\n\n brainextraction_wf = init_brainextraction_wf()\n\n # Extract nonzero component\n extract_field = pe.Node(niu.Function(function=_extract_field), name=\"extract_field\")\n\n # Regularize with B-Splines\n bs_filter = pe.Node(BSplineApprox(), n_procs=omp_nthreads, name=\"bs_filter\")\n bs_filter.interface._always_run = debug\n bs_filter.inputs.bs_spacing = (\n [DEFAULT_LF_ZOOMS_MM, DEFAULT_HF_ZOOMS_MM] if not debug else [DEFAULT_ZOOMS_MM]\n )\n bs_filter.inputs.extrapolate = not debug\n\n # fmt: off\n workflow.connect([\n (inputnode, transform_list, [(\"anat2epi_xfm\", \"in1\"),\n (\"std2anat_xfm\", \"in2\")]),\n (inputnode, invert_t1w, [(\"anat_brain\", \"in_file\"),\n ((\"epi_ref\", _pop), \"ref_file\")]),\n (inputnode, anat2epi, [((\"epi_ref\", _pop), \"reference_image\"),\n (\"anat2epi_xfm\", \"transforms\")]),\n (inputnode, deoblique, [((\"epi_ref\", _pop), \"in_epi\"),\n (\"epi_mask\", \"mask_epi\")]),\n (inputnode, reoblique, [((\"epi_ref\", _pop), \"in_epi\")]),\n (inputnode, syn, [((\"epi_ref\", _warp_dir), \"restrict_deformation\")]),\n (inputnode, unwarp_ref, [((\"epi_ref\", _pop), \"reference_image\"),\n ((\"epi_ref\", _pop), \"input_image\")]),\n (inputnode, prior2epi, [((\"epi_ref\", _pop), \"reference_image\")]),\n (inputnode, extract_field, [(\"epi_ref\", \"epi_meta\")]),\n (invert_t1w, anat2epi, [(\"out_file\", \"input_image\")]),\n (transform_list, prior2epi, [(\"out\", \"transforms\")]),\n (prior2epi, atlas_msk, [(\"output_image\", \"in_file\")]),\n (anat2epi, deoblique, [(\"output_image\", \"in_anat\")]),\n (atlas_msk, deoblique, [(\"out_mask\", \"mask_anat\")]),\n (deoblique, syn, [(\"out_epi\", \"moving_image\"),\n (\"out_anat\", \"fixed_image\"),\n (\"mask_epi\", \"moving_image_masks\"),\n ((\"mask_anat\", _fixed_masks_arg), \"fixed_image_masks\")]),\n (syn, extract_field, [(\"forward_transforms\", \"in_file\")]),\n (syn, unwarp_ref, [(\"forward_transforms\", \"transforms\")]),\n (unwarp_ref, reoblique, [(\"output_image\", \"in_plumb\")]),\n (reoblique, brainextraction_wf, [(\"out_epi\", \"inputnode.in_file\")]),\n (extract_field, reoblique, [(\"out\", \"in_field\")]),\n (reoblique, bs_filter, [(\"out_field\", \"in_data\")]),\n (brainextraction_wf, bs_filter, [(\"outputnode.out_mask\", \"in_mask\")]),\n (reoblique, outputnode, [(\"out_epi\", \"fmap_ref\")]),\n (brainextraction_wf, outputnode, [(\"outputnode.out_mask\", \"fmap_mask\")]),\n (bs_filter, outputnode, [\n (\"out_extrapolated\" if not debug else \"out_field\", \"fmap\"),\n (\"out_coeff\", \"fmap_coeff\")]),\n ])\n # fmt: on\n\n return workflow\n\n\ndef _warp_dir(intuple):\n \"\"\"\n Extract the ``restrict_deformation`` argument from metadata.\n\n Example\n -------\n >>> _warp_dir((\"epi.nii.gz\", {\"PhaseEncodingDirection\": \"i-\"}))\n [[1, 0, 0], [1, 0, 0]]\n\n >>> _warp_dir((\"epi.nii.gz\", {\"PhaseEncodingDirection\": \"j-\"}))\n [[0, 1, 0], [0, 1, 0]]\n\n \"\"\"\n pe = intuple[1][\"PhaseEncodingDirection\"][0]\n return 2 * [[int(pe == ax) for ax in \"ijk\"]]\n\n\ndef _fixed_masks_arg(mask):\n \"\"\"\n Prepare the ``fixed_image_masks`` argument of SyN.\n\n Example\n -------\n >>> _fixed_masks_arg(\"atlas_mask.nii.gz\")\n ['NULL', 'atlas_mask.nii.gz']\n\n \"\"\"\n return [\"NULL\", mask]\n\n\ndef _extract_field(in_file, epi_meta):\n \"\"\"\n Extract the nonzero component of the deformation field estimated by ANTs.\n\n Examples\n --------\n >>> nii = nb.load(\n ... _extract_field(\n ... [\"field.nii.gz\"],\n ... (\"epi.nii.gz\", {\"PhaseEncodingDirection\": \"j-\", \"TotalReadoutTime\": 0.005}))\n ... )\n >>> nii.shape\n (10, 10, 10)\n\n >>> np.allclose(nii.get_fdata(), -200)\n True\n\n \"\"\"\n from nipype.utils.filemanip import fname_presuffix\n import numpy as np\n import nibabel as nb\n from sdcflows.utils.epimanip import get_trt\n\n fieldnii = nb.load(in_file[0])\n trt = get_trt(epi_meta[1], in_file=epi_meta[0])\n data = (\n np.squeeze(fieldnii.get_fdata(dtype=\"float32\"))[\n ..., \"ijk\".index(epi_meta[1][\"PhaseEncodingDirection\"][0])\n ]\n / trt\n * (-1.0 if epi_meta[1][\"PhaseEncodingDirection\"].endswith(\"-\") else 1.0)\n )\n out_file = fname_presuffix(in_file[0], suffix=\"_fieldmap\")\n nii = nb.Nifti1Image(data, fieldnii.affine, None)\n nii.header.set_xyzt_units(fieldnii.header.get_xyzt_units()[0])\n nii.to_filename(out_file)\n return out_file\n","sub_path":"sdcflows/workflows/fit/syn.py","file_name":"syn.py","file_ext":"py","file_size_in_byte":13104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47810438","text":"from kivy.app import App\nfrom kivy.uix.modalview import ModalView\nimport os.path\nimport imaplib\nimport email\nimport os\nimport re\nimport json\nimport threading\nimport time\nimport datetime as dt\nfrom reportbanner import ReportBanner\nfrom kivy.clock import mainthread\nfrom kivy.factory import Factory\n\n\nclass CheckEmailsPopup(ModalView):\n \"\"\"\n Checks the mailbox and downloads the files in the mails from the trainer.\n\n ...\n Attributes\n ----------\n app : App Class\n The base of the application\n con : imaplib.IMAP4_SSL object\n This is a subclass derived from IMAP4 that connects over an SSL\n encrypted socket.\n year : int\n The apprenticeship year\n imap_servers : dict\n Contains a bunch of imap server addresses\n\n Methods\n -------\n connect()\n Create a connection to the imap\n remove_update_button()\n Remove the update button from the home screen\n add_update_button()\n Add a update button to the home screen\n start_checking()\n Check the inbox for new reports\n check_email()\n Iterate over all payloads of the new received emails and downloads\n attached pdf files\n search(c1, c2, val1)\n Search for the specific emails\n report_rejected(num)\n Change status of the specific calendar week\n get_emails()\n Get the specific emails from the trainer\n get_email_body(msg)\n Get the body of the email\n get_attachments(msg, check)\n Get the pdf file of the email\n decode_mime_header(s)\n Decode the encoded chunks (encoded-words)\n \"\"\"\n def __init__(self, **kwargs):\n super(CheckEmailsPopup, self).__init__(**kwargs)\n self.app = App.get_running_app()\n self.con = None\n self.year = 1\n self.imap_servers = {\"gmail\": \"imap.gmail.com\",\n \"gmx\": \"imap.gmx.net\",\n \"yahoo\": \"imap.mail.yahoo.com\",\n \"t-online\": \"secureimap.t-online.de\",\n \"freenet\": \"mx.freenet.de\",\n \"1und1\": \"imap.1und1.de\",\n \"mail\": \"imap.mail.de\",\n \"aol.com\": \"imap.de.aol.com\",\n \"aim\": \"imap.aim.com\",\n \"aol.de\": \"imap.aim.com\",\n \"arcor\": \"imap.arcor.de\",\n \"eclipso\": 'mail.eclipso.de',\n \"firemail\": 'firemail.de',\n \"me\": 'imap.mail.me.com',\n \"mailbox\": 'imap.mailbox.org',\n \"smart-mail\": 'imap.smart-mail.de',\n \"outlook\": 'imap-mail.outlook.com',\n \"netcologne\": 'imap.netcologne.de',\n \"o2online\": 'imap4.o2online.de',\n \"web\": \"imap.web.de\",\n \"vodafone\": 'imap.vodafonemail.de'}\n\n def connect(self, pw):\n \"\"\"Create a connection to the imap server.\"\"\"\n incoming_mail_server = ''\n pattern = re.compile(\n (r'(?<=[@|\\.])(gmx|mail|1und1|freenet|vodafone|aim'\n r'|gmail|t-online|web|yahoo|outlook|aol|arcor|'\n r'|o2online|netcologne|smart-mail|mailbox|firemail|eclipso|me)'),\n re.I)\n try:\n # get the right SERVER for the specific e-mail\n match = pattern.search(self.app.MY_EMAIL)\n if match.group(0) == 'aol':\n tld = self.app.MY_EMAIL.split('.')[1]\n incoming_mail_server = \\\n self.imap_servers[match.group(1)+'.'+tld]\n if match.group(0) in self.imap_servers:\n incoming_mail_server = self.imap_servers[match.group(1)]\n try:\n self.con = imaplib.IMAP4_SSL(incoming_mail_server)\n self.con.login(self.app.MY_EMAIL, pw)\n # Check if there is a new email\n threading.Thread(target=self.start_checking,\n daemon=True).start()\n except Exception:\n error = (\"Bitte überprüfen Sie ihre E-Mail-Adresse und Ihr\"\n \" dazu gehöriges Passwort bzw. sorgen Sie dafür, \"\n \"dass bei ihrem E-Mail Provider der Zugriff über \"\n \"IMAP und POP3 nicht deaktiviert ist.\")\n self.app.open_error_popup(error)\n except Exception:\n error = \"Der Provider Ihrer E-Mail-Adresse wird nicht unterstützt\"\n self.app.open_error_popup(error)\n\n @mainthread\n def remove_update_button(self, *args):\n \"\"\"Remove the update button from the home screen.\"\"\"\n for w in self.app.root.ids['home_screen'].ids['home'].children:\n if self.app.fb == w:\n (self.app.root.ids['home_screen'].ids['home']\n .remove_widget(w))\n\n @mainthread\n def add_update_button(self, *args):\n \"\"\"Add a update button to the home screen.\"\"\"\n self.app.fb = Factory.FloatButton()\n (self.app.root.ids['home_screen'].ids['home']\n .add_widget(self.app.fb))\n\n def start_checking(self):\n \"\"\"Check the inbox for new reports.\"\"\"\n try:\n self.remove_update_button()\n for _ in range(15):\n self.check_email()\n time.sleep(20)\n self.add_update_button()\n self.con.close()\n self.con.logout()\n return\n except Exception:\n error = \"Ein Fehler ist aufgetreten\"\n self.app.open_error_popup(error)\n self.con.close()\n self.con.logout()\n\n def check_email(self):\n \"\"\"Iterate over all payloads of the new received emails and downloads attached pdf files.\"\"\"\n for msg in self.get_emails():\n payload, file_name = \\\n self.get_attachments(msg, (lambda x: x.endswith('.pdf')))\n attachment_dir = os.path.join(os.getcwd(),\n 'reports',\n f'fertige-berichte-{self.year}')\n if payload is not None:\n file_path = os.path.join(attachment_dir, file_name)\n if not os.path.exists(file_path):\n with open(file_path, 'wb') as f:\n f.write(payload)\n\n def search(self, c1, c2, val1):\n \"\"\"Search for the specific emails.\"\"\"\n typ, data = \\\n self.con.search(None, f'({c1.upper()} \"{val1}\" {c2.upper()})')\n return (typ, data)\n\n @mainthread\n def report_rejected(self, num):\n \"\"\"Change status of the specific calendar week.\"\"\"\n current_c_w = \\\n (dt.date(*list(map(int, reversed(self.app.START_DATES[self.year-1]\n .split('.')))))\n .isocalendar()[1])\n total_weeks = \\\n (dt.date(int(self.app.START_DATES[self.year-1][-4:]), 12, 28)\n .isocalendar()[1])\n max_calws = 53 if current_c_w == 53 or total_weeks == 53 else 52\n with open(os.path.join(os.getcwd(), 'data', 'Bh_data.json'), 'r') as f:\n d = json.load(f)\n for widget in self.app.banner_grid.children:\n # find the selected banner\n if num == widget.id_number:\n # deletes old banner and replace it with the new\n # banner with the right status\n self.app.banner_grid.remove_widget(widget)\n self.app.banner_grid.add_widget(\n ReportBanner(num,\n self.app.get_period(self.app.START_YEAR, num),\n (((current_c_w + num - 2) % max_calws) + 1),\n os.path.join(self.app.cwd, 'icons',\n 'notFilledOutSymbol.png'),\n widget.total_hours),\n len(self.app.banner_grid.children)-(num-1))\n\n (d['record_book']['content'][self.year-1]\n ['calendar_week'][num-1]['header']['status']) = \\\n os.path.join(os.getcwd(),\n 'icons', 'notFilledOutSymbol.png')\n with open(os.path.join(os.getcwd(), 'data', 'Bh_data.json'),\n 'w', encoding='utf-8') as f:\n json.dump(d, f, ensure_ascii=False, indent=2)\n\n def get_emails(self):\n \"\"\"Get the specific emails from the trainer.\"\"\"\n self.con.select('INBOX')\n trainer_email_addr = self.app.TRAINER_EMAIL\n res, data = self.search('FROM', 'UNSEEN', trainer_email_addr)\n if res == 'OK':\n for id in data[0].split():\n typ, data = self.con.fetch(id, '(RFC822)')\n email_msg = \\\n email.message_from_string(data[0][1].decode(\"utf-8\"))\n msg = email.message_from_bytes(data[0][1])\n try:\n subject = self.decode_mime_header(email_msg['Subject'])\n except Exception:\n subject = email_msg['Subject']\n self.year = int(subject[-1])\n if 'ABGELEHNT' in subject:\n email_body = self.get_email_body(msg).decode(\"utf-8\")\n num = subject.split(' - ')[0][-1]\n self.report_rejected(int(num))\n error = email_body\n self.app.open_error_popup(error)\n continue\n yield msg\n\n def get_email_body(self, msg):\n \"\"\"Get the body of the email.\"\"\"\n if msg.is_multipart():\n return self.get_email_body(msg.get_payload(0))\n else:\n return msg.get_payload(None, True)\n\n def get_attachments(self, msg, check):\n \"\"\"Get the pdf file of the email.\"\"\"\n try:\n for part in msg.walk():\n if part.get_content_maintype() == 'multipart':\n continue\n if part.get('Content-Disposition') is None:\n continue\n file_name = part.get_filename()\n if bool(file_name) and check(file_name):\n return (part.get_payload(decode=True), file_name)\n else:\n return None, ''\n return None, ''\n except Exception:\n pass\n\n def decode_mime_header(self, s):\n \"\"\"Decode the encoded chunks (encoded-words).\"\"\"\n return (''.join(word.decode(encoding or 'utf8')\n for word, encoding in email.header.decode_header(s)))\n","sub_path":"CheckEmails.py","file_name":"CheckEmails.py","file_ext":"py","file_size_in_byte":10705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"282035991","text":"import json\nimport requests\nimport time\n\n\nclass ElasticSearch:\n def __init__(self, url, index):\n \"\"\"\n ElasticSearch Class\n\n Usage:\n >>> from elasticsearch_metadata import ElasticSearch\n\n # Instantiate DB class with ElasticSearch URL & index\n >>> db = ElasticSearch(ELASTIC_URL, INDEX)\n\n Params:\n - ELASTIC_URL: Elastic Search URL string\n - index: Elastic data index\n \"\"\"\n self._url = url + \"/\" + index\n\n def get_timestamp(self):\n return str(int(round(time.time() * 1000)))\n\n def query(self, query={}, params=\"\", method=\"post\"):\n \"\"\"Query ElasticSearch\n\n Args:\n query (object, optional): Query object. Defaults to {}.\n params (string, optional): URL params. Defaults to \"\".\n method (string, optional): HTTP Method (\"get\" | \"post\"). Defaults to \"post\".\n\n Returns:\n object: Response from ElasticSearch\n \"\"\"\n res = False\n\n if(method == \"post\"):\n res = json.loads(requests.post(\n self._url + \"/\" + params, json=query).text)\n elif(method == \"get\"):\n res = json.loads(requests.get(self._url + \"/\" + params).text)\n elif(method == \"delete\"):\n res = json.loads(requests.delete(self._url + \"/\" + params).text)\n return res\n\n def get_document(self, doc_id):\n \"\"\"Get document by id\n\n Args:\n doc_id (string): Document ID\n\n Returns:\n object: ElasticSearch _source object\n \"\"\"\n result = self.query(params=\"_doc/%s\" % (doc_id), method=\"get\")\n\n if \"_source\" in result:\n return result[\"_source\"]\n else:\n return False\n\n def create_document(self, metadata, alternatives, masterUUIDSeries=None):\n \"\"\"Create new document on ElasticSearch\n\n Args:\n metadata (object): Metadata object\n\n Returns: Document ID of new object\n \"\"\"\n\n for key, value in metadata.items():\n if type(value) is list:\n for item in value:\n if str(item.get(\"type\")).lower() == \"sched\":\n # Add lastUpdate\n item[\"lastUpdate\"] = self.get_timestamp()\n\n newDocument = {\n \"masterUUID\": metadata[\"UUID\"] if masterUUIDSeries == None else masterUUIDSeries,\n \"providerData\": [metadata],\n \"lastUpdate\": self.get_timestamp()\n }\n\n for alternative in alternatives:\n alternative[\"UUID\"] = metadata[\"UUID\"]\n newDocument[\"providerData\"].append(alternative)\n\n result = self.query(newDocument, params=\"_doc\")\n return result[\"_id\"]\n\n def update_document(self, doc_id, values):\n updateDocumentQuery = {\n \"doc\": values\n }\n result = self.query(updateDocumentQuery,\n params=\"_update/%s\" % (doc_id))\n\n return result\n\n def delete_document(self, doc_id) -> bool:\n result = self.query(method=\"delete\", params=\"_doc/%s\" % (doc_id))\n\n return result\n\n def add_metadata(self, doc_id, metadata):\n \"\"\"Add metadata to existing document\n\n Args:\n doc_id (string): Document id on ElasticSearch\n metadata (object): Metadata object\n\n Returns:\n object: Response from ElasticSearch\n \"\"\"\n addMetadataQuery = {\n \"script\": {\n \"source\": \"ctx._source.providerData.add(params)\",\n \"params\": metadata\n }\n }\n\n try:\n for key, value in list(metadata.items()):\n if type(value) is list:\n for item in value:\n if str(item.get(\"type\")) == \"ENRICH\":\n self.update_document(doc_id, {\"is_enriched\": True})\n break\n except Exception as e:\n print(e)\n return False\n\n result = self.query(addMetadataQuery, params=\"_update/%s\" % (doc_id))\n return result\n\n def update_metadata(self, doc_id, metadata, alternatives=[]):\n \"\"\"Update metadata to existing document\n\n Args:\n doc_id (string): Document id on ElasticSearch\n metadata (object): Metadata object\n\n Returns:\n object: Response from ElasticSearch\n \"\"\"\n\n # Get metadata\n oldMetadata = self.get_metadata(doc_id, metadata)\n\n if oldMetadata == False:\n return False\n\n # Loop throw alternatives array\n for alternative in alternatives:\n # Check if providerData contains providerID\n if self.get_metadata(doc_id, alternative) == False:\n # If not exists add to metadata array object with providerInfo { providerID, providerName }\n alternative[\"UUID\"] = metadata[\"UUID\"]\n self.add_metadata(doc_id, alternative)\n\n try:\n # Iterate over metadata\n for key, value in list(metadata.items()):\n\n # If metadata value is list don't override\n if type(value) is list:\n for item in value:\n # If type is equal to SCHED add if not exists and keep the others\n if str(item.get(\"type\")) == \"SCHED\":\n # Iterate on object\n for keyObj, valueObj in list(item.items()):\n if keyObj != \"type\" and keyObj != \"lastUpdate\":\n # Check if same element with value is found\n found = list(\n filter(lambda obj: obj[keyObj] == valueObj, oldMetadata[key]))\n if len(found) == 0:\n # Add lastUpdate\n item[\"lastUpdate\"] = self.get_timestamp()\n oldMetadata[\"lastUpdate\"] = self.get_timestamp(\n )\n\n # Append to array if not found\n oldMetadata[key].append(item)\n\n # If type is equal to ENRICH replace all ENRICH with the new item\n elif str(item.get(\"type\")) == \"ENRICH\":\n\n # Filter out all objects with type ENRICH\n others = list(filter(lambda obj: str(\n obj.get(\"type\")) != \"ENRICH\", oldMetadata[key]))\n\n # Append new item\n others.append(item)\n oldMetadata[key] = others\n\n # Set is_enriched flag to true\n self.update_document(doc_id, {\"is_enriched\": True})\n\n # If no type is specified add if not exists\n else:\n # Iterate on object\n for keyObj, valueObj in list(item.items()):\n\n # Check if same element with value is found\n found = list(\n filter(lambda obj: obj[keyObj] == valueObj, oldMetadata[key]))\n if len(found) == 0:\n # Append to array if not found\n oldMetadata[key].append(item)\n\n # If metadata value is dictionary\n elif type(value) is dict:\n for keyObj, valueObj in value.items():\n oldMetadata[key][keyObj] = valueObj\n\n # If metadata value is string\n elif type(value) is str:\n oldMetadata[key] = value\n\n # If metadata value is boolean\n elif type(value) is bool:\n oldMetadata[key] = value\n\n updateMetadataQuery = {\n \"script\": {\n \"source\": \"\"\"\n def targets = ctx._source.providerData.findAll(data -> data.providerInfo.providerID == params.providerInfo.providerID);\n for(data in targets) {\n for(metadata in data.entrySet()){\n if(params.containsKey(metadata.getKey())){\n data[metadata.getKey()] = params[metadata.getKey()]\n }\n }\n }\n ctx._source.lastUpdate = params[\"lastUpdate\"]\n \"\"\",\n \"params\": oldMetadata\n }\n }\n\n result = self.query(updateMetadataQuery,\n params=\"_update/%s\" % (doc_id))\n\n except Exception as e:\n print(e)\n return False\n\n return True\n\n def delete_metadata(self, doc_id, metadata):\n \"\"\"Delete metadata from object\n\n Args:\n doc_id (string): Document ID on ElasticSearch\n metadata (object): Metadata object\n\n Returns:\n object: Response from ElasticSearch\n \"\"\"\n deleteMetadataQuery = {\n \"script\": {\n \"source\": \"ctx._source.providerData.removeIf(data -> data.providerInfo.providerID == params.providerInfo.providerID)\",\n \"params\": metadata\n }\n }\n result = self.query(deleteMetadataQuery,\n params=\"_update/%s\" % (doc_id))\n return result\n\n def _filter_metadata(self, metadata_source, metadata_match) -> bool:\n \"\"\"Filter metadata function\n\n Args:\n metadata_source (object): Metadata source object\n metadata_match (object): Metadata to match\n\n Returns:\n bool: True if object has the same providerID\n \"\"\"\n if metadata_source[\"providerInfo\"][\"providerID\"] == metadata_match[\"providerInfo\"][\"providerID\"]:\n return True\n else:\n return False\n\n def get_metadata(self, doc_id, metadata_match):\n \"\"\"Get single metadata from document\n\n Args:\n doc_id (string): Document ID\n metadata_match (object): Metadata match object (with providerID)\n\n Returns:\n object: Metadata object\n \"\"\"\n # Get document\n doc = self.get_document(doc_id)\n\n # Filter metadata\n source_metadata_object = list(\n filter(lambda obj: self._filter_metadata(obj, metadata_match), doc[\"providerData\"]))\n\n if(len(source_metadata_object) == 1):\n return source_metadata_object[0]\n else:\n return False\n\n def get_document_by_UUID(self, masterUUID):\n \"\"\"Get document by UUID\n\n Args:\n masterUUID (string): Master UUID\n\n Returns:\n object: ES object\n \"\"\"\n\n # Create query by masterUUID\n queryUUID = {\n \"query\": {\n \"match\": {\n \"masterUUID\": masterUUID\n }\n }\n }\n\n # Query ES\n result = self.query(queryUUID, params=\"_search\")\n\n # If document is found\n if(len(result[\"hits\"][\"hits\"]) != 0):\n document = result[\"hits\"][\"hits\"][0][\"_source\"]\n else:\n document = False\n\n return document\n\n def get_document_id_by_UUID(self, masterUUID):\n queryUUID = {\n \"query\": {\n \"match\": {\n \"masterUUID\": masterUUID\n }\n }\n }\n\n # Get document ID\n result = self.query(queryUUID, params=\"_search\")\n\n # If document is found\n if(len(result[\"hits\"][\"hits\"]) != 0):\n doc_id = result[\"hits\"][\"hits\"][0][\"_id\"]\n else:\n doc_id = False\n\n return doc_id\n\n def update_document_by_UUID(self, masterUUID, values):\n doc_id = self.get_document_id_by_UUID(masterUUID)\n\n result = self.update_document(doc_id, values)\n\n return result\n\n def add_metadata_by_UUID(self, masterUUID, metadata):\n queryUUID = {\n \"query\": {\n \"match\": {\n \"masterUUID\": masterUUID\n }\n },\n \"script\": {\n \"source\": \"ctx._source.providerData.add(params)\",\n \"params\": metadata\n }\n }\n\n return self.query(queryUUID, params=\"_update_by_query\")\n\n def delete_metadata_by_UUID(self, masterUUID, UUID):\n removeQueryUUID = {\n \"query\": {\n \"match\": {\n \"masterUUID\": masterUUID\n }\n },\n \"script\": {\n \"source\": \"ctx._source.providerData.removeIf(data -> data.UUID == params.UUID)\",\n \"params\": {\n \"UUID\": UUID\n }\n }\n }\n\n return self.query(removeQueryUUID, params=\"_update_by_query\")\n\n def move_metadata_to_existing(self, source_doc_id, dest_doc_id, metadata) -> bool:\n \"\"\"Move metadata to existing document\n\n Args:\n source_doc_id (string): Source document ID\n dest_doc_id (string): Destination document ID\n metadata (object): Metadata Object\n \"\"\"\n\n try:\n # Delete metadata from ES document\n self.delete_metadata(\n source_doc_id, metadata[\"providerInfo\"][\"providerID\"])\n\n # Add metadata to destination ES document\n self.add_metadata(dest_doc_id, metadata)\n\n return True\n except:\n return False\n\n def move_metadata_to_new(self, source_doc_id, dest_UUID, metadata):\n \"\"\"Move metadata to existing document\n\n Args:\n source_doc_id (string): Source document ID\n dest_UUID (string): Destination Master UUID\n metadata (object): Metadata Object\n \"\"\"\n\n # Delete metadata from source_doc_id\n self.delete_metadata(\n source_doc_id, metadata[\"providerInfo\"][\"providerID\"])\n\n # Create document and return document ID\n return self.create_document(dest_UUID, metadata)\n","sub_path":"layers/elasticsearch_metadata/python/elasticsearch_metadata/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"442387609","text":"# Basic Data types challenge - 1 : letter counter program\n\n#greeter\nprint(\"Welcome to the letter counter app\")\n\n#user input\nname = input('Enter your name : ')\nprint(\"Hello\",name)\nprint(\"Enter the message and corresponding letter you want to count\")\nmsg = input('Enter your message : ')\nchar = input('Enter the letter : ')\n\n#standardize to lower case \nmsg = msg.lower()\nchar = char.lower()\n\n#count characters\ncount = 0\nfor i in msg :\n if i == char :\n count += 1\n \n#print output\nprint(\"{},your msg has {}'s {} in it\".format(name,count,char))\n","sub_path":"UdemyCourse - 40 projects/LetterCounter.py","file_name":"LetterCounter.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483761469","text":"#!/usr/bin/env python3\n\"\"\"Class Initialize Bayesian Optimization\"\"\"\nimport numpy as np\nGP = __import__('2-gp').GaussianProcess\n\n\nclass BayesianOptimization:\n \"\"\"performs Bayesian optimization on a noiseless 1D Gaussian process\"\"\"\n def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1,\n sigma_f=1, xsi=0.01, minimize=True):\n self.f = f\n self.gp = GP(X_init, Y_init, l, sigma_f)\n X_s = np.linspace(bounds[0], bounds[1], num=ac_samples)\n self.X_s = (np.sort(X_s)).reshape(-1, 1)\n self.xsi = xsi\n self.minimize = minimize\n","sub_path":"unsupervised_learning/0x03-hyperparameter_tuning/3-bayes_opt.py","file_name":"3-bayes_opt.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249286969","text":"from django.shortcuts import render , get_object_or_404\nfrom django.http import HttpResponse\nfrom . import models\nfrom django.db.models import Avg\nfrom . import forms\nfrom django.views.generic import FormMixn\n\n\ndef index(request):\n context={}\n return render(request,r'main\\index.html',context)\n\ndef Restaurants(request):\n qs=models.Restaurant.objects.all()\n \n f=request.GET['filter']\n r=request.GET['reverse']\n\n if f=='a2z' and r=='0':\n qs=qs.order_by('name')\n elif f=='a2z' and r=='1':\n qs=qs.order_by('-name')\n elif f=='rating' and r=='0':\n qs=qs.annotate(average_rating=Avg('review__rating')).order_by('average_rating')\n elif f=='rating' and r=='1':\n qs=qs.annotate(average_rating=Avg('review__rating')).order_by('-average_rating')\n\n\n print(request.GET)\n context={\n 'qs' :qs,\n 'r':r,\n 'f':f\n }\n return render(request,r'main\\restaurants.html',context )\ndef add_rest(request):\n if request.method == \"GET\":\n form = forms.RestaurantForm()\n else:\n form = forms.RestaurantForm(request.POST)\n\n if form.is_valid():\n obj = form.save()\n return HttpResponse(\"Form Added with id \" + str(obj.pk))\n\n context = {\n 'form': form\n }\n return render(request, r'main/addRestaurant.html', context)\n\ndef restaurant(request, id):\n \n rest = get_object_or_404(models.Restaurant, pk = id)\n success = False\n \n # Handling the form\n if request.method == \"GET\":\n form = forms.ReviewForm()\n else:\n form = forms.ReviewForm(request.POST)\n if form.is_valid():\n obj = form.save(commit = False)\n obj.restaurant = rest\n obj.save()\n success = True\n form = forms.ReviewForm()\n\n context = {\n 'restaurant': rest,\n 'form': form,\n 'success': success\n }\n return render(request, r'main\\restaurant.html', context)\n\ndef review(request, id):\n obj = get_object_or_404(models.Review, pk = id)\n\n context = {\n 'review': obj\n }\n return render(request, r'main/review.html', context)\n\n\n\n","sub_path":"Lecture_10/zomato/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125338018","text":"#1\ntekst=\"Czym jest Lorem Impsum\"\nprint(tekst)\n#2\nimie=\"Krystian\"\nnazwisko=\"Nagadowski\"\nliczba_liter1=imie.count(imie[1])\nliczba_liter2=nazwisko.count(nazwisko[2])\nprint(f\"W tekście jest {liczba_liter1} liter oraz {liczba_liter2}\")\n#4\n#tekst1='Tomek w krainie kangurów'\n#print(dir(tekst1))\n#help(tekst1.format_map())\n#5\nprint(imie[::-1].capitalize() + \" \" + nazwisko[::-1].capitalize())\n#6\nlista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nlista1=lista[0:5]\nlista2=lista[5:11]\n#7\nlista1.extend(lista2)\nlista1.insert(0,0)\nlista_copy=lista1.copy()\nlista_copy.sort(reverse=True)\nprint(lista_copy)\n#8\npierwszy = (123532,'Adam','Kowalski')\ndrugi = (335643,'Euzebiusz','Smolarek')\nlista_studentow = []\nlista_studentow.append(pierwszy)\nlista_studentow.append(drugi)\nprint(lista_studentow)\n#9\nstudent1 = {'imie':'Adam','nazwisko':'Kowalski','nrIndeksu':123532,'wiek':22,'adres e-mail':\"kowalski1230@wp.pl\",'Adres zamieszkania':'Piłsudskiego 25/3'}\nstudent2 = {'imie':'Euzebiusz','nazwisko':'Smolarek','nrIndeksu':335643,'wiek':31,'adres e-mail':\"smolariusz@wp.pl\",'Adres zamieszkania':'Mickiewicza 5'}\nstudent3 = {'imie':'Mariusz','nazwisko':'Kołowrotek','nrIndeksu':666333,'wiek':55,'adres e-mail':\"kołowrotek@interia.pl\",'Adres zamieszkania':'Słoneczna 12'}\n#10\nnumery=[333221523,333221532,999324563,333221523]\nnumery=set(numery)\nprint(numery)\n#11\nfor i in range(11):\n print(i)\nprint()\n#12\nfor j in range(100,19,-5):\n print(j)\n","sub_path":"zadania/1 i 2/PSI1.py","file_name":"PSI1.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"222210472","text":"import os\n# import sys\n\n\n# project path\nproject_path = os.path.dirname(os.getcwd())\n\n\n# class file path\n\n\n# main file path\nmain_file_path = os.path.join(project_path + os.sep + 'core' + os.sep + 'core')\n\n\n# Data file path\nDataFilePath = os.path.join(project_path + os.sep + 'data' + os.sep)\n\n# Data filename\nF_sch = 'school'\nF_cou = 'course'\nF_cla = 'class'\nF_user = 'user'\nF_tea = 'teacher'\nF_stu = 'student'\n\n","sub_path":"Basis_of_Python/201706week/Subject_System/conf/Settings.py","file_name":"Settings.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"218163478","text":"import socket\r\nfrom multiprocessing import *\r\n \r\n \r\ns = socket.socket()\r\nhost = socket.gethostname()\r\ns.bind((host,1234))\r\ns.listen(100)\r\nprint(\"Waiting for connection......\")\r\n \r\ndef tcplink(sock,addr):\r\n print(\"Accept new connection from %s:%s\" % addr)\r\n data = sock.recv(1024)\r\n i = int(data)\r\n sock.send(bytes(str(i*i*i*i), encoding = 'utf8'))\r\n sock.close()\r\n print(\"connection closed!\")\r\n \r\nwhile True:\r\n sock, addr = s.accept()\r\n t = Process(target = tcplink, args = (sock,addr))\r\n t.start()\r\n","sub_path":"计试81_白思雨_2186123935_操作系统作业/第四章_白思雨_计试81_2186123935/server_process.py","file_name":"server_process.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"602019728","text":"from __future__ import print_function\nimport math\nimport random\nfrom simanneal import Annealer\nimport networkx as nx\n\n\ndef distance(a, b):\n \"\"\"Calculates distance between two latitude-longitude coordinates.\"\"\"\n R = 3963 # radius of Earth (miles)\n lat1, lon1 = math.radians(a[0]), math.radians(a[1])\n lat2, lon2 = math.radians(b[0]), math.radians(b[1])\n return math.acos(math.sin(lat1) * math.sin(lat2) +\n math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2)) * R\n\n\nclass TravellingSalesmanProblem(Annealer):\n\n \"\"\"Test annealer with a travelling salesman problem.\n \"\"\"\n \n # pass extra data (the distance matrix) into the constructor\n def __init__(self, state, distance_matrix):\n self.distance_matrix = distance_matrix\n super(TravellingSalesmanProblem, self).__init__(state) # important! \n\n def move(self):\n \"\"\"Swaps two cities in the route.\"\"\"\n a = random.randint(0, len(self.state) - 1)#\n b = random.randint(0, len(self.state) - 1)\n self.state[a], self.state[b] = self.state[b], self.state[a]\n\n def energy(self):\n \"\"\"Calculates the length of the route.\"\"\"\n e = 0\n for i in range(len(self.state)):\n e += self.distance_matrix[self.state[i-1]][self.state[i]]\n return e\n\nclass recalculatebySA(Annealer):\n def distance(self , tpath ,graph):\n '''\n cost+=graph[][]['cost']\n '''\n if len(tpath) == 2:\n return self.graph[tpath[0]][tpath[1]]['cost']\n if len(tpath) == 1:\n return 0\n \n else:\n cost = 0\n for i in (0,len(tpath)-2):\n cost = cost + self.graph[tpath[i]][tpath[i+1]]['cost']\n return cost\n def __init__(self , state , graph):\n self.graph = graph\n self.path = {}\n self.flow = {}\n super(recalculatebySA, self).__init__(state) \n def move(self):\n #2 method to move ?!? \n '''\n for flowkey in self.flow.keys():\n self.state[flowkey] = self.path[flowkey][random.randint(0, len(self.path[flowkey]) - 1)]\n '''\n #random select a key\n #'''\n li = list(self.flow.keys())\n flowkey = li[random.randint(0, len(li) - 1)]\n #random select a path\n self.state[flowkey] = self.path[flowkey][random.randint(0, len(self.path[flowkey]) - 1)]\n #'''\n\n\n def energy(self):\n '''\n all the cost\n '''\n e = 0\n for flowkey in self.flow.keys():\n e = e + self.distance(self.state[flowkey] , self.graph)\n\n return e\n\n\n\nif __name__ == '__main__':\n '''\n test function\n '''\n # init a graph\n g = nx.Graph()\n g.add_edge(1,2,weight=1)\n g.add_edge(1,3,weight=1)\n g.add_edge(2,4,weight=1)\n g.add_edge(3,4,weight=1)\n g[1][2]['cost'] = 2\n g[1][3]['cost'] = 2\n g[2][4]['cost'] = 2\n g[3][4]['cost'] = 2\n g.add_edge(2,3,weight=1)\n g[2][3]['cost'] = 3\n\n #init some flows\n flow = {}\n path = {}\n selectpath = {}\n app = []\n '''\n for a in nx.shortest_simple_paths(g, source=1,target=4, weight='cost'):\n app.append(a)\n print (app)\n '''\n flow[('10.0.0.1','10.0.0.4')] = {'ip_src':'10.0.0.1','ip_dst':'10.0.0.4','src':1,'dst':4} \n flow[('10.0.0.2','10.0.0.3')] = {'ip_src':'10.0.0.2','ip_dst':'10.0.0.3','src':2,'dst':3} \n flow[('10.0.0.4','10.0.0.2')] = {'ip_src':'10.0.0.4','ip_dst':'10.0.0.2','src':4,'dst':2} \n flow[('10.0.0.4','10.0.0.1')] = {'ip_src':'10.0.0.4','ip_dst':'10.0.0.1','src':4,'dst':1} \n flow[('10.0.0.3','10.0.0.4')] = {'ip_src':'10.0.0.3','ip_dst':'10.0.0.4','src':3,'dst':4} \n for flowkey in flow.keys():\n '''\n generator must change to list or dict\n '''\n path[flowkey] = []\n for a in nx.shortest_simple_paths(g, source=flow[flowkey]['src'],\n target=flow[flowkey]['dst'], weight='cost'):\n path[flowkey].append(a)\n for flowkey in flow:\n selectpath[flowkey] = path[flowkey][random.randint(0, len(path[flowkey]) - 1)]\n #print self.selectpath[flowkey]\n tsp = recalculatebySA(selectpath , g )\n tsp.path = path\n tsp.flow = flow\n tsp.copy_strategy = \"method\"\n state, e = tsp.anneal()\n print (selectpath)\n print (\"cost %d\" % e )\n print (state)\n \"\"\"\n state results are wrong but the enegry ,or the cost is right\n cost 15\n {('10.0.0.2', '10.0.0.3'): [2, 3], ('10.0.0.1', '10.0.0.4'): [1, 3, 2, 4], ('10.0.0.4', '10.0.0.2'): [4, 2],\n ('10.0.0.3' , '10.0.0.4'): [3, 4], ('10.0.0.4', '10.0.0.1'): [4, 2, 1]}\n 3+7+2+2+4???\n \"\"\"\n\n # initial state, a randomly-ordered itinerary\n # init_state = list(cities.keys())\n # random.shuffle(init_state)\n\n # # create a distance matrix\n # distance_matrix = {}\n # for ka, va in cities.items():\n # distance_matrix[ka] = {}\n # for kb, vb in cities.items():\n # if kb == ka:\n # distance_matrix[ka][kb] = 0.0\n # else:\n # distance_matrix[ka][kb] = distance(va, vb)\n\n # initial_state = ['Phoenix','Columbus','Charlotte','New York City', 'Los Angeles', 'Houston']\n # tsp = TravellingSalesmanProblem(init_state, distance_matrix)\n # # since our state is just a list, slice is the fastest way to copy\n # tsp.copy_strategy = \"slice\" \n # state, e = tsp.anneal()\n\n # while state[0] != 'New York City':\n # state = state[1:] + state[:1] # rotate NYC to start\n # print(\"%i mile route:\" % e)\n # for city in state:\n # print(\"\\t\", city)\n\n","sub_path":"examples/salesman.py","file_name":"salesman.py","file_ext":"py","file_size_in_byte":5656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"591958706","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 4 # antall grafer\nslow_tid_needle100k = (65.28, 71.89, 43.54, 44.62) # Setter verdiene til grafen.\n\n\nind = np.arange(N)\nwidth = 0.35 # setter bredden på grafen.\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(ind, slow_tid_needle100k, width, color='r')\n\nslow_tid_needle900k = (60.88, 71.31, 41.27, 43.98)\n\nrects2 = ax.bar(ind + width, slow_tid_needle900k, width, color='b')\n\nax.set_ylabel('Tid i sekunder * 100') # navngir Y aksen\nax.set_title('Search_Slow Algoritme - Haystack = 1 million') # navngir tittelen\nax.set_xticks(ind + width)\nax.set_xticklabels(('Magnus', 'Erik', 'Mohammad/John/Eirik', 'Per')) #navngir hver graf.\n\nax.legend((rects1[0], rects2[0]), ('Needle=100k', 'Needle=900k'))\n\n\ndef autolabel(rects): #metode som lager grafene. \n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2., 5.05*height,\n '%d' % int(height),\n ha='center', va='bottom')\n\nautolabel(rects1)\nautolabel(rects2)\n\nplt.show()\n\n#\"\"\"\n#Referanse:\n#http://matplotlib.org/examples/api/barchart_demo.html\n#\"\"\"\n","sub_path":"ICA05/OppgaveC/SlowGammel.py","file_name":"SlowGammel.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"148789973","text":"import requests\nfrom auth import *\n\naccess_token = token()\n\ndata_inicio = '2021-01-14T16:01:35Z'\ndata_fim = '2021-01-15T16:01:35Z'\n\nendpoint= f'{url}v2/cob?inicio={data_inicio}&fim={data_fim}'\n\npayload={}\n\nheaders = {\n 'authorization': f'Bearer {access_token}',\n 'Content-Type': 'application/json'\n}\n\nresponse = requests.request(\"GET\", endpoint, headers=headers, data=payload, cert=cert)\n\nprint(response.text.encode('utf8'))\n","sub_path":"consultar_lista_cobrancas.py","file_name":"consultar_lista_cobrancas.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288498405","text":"__author__ = 'marcotagliabue'\n\nimport sys\nimport logging\n\nimport pymongo\nfrom pymongo.errors import DuplicateKeyError\nimport configuration\n\nclass MongoManager():\n def __init__(self, name_db):\n \"\"\"This will be called each time we receive stream data\"\"\"\n client = pymongo.MongoClient(configuration.address_local, configuration.port_local)\n self.db = client[name_db]\n\n def write_mongo(self, collection, data):\n try:\n return self.db[collection].insert(data)\n except DuplicateKeyError as e:\n pass\n #logging.error(\"\")\n\n def write_mongo_no_duplicates(self, collection, data, unique_key):\n self.db[collection].update({unique_key: data[unique_key]}, data, upsert=True)\n\n def find_one(self, collection):\n return self.db[collection].find_one()\n\n def find(self, collection, query, limite=sys.maxsize,project={}):\n return self.db[collection].find(query)\n\n def delete_element(self, collection, query):\n return self.db[collection].delete_many(query)\n\n def update(self, collection, query, data):\n return self.db[collection].update(query, data, True)\n\n def aggregate(self, collection, query):\n return self.db[collection].aggregate(query)\n\n def drop_collection(self, collection):\n return self.db.drop_collection(collection)\n \n def get_dandelion_keys(self):\n query = {\n \"service\":\"dandelion\"\n }\n return self.db[\"application_keys\"].find(query)\n \n def get_twitter_keys(self):\n query = {\n \"service\":\"twitter\"\n }\n return self.db[\"application_keys\"].find(query)\n \n # Avoid duplicates based on the key\n def create_index(self, collection, key):\n unique = True\n self.db[collection].create_index(key, unique=unique)\n\n def delete_one(self, collection, query):\n result = self.db[collection].delete_one(query)\n if (result.deleted_count > 0):\n return True\n else:\n return False\n\n def delete_many(self, collection, query):\n result = self.db[collection].delete_many(query)\n if (result.deleted_count > 0):\n return True\n else:\n return False\n \n # knowledge extractor pipeline method\n def getExpertTypes(self,experimentId):\n collection=\"experiment\"\n query={\n \"_id\":experimentId\n }\n experiment = list(self.find(collection,query,project={\"expert_types\":1}))[0]\n return experiment[\"expert_types\"]\n\n def getSeeds(self,query):\n collection = \"seeds\"\n query.update({\"hub\":False})\n return list(self.find(collection,query))\n \n def getHubs(self,query):\n collection = \"seeds\"\n query.update({\"hub\":True})\n return list(self.find(collection,query))\n\n def getCandidates(self,query):\n collection = \"rank_candidates\"\n return list(self.find(collection,query))\n\n def getMentions(self,query):\n collection = \"entity\"\n return self.find(collection,query,project={\"spot\":1,\"types\":1,\"label\":1})\n \n def getMentionType(self,query):\n collection = \"entity\"\n return self.find(collection,query,project={\"types\":1})\n\n def saveScores(self,scores,id_experiment):\n collection = \"rankings\"\n for k,v in scores.items():\n score = {\n \"handle\":k,\n \"score\":v,\n \"experiment_id\":id_experiment\n }\n self.write_mongo(collection,score)\n \n def getExperiment(self,experiment_id):\n collection = \"experiment\"\n query={\n \"_id\":experiment_id\n }\n return self.find(collection,query)\n \n def getResults(self,experiment_id,limit=False,skip=None):\n collection = \"rankings\"\n query = {\n \"experiment_id\":experiment_id,\n \"score\":{\"$ne\":float('nan')}\n }\n if(limit):\n if(skip!=None):\n return self.find(collection,query).sort(\"score\",-1).limit(20).skip(skip)\n\n return self.find(collection,query).sort(\"score\",-1).limit(20)\n else:\n return self.find(collection,query).sort(\"score\",-1)\n \n def register_evaluation(self,query,update):\n collection=\"evaluation\"\n return self.db[collection].update(query,update,upsert=True)\n \n def get_evaluations(self,experiment_id):\n collection=\"evaluation\"\n query = {\n \"experiment\":experiment_id\n }\n return self.find(collection,query)\n \n def get_user_twitter_tokens(self,experiment_id):\n experiment = list(self.getExperiment(experiment_id))[0]\n user_id = experiment[\"user_id\"]\n query = {\n \"_id\":user_id\n }\n user = list(self.find(\"auth_users\",query))[0]\n tokens = {\n \"access_token\":user[\"access_token\"],\n \"access_token_secret\":user[\"access_token_secret\"]\n }\n return tokens\n\n def update_user_twitter(self,user_id,access_token,access_token_secret,profile_img):\n collection=\"auth_users\"\n query={\n \"_id\":user_id\n }\n update={\n \"$set\":{\n \"access_token\":access_token,\n \"access_token_secret\":access_token_secret,\n \"profile_img\":profile_img\n }\n }\n return self.db[collection].update(query,update)\n \n def get_recipe(self,name):\n collection = \"recipe\"\n query = {\n \"name\":name\n }\n return self.find(collection,query)\n \n def store_seeds(self,seeds,experiment_id):\n collection = \"seeds\"\n for seed in seeds:\n s = {\n \"id_experiment\":experiment_id,\n \"starting\":True,\n \"hub\":False,\n \"handle\":seed\n }\n self.db[collection].insert(s)\n\n def store_feature_ast_vector(self,fv,experiment_id):\n collection = \"seeds\"\n for handle,row in fv.itertuples():\n query={\n \"id_experiment\":experiment_id,\n \"handle\":handle\n }\n update={\n \"$set\":{\n \"fv\":row\n }\n }\n return self.db[collection].update(query,update)\n\n def store_hubs(self,hubs,experiment_id):\n collection = \"seeds\"\n for hub in hubs:\n h = {\n \"id_experiment\":experiment_id,\n \"starting\":True,\n \"hub\":True,\n \"handle\":hub\n }\n self.db[collection].insert(h)\n \n def store_candidates(self,candidates,experiment_id):\n collection = \"seeds\"\n for cand in candidates:\n c = {\n \"id_experiment\":experiment_id,\n \"starting\":False,\n \"hub\":False,\n \"handle\":cand[\"handle\"],\n \"origin\":cand[\"origin\"]\n }\n self.db[collection].insert(c)\n \n def get_unranked_candidates(self,experiment_id):\n collection = \"seeds\"\n query = {\n \"id_experiment\":experiment_id,\n \"starting\":False,\n \"hub\":False\n }\n return list(self.find(collection,query))\n\n def get_mentions_by_type(self,experiment_id,type_name,confidence,seed_ids):\n collection = \"entity\"\n query = {\n \"id_experiment\":experiment_id,\n \"concrete_types\":type_name,\n \"confidence\":{\"$gt\":confidence},\n \"seed\":{\"$in\":seed_ids}\n }\n aggregation=[\n {\n \"$match\":query\n },\n {\n \"$group\":{\n \"_id\":{\n \"spot\":\"$spot\",\n \"title\":\"$title\"\n },\n \"uri\":{\n \"$first\":\"$uri\"\n },\n \"title\":{\n \"$first\":\"$title\"\n }\n }\n }\n ]\n #return list(self.db[collection].find(query,{\"_id\":0,\"tweet\":0,\"seed\":0,\"id_experiment\":0}).distinct(\"spot\"))\n return list(self.db[collection].aggregate(aggregation))\n \n def get_mention_count_all(self,experiment_id):\n collection = \"entity\"\n query = ([{\"$match\":{\"id_experiment\":experiment_id,\"types\":{\"$not\":{\"$size\":0}}}},{\"$project\":{\"seed\":1,\"types\":{\"$slice\":[\"$types\",1]}}},{\"$unwind\":\"$types\"},{\"$group\":{_id:\"$types\",count:{\"$sum\":1}}},{\"$sort\":{count:-1}}])\n return list(self.db[collection].aggregate(query))[:10]\n \n def get_mention_count_by_seeds(self,experiment_id,seed_ids,ontology):\n collection = \"entity\"\n query = ([{\"$match\":{\"confidence\":{\"$gt\":0.6},\"id_experiment\":experiment_id,\"seed\":{\"$in\":seed_ids},\"concrete_types\":{\"$not\":{\"$size\":0}}}},{\"$project\":{\"seed\":1,\"concrete_types\":1}},{\"$unwind\":\"$concrete_types\"},{\"$match\":{\"concrete_types\":{\"$nin\":[\"http://dbpedia.org/ontology/Location\",\"http://dbpedia.org/ontology/Wikidata:Q11424\",\"http://dbpedia.org/ontology/Jurisdiction>\"]}}},{\"$group\":{\"_id\":\"$concrete_types\",\"count\":{\"$sum\":1}}},{\"$sort\":{\"count\":-1}}])\n #query = ([{\"$match\":{\"confidence\":{\"$gt\":0.6},\"id_experiment\":experiment_id,\"seed\":{\"$in\":seed_ids},\"leaf_types\":{\"$not\":{\"$size\":0}}}},{\"$project\":{\"seed\":1,\"leaf_types\":1}},{\"$unwind\":\"$leaf_types\"},{\"$group\":{\"_id\":\"$leaf_types\",\"count\":{\"$sum\":1}}},{\"$sort\":{\"count\":-1}}])\n return list(self.db[collection].aggregate(query))[:10]\n \n def get_seed_name(self,seed_id):\n collection = \"tweets\"\n query = {\n \"seed\":seed_id\n }\n tweets = list(self.db[collection].find(query))\n\n # some seeds may not have any tweets (tweets rate limit exceeded)\n if(len(tweets)>0):\n return tweets[0][\"user\"][\"name\"]\n else:\n return None\n\nif __name__ == '__main__':\n db_manager = MongoManager(configuration.db_name)\n","sub_path":"utils/mongo_manager.py","file_name":"mongo_manager.py","file_ext":"py","file_size_in_byte":10019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147121221","text":"import cv2\nimport glob\nimport os\nimport numpy as np\nix, iy = -1, -1\n'''标注框保存结果为 \n值范围为[0,1],为相对图像大小的比例\n'''\n\n\n# 目标框标注程序\nclass CLabeled:\n def __init__(self, image_folder):\n # 存放需要标注图像的文件夹\n self.image_folder = image_folder\n # 需要标注图像的总数量\n self.total_image_number = 0\n # 需要标注图像的地址列表\n self.images_list = list()\n # 当前标注图片的索引号,也是已标注图片的数量\n self.current_label_index = 0\n # 待标注图片\n self.image = None\n # 目标框的分类索引号\n self.label_index = 0\n # 当前图片\n self.current_image = None\n # 标注框的保存文件地址\n self.label_path = None\n # 记录历史标注位置的文本文件地址\n self.checkpoint_path = os.path.join(image_folder, \"checkpoint\")\n # 标注框信息\n self.boxes = list()\n # 图像宽\n self.width = 320\n # 图像高\n self.height = 288\n # 显示窗口的名称\n self.windows_name = \"image\"\n self.labeled()\n\n # 重置\n def _reset(self):\n self.image = None\n self.current_image = None\n self.label_path = None\n self.boxes = list()\n\n # 统计所有图片个数\n def _compute_total_image_number(self):\n self.total_image_number = len(self.images_list)\n\n # 当前标注位置倒退一个\n def _backward(self):\n self.current_label_index -= 1\n self.current_label_index = max(0, self.current_label_index)\n\n # 限定鼠标坐标区域的大小\n def _roi_limit(self, x, y):\n if x < 0:\n x = 0\n if y < 0:\n y = 0\n if x > self.width:\n x = self.width\n if y > self.height:\n y = self.height\n return x, y\n\n # 标注感兴趣区域\n def _draw_roi(self, event, x, y, flags, param, mode=True):\n global ix, iy\n dst = self.image.copy()\n self._draw_box_on_image(dst, self.boxes)\n if event == cv2.EVENT_LBUTTONDOWN: # 按下鼠标左键\n x, y = self._roi_limit(x, y)\n ix, iy = x, y\n cv2.imshow(self.windows_name, dst)\n elif event == cv2.EVENT_MOUSEMOVE and not (flags and cv2.EVENT_FLAG_LBUTTON): # 鼠标移动\n x, y = self._roi_limit(x, y)\n if mode:\n cv2.line(dst, (x, 0), (x, self.height), (255, 0, 0), 1, 8, )\n cv2.line(dst, (0, y), (self.width, y), (255, 0, 0), 1, 8)\n else:\n cv2.circle(dst, (x, y), 5, (0, 0, 255), -1)\n cv2.imshow(self.windows_name, dst)\n elif event == cv2.EVENT_MOUSEMOVE and (flags and cv2.EVENT_FLAG_LBUTTON): # 按住鼠标左键进行移动\n x, y = self._roi_limit(x, y)\n if mode:\n cv2.rectangle(dst, (ix, iy), (x, y), (0, 255, 0), 2)\n else:\n cv2.circle(dst, (x, y), 5, (0, 0, 255), -1)\n cv2.imshow(self.windows_name, dst)\n elif event == cv2.EVENT_LBUTTONUP: # 鼠标左键松开\n x, y = self._roi_limit(x, y)\n if mode:\n if abs(x - ix) > 10 and abs(y - iy) > 10:\n cv2.rectangle(self.current_image, (ix, iy), (x, y), (0, 255, 0), 2)\n self.boxes.append([ix/self.width, iy/self.height, x/self.width, y/self.height])\n else:\n cv2.circle(self.current_image, (x, y), 5, (0, 0, 255), -1)\n # print(self.boxes)\n cv2.imshow(self.windows_name, self.current_image)\n elif event == cv2.EVENT_RBUTTONDOWN: # 撤销上一次标注\n self.current_image = self.image.copy()\n if len(self.boxes):\n del self.boxes[-1]\n self._draw_box_on_image(self.current_image, self.boxes)\n\n # 将标注框显示到图像上\n def _draw_box_on_image(self, image, boxes):\n for box in boxes:\n pt1 = (int(image.shape[1] * box[0]), int(image.shape[0] * box[1]))\n pt2 = (int(image.shape[1] * box[2]), int(image.shape[0] * box[3]))\n cv2.rectangle(image, pt1, pt2, (0, 0, 255), 2)\n cv2.imshow(self.windows_name, image)\n\n # 从文本读取标注框信息\n def read_label_file(self, label_file_path):\n boxes = []\n with open(label_file_path) as label_file:\n for line in label_file:\n x, y, w, h = [float(e) for e in line.strip().split()][1:]\n x1 = x - w / 2\n y1 = y - h / 2\n x2 = x + w / 2\n y2 = y + h / 2\n x1 = max(x1, 0)\n y1 = max(y1, 0)\n x2 = min(x2, 1)\n y2 = min(y2, 1)\n box = [x1, y1, x2, y2]\n boxes.append(box)\n self.boxes = boxes\n\n # 将标注框信息保存到文本\n def write_label_file(self, label_file_path, boxes, label_index):\n label_file = open(label_file_path, \"w\")\n for box in boxes:\n if box[0] > box[2]:\n temp = box[0]\n box[0] = box[2]\n box[2] = temp\n if box[1] > box[3]:\n temp = box[1]\n box[1] = box[3]\n box[3] = temp\n center_x = (box[0]+box[2])/2\n center_y = (box[1]+box[3])/2\n width = box[2]-box[0]\n height = box[3]-box[1]\n label_file.writelines(\"{} {} {} {} {}\\n\".format(label_index, center_x, center_y, width, height))\n label_file.close()\n\n # 记录当前已标注位置,写到文本\n def write_checkpoint(self, checkpoint_path):\n if not os.path.exists(os.path.dirname(checkpoint_path)):\n os.makedirs(os.path.dirname(checkpoint_path))\n checkpoint_file = open(checkpoint_path, \"w\")\n checkpoint_file.writelines(str(self.current_label_index))\n\n # 从文本读取当前已标注位置\n def read_checkpoint(self, checkpoint_path):\n checkpoint_file = open(checkpoint_path, \"r\")\n for line in checkpoint_file.readlines():\n self.current_label_index = int(line.strip())\n checkpoint_file.close()\n\n # 标注程序主流程部分\n def labeled(self):\n self.images_list = sorted(glob.glob(\"{}/*.jpg\".format(self.image_folder)))\n self._compute_total_image_number()\n print(\"需要标注的图片总数为: \", self.total_image_number)\n if os.path.exists(self.checkpoint_path):\n self.read_checkpoint(self.checkpoint_path)\n cv2.namedWindow(self.windows_name, cv2.WINDOW_NORMAL)\n while self.current_label_index < self.total_image_number:\n print(\"已标注的图片数量为:{}, 图片地址为: {} \".format(self.current_label_index,\n self.images_list[self.current_label_index]))\n self._reset()\n self.image = cv2.imdecode(np.fromfile(self.images_list[self.current_label_index], dtype=np.uint8), 1)\n self.current_image = self.image.copy()\n self.label_path = self.images_list[self.current_label_index].replace(\".jpg\", \".txt\")\n if os.path.exists(self.label_path):\n self.read_label_file(self.label_path)\n self.width = self.image.shape[1]\n self.height = self.image.shape[0]\n # cv2.imshow(self.windows_name, self.image)\n self._draw_box_on_image(self.current_image, self.boxes)\n cv2.setMouseCallback(self.windows_name, self._draw_roi)\n k = cv2.waitKey(0)\n self.write_label_file(self.label_path, self.boxes, self.label_index)\n if k == ord('a') or k == ord('A'): # 后退一张\n self._backward()\n continue\n if k == ord('d') or k == ord('D'): # 删除当前图\n os.remove(self.images_list[self.current_label_index])\n os.remove(self.label_path)\n del self.images_list[self.current_label_index]\n self._compute_total_image_number()\n self._backward()\n continue\n elif k == 27: # 退出\n self.write_checkpoint(self.checkpoint_path)\n break\n else: # 其他按键\n self.current_label_index += 1\n self.current_label_index = min(self.current_label_index, self.total_image_number-1)\n self.write_checkpoint(self.checkpoint_path)\n\n\ndef main():\n image_folder = r\"./test\"\n CLabeled(image_folder)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/dataset_process/目标检测标注脚本/labeled.py","file_name":"labeled.py","file_ext":"py","file_size_in_byte":8722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195603962","text":"#Created by JaX to Test servo fun\n\nimport RPi.GPIO as GPIO\nimport time\n\nmotionSensorPIN = 11\nservoPIN = 12\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(servoPIN, GPIO.OUT)\n\npin = GPIO.PWM(servoPIN, 50)\npin.start(3)\n\ntry:\n while True:\n usrInput = input(\"open or close: \")\n if usrInput == \"open\" or usrInput == \"Open\":\n inNum = 11\n elif usrInput == \"close\" or usrInput == \"Close\":\n inNum = 1\n else:\n inNum = 11\n\n pin.ChangeDutyCycle(float(inNum))\nexcept KeyboardInterrupt:\n pin.stop()\n GPIO.cleanup()\n","sub_path":"raspberryPI/clawOpenClose.py","file_name":"clawOpenClose.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462607648","text":"from typing import Dict\n\nfrom vnpy.event import Event, EventEngine\nfrom vnpy.trader.engine import MainEngine\nfrom vnpy.trader.ui import QtCore, QtGui, QtWidgets\nfrom vnpy.trader.ui.widget import (\n MsgCell,\n TimeCell,\n BaseMonitor\n)\nfrom ..base import (\n APP_NAME,\n EVENT_PORTFOLIO_LOG,\n EVENT_PORTFOLIO_STRATEGY\n)\nfrom ..engine import StrategyEngine\n\n\nclass PortfolioStrategyManager(QtWidgets.QWidget):\n \"\"\"\"\"\"\n\n signal_log = QtCore.pyqtSignal(Event)\n signal_strategy = QtCore.pyqtSignal(Event)\n\n def __init__(self, main_engine: MainEngine, event_engine: EventEngine):\n \"\"\"\"\"\"\n super().__init__()\n\n self.main_engine: MainEngine = main_engine\n self.event_engine: EventEngine = event_engine\n self.strategy_engine: StrategyEngine = main_engine.get_engine(APP_NAME)\n\n self.managers: Dict[str, StrategyManager] = {}\n\n self.init_ui()\n self.register_event()\n self.strategy_engine.init_engine()\n self.update_class_combo()\n\n def init_ui(self) -> None:\n \"\"\"\"\"\"\n self.setWindowTitle(\"组合策略\")\n\n # Create widgets\n self.class_combo = QtWidgets.QComboBox()\n\n add_button = QtWidgets.QPushButton(\"添加策略\")\n add_button.clicked.connect(self.add_strategy)\n\n init_button = QtWidgets.QPushButton(\"全部初始化\")\n init_button.clicked.connect(self.strategy_engine.init_all_strategies)\n\n start_button = QtWidgets.QPushButton(\"全部启动\")\n start_button.clicked.connect(self.strategy_engine.start_all_strategies)\n\n stop_button = QtWidgets.QPushButton(\"全部停止\")\n stop_button.clicked.connect(self.strategy_engine.stop_all_strategies)\n\n clear_button = QtWidgets.QPushButton(\"清空日志\")\n clear_button.clicked.connect(self.clear_log)\n\n self.scroll_layout = QtWidgets.QVBoxLayout()\n self.scroll_layout.addStretch()\n\n scroll_widget = QtWidgets.QWidget()\n scroll_widget.setLayout(self.scroll_layout)\n\n scroll_area = QtWidgets.QScrollArea()\n scroll_area.setWidgetResizable(True)\n scroll_area.setWidget(scroll_widget)\n\n self.log_monitor = LogMonitor(self.main_engine, self.event_engine)\n\n # Set layout\n hbox1 = QtWidgets.QHBoxLayout()\n hbox1.addWidget(self.class_combo)\n hbox1.addWidget(add_button)\n hbox1.addStretch()\n hbox1.addWidget(init_button)\n hbox1.addWidget(start_button)\n hbox1.addWidget(stop_button)\n hbox1.addWidget(clear_button)\n\n hbox2 = QtWidgets.QHBoxLayout()\n hbox2.addWidget(scroll_area)\n hbox2.addWidget(self.log_monitor)\n\n vbox = QtWidgets.QVBoxLayout()\n vbox.addLayout(hbox1)\n vbox.addLayout(hbox2)\n\n self.setLayout(vbox)\n\n def update_class_combo(self):\n \"\"\"\"\"\"\n self.class_combo.addItems(\n self.strategy_engine.get_all_strategy_class_names()\n )\n\n def register_event(self):\n \"\"\"\"\"\"\n self.signal_strategy.connect(self.process_strategy_event)\n\n self.event_engine.register(\n EVENT_PORTFOLIO_STRATEGY, self.signal_strategy.emit\n )\n\n def process_strategy_event(self, event):\n \"\"\"\n Update strategy status onto its monitor.\n \"\"\"\n data = event.data\n strategy_name = data[\"strategy_name\"]\n\n if strategy_name in self.managers:\n manager = self.managers[strategy_name]\n manager.update_data(data)\n else:\n manager = StrategyManager(self, self.strategy_engine, data)\n self.scroll_layout.insertWidget(0, manager)\n self.managers[strategy_name] = manager\n\n def remove_strategy(self, strategy_name):\n \"\"\"\"\"\"\n manager = self.managers.pop(strategy_name)\n manager.deleteLater()\n\n def add_strategy(self):\n \"\"\"\"\"\"\n class_name = str(self.class_combo.currentText())\n if not class_name:\n return\n\n parameters = self.strategy_engine.get_strategy_class_parameters(class_name)\n editor = SettingEditor(parameters, class_name=class_name)\n n = editor.exec_()\n\n if n == editor.Accepted:\n setting = editor.get_setting()\n vt_symbols = setting.pop(\"vt_symbols\").split(\",\")\n strategy_name = setting.pop(\"strategy_name\")\n\n self.strategy_engine.add_strategy(\n class_name, strategy_name, vt_symbols, setting\n )\n\n def clear_log(self):\n \"\"\"\"\"\"\n self.log_monitor.setRowCount(0)\n\n def show(self):\n \"\"\"\"\"\"\n self.showMaximized()\n\n\nclass StrategyManager(QtWidgets.QFrame):\n \"\"\"\n Manager for a strategy\n \"\"\"\n\n def __init__(\n self,\n strategy_manager: PortfolioStrategyManager,\n strategy_engine: StrategyEngine,\n data: dict\n ):\n \"\"\"\"\"\"\n super().__init__()\n\n self.strategy_manager = strategy_manager\n self.strategy_engine = strategy_engine\n\n self.strategy_name = data[\"strategy_name\"]\n self._data = data\n\n self.init_ui()\n\n def init_ui(self):\n \"\"\"\"\"\"\n self.setFixedHeight(300)\n self.setFrameShape(self.Box)\n self.setLineWidth(1)\n\n self.init_button = QtWidgets.QPushButton(\"初始化\")\n self.init_button.clicked.connect(self.init_strategy)\n\n self.start_button = QtWidgets.QPushButton(\"启动\")\n self.start_button.clicked.connect(self.start_strategy)\n self.start_button.setEnabled(False)\n\n self.stop_button = QtWidgets.QPushButton(\"停止\")\n self.stop_button.clicked.connect(self.stop_strategy)\n self.stop_button.setEnabled(False)\n\n self.edit_button = QtWidgets.QPushButton(\"编辑\")\n self.edit_button.clicked.connect(self.edit_strategy)\n\n self.remove_button = QtWidgets.QPushButton(\"移除\")\n self.remove_button.clicked.connect(self.remove_strategy)\n\n strategy_name = self._data[\"strategy_name\"]\n class_name = self._data[\"class_name\"]\n author = self._data[\"author\"]\n\n label_text = (\n f\"{strategy_name} - ({class_name} by {author})\"\n )\n label = QtWidgets.QLabel(label_text)\n label.setAlignment(QtCore.Qt.AlignCenter)\n\n self.parameters_monitor = DataMonitor(self._data[\"parameters\"])\n self.variables_monitor = DataMonitor(self._data[\"variables\"])\n\n hbox = QtWidgets.QHBoxLayout()\n hbox.addWidget(self.init_button)\n hbox.addWidget(self.start_button)\n hbox.addWidget(self.stop_button)\n hbox.addWidget(self.edit_button)\n hbox.addWidget(self.remove_button)\n\n vbox = QtWidgets.QVBoxLayout()\n vbox.addWidget(label)\n vbox.addLayout(hbox)\n vbox.addWidget(self.parameters_monitor)\n vbox.addWidget(self.variables_monitor)\n self.setLayout(vbox)\n\n def update_data(self, data: dict):\n \"\"\"\"\"\"\n self._data = data\n\n self.parameters_monitor.update_data(data[\"parameters\"])\n self.variables_monitor.update_data(data[\"variables\"])\n\n # Update button status\n variables = data[\"variables\"]\n inited = variables[\"inited\"]\n trading = variables[\"trading\"]\n\n if not inited:\n return\n self.init_button.setEnabled(False)\n\n if trading:\n self.start_button.setEnabled(False)\n self.stop_button.setEnabled(True)\n self.edit_button.setEnabled(False)\n self.remove_button.setEnabled(False)\n else:\n self.start_button.setEnabled(True)\n self.stop_button.setEnabled(False)\n self.edit_button.setEnabled(True)\n self.remove_button.setEnabled(True)\n\n def init_strategy(self):\n \"\"\"\"\"\"\n self.strategy_engine.init_strategy(self.strategy_name)\n\n def start_strategy(self):\n \"\"\"\"\"\"\n self.strategy_engine.start_strategy(self.strategy_name)\n\n def stop_strategy(self):\n \"\"\"\"\"\"\n self.strategy_engine.stop_strategy(self.strategy_name)\n\n def edit_strategy(self):\n \"\"\"\"\"\"\n strategy_name = self._data[\"strategy_name\"]\n\n parameters = self.strategy_engine.get_strategy_parameters(strategy_name)\n editor = SettingEditor(parameters, strategy_name=strategy_name)\n n = editor.exec_()\n\n if n == editor.Accepted:\n setting = editor.get_setting()\n self.strategy_engine.edit_strategy(strategy_name, setting)\n\n def remove_strategy(self):\n \"\"\"\"\"\"\n result = self.strategy_engine.remove_strategy(self.strategy_name)\n\n # Only remove strategy gui manager if it has been removed from engine\n if result:\n self.strategy_manager.remove_strategy(self.strategy_name)\n\n\nclass DataMonitor(QtWidgets.QTableWidget):\n \"\"\"\n Table monitor for parameters and variables.\n \"\"\"\n\n def __init__(self, data: dict):\n \"\"\"\"\"\"\n super(DataMonitor, self).__init__()\n\n self._data = data\n self.cells = {}\n\n self.init_ui()\n\n def init_ui(self):\n \"\"\"\"\"\"\n labels = list(self._data.keys())\n self.setColumnCount(len(labels))\n self.setHorizontalHeaderLabels(labels)\n\n self.setRowCount(1)\n self.verticalHeader().setSectionResizeMode(\n QtWidgets.QHeaderView.Stretch\n )\n self.verticalHeader().setVisible(False)\n self.setEditTriggers(self.NoEditTriggers)\n\n for column, name in enumerate(self._data.keys()):\n value = self._data[name]\n\n cell = QtWidgets.QTableWidgetItem(str(value))\n cell.setTextAlignment(QtCore.Qt.AlignCenter)\n\n self.setItem(0, column, cell)\n self.cells[name] = cell\n\n def update_data(self, data: dict):\n \"\"\"\"\"\"\n for name, value in data.items():\n cell = self.cells[name]\n cell.setText(str(value))\n\n\nclass LogMonitor(BaseMonitor):\n \"\"\"\n Monitor for log data.\n \"\"\"\n\n event_type = EVENT_PORTFOLIO_LOG\n data_key = \"\"\n sorting = False\n\n headers = {\n \"time\": {\"display\": \"时间\", \"cell\": TimeCell, \"update\": False},\n \"msg\": {\"display\": \"信息\", \"cell\": MsgCell, \"update\": False},\n }\n\n def init_ui(self):\n \"\"\"\n Stretch last column.\n \"\"\"\n super(LogMonitor, self).init_ui()\n\n self.horizontalHeader().setSectionResizeMode(\n 1, QtWidgets.QHeaderView.Stretch\n )\n\n def insert_new_row(self, data):\n \"\"\"\n Insert a new row at the top of table.\n \"\"\"\n super().insert_new_row(data)\n self.resizeRowToContents(0)\n\n\nclass SettingEditor(QtWidgets.QDialog):\n \"\"\"\n For creating new strategy and editing strategy parameters.\n \"\"\"\n\n def __init__(\n self, parameters: dict, strategy_name: str = \"\", class_name: str = \"\"\n ):\n \"\"\"\"\"\"\n super(SettingEditor, self).__init__()\n\n self.parameters = parameters\n self.strategy_name = strategy_name\n self.class_name = class_name\n\n self.edits = {}\n\n self.init_ui()\n\n def init_ui(self):\n \"\"\"\"\"\"\n form = QtWidgets.QFormLayout()\n\n # Add vt_symbols and name edit if add new strategy\n if self.class_name:\n self.setWindowTitle(f\"添加策略:{self.class_name}\")\n button_text = \"添加\"\n parameters = {\"strategy_name\": \"\", \"vt_symbols\": \"\"}\n parameters.update(self.parameters)\n else:\n self.setWindowTitle(f\"参数编辑:{self.strategy_name}\")\n button_text = \"确定\"\n parameters = self.parameters\n\n for name, value in parameters.items():\n type_ = type(value)\n\n edit = QtWidgets.QLineEdit(str(value))\n if type_ is int:\n validator = QtGui.QIntValidator()\n edit.setValidator(validator)\n elif type_ is float:\n validator = QtGui.QDoubleValidator()\n edit.setValidator(validator)\n\n form.addRow(f\"{name} {type_}\", edit)\n\n self.edits[name] = (edit, type_)\n\n button = QtWidgets.QPushButton(button_text)\n button.clicked.connect(self.accept)\n form.addRow(button)\n\n self.setLayout(form)\n\n def get_setting(self):\n \"\"\"\"\"\"\n setting = {}\n\n if self.class_name:\n setting[\"class_name\"] = self.class_name\n\n for name, tp in self.edits.items():\n edit, type_ = tp\n value_text = edit.text()\n\n if type_ == bool:\n if value_text == \"True\":\n value = True\n else:\n value = False\n else:\n value = type_(value_text)\n\n setting[name] = value\n\n return setting\n","sub_path":"vnpy/app/portfolio_strategy/ui/widget.py","file_name":"widget.py","file_ext":"py","file_size_in_byte":12834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"21559378","text":"import turtle\r\nimport random\r\nimport winsound\r\n\r\n# Group Members: (NURİ BURAK AYDIN-1107090026 RIFAT ONUR KAFALI-1107090031)\r\n\r\ncell_size = 23 # keep it odd\r\nwidth = 11\r\nheight = 9\r\nbg_color = \"yellow\" # background color\r\nwall_color = \"black\"\r\n\r\ntime = 30 # game time is 30 second \r\ntime_count = 0\r\n\r\n# directions\r\n(UP, DOWN, LEFT, RIGHT, STAND) = (1,2,3,4,5)\r\ndir_updates = { UP:(0,1), DOWN:(0,-1), LEFT:(-1,0), RIGHT: (1,0) }\r\n\r\nwn = turtle.Screen()\r\nwn.bgcolor(bg_color)\r\nwn.title(\"Maze\")\r\nwn.setup(710,710)\r\nwn.screensize(700,700)\r\n\r\ndef cell_to_coord(row, col, top_left = False):\r\n \"\"\" Returns the midpoint (or top_left corner) of the cell as screen\r\n coordinates \"\"\"\r\n global cell_size\r\n x = row * cell_size\r\n y = col * cell_size\r\n if (top_left):\r\n x -= cell_size / 2\r\n y += cell_size / 2\r\n return (x,y)\r\n\r\nscorer=turtle.Turtle() #SCOREBOARD\r\nscorer.hideturtle()\r\nscorer.penup()\r\nscorer.goto (250,250)\r\n\r\n\r\nliver=turtle.Turtle() #LIVEBOARD\r\nliver.hideturtle()\r\nliver.penup()\r\nliver.goto (-250,250)\r\n\r\ntimer = turtle.Turtle() #TIMEBOARD\r\ntimer.hideturtle()\r\ntimer.penup()\r\ntimer.goto(0,275)\r\n\r\ndoor_drawer = turtle.Turtle() #TELEPORT DOORS\r\ndoor_drawer.hideturtle()\r\ndoor_drawer.up()\r\ndoor_drawer.shape('arrow')\r\ndoor_drawer.color(\"black\", \"pink\")\r\n\r\ndef fill_rect(t,x,y,w,h):\r\n \"\"\" Makes turtle t to draw a filled rectangle where\r\n (x,y) is the top left corner, w is the width,\r\n h is the height \"\"\"\r\n t.goto(x,y)\r\n t.begin_fill()\r\n t.goto(x+w,y)\r\n t.goto(x+w,y-h)\r\n t.goto(x,y-h)\r\n t.goto(x,y)\r\n t.end_fill()\r\n\r\ndef item_key(i,j):\r\n return \"(\" + str(i) + \",\" + str(j) + \")\"\r\n\r\ndef drawer_write(message):\r\n (x,y) = cell_to_coord(0,height+1)\r\n y += cell_size / 2\r\n drawer.goto(x,y)\r\n drawer.write(message, font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n\r\ndef check_wall(i,j):\r\n \"\"\" returns True if this coordinate is an inner or outer wall\r\n otherwise returns False \"\"\"\r\n global width, height, wall_coords\r\n return (abs(i) == width + 1) or \\\r\n (abs(j) == height + 1) or \\\r\n (i,j) in wall_coords\r\n\r\ndrawer = turtle.Turtle()\r\ndrawer.fillcolor(wall_color)\r\ndrawer.speed(0)\r\ndrawer.hideturtle()\r\ndrawer.penup()\r\n\r\n# draw the borders of the maze\r\nshort_side = cell_size\r\nlong_side_w = (2*width+3)*cell_size\r\nlong_side_h = (2*height+3)*cell_size\r\n(x,y) = cell_to_coord(-width-1, height+1, True)\r\nfill_rect(drawer,x,y,short_side, long_side_h)\r\nfill_rect(drawer,x,y,long_side_w,short_side)\r\n(x,y) = cell_to_coord(-width-1, -height-1, True)\r\nfill_rect(drawer,x,y,long_side_w,short_side)\r\n(x,y) = cell_to_coord(width+1, height+1, True)\r\nfill_rect(drawer,x,y,short_side,long_side_h)\r\n\r\nrng = random.Random()\r\n\r\nmario = { 'turtle': turtle.Turtle(), 'i':0, 'j':0, 'dir': STAND, 'score':0, 'lives':3}\r\nmario['turtle'].shape('turtle')\r\nmario['turtle'].shapesize(1.0, 1.0)\r\nmario['turtle'].penup()\r\nmario['turtle'].color(\"black\", \"blue\")\r\n\r\nscorer.write(\"score={}\".format(mario['score']),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\nliver.write(\"lives={}\".format(mario['lives']),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\ntimer.write(\"time = {}\".format(time),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n\r\n# global variables needed in different functions\r\nitems = {}\r\nwall_coords = []\r\nbad_turtles = []\r\njoker_coords = []\r\ndoor1=[]\r\ndoor2=[]\r\n\r\ndef init_game():\r\n global items, wall_coords, bad_turtles, joker_coords, door1, door2\r\n items = {}\r\n wall_coords = []\r\n item_coords = []\r\n\r\n drawer.color(\"black\", \"green\")\r\n drawer.shape(\"circle\")\r\n drawer.shapesize(1.1, 1.1)\r\n for a in range(10):\r\n i = rng.randint(-width+1, width-1)\r\n j = rng.randint(-height+1, height-1)\r\n (x,y) = cell_to_coord(i,j)\r\n drawer.goto(x,y)\r\n stamp_id = drawer.stamp()\r\n item_coords.append((i,j))\r\n items[item_key(i,j)] = {'type':'apple', 'stamp': stamp_id}\r\n print(\"Items\",items)\r\n\r\n joker_coords = []\r\n while (len(joker_coords) < 1):\r\n i = rng.randint(-width+1, width-1)\r\n j = rng.randint(-height+1, height-1)\r\n if ((i == 0 and j == 0) or (i,j) in (wall_coords + item_coords + joker_coords)): continue\r\n else:\r\n joker_coords.append((i,j))\r\n\r\n for (i,j) in joker_coords:\r\n (x,y) = cell_to_coord(i,j)\r\n joker.goto(x,y)\r\n joker.stamp()\r\n\r\n door1 = []\r\n while (len(door1) < 1):\r\n i = rng.randint(-width+1, width-1)\r\n j = rng.randint(-height+1, height-1)\r\n if ((i == 0 and j == 0) or (i,j) in (wall_coords + item_coords + joker_coords + door1)): continue\r\n else:\r\n door1.append((i,j))\r\n\r\n for (i,j) in door1:\r\n (x,y) = cell_to_coord(i,j)\r\n door_drawer.goto(x,y)\r\n door_drawer.stamp()\r\n\r\n door2 = []\r\n while (len(door2) < 1):\r\n i = rng.randint(-width+1, width-1)\r\n j = rng.randint(-height+1, height-1)\r\n if ((i == 0 and j == 0) or (i,j) in (wall_coords + item_coords + joker_coords + door1)): continue\r\n else:\r\n door2.append((i,j))\r\n\r\n for (i,j) in door2:\r\n (x,y) = cell_to_coord(i,j)\r\n door_drawer.goto(x,y)\r\n door_drawer.stamp()\r\n \r\n #draw inner walls\r\n wall_count = 0\r\n while (wall_count < 20):\r\n i = rng.randint(-width+1, width-1)\r\n j = rng.randint(-height+1, height-1)\r\n if ((i == 0 and j == 0) or (i,j) in (wall_coords + item_coords)): continue\r\n else:\r\n wall_coords.append((i,j))\r\n wall_count += 1\r\n\r\n # print(\"Walls:\",wall_coords)\r\n\r\n drawer.color(wall_color)\r\n for (i,j) in wall_coords:\r\n (x,y) = cell_to_coord(i,j,top_left=True)\r\n fill_rect(drawer, x,y,cell_size, cell_size)\r\n\r\n filled_coords = wall_coords + item_coords + [(0,0)]\r\n bad_turtles = []\r\n while (len(bad_turtles) < 3):\r\n i = rng.randint(-width+1, width-1)\r\n j = rng.randint(-height+1, height-1)\r\n if (i,j) in filled_coords: continue\r\n else: # found an empty cell\r\n new_turtle = turtle.Turtle()\r\n new_turtle.shape('turtle')\r\n new_turtle.shapesize(1.0, 1.0)\r\n new_turtle.penup()\r\n new_turtle.color(\"black\", \"red\")\r\n (x,y) = cell_to_coord(i,j)\r\n new_turtle.goto(x,y)\r\n bad_turtle = { 'turtle': new_turtle, 'i':i, 'j':j }\r\n bad_turtle['dir'] = rng.choice([UP,DOWN,LEFT,RIGHT])\r\n bad_turtles.append(bad_turtle)\r\n filled_coords.append((i,j))\r\n\r\n drawer_write(\"Mario: {}, {}\".format(mario['i'], mario['j']))\r\n\r\ndef turn_left():\r\n mario['dir'] = LEFT\r\n\r\ndef turn_right():\r\n mario['dir'] = RIGHT\r\n\r\ndef turn_up():\r\n mario['dir'] = UP\r\n\r\ndef turn_down():\r\n mario['dir'] = DOWN\r\n\r\ndef set_direction(bad_turtle):\r\n prob = rng.uniform(0,100)\r\n if 60 < prob < 80:\r\n bad_turtle['dir'] = rng.choice([UP,DOWN,LEFT,RIGHT])\r\n elif prob >= 80: # turn towards mario\r\n (i1,j1) = (mario['i'], mario['j'])\r\n (i2,j2) = (bad_turtle['i'], bad_turtle['j'])\r\n p = rng.randint(1,2)\r\n if p == 1:\r\n if (i1 < i2): bad_turtle['dir'] = LEFT\r\n elif (i1 > i2): bad_turtle['dir'] = RIGHT\r\n else:\r\n if (j1 < j2): bad_turtle['dir'] = DOWN\r\n elif (j1 > j2): bad_turtle['dir'] = UP\r\n\r\ndef move_turtle(maze_turtle):\r\n \"\"\" Moves the turtle according to the latest direction if not facing a wall\r\n at the next step. Returns True if turtle moved successfully otherwise\r\n returns False \"\"\"\r\n global UP, DOWN, LEFT, RIGHT, STAND\r\n if (maze_turtle['dir'] == STAND):\r\n return False\r\n else:\r\n old_heading = maze_turtle['turtle'].heading()\r\n if (maze_turtle['dir'] == LEFT): new_heading = 180\r\n elif (maze_turtle['dir'] == RIGHT): new_heading = 0\r\n elif (maze_turtle['dir'] == UP): new_heading = 90\r\n else: new_heading = 270\r\n if (old_heading != new_heading): # turn maze_turtle\r\n old_speed = maze_turtle['turtle'].speed()\r\n maze_turtle['turtle'].speed(0) # turn off animation\r\n maze_turtle['turtle'].setheading(new_heading)\r\n maze_turtle['turtle'].speed(old_speed)\r\n # determine new cell assuming maze_turtle can move\r\n (i1,j1) = (maze_turtle['i'], maze_turtle['j'])\r\n (offset_i,offset_j) = dir_updates[maze_turtle['dir']]\r\n (i2,j2) = (i1+offset_i,j1+offset_j)\r\n if not check_wall(i2,j2):\r\n maze_turtle['turtle'].forward(cell_size)\r\n maze_turtle['i'] = i2\r\n maze_turtle['j'] = j2\r\n return True\r\n else: # maze_turtle can't move\r\n maze_turtle['dir'] = STAND\r\n return False\r\n\r\njoker = turtle.Turtle() # JOKER\r\njoker.hideturtle()\r\njoker.shape(\"triangle\")\r\njoker.speed(0)\r\njoker.color(\"black\", \"white\")\r\njoker.penup()\r\n\r\nstart_sound = winsound.PlaySound(\"gamestart.wav\", winsound.SND_FILENAME) # GAME START SOUND\r\n\r\ndef update():\r\n global time, time_count\r\n time_count += 1\r\n if(time_count % 5 == 0):\r\n timer.clear()\r\n time -= 1\r\n timer.write(\"time = {}\".format(time),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n moved = move_turtle(mario)\r\n if moved:\r\n (i1,j1) = (mario['i'], mario['j'])\r\n drawer.undo() # clear the previous message written\r\n drawer_write(\"Mario: {}, {}\".format(i1, j1))\r\n item = items.get(item_key(i1,j1))\r\n if item != None: # there is an item at this coordinate\r\n print(item[\"type\"] + \" eaten\")\r\n scorer.clear()\r\n mario['score']+= 10\r\n scorer.write(\"score={}\".format(mario['score']),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n good_sound = winsound.PlaySound(\"beep-07.wav\", winsound.SND_FILENAME) #EAT APPLE SOUND\r\n\r\n \r\n stamp_id = item[\"stamp\"]\r\n drawer.clearstamp(stamp_id)\r\n del items[item_key(i1,j1)]\r\n\r\n (i4,j4) = door1[0]\r\n (i5,j5) = door2[0]\r\n if(i1==i4 and j1==j4):\r\n mario['turtle'].hideturtle()\r\n (x,y) = cell_to_coord(i5,j5)\r\n mario['turtle'].goto(x,y)\r\n (mario['i'],mario['j']) = (i5,j5)\r\n mario['turtle'].showturtle()\r\n teleport_sound = winsound.PlaySound(\"teleport.wav\", winsound.SND_FILENAME) # TELEPORT SOUND\r\n if(i1==i5 and j1==j5):\r\n mario['turtle'].hideturtle()\r\n (x,y) = cell_to_coord(i4,j4)\r\n mario['turtle'].goto(x,y)\r\n (mario['i'],mario['j']) = (i4,j4)\r\n mario['turtle'].showturtle()\r\n teleport_sound = winsound.PlaySound(\"teleport.wav\", winsound.SND_FILENAME)\r\n\r\n \r\n for (i3,j3) in joker_coords:\r\n if i1==i3 and j1==j3: #mario is at same cell with joker\r\n liver.clear()\r\n mario['lives'] += 1\r\n liver.write(\"lives={}\".format(mario['lives']),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n joker.clear()\r\n joker_sound = winsound.PlaySound(\"joker.wav\", winsound.SND_FILENAME) #JOKER SOUND\r\n for bad_turtle in bad_turtles:\r\n (i2,j2) = (bad_turtle['i'], bad_turtle['j'])\r\n if i1==i2 and j1==j2: # mario is at the same cell with bad_turtle\r\n print(\"Mario lost a life\")\r\n liver.clear()\r\n mario['lives']-= 1\r\n liver.write(\"lives={}\".format(mario['lives']),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n bad_sound = winsound.PlaySound(\"beep-03.wav\", winsound.SND_FILENAME) #BAD TURTLE SOUND\r\n \r\n \r\n wn.title(\"Mario at ({0}, {1}) DIR:{2}\".format(mario['i'], mario['j'], mario['dir']))\r\n for bad_turtle in bad_turtles:\r\n set_direction(bad_turtle)\r\n moved = move_turtle(bad_turtle)\r\n if moved:\r\n (i1,j1) = (mario['i'], mario['j'])\r\n (i2,j2) = (bad_turtle['i'], bad_turtle['j'])\r\n if i1==i2 and j1==j2:\r\n print(\"Mario is eaten\")\r\n liver.clear()\r\n mario['lives']-= 1\r\n liver.write(\"lives={}\".format(mario['lives']),font=(\"Comic Sans MS\", 15, \"underline\"), align=\"center\")\r\n bad_sound = winsound.PlaySound(\"beep-03.wav\", winsound.SND_FILENAME)\r\n if mario['lives'] == 0:\r\n print(\"Game over.\")\r\n liver.goto (0,-325)\r\n liver.write(\"YOU LOST\", font=(\"Comic Sans MS\", 30, \"bold\"), align=\"center\")\r\n lost_sound = winsound.PlaySound(\"youlost.wav\", winsound.SND_FILENAME) #LOST SOUND\r\n elif time == 0:\r\n print(\"Time is up.\")\r\n liver.goto (0,-325)\r\n liver.write(\"TIME IS UP\", font=(\"Comic Sans MS\", 30, \"bold\"), align=\"center\")\r\n timeisup_sound = winsound.PlaySound(\"timeisup.wav\", winsound.SND_FILENAME) #TIME IS UP SOUND\r\n elif len(items) == 0:\r\n print(\"Game completed.\")\r\n scorer.goto (0,-325)\r\n scorer.write(\"YOU WON\", font=(\"Comic Sans MS\", 30, \"bold\"), align=\"center\")\r\n youwon_sound = winsound.PlaySound(\"youwon.wav\", winsound.SND_FILENAME) # YOU WON SOUND\r\n else:\r\n wn.ontimer(update, 200)\r\n\r\nwn.onkey(turn_left, \"Left\")\r\nwn.onkey(turn_right, \"Right\")\r\nwn.onkey(turn_up, \"Up\")\r\nwn.onkey(turn_down, \"Down\")\r\n\r\ninit_game() # fill items, walls etc.\r\nupdate() # start game\r\n\r\nwn.listen() # listen events on this window\r\nwn.mainloop() # keep the window open\r\n","sub_path":"game_project.py","file_name":"game_project.py","file_ext":"py","file_size_in_byte":13296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407374252","text":"#!/usr/bin/env python3\n# -*- utf8 -*-\n# author=dave.fang@outlook.com\n# create=20160410\n\n\"\"\"\n* A Tool For Fuzzing Sub-domain.\n* GitHub: https://github.com/DavexPro/FuzSub\n* Version: 1.1\n* SUPPORT TOP-LEVEL\n\"\"\"\nimport random\nimport sys\nimport datetime\nfrom common.dns import *\nfrom common.evil import Evil\n\nDNS_LIST = ['8.8.8.8']\nTHREAD_BRUTE = 30\n\n\ndef get_pan_ip(dns, domain):\n \"\"\"\n :param dns: DNS服务器\n :param domain: 顶级域名\n :return: 泛解析IP\n \"\"\"\n ban_ip = find_ip_from_dns(dns, '500accfde65a0c66c2415017ca8104a6.' + domain)\n return ban_ip\n\n\ndef start_fuzz(domain):\n print('[*] Target: %s' % domain)\n ban_ip = get_pan_ip(random.choice(DNS_LIST), domain)\n evil = Evil(DNS_LIST, domain, ban_ip, THREAD_BRUTE)\n evil.start()\n\n\nif __name__ == '__main__':\n start_time = datetime.datetime.now()\n print('[*] FuzSub is hot.')\n if len(sys.argv) != 2:\n print('[-] E.g. python3 fuzz.py foo.com')\n else:\n fuzz_domain = sys.argv[1]\n print('[+] ' + fuzz_domain + ' ' + str(find_ip_from_dns('8.8.8.8', fuzz_domain)))\n start_fuzz(fuzz_domain)\n end_time = datetime.datetime.now()\n print('[*] Total Time Consumption: ' + \\\n str((end_time - start_time).seconds) + 's')\n","sub_path":"fuzz.py","file_name":"fuzz.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138022115","text":"import numpy as np\n\n\nclass MaxPoolLayer(object):\n def __init__(self, size=2):\n \"\"\"\n MaxPool layer\n Ok to assume non-overlapping regions\n \"\"\"\n self.locs = None # to store max locations\n self.size = size # size of the pooling\n\n def forward(self, x):\n \"\"\"\n Compute \"forward\" computation of max pooling layer\n\n Parameters\n ----------\n x : np.array\n The input data of size number of training samples x number\n of input channels x number of rows x number of columns\n\n Returns\n -------\n np.array\n The output of the maxpooling\n\n Stores\n -------\n self.locs : np.array\n The locations of the maxes (needed for back propagation)\n \"\"\"\n size = self.size\n ind = np.zeros(np.shape(x))\n max_op = np.zeros((x.shape[0],x.shape[1],x.shape[2]/self.size, x.shape[3]/self.size))\n #print np.shape(x)\n for i in range(x.shape[0]):\n for j in range(x.shape[1]):\n for r in range(x.shape[2]/self.size):\n for c in range(x.shape[3]/self.size):\n temp1 = np.max(x[i][j][r*size:(r*size+size), c*size:(c*size+size)])\n max_op[i][j][r][c] =temp1\n temp2 = ((x[i][j][r*self.size:r*self.size + self.size,c*self.size:c*self.size + self.size]))\n for row in range(self.size):\n for column in range(self.size):\n if (temp2[row][column] == temp1):\n ind[i][j][r * self.size + row][c * self.size + column] = 1\n\n\n\n\n #print \"ind = \", ind\n self.locs = ind\n return max_op\n\n\n\n\n def backward(self, y_grad):\n \"\"\"\n Compute \"backward\" computation of maxpool layer\n\n Parameters\n ----------\n y_grad : np.array\n The gradient at the output\n\n Returns\n -------\n np.array\n The gradient at the input\n \"\"\"\n size = self.size\n ind = self.locs\n updated_ip = np.zeros(np.shape(ind))\n #print \"y_grad = \", y_grad[0][2]\n for i in range(y_grad.shape[0]):\n for j in range(y_grad.shape[1]):\n for r in range(y_grad.shape[2]):\n for c in range(y_grad.shape[3]):\n updated_ip[i][j][r*size:(r*size+size), c*size:(c*size+size)] = ind[i][j][r*size:(r*size+size), c*size:(c*size+size)]*y_grad[i][j][r][c]\n\n\n return updated_ip\n #raise NotImplementedError\n\n def update_param(self, lr):\n pass\n","sub_path":"EEE598/ANIK_JHA_LAB4/layers_template/maxpool.py","file_name":"maxpool.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"406077394","text":"import numpy as np # Numeric and matrix computation\nimport pandas as pd # Optional: good package for manipulating data\nimport sklearn as sk # Package with learning algorithms implemented\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import *\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom imblearn import over_sampling as os\nfrom sklearn.preprocessing import OneHotEncoder\n\n\npath=\"E:/Marc/Cole/Uni/7eQ/MD/DataMiningOverDiabetics/processed_data.csv\"\ndf=pd.read_csv(path)\n\n\ndf = df.drop(df.columns[0], axis=1)\n\ndf = df.drop(['X.1', 'X', 'encounter_id', 'patient_n', 'weight', 'payer_code', 'specialty'], axis=1)\n\ndrop_Idx = set(df[(df['diag_2'] == '?') & (df['diag_3'] == '?')].index)\ndrop_Idx = drop_Idx.union(set(df['gender'][df['gender'] == 'Unknown/Invalid'].index))\nnew_Idx = list(set(df.index) - set(drop_Idx))\ndf = df.iloc[new_Idx]\n\ndf['readmitted'] = df['readmitted'].replace('>30', 0)\ndf['readmitted'] = df['readmitted'].replace('<30', 1)\ndf['readmitted'] = df['readmitted'].replace('NO', 0)\n\nprint(df.head())\n\ndf['age'] = df['age'].replace('[0-10)', 0)\ndf['age'] = df['age'].replace('[10-20)', 1)\ndf['age'] = df['age'].replace('[20-30)', 2)\ndf['age'] = df['age'].replace('[30-40)', 3)\ndf['age'] = df['age'].replace('[40-50)', 4)\ndf['age'] = df['age'].replace('[50-60)', 5)\ndf['age'] = df['age'].replace('[60-70)', 6)\ndf['age'] = df['age'].replace('[70-80)', 7)\ndf['age'] = df['age'].replace('[80-90)', 8)\ndf['age'] = df['age'].replace('[90-100)', 9)\n\ndf['disch_id'] = df['disch_id'].replace(6,1)\ndf['disch_id'] = df['disch_id'].replace(8,1)\ndf['disch_id'] = df['disch_id'].replace(9,1)\ndf['disch_id'] = df['disch_id'].replace(13,1)\ndf['disch_id'] = df['disch_id'].replace(3,2)\ndf['disch_id'] = df['disch_id'].replace(4,2)\ndf['disch_id'] = df['disch_id'].replace(5,2)\ndf['disch_id'] = df['disch_id'].replace(14,2)\ndf['disch_id'] = df['disch_id'].replace(22,2)\ndf['disch_id'] = df['disch_id'].replace(23,2)\ndf['disch_id'] = df['disch_id'].replace(24,2)\ndf['disch_id'] = df['disch_id'].replace(12,10)\ndf['disch_id'] = df['disch_id'].replace(15,10)\ndf['disch_id'] = df['disch_id'].replace(16,10)\ndf['disch_id'] = df['disch_id'].replace(17,10)\ndf['disch_id'] = df['disch_id'].replace(25,18)\ndf['disch_id'] = df['disch_id'].replace(26,18)\ndf[\"disch_id\"] = df[\"disch_id\"].replace(11, np.NaN)\ndf.dropna(inplace = True)\n\ndf['A1Cresult'] = df['A1Cresult'].replace('>7', 1)\ndf['A1Cresult'] = df['A1Cresult'].replace('>8', 1)\ndf['A1Cresult'] = df['A1Cresult'].replace('Norm', 0)\ndf['A1Cresult'] = df['A1Cresult'].replace('None', -99)\n\ndf['circulatory'] = 0\ndf.loc[df['diag_1'] == 'Circulatory', 'circulatory'] = 1\ndf.loc[df['diag_2'] == 'Circulatory', 'circulatory'] = 1\ndf.loc[df['diag_3'] == 'Circulatory', 'circulatory'] = 1\n\ndf['diabetes'] = 0\ndf.loc[df['diag_1'] == 'Diabetes', 'diabetes'] = 1\ndf.loc[df['diag_2'] == 'Diabetes', 'diabetes'] = 1\ndf.loc[df['diag_3'] == 'Diabetes', 'diabetes'] = 1\n\ndf['digestive'] = 0\ndf.loc[df['diag_1'] == 'Digestive', 'digestive'] = 1\ndf.loc[df['diag_2'] == 'Digestive', 'digestive'] = 1\ndf.loc[df['diag_3'] == 'Digestive', 'digestive'] = 1\n\ndf['genitourinary'] = 0\ndf.loc[df['diag_1'] == 'Genitourinary', 'genitourinary'] = 1\ndf.loc[df['diag_2'] == 'Genitourinary', 'genitourinary'] = 1\ndf.loc[df['diag_3'] == 'Genitourinary', 'genitourinary'] = 1\n\ndf['injury'] = 0\ndf.loc[df['diag_1'] == 'Injury', 'injury'] = 1\ndf.loc[df['diag_2'] == 'Injury', 'injury'] = 1\ndf.loc[df['diag_3'] == 'Injury', 'injury'] = 1\n\ndf['musculoskeletal'] = 0\ndf.loc[df['diag_1'] == 'Musculoskeletal', 'musculoskeletal'] = 1\ndf.loc[df['diag_2'] == 'Musculoskeletal', 'musculoskeletal'] = 1\ndf.loc[df['diag_3'] == 'Musculoskeletal', 'musculoskeletal'] = 1\n\ndf['neoplasms'] = 0\ndf.loc[df['diag_1'] == 'Neoplasms', 'neoplasms'] = 1\ndf.loc[df['diag_2'] == 'Neoplasms', 'neoplasms'] = 1\ndf.loc[df['diag_3'] == 'Neoplasms', 'neoplasms'] = 1\n\ndf['other'] = 0\ndf.loc[df['diag_1'] == 'Other', 'other'] = 1\ndf.loc[df['diag_2'] == 'Other', 'other'] = 1\ndf.loc[df['diag_3'] == 'Other', 'other'] = 1\n\ndf['respiratory'] = 0\ndf.loc[df['diag_1'] == 'Respiratory', 'respiratory'] = 1\ndf.loc[df['diag_2'] == 'Respiratory', 'respiratory'] = 1\ndf.loc[df['diag_3'] == 'Respiratory', 'respiratory'] = 1\n\ndf = df.drop(['diag_1', 'diag_2', 'diag_3'], axis=1)\n\n# stacked = df[['race', 'gender', 'diag_1', 'diag_2', 'diag_3', 'A1Cresult', 'metformin', 'insulin', 'change', 'diabetesMed', 'other_meds']].stack()\n# df[['race', 'gender', 'diag_1', 'diag_2', 'diag_3', 'A1Cresult', 'metformin', 'insulin', 'change', 'diabetesMed', 'other_meds']] = pd.Series(stacked.factorize()[0], index=stacked.index).unstack()\n\n\ncategoricals = ['gender', 'race', 'metformin', 'insulin', 'change', 'diabetesMed', 'other_meds']\nle = LabelEncoder()\nonehot_encoder = OneHotEncoder(sparse=False)\nfor vname in categoricals:\n integer_encoded = le.fit_transform(df[vname])\n integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n onehot_encoded = onehot_encoder.fit_transform(integer_encoded)\n df[vname] = onehot_encoded\n\nprint(df.head().T)\n\nnumericV = ['age', 'time_in_hpt', 'n_lab_proc', 'n_proc', 'n_med', 'n_outp', 'n_emerg', 'n_inp', 'n_diag']\nfor var in numericV:\n if (abs(df[var].skew()) >2) & (abs(df[var].kurtosis()) >2):\n print(var, \" needs log\")\n df[var] = np.log1p(df[var])\n\ninputSet = df.drop(\"readmitted\", axis=1)\noutputSet = df[\"readmitted\"]\n\ny = df['readmitted'].values\n\nX_train, X_test, y_train, y_test = train_test_split(inputSet, outputSet, random_state=42,test_size=0.3)\n\nsmoter = os.SMOTE(random_state = 42)\nX_train, y_train = smoter.fit_sample(X_train, y_train)\n\nTRAIN = pd.DataFrame(X_train, columns = list(inputSet))\nTRAIN[\"TARGET\"] = y_train\nTRAIN.to_csv('./TRAIN.csv')\n\nTEST = X_test\nTEST[\"TARGET\"] = y_test\nTEST.to_csv('./TEST.csv')\n\nX = df.drop(['readmitted'], axis=1).as_matrix()\n\nlrf=[]\n# for nest in [1,2,5,10,20,50,100,200]:\n# scores = cross_val_score(RandomForestClassifier(n_estimators=nest), X, y, cv=cv, scoring='accuracy')\n# print(\"Accuracy: %0.3f [%s]\" % (scores.mean(), nest))\n# lrf.append(scores.mean())\n\n# predicted = cross_val_predict(RandomForestClassifier(n_estimators=30), X,y, cv=50)\n# print(\"-------\")\n# print(confusion_matrix(y, predicted))\n# print(\"-------\")\n# print(\"accuracy = \" + str(accuracy_score(y, predicted)))\n# print(\"-------\")\n# print(classification_report(y,predicted))","sub_path":"proves_marc(notFinal)/Preprocessing_recall.py","file_name":"Preprocessing_recall.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"255035596","text":"# -*- encoding: utf-8 -*-\n# Script en python para la generación de albaranes de producto semi-elavorado.\n# Todo lo introducido se trata como una cadena de texto.\n\nimport datetime # Importa el modulo para el manejo de fechas\nimport os # Importa el modulo que permite abrir el albaran generado\nimport hashlib # Importa el modulo para calcular funciones hash\n\nrutaArchivo=\"\" # Especificar la carpeta donde se guardaran los albaranes generados, en blanco para usar la misma que la raiz\nrutaMaster =\"\" # Especificar la ruta donde se guardara la lista de todos los albaranes, en blanco para usar la misma que la raiz\n\n# Variables de uso general\nfinal=False\nmatriz_conceptos=[]\nmatriz_cantidades=[]\ncontador=0\nconfirmar=False\n\n# Obtiene la fecha y genera el numero de albaran\ngeneracion= datetime.datetime.now()\nn_albaran=str(generacion.year)+str(generacion.month)+\"_\"+str(generacion.day)+str(generacion.hour)+str(generacion.minute)\ngeneracion=str(generacion.day)+\"/\"+str(generacion.month)+\"/\"+str(generacion.year)+\" - \"+str(generacion.hour)+\":\"+str(generacion.minute)\n\n# Bateria de preguntas para la cabecera del albaran\nentrega = raw_input(\"Introduce el cliente/entrega: \")\nhr=raw_input(\"Introduce la h.r.: \")\ntitulo=raw_input(\"Introduce el titulo: \")\n\n# Bucle para introducir las filas del albaran. Maximo 13\nwhile (final==False):\n matriz_cantidades.append(raw_input(\"Introduce cantidad del concepto: \"))\n matriz_conceptos.append(raw_input(\"Introduce concepto: \"))\n contador=contador+1\n \n # Si llega a 10 para el bucle y avisa\n if contador == 10 :\n final=True\n print (\"Has alcanzado el maximo de filas, si hay mas conceptos abre otro albaran.\")\n \n # Pregunta si hay mas conceptos para introducir, si no para el bucle\n if final==False:\n acabar=raw_input(\"Quieres introducir mas conceptos (s/n): \")\n if acabar==\"n\" or acabar ==\"N\":\n final=True\ncomentario=raw_input(\"Poner comentario, sino deja esto en blanco: \")\n\n# Muestra un resumen de los datos para confirmar\nwhile (confirmar==False):\n print (\"=================================================================\")\n print (\"= C O N F I R M A R D A T O S =\")\n print (\"=================================================================\")\n print (\"H.R.: \"+str(hr)+\".- \"+titulo)\n print (\"Entregar en: \"+entrega+\" / n albaran: \"+n_albaran)\n print (\"\")\n for i in range(len(matriz_cantidades)):\n print (str(matriz_cantidades[i])+\" -> \"+matriz_conceptos[i])\n print (\"\")\n print (comentario)\n print (\"Albaran generado: \"+str(generacion))\n print (\"=================================================================\")\n acabar=raw_input(\"Confirmar albaran (s/n): \")\n if acabar == \"s\" or acabar == \"S\":\n confirmar=True\n\n# TODO: incluir codigo para modificar el albaran\n\n# Crea el archivo del albaran. Hace dos iteraciones para sacar en un A4 dos copias del mismo albaran\narchivo=open(rutaArchivo+n_albaran+\".htm\",\"w\")\narchivo.write (\"\")\narchivo.write (\"Albaran \"+n_albaran+\"\")\narchivo.write (\"\")\nfor impresion in range (2):\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\narchivo.write (\"\")\narchivo.write (\"
    \")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n for i in range(len(matriz_cantidades)):\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n if len(matriz_cantidades) < 10:\n filasVacias =10-len(matriz_cantidades)\n for j in range (filasVacias):\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"\")\n archivo.write (\"
    \")\n archivo.write (\"\") # ATENCION AQUI. SI QUIERES UN LOGO ESTA EN ESTA RUTA\n archivo.write (\"\")\n archivo.write (\"EMPRESA
    direccion
    \")\n archivo.write (\"
    \")\n archivo.write (\"ALBARAN\")\n archivo.write (\"
    \")\n archivo.write (\"
    \")\n archivo.write (\"N. Albaran: \"+n_albaran)\n archivo.write (\"\")\n archivo.write (\"Fecha: \"+str(generacion))\n archivo.write (\"
    \")\n archivo.write (\"H. R.: \"+hr+\".- \"+titulo)\n archivo.write (\"
    \")\n archivo.write (\"Entrega en: \"+entrega+\"

    \")\n archivo.write (\"
    \")\n archivo.write (str(matriz_cantidades[i])+\" - \"+matriz_conceptos[i])\n archivo.write (\"
    \")\n archivo.write (\"\")\n archivo.write (\"
    \")\n archivo.write (\"Observaciones: \"+comentario)\n archivo.write (\"
    \")\n archivo.write (\"
    \")\narchivo.close ()\n\n# Obtiene la funcion hash sha1 del archivo generado\nsumaHash = open(rutaArchivo+n_albaran+\".htm\", \"rb\").read()\nsumaHash_string = hashlib.sha1(sumaHash).hexdigest()\n\n# Introduce los datos en el archivo master.csv\nmaster = open(rutaMaster+\"master.csv\",\"a\")\nmaster.write(n_albaran+\";\"+str(generacion)+\";\"+entrega+\";\"+hr+\";\"+titulo+\";\"+str(sumaHash_string)+\"\\n\")\nmaster.close()\n\n# Muestra el archivo generado\nos.startfile(rutaArchivo+n_albaran+\".htm\")\n","sub_path":"albaranes.py","file_name":"albaranes.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79846797","text":"#!/usr/bin/env python3\n\"\"\"\nTakes the minimal VCF file containing dToxoG filters and\nannotates the full VCF with the filtering tag. In addition,\nit mutates the header to add the 'oxog' filter metadata.\n\"\"\"\nimport os\nimport argparse\nimport logging\nimport time\nimport sys\nimport datetime\nimport pysam\nimport subprocess\n\ndef main(args):\n \"\"\"\n Main wrapper function for annotating VCFs with oxog\n \"\"\"\n # reader of full input VCF \n reader = pysam.VariantFile(args.input_vcf)\n\n # Update header\n reader.header.filters.add('oxog', None, None, 'Failed dToxoG') \n\n # Writer\n writer = pysam.VariantFile(args.output_vcf, 'w', header=reader.header)\n\n # dtoxog vcf\n dtoxog = pysam.TabixFile(args.input_dtoxog)\n for record in reader.fetch():\n region = '{0}:{1}-{2}'.format(record.contig, record.pos, record.pos)\n # Check if overlaps dtoxo\n try:\n for row in dtoxog.fetch(region=region, parser=pysam.asTuple()): \n if record.ref.upper() == row[3].upper():\n # Add filter if failed oxog\n record.filter.add('oxog')\n\n # break\n break\n except ValueError:\n pass \n\n writer.write(record)\n\n reader.close()\n writer.close()\n dtoxog.close()\n\n # bgzip\n logger.info(\"BGzip compressing...\")\n cmd = ['bgzip', '-@', '4', '-f', args.output_vcf]\n p = subprocess.check_call(cmd)\n\n # tabix index\n logger.info(\"Tabix index...\")\n cmd = ['tabix', '-p', 'vcf', args.output_vcf + '.gz']\n p = subprocess.check_call(cmd)\n\ndef get_args():\n ''' Argument parser setup '''\n p = argparse.ArgumentParser(description='Annotate VCF with D-ToxoG data')\n p.add_argument('input_vcf', type=str, help='input VCF file')\n p.add_argument('input_dtoxog', type=str, help='input dtoxog minimal tabix-indexed VCF')\n p.add_argument('output_vcf', type=str, help='output annotated VCF file')\n\n return p.parse_args()\n\nif __name__ == '__main__':\n start = time.time()\n\n # Set up logger\n logger = logging.getLogger('AddOxoGFilters')\n logger.setLevel(logging.INFO)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n formatter = logging.Formatter('[%(levelname)s] [%(asctime)s] [%(name)s] - %(message)s',\n datefmt='%H:%M:%S')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n # Print header\n logger.info('-'*75)\n logger.info('AddOxoGFiltersToVcf.py')\n logger.info(\"Program Args: AddOxoGFiltersToVcf.py \" + \" \".join(sys.argv[1::]))\n logger.info('Date/time: {0}'.format(datetime.datetime.now()))\n logger.info('-'*75)\n logger.info('-'*75)\n\n # Args\n args = get_args()\n\n # Main\n main(args)\n \n # Done\n logger.info(\"Finished, took {0} seconds.\".format(\n time.time() - start))\n","sub_path":"src/AddOxoGFiltersToVcf.py","file_name":"AddOxoGFiltersToVcf.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"77089473","text":"# coding=utf-8\nfrom django.shortcuts import render\n\nfrom eventcity.models import Event, City\n\nfrom datetime import datetime\nDATE_NOW = datetime.now()\n\n\ndef home(request):\n\tevents = Event.objects.filter(date__gte=DATE_NOW)\n\treturn render(request, 'eventcity/home.html', dict(events=events))\n\n\ndef city(request, city_name):\n\tc = City.objects.filter(city__contains=city_name)\n\ttry:\n\t\tc = c[0].id\n\texcept IndexError:\n\t\tc = None\n\tevents = Event.objects.filter(date__gte=DATE_NOW, city_event=c)\n\tevents = dict(events=events)\n\tevents['city_name'] = city_name\n\treturn render(request, 'eventcity/home.html', events)\n","sub_path":"eventcity/views/city.py","file_name":"city.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"116874857","text":"import plot\n\nscenario = 'EAX-no-500'\n\n#(required) Specify the input file with the tab-separated data that you want to plot\ninFile = 'scenarios/' + scenario + '/configs-constant/configs.csv'\n#(optional) Specify the output file name\noutFile = 'scenarios/' + scenario + '/paramSPLOM'\n#(optional) Set the title of the SPLOM\ntitle = 'Problem Instance Size vs configured parameters'\n\n#Get the parameter names\nparams = []\nparamType = {}\nparamRange = {}\nwith open('scenarios/' + scenario + '/params-constant.pcs','r') as f_config:\n for line in f_config:\n if('#' in line[0] or len(line) < 1 or '\\n' in line.split(' ')[0]):\n continue\n newParam = line.split(' ')[0]\n if(newParam not in params):\n params.append(newParam)\n paramType[newParam] = line.split(' ')[1]\n if('integer' == paramType[newParam] or 'real' == paramType[newParam]):\n rng = line.split('[')[1].split(']')[0].split(',')\n\n diff = (float(rng[1])-float(rng[0]))/5\n rng[0] = str(float(rng[0]) - diff)\n rng[1] = str(float(rng[1]) + diff)\n paramRange[newParam] = '[' + rng[0] + ':' + rng[1] + ']'\n else:\n paramRange[newParam] = line.split('{')[1].split('}')[0]\nparams = sorted(params)\n\n#Add in the size\n#(required) Specify the columns (in the data-file) to be ploted on the x-axis\nxCol = [2];\n#(required) Specify the columns to be plotted on the y-axis\nyCol = [2];\n\n#(optional) Create a dictionary mapping data-columns to their respective labels\nlabel = {}; \nlabel[2] = 'Problem Instance Size'; \n\n#(optional) Create a dictionary mapping data-columns to their respective ranges.#Column range format needs to be in the same format as used in gnuplot. \n#If no range is supplied for a column (and no default is assigned) the gnuplot\n#auto range option will be used.\nrange = {}; \nrange[2] = '[400:1400]';\n\ncol = 4\nfor param in params:\n if(paramType[param] == 'integer' or paramType[param] == 'real'):\n xCol.append(col)\n yCol.append(col)\n label[col] = param\n range[col] = paramRange[param]\n col += 1\n\n#(optional) Create a dictionary that sets whether or not each data-column should\n#be plotted on a log plot. Note again the usage of the 'default' setting to \n#specify most of the columns. \nlog = {}; \nlog['default'] = False; \n\n#(recommended) Create a dictionary mapping data-columns to tic labels. We \n#recommend using this setting because often the default tic-labels will overlap\n#between adjacent scatter plots\ntic = {}; \n#tic[2] = \"(500, 700, 900, 1100, 1300)\";\n#tic[5] = \"(50, 100, 150, 200)\"\n#tic[4] = \"(25, 50, 75, 100)\"\n \n\nfontsize = 12\n\nplot.SPLOM(inFile = inFile, title = title, xCol = xCol, yCol = yCol, outFile = outFile, range = range, tic = tic, label = label, log = log, fontsize = fontsize)\n","sub_path":"plotFitPSCs.py","file_name":"plotFitPSCs.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166891868","text":"from core.exceptions import ElementNotAllowed\n\n\nclass Element:\n name = None\n self_closing = False # Allow element to self-close ( )\n allow_content = True # Allow inner text in element\n ending_slash = False # /> or >\n\n allowed_attrs = []\n allowed_childs = []\n\n def _get_allowed_attrs(self):\n default_attrs = [\n \"class\",\n ]\n\n return default_attrs + self.allowed_attrs\n\n def _get_allowed_childs(self):\n return self.allowed_childs\n\n def check_allowed_attrs(self):\n allowed = self._get_allowed_attrs()\n for attr in self.attrs.keys():\n if attr not in allowed:\n raise AttributeError(\"Attribute '%s' not allowed to use in element '%s'\" %(attr, self.name))\n\n def check_allowed_childs(self):\n allowed = self._get_allowed_childs()\n for child in self.childs:\n if isinstance(child, Element):\n if child.name not in allowed:\n raise ElementNotAllowed(\"Element '%s' not allowed in '%s'\" % (child.name, self.name))\n\n def __init__(self, childs=None, attrs=None, ):\n if not self.allow_content and childs:\n raise ElementNotAllowed(\"Childs in element '%s' is not allowed.\" % self.name)\n\n self.attrs = attrs or {}\n\n if not hasattr(childs, \"__iter__\"):\n if childs:\n self.childs = [childs, ]\n else:\n self.childs = []\n else:\n self.childs = childs\n\n self.check_allowed_attrs()\n self.check_allowed_childs()\n\n def _get_attrs_string(self):\n return \" \".join([ \"%s=\\\"%s\\\"\" % (k,str(v).replace('\"', \"'\")) for k,v in self.attrs.items() ])\n\n def _open(self):\n attrs = self._get_attrs_string()\n return \"<\"+ \" \".join([self.name, attrs]).strip() + \">\"\n\n def _content(self):\n res = \"\"\n for element in self.childs:\n res += element.render() if isinstance(element, Element) else str(element)\n return res\n\n def _end(self):\n return \"\".format(name=self.name)\n\n\n def render(self):\n content = self._content()\n\n if self.self_closing:\n if not content:\n attrs = self._get_attrs_string()\n return \"<\"+ \" \".join([self.name, attrs]).strip() + (\" />\" if self.ending_slash else \">\")\n\n return \"{start}{el_el}{end}\".format(\n start= self._open(),\n el_el= self._content(),\n end= self._end(),\n )\n","sub_path":"core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"173908684","text":"# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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\nfrom nemo_text_processing.text_normalization.de.utils import get_abs_path\nfrom nemo_text_processing.text_normalization.en.graph_utils import GraphFst, insert_space\n\ntry:\n import pynini\n from pynini.lib import pynutil\n\n quantities = pynini.string_file(get_abs_path(\"data/numbers/quantities.tsv\"))\n\n PYNINI_AVAILABLE = True\nexcept (ModuleNotFoundError, ImportError):\n PYNINI_AVAILABLE = False\n quantities = None\n\n\ndef get_quantity(decimal: 'pynini.FstLike', cardinal_up_to_hundred: 'pynini.FstLike') -> 'pynini.FstLike':\n \"\"\"\n Returns FST that transforms either a cardinal or decimal followed by a quantity into a numeral,\n e.g. 1 million -> integer_part: \"eine\" quantity: \"million\"\n e.g. 1.4 million -> integer_part: \"eins\" fractional_part: \"vier\" quantity: \"million\"\n\n Args: \n decimal: decimal FST\n cardinal_up_to_hundred: cardinal FST\n \"\"\"\n numbers = cardinal_up_to_hundred\n\n res = (\n pynutil.insert(\"integer_part: \\\"\")\n + numbers\n + pynutil.insert(\"\\\"\")\n + pynini.accep(\" \")\n + pynutil.insert(\"quantity: \\\"\")\n + quantities\n + pynutil.insert(\"\\\"\")\n )\n res |= decimal + pynini.accep(\" \") + pynutil.insert(\"quantity: \\\"\") + quantities + pynutil.insert(\"\\\"\")\n return res\n\n\nclass DecimalFst(GraphFst):\n \"\"\"\n Finite state transducer for classifying decimal, e.g. \n -11,4006 billion -> decimal { negative: \"true\" integer_part: \"elf\" fractional_part: \"vier null null sechs\" quantity: \"billion\" preserve_order: true }\n 1 billion -> decimal { integer_part: \"eins\" quantity: \"billion\" preserve_order: true }\n Args:\n cardinal: CardinalFst\n deterministic: if True will provide a single transduction option,\n for False multiple transduction are generated (used for audio-based normalization)\n \"\"\"\n\n def __init__(self, cardinal: GraphFst, deterministic: bool = True):\n super().__init__(name=\"decimal\", kind=\"classify\", deterministic=deterministic)\n\n graph_digit = pynini.string_file(get_abs_path(\"data/numbers/digit.tsv\")).invert()\n graph_digit |= pynini.string_file(get_abs_path(\"data/numbers/zero.tsv\")).invert()\n graph_digit |= pynini.cross(\"1\", \"eins\")\n self.graph = graph_digit + pynini.closure(insert_space + graph_digit).optimize()\n\n point = pynutil.delete(\",\")\n optional_graph_negative = pynini.closure(pynutil.insert(\"negative: \") + pynini.cross(\"-\", \"\\\"true\\\" \"), 0, 1)\n\n self.graph_fractional = pynutil.insert(\"fractional_part: \\\"\") + self.graph + pynutil.insert(\"\\\"\")\n self.graph_integer = pynutil.insert(\"integer_part: \\\"\") + cardinal.graph + pynutil.insert(\"\\\"\")\n final_graph_wo_sign = self.graph_integer + point + insert_space + self.graph_fractional\n\n self.final_graph_wo_negative = final_graph_wo_sign | get_quantity(\n final_graph_wo_sign, cardinal.graph_hundred_component_at_least_one_none_zero_digit\n )\n final_graph = optional_graph_negative + self.final_graph_wo_negative\n final_graph += pynutil.insert(\" preserve_order: true\")\n\n final_graph = self.add_tokens(final_graph)\n\n self.fst = final_graph.optimize()\n","sub_path":"nemo_text_processing/text_normalization/de/taggers/decimal.py","file_name":"decimal.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"50178129","text":"# fim_hash_continuous.py\nimport os, hashlib\nimport shelve\nimport time\n\ndef walk(dir):\n for file in [item for item in os.listdir(dir) if os.path.isfile(os.path.join(dir,item))]:\n hash = hashlib.md5()\n with open(os.path.join(dir,file), encoding='utf-8') as f:\n for chunk in iter(lambda: f.read(2048), \"\"):\n hash.update(chunk.encode('utf-8'))\n md5 = hash.hexdigest()\n if file in files and md5 != files[file]:\n print(f'{file} has been changed at {time.strftime(\"%Y-%m-%d %H:%M:%S\")}!')\n files[file]=md5\n\nfiles={}\n\nwhile True:\n walk(os.getcwd() + '/repo')\n time.sleep(1)\n\nFILENAME = \"repohash\"\n\nfor k, v in files.items():\n with shelve.open(FILENAME) as repo:\n repo[k] = v\n\nwith shelve.open(FILENAME) as repo:\n for f in repo.keys():\n print(f) \n print()\n for h in repo.values():\n print(h) \n","sub_path":"Janus/python-base-unit_08/FIM/fim_hash_continuous.py","file_name":"fim_hash_continuous.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316752345","text":"\"\"\"\nThe little schemer, chapter 2\n\n第一条铁律: 始终在递归函数的第一个问题进行判空.\n\n个人规律总结:\n1. 递归程序的if-else分支结构应该尽量与递归数据结构保持一致.\n 这个意思是, 对于list而言, 当我们首先问了len(lat)这个对list的整体操作后,\n 如果后续没有对list的整体condition判断了, 应该直接进入else, 进入元素级别的判断\n\n\"\"\"\n\ndef member(a, lat):\n \"\"\"判断a是否是lat的一员\"\"\"\n if len(lat) == 0:\n return False\n else:\n if a == lat[0]:\n return True\n else:\n return member(a, lat[1:])\n\nif __name__ == \"__main__\":\n print(member(\"tea\", [\"coffee\", \"tea\", \"or\", \"milk\"]))\n print(member(\"poached\", [\"coffee\", \"tea\", \"or\", \"milk\"]))","sub_path":"chapter_2.py","file_name":"chapter_2.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"458387591","text":"import pymongo\nimport json\n\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n\n#print(myclient.list_database_names())\n\n\ndef insert_into_database(name, topic):\n\t#print(\"name: \", name)\n\t#print(\"topic: \", topic)\n\n\tmongoClientDB = myclient['mywikidump']\n\tcollection = mongoClientDB[topic]\n\ttopic = topic + '.xml'\n\tjson_file = open(name, encoding=\"utf8\")\n\tarray = [line[:-1] for line in json_file]\n\tarray[-1] = array[-1] + \"}\"\n\t#json_file = json.dumps(json_file)\n\t#data = json.load(json_file)\n\t#print(array)\n\n\tfinal_array = []\n\n\t#for item in array:\n\t\t#final_array.append(json.loads(item))\n\n\t#print(final_array)\n\t#collection.insert_many(array, ordered=False)\n\n\n\tfor item in array:\n\t\t#pass\n\t\t#print(\"item: \", item)\n\t\tins = json.loads(item)\n\t\tcollection.insert(ins)","sub_path":"xml_files_parse/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"50252449","text":"import tokenfile\nfrom tokenfile import connection\n\ndb = connection\n\n\ndef new_server(sv, md): # adds new server to db, defaults to sfw\n cursor = tokenfile.get_cursor(connection)\n query = \"INSERT INTO Servers (server_id, mode) VALUES (%s, %s)\"\n cursor.execute(query, (sv, md))\n db.commit()\n\n\ndef change_mode(sv, md): # changes sfw mode\n cursor = tokenfile.get_cursor(connection)\n query = \"UPDATE Servers SET mode=%s WHERE server_id=%s\"\n cursor.execute(query, (md, sv))\n db.commit()\n\n\ndef check_mode(sv): # checks and returns mode\n cursor = tokenfile.get_cursor(connection)\n query = \"SELECT mode FROM Servers WHERE server_id=%s\"\n cursor.execute(query, (sv,))\n mode = cursor.fetchall() # returns list of tuples, use double index to get actual values\n return mode[0][0]\n\n\ndef get_prefix(sv): # gets prefix for current server\n cursor = tokenfile.get_cursor(connection)\n query = \"SELECT prefix FROM Servers WHERE server_id=%s\"\n cursor.execute(query, (sv,))\n prefix = cursor.fetchall() # returns list of tuples, use double index to get actual values\n return prefix[0][0]\n\n\ndef change_prefix(sv, pf): # changes prefix for current server\n cursor = tokenfile.get_cursor(connection)\n query = \"UPDATE Servers SET prefix=%s WHERE server_id=%s\"\n cursor.execute(query, (pf, sv))\n db.commit()\n\n\ndef send_query(q): # executes query q\n cursor = tokenfile.get_cursor(connection)\n cursor.execute(q)\n db.commit()\n","sub_path":"sql/sql_modes.py","file_name":"sql_modes.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"424542521","text":"from analyze1 import loadingData\nimport gensim\nimport nltk\nfrom nltk import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom os import listdir\nfrom os.path import isfile, join\nimport re\nimport numpy\nimport os\n\n\n\n#running using Python 2.7\n\n#label sentence object\nclass LabeledLineSentence(object):\n def __init__(self, doc_list, labels_list):\n self.labels_list = labels_list\n self.doc_list = doc_list\n def __iter__(self):\n for idx, doc in enumerate(self.doc_list):\n yield gensim.models.doc2vec.LabeledSentence(doc,\n [self.labels_list[idx]])\n \n# network creating layer\nclass commentsLayer(object):\n def __init__(self):\n self.bus_id = []\n self.review = []\n self.folderPath = \"C:/Users/Farreltin/Documents/fall2018/CourseData/result/\"\n #print('prepare docLabels...')\n #self.docLabels = [f for f in listdir(self.folderPath)]\n #print('prepare data...')\n #self.data = self.readDoc()\n #print('finished initialization...')\n # two libraries used to preprocess the comment\n #self.tokenizer = RegexpTokenizer(r'\\w+')\n #self.stopword_set = set(stopwords.words('english'))\n \n def initVariables(self):\n l = loadingData()\n self.bus_id = l.business_id\n self.review = l.review\n\n \n def readDoc(self):\n data = []\n for doc in self.docLabels:\n data.append(open(self.folderPath + doc).read())\n return data\n \n #create comment txt files\n def com2txt(self):\n business_c = []\n self.initVariables()\n print('Writing comments to txt...')\n\n for i in range(len(self.review)):\n text = self.review[i][\"text\"]\n busid = self.review[i][\"business_id\"]\n id = self.review[i][\"review_id\"]\n business_c.append(text)\n osPath = self.folderPath+ busid + 'comment[' + id+'].txt'\n with open(osPath,'w') as file:\n file.write(\"%s\\n\" % text.encode('utf-8'))\n print('finished writing txt!')\n return 0\n \n # preprocess the words\n def nlp_clean(self, data):\n new_data = []\n for d in data:\n new_str = d.lower()\n dlist = self.tokenizer.tokenize(new_str)\n dlist = list(set(dlist).difference(self.stopword_set))\n new_data.append(dlist)\n return new_data\n \n # training the model\n def createModel(self):\n self.initVariables()\n #self.com2txt()\n \n print('creating models....')\n self.data = self.nlp_clean(self.data)\n it = LabeledLineSentence(self.data, self.docLabels)\n # 50 features should be good enough?\n model = gensim.models.Doc2Vec(size=50, min_count=0, \n alpha=0.025, min_alpha=0.025)\n model.build_vocab(it)\n #training of model\n for epoch in range(100):\n print('iteration '+str(epoch+1))\n model.train(it, total_examples=model.corpus_count, epochs=model.iter)\n model.alpha -= 0.002\n model.min_alpha = model.alpha\n #saving the created model\n model.save(\"commentLayer.model\")\n print(\"model saved\")\n return 0\n \n def createNetwork(self):\n model = gensim.models.doc2vec.Doc2Vec.load('commentLayer.model')\n index = lambda nums: int(''.join(str(i) for i in nums)) \n #generating index for each comments\n size = len(self.docLabels)\n G = numpy.zeros((size,size))\n print('Making Network....')\n for i in range(size):\n #using Regex to get the number of the two document we are comparing\n m = re.findall(r\"\\d\", self.docLabels[i])\n m = index(m)\n for j in range(i+1, size):\n n = re.findall(r\"\\d\", self.docLabels[j])\n n = index(n)\n sim_doc = model.docvecs.similarity(i,j)\n G[m][n] = sim_doc\n G[n][m] = sim_doc\n \n numpy.savetxt(\"firstLayer.csv\", G, delimiter= \",\")\n print('NetWork saved.')\n return 0\n\nc = commentsLayer()\nc.com2txt()\n#c.createNetwork()\n\n\n\n\n\n\n\n \n","sub_path":"comments_layer.py","file_name":"comments_layer.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"646589575","text":"from RBNode import RBTNode\r\n\r\n\r\nclass RedBlackTree:\r\n def __init__(self):\r\n self.root = None\r\n\r\n def __len__(self):\r\n if self.root is None:\r\n return 0\r\n return self.root.count()\r\n\r\n def insert(self, key):\r\n new_node = RBTNode(key, None, True, None, None)\r\n self.insert_node(new_node)\r\n\r\n def insert_node(self, node):\r\n\r\n if self.root is None:\r\n self.root = node\r\n else:\r\n cur_node = self.root\r\n while cur_node is not None:\r\n if node.key < cur_node.key:\r\n if cur_node.left is None:\r\n cur_node.set_child(\"left\", node)\r\n break\r\n else:\r\n cur_node = cur_node.left\r\n else:\r\n if cur_node.right is None:\r\n cur_node.set_child(\"right\", node)\r\n break\r\n else:\r\n cur_node = cur_node.right\r\n\r\n node.color = \"red\"\r\n\r\n self.insertion_balance(node)\r\n\r\n def is_none_black(self, node):\r\n if node is None:\r\n return True\r\n return node.is_black()\r\n\r\n def is_not_empty_red(self, node):\r\n if node is None:\r\n return False\r\n return node.is_red()\r\n\r\n def rotate_left(self, node):\r\n right_left_child = node.right.left\r\n if node.parent is not None:\r\n node.parent.replace_child(node, node.right)\r\n else: # node is root\r\n self.root = node.right\r\n self.root.parent = None\r\n node.right.set_child(\"left\", node)\r\n node.set_child(\"right\", right_left_child)\r\n\r\n def rotate_right(self, node):\r\n left_right_child = node.left.right\r\n if node.parent is not None:\r\n node.parent.replace_child(node, node.left)\r\n else: # node is root\r\n self.root = node.left\r\n self.root.parent = None\r\n node.left.set_child(\"right\", node)\r\n node.set_child(\"left\", left_right_child)\r\n\r\n def insertion_balance(self, node):\r\n # If node is root, set color black\r\n if node.parent is None:\r\n node.color = \"black\"\r\n return\r\n\r\n if node.parent.is_black():\r\n return\r\n\r\n parent = node.parent\r\n grandparent = node.get_grandparent()\r\n uncle = node.get_uncle()\r\n\r\n # change parent and uncle from red to black to color grandparent red\r\n if uncle is not None and uncle.is_red():\r\n parent.color = \"black\"\r\n uncle.color = \"black\"\r\n grandparent.color = \"red\"\r\n self.insertion_balance(grandparent)\r\n return\r\n\r\n # If node is parent's right and parent is grandparent's left, rotate left at parent\r\n if node is parent.right and parent is grandparent.left:\r\n self.rotate_left(parent)\r\n node = parent\r\n parent = node.parent\r\n # If node is parent's left and parent is grandparent's right, rotate right at parent\r\n elif node is parent.left and parent is grandparent.right:\r\n self.rotate_right(parent)\r\n node = parent\r\n parent = node.parent\r\n\r\n # change parent black and grandparent red\r\n parent.color = \"black\"\r\n grandparent.color = \"red\"\r\n\r\n # If node is parent's left child, then rotate right at grandparent, otherwise rotate left at grandparent\r\n if node is parent.left:\r\n self.rotate_right(grandparent)\r\n else:\r\n self.rotate_left(grandparent)\r\n\r\n def _bst_remove(self, key):\r\n node = self.search(key)\r\n self._bst_remove_node(node)\r\n\r\n def _bst_remove_node(self, node):\r\n if node is None:\r\n return\r\n\r\n # Root node (with 1 or 0 children)\r\n elif node is self.root:\r\n if node.left is not None:\r\n self.root = node.left\r\n else:\r\n self.root = node.right\r\n\r\n if self.root is not None:\r\n self.root.parent = None\r\n\r\n # Internal, left child only else right child only\r\n elif node.left is not None:\r\n node.parent.replace_child(node, node.left)\r\n else:\r\n node.parent.replace_child(node, node.right)\r\n\r\n # Internal node with 2 child nodes\r\n if node.left is not None and node.right is not None:\r\n successor_node = node.right\r\n while successor_node.left is not None:\r\n successor_node = successor_node.left\r\n\r\n successor_key = successor_node.key\r\n\r\n self._bst_remove_node(successor_node)\r\n\r\n node.key = successor_key\r\n\r\n def remove(self, key):\r\n node = self.search(key)\r\n if node is not None:\r\n self.remove_node(node)\r\n return True\r\n return False\r\n\r\n def remove_node(self, node):\r\n if node.left is not None and node.right is not None:\r\n predecessor_node = node.get_predecessor()\r\n predecessor_key = predecessor_node.key\r\n self.remove_node(predecessor_node)\r\n node.key = predecessor_key\r\n return\r\n\r\n if node.is_black():\r\n self.prepare_for_removal(node)\r\n self._bst_remove(node.key)\r\n\r\n # One special case if the root was changed to red\r\n if self.root is not None and self.root.is_red():\r\n self.root.color = \"black\"\r\n\r\n def search(self, key):\r\n current_node = self.root\r\n while current_node is not None:\r\n # Return the node if the key matches.\r\n if current_node.key == key:\r\n return current_node\r\n # Move left if key is less than the node's key.\r\n elif key < current_node.key:\r\n current_node = current_node.left\r\n # Move right if key is bigger than the node's key.\r\n else:\r\n current_node = current_node.right\r\n\r\n # key not found\r\n return None\r\n","sub_path":"Lab 3/RBTree.py","file_name":"RBTree.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459067913","text":"\"\"\"Configuration file for the Sphinx documentation builder.\n\nhttps://www.sphinx-doc.org/en/master/usage/configuration.html\n\"\"\"\nimport os\nimport sys\n\nimport sphinx_rtd_theme # noqa:F401\n\n\nsys.path.insert(0, os.path.abspath('../..'))\n\nproject = 'Python Polympics Wrapper'\ncopyright = '2021, Artemis'\nauthor = 'Artemis'\nrelease = '0.6.2'\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx_rtd_theme'\n]\n\nhtml_theme = 'sphinx_rtd_theme'\n","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129428344","text":"#!/usr/bin/env python\nfrom django.http import HttpResponse\nimport os\nimport json\n\ndef ProjectList(request):\n\n data = \"{\\n\"\n first = True\n\n for root, dirs, files in os.walk(\"./projects/\"):\n for file in files:\n if file.endswith(\".cxml\"):\n if first == False:\n data += \",\\n\"\n else:\n first = False\n data += \"\\t\\\"\" + file + \"\\\": \\\"\" + os.path.join(root, file).replace(\"\\\\\", \"/\") + \"\\\"\"\n \n data += \"\\n}\"\n return HttpResponse(data, content_type=\"application/json\")","sub_path":"pv/project_list.py","file_name":"project_list.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611710954","text":"\n# coding: utf-8\n\n# In[58]:\n\nimport numpy as np\n\n#Data Definitions\nN = 100\nd_in = 10\nd_out = 1\n\ninput = np.random.randn(N,d_in)\noutput = np.random.randn(N, d_out)\n\n#Neural Network Definitions\nhidden_size = 2\n\nW1 = np.random.randn(d_in, hidden_size)\nW2 = np.random.randn(hidden_size, d_out)\n\n#Training parameters\nnum_epochs = 4000\nlr = 0.0001\n\n\n# In[59]:\n\ndef learn(W1,W2,input,output, num_epochs,switch=True):\n loss_vals = []\n\n for e in range(num_epochs):\n\n #Forward Pass\n h = input.dot(W1) #Shape [N, hidden_size]\n h_relu = np.maximum(h,0)\n y = h.dot(W2)\n\n loss = np.average(np.square(y - output), axis=0)\n print(\"loss is \" + str(loss.T))\n\n loss_grad = 2 * (y - output) #Shape [N, d_out]\n w2_grad = np.average(loss_grad * h_relu,axis = 0)\n w2_grad = np.expand_dims(w2_grad, axis=1)\n\n\n h_relu_grad = np.average(h_relu>0, axis=0)\n relu_mask = np.expand_dims(h_relu_grad * W2[:,0],axis=1)\n\n averaged_weight = np.average(loss_grad * input, axis=0) #shape: [d_in,]\n \n #Taking care of ReLUs\n if(switch):\n w1_grad = averaged_weight * relu_mask\n\n #Not Taking care of ReLUs\n if(not switch):\n w1_grad = averaged_weight * W2\n\n W1 = W1 - lr * w1_grad.transpose()\n W2 = W2 - lr * w2_grad\n\n loss_vals.append(loss)\n \n return loss_vals\n\n \n\n\n# In[60]:\n\nfrom matplotlib import pyplot as plt\nfrom copy import copy as cp\n\nW1_temp = cp(W1)\nW2_temp = cp(W2)\n\n\nloss_vals_relu_on = learn(W1_temp,W2_temp,input,output,num_epochs)\n\nW1_temp = cp(W1)\nW2_temp = cp(W2)\nloss_vals_relu_off = learn(W1_temp,W2_temp,input,output,num_epochs, False)\n\nplt.plot(loss_vals_relu_on, label='relu_on')\nplt.plot(loss_vals_relu_off, label='relu_off')\nplt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n","sub_path":"FC_net/fc.py","file_name":"fc.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"592981440","text":"import time\nimport datetime\n\nfrom sumologic import sumologic\n\nfrom disclose_ai.abc.client import AbstractClient\nfrom disclose_ai.abc.service import AbstractService\n\n\nclass SumoLogicClient(AbstractClient):\n def __init__(self, *, access_id, access_key):\n self._client = sumologic.SumoLogic(access_id, access_key)\n\n def delete_search_job(self, search_job):\n return self._client.delete('/search/jobs/' + str(search_job['id']))\n\n\nclass SumoLogicService(AbstractService):\n DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'\n\n GATHERING_RESULTS_STATE = 'GATHERING RESULTS'\n DONE_GATHERING_RESULTS_STATE = 'DONE GATHERING RESULTS'\n CANCELLED_STATE = 'CANCELLED'\n\n def __init__(self, *, access_id, access_key):\n self._client = SumoLogicClient(access_id=access_id, access_key=access_key)\n\n def search(self, query, *, from_time, to_time, limit):\n search_job = self._client.search_job(\n query,\n fromTime=from_time.strftime(self.DATETIME_FORMAT),\n toTime=to_time.strftime(self.DATETIME_FORMAT))\n\n try:\n status = self._client.search_job_status(search_job)\n while status['state'] != self.DONE_GATHERING_RESULTS_STATE:\n if status['state'] == self.CANCELLED_STATE:\n break\n\n time.sleep(0.1)\n status = self._client.search_job_status(search_job)\n else:\n count = status['messageCount']\n limit = count if count < limit and count != 0 else limit\n job_messages = self._client.search_job_messages(search_job, limit=limit)\n return job_messages['messages']['map']['_raw']\n finally:\n self._client.delete_search_job(search_job)\n\n\nsumo = SumoLogicService(\n access_id='su6pUpeGpJ26Dg',\n access_key='jsj8D2JJyUIlK9saNxiULCbGLVWBLcFO8HCMFGlZ3oGpLv2hIWIJwvVpqo7WYRmY')\n\nq = \"\"\"\n _collector=prod-fulfillment-api-v2-build*\n \"\"\"\n\nfor m in sumo.search(\n q,\n from_time=datetime.datetime.utcnow() - datetime.timedelta(minutes=2),\n to_time=datetime.datetime.utcnow(),\n limit=50):\n print(m)\n","sub_path":"app/disclose_ai/integrations/sumo_logic.py","file_name":"sumo_logic.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587572993","text":"\n# coding: utf-8\n\n# # Binomial Distribution\n# \n# ----\n# \n# ## 1. Tổng quan : \n# Nếu các biến X tuân theo luật phân phối nhị thức với parameter :\n# - n ∈ ℕ (n là số lượng phép thử, ℕ số lần lặp lại phép thử)\n# - p ∈ [0,1] : p xác xuất True or False \n# - k : Số lần thành công trong n phép thử đó.\n# \n# #### Kí hiệu : X ~ B(n, p). B viết tắt Binomial\n# \n# Ví dụ : Tung 5 đồng xu (n = 5), xác xuất xuất hiện mặt trước và sau là như nhau (p = 0.5), ta thu được 2 đồng sấp, 3 đồng ngữa.\n# Gọi k là số mặt ngữa, ta có k = 2.\n# \n# Thực hiện việc tung 5 đồng xu trên 100 lần (N = 100), ta thu được tập k chứa các phần tử có giá trị p ∈ [0,5].\n# \n# ## 2. Probability\n# \n# Xác xuất để có k lần thành công : \n# \\begin{equation*}\n# Pr(X=k) = C{n \\choose k} p^k (1-p)^{ n-k}\n# \\end{equation*}\n# \n# Với k = 0,1,2,...,n thì : (combinaisons - Tổ hợp)\n# \\begin{equation*}\n# C{n \\choose k} = \\frac{n!}{k!(n-k)!}\n# \\end{equation*}\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import binom\nimport matplotlib.pyplot as plt\n\n\n# ## 3. Công thức\n# \n# Trong đó : \n# - Factoria : Function giai thừa\n# - Combinasisons : Function tính tổ hợp \n# - Pr_Binomail : Function tính xác suất thành công với (n : số phép thử mỗi lần, p : Xác xuất thành công, k : số thành công)\n\n# In[61]:\n\n\n# factorial - Giai thừa\ndef factoria(n):\n x = 1\n if n==0:\n return 1\n for i in range(n):\n x = x * (i+1)\n return x\n\n# Combinaisons - Tổ hợp\n# Từ 1 hộp 4 viên xanh đỏ tím vàng, có bao nhiêu cách lấy ra 2 viên, biết (xanh đỏ) (đỏ xanh) là một\ndef combinaisons(n, k): \n return (factoria(n) / ((factoria(k) * (factoria(n-k)))))\n\n# Probability \ndef pr_binomial(n, p, k):\n '''\n n : Số phép thử trong 1 lần\n p : Xác xuất thành công mỗi phép thử\n k : Số lần thanahf công trong mỗi phép thử\n '''\n return combinaisons(n, k) * np.power(p,k) * np.power(1-p, n-k)\n\n\n# ## 4. Example\n# \n# ### 4.1 Example 1 : Tung 1 đồng xu với xác xuất 0.5\n# Tạo Sample Data đếm số mặt sấp và ngữa khi tung 1 đồng xu.\n# \n# Trong đó : \n# - n = 1. (Tung1 đồng xu)\n# - p = 0,5 Xác xuất xuất hiện 2 mặt là như nhau\n# - N = 1000. Thực hiện 1000 phép thử\n# \n# K có 2 giá trị :\n# - 0 : không có mặt ngữa nào xuất hiện\n# - 1 : Có 1 mặt ngữa xuất hiện\n# \n# 【ASK】Tính xác xuất : \n# - Pr(0)\n# - Pr(1)\n\n# In[22]:\n\n\nN = 1000\nsample = pd.DataFrame(np.random.binomial(n = 1, p = 0.5, size = N), columns=['count'])\nsample['temp'] = [1] * len(sample)\n\n\n# #### 4.1.1 Tập data ghi lại kết quả sau mỗi lần tung đồng xu\n\n# In[58]:\n\n\npd.DataFrame(sample['count'].head())\n\n\n# #### 4.1.2 Xác xuất được tính theo data\n\n# In[59]:\n\n\nsample.groupby('count').count()/N\n\n\n# In[30]:\n\n\nprint('Xác xuất xuất hiện K = 0 và K = 1 là như nhau = 0.5')\nplt.hist(sample['count'])\n\n\n# #### 4.1.3 Xác xuất tính theo công thức\n\n# In[64]:\n\n\n# n = 1 , p = 0.5, k = 1)\n\nprint('Xác xuất suất hiện mặt ngữa là : '+str(pr_binomial(1, 0.5, 1)))\n\n\n# ### 4.2 Example 2 : Tung 5 đồng xu với xác xuất 0.5\n# \n# Tạo Sample Data đếm số mặt sấp và ngữa khi tung 1 đồng xu.\n# \n# Trong đó : \n# - n = 5. (Tung 5 đồng xu)\n# - p = 0,5 Xác xuất xuất hiện 2 mặt là như nhau\n# - N = 1000. Thực hiện 1000 phép thử\n# \n# K có 5 giá trị :\n# - 0 : không có mặt ngữa nào xuất hiện\n# - 1 : Có 1 mặt ngữa xuất hiện\n# - 2 : Có 2 mặt ngữa xuất hiện\n# - 3 : Có 3 mặt ngữa xuất hiện\n# - 4 : Có 4 mặt ngữa xuất hiện\n# - 5 : Có 5 mặt ngữa xuất hiện\n# \n# 【ASK】Tính xác xuất : \n# - Pr(k = 0)\n# - Pr(k = 1)\n# - Pr(k = 2)\n# - Pr(k = 3)\n# - Pr(k = 4)\n# - Pr(k = 5)\n\n# In[81]:\n\n\nN = 1000\nsample1 = pd.DataFrame(np.random.binomial(n = 5, p = 0.5, size = N), columns = ['count'])\nsample1['temp'] = [1] * len(sample1)\n\n\n# #### 4.2.1 Tập data ghi lại kết quả sau mỗi lần tung đồng xu\n\n# In[86]:\n\n\npd.DataFrame(sample1['count'][0:10])\n\n\n# #### 4.1.2 Xác xuất được tính theo data\n\n# In[91]:\n\n\nsample1.groupby('count').count()/N\n\n\n# In[93]:\n\n\n(sample1.groupby('count').count()/N).plot()\n\n\n# #### 4.1.3 Xác xuất tính theo công thức\n\n# In[117]:\n\n\npr = []\nfor i in range(6):\n pr.append(pr_binomial(5, 0.5, i))\n\npd.DataFrame(pr).plot()\n\n\n# #### So sánh xác xuất được tính dựa vào data thực tế và xác xuất dựa vào công thức, ta thấy kết quả xấp xỉ nhau\n\n# In[120]:\n\n\nprint('Kết quả được tính dựa theo công thức : ')\npd.DataFrame(pr)\n\n\n# In[122]:\n\n\nprint('Kết quả được tính dựa vào data : ')\nsample1.groupby('count').count()/N\n\n\n# ### 4.3 Example 3 : Tung 5 đồng xu với xác xuất 0.3\n# \n# #### Assumptions : Đồng xu không đều, mặt sấp xuất hiện ít hơn mặt ngữa. Xác xuất xuất hiện mặt sấp là 0.3\n# \n# Tạo Sample Data đếm số mặt sấp và ngữa khi tung 1 đồng xu.\n# \n# Trong đó : \n# - n = 5. (Tung 5 đồng xu)\n# - p = 0,3 Xác xuất xuất hiện 2 mặt là như nhau\n# - N = 1000. Thực hiện 1000 phép thử\n# \n# K có 5 giá trị :\n# - 0 : không có mặt ngữa nào xuất hiện\n# - 1 : Có 1 mặt ngữa xuất hiện\n# - 2 : Có 2 mặt ngữa xuất hiện\n# - 3 : Có 3 mặt ngữa xuất hiện\n# - 4 : Có 4 mặt ngữa xuất hiện\n# - 5 : Có 5 mặt ngữa xuất hiện\n# \n# 【ASK】Tính xác xuất : \n# - Pr(k = 0)\n# - Pr(k = 1)\n# - Pr(k = 2)\n# - Pr(k = 3)\n# - Pr(k = 4)\n# - Pr(k = 5)\n\n# In[130]:\n\n\nsample4 = pd.DataFrame(np.random.binomial(n = 5, p = 0.3, size = N), columns = ['count'])\nsample4['temp'] = [1] * len(sample4)\n\n\n# ## Analytics : \n# \n# Từ đồ thị, thấy rằng xác xuất xuất hiện mặt sấp = 1 trong 5 lần tung là cao nhất.\n\n# In[134]:\n\n\nsample4.groupby('count').count().plot()\n\n\n# In[136]:\n\n\nprint('Xác xuất tính theo data : ')\nsample4.groupby('count').count()/N\n\n\n# In[138]:\n\n\nprint('Xác xuất tính theo công thức : ')\npr = []\nfor i in range(6):\n pr.append(pr_binomial(5, 0.3, i))\n\npd.DataFrame(pr)\n\n\n# ## 5. Example from Real world\n# \n# Bài toán thực tế : \n# \n# Dây chuyển sản xuất Iphone gồm 10 Robot, cứ mỗi giờ tình trạng của Robot được update với Status [Hỏng, Chạy tốt]\n# * Xác xuất một máy có khả năng hỏng mỗi giờ 10%.\n# \n# Tìm xác xuất các trường hợp sau : \n# * TH1. Một máy hỏng \n# * TH2. 2 máy hỏng cùng lúc\n# * TH3. 3 máy hỏng cùng lúc\n# * TH4. 4 máy hỏng cùng lúc\n# ....\n# * TH10. 10 máy hỏng cùng lúc\n","sub_path":"07_Statistics/03_Distribution/03_Binomial Distribution.py","file_name":"03_Binomial Distribution.py","file_ext":"py","file_size_in_byte":6854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457265255","text":"import hashlib, time\n\nstartSeed = str(time.time()) + '|'\nmin = 10\nmax = 20\nfor i in range(5):\n nextSeed = startSeed + str(i)\n hash = hashlib.sha256(nextSeed.encode('ascii')).digest()\n bigRand = int.from_bytes(hash, 'big')\n rand = min + bigRand % (max - min + 1)\n print(nextSeed, bigRand, '-->', rand)\n","sub_path":"pseudoRN.py","file_name":"pseudoRN.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47288170","text":"#Webbrowser prank! :)\n\nimport webbrowser\nfrom random import randint\nimport time\nimport sys\n\nx = 10\ndef interval():\n while True:\n time.sleep(randint(300,600))\n webbrowser.open('https://www.youtube.com/watch?v=iFzncBVM9Js')\n\ndef spam():\n while True:\n time.sleep(0)\n webbrowser.open('https://www.youtube.com/watch?v=iFzncBVM9Js')\n\ndef kill():\n quit()\ndef countdown(x):\n while True:\n time.sleep(1)\n x = x - 1\n print(\"You have\", x, \"seconds until spam!\")\n if x <= 0:\n print(\"Spam has begun\")\n spam()\n break\n\n","sub_path":"Projects/Webbrowser Prank 101 very epic much gamer.py","file_name":"Webbrowser Prank 101 very epic much gamer.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"139644195","text":"\"\"\"Get daily forecast from IMS.gov\"\"\"\r\nimport html\r\nimport json\r\nfrom datetime import datetime as dt\r\nfrom time import sleep\r\n\r\nimport feedparser\r\nfrom paho.mqtt import client as mqtt\r\n\r\nRSS = \"https://ims.gov.il/sites/default/files/ims_data/rss/forecast_country/rssForecastCountry_he.xml\"\r\nBROKER = \"10.0.0.6\"\r\nFEED = task.executor(feedparser.parse, RSS)\r\n\r\nclient = mqtt.Client()\r\n\r\n\r\ndef state() -> str:\r\n \"\"\"Return the state of the sensor.\"\"\"\r\n for item in FEED.entries:\r\n last_updated = str(item.guid).replace(\"Country \", \"\")\r\n last_updated = str(dt.strptime(last_updated, \"%a, %d %b %Y %H:%M:%S GMT\"))\r\n\r\n return last_updated\r\n\r\n\r\ndef link() -> str:\r\n \"\"\"Return the link.\"\"\"\r\n link = FEED.feed.link\r\n\r\n return link\r\n\r\n\r\n# The order is importent\r\nslag = [\r\n \"br />\",\r\n \"/b>\",\r\n \"b>\",\r\n \">\",\r\n \"style="text-decoration: underline;"\",\r\n \"<\",\r\n \"/font>\",\r\n \""\",\r\n \"עדכון אחרון:\",\r\n \"font \",\r\n \"/\",\r\n]\r\n\r\n\r\ndef clean(desc) -> str:\r\n \"\"\"Helper method that clean-up the feed.\"\"\"\r\n # First pass\r\n for i in slag:\r\n desc = desc.replace(i, \" \")\r\n\r\n # Second pass\r\n # The order is importent\r\n desc = desc.replace(\":\", \"\\n\")\r\n desc = desc.replace(\"\\n\", \" \")\r\n desc = desc.replace(\" \", \"\")\r\n desc = desc.replace(\" \", \" \")\r\n desc = desc.replace(\"-\", \"\")\r\n\r\n # Replace common acronyms\r\n desc = desc.replace(\"אחה צ\", \"אחר הצהריים\")\r\n desc = desc.replace(\"בד כ\", \"בדרך כלל\")\r\n\r\n # Remove numbers\r\n cleaned_str = \"\".join([i for i in desc if not i.isdigit()])\r\n\r\n return cleaned_str\r\n\r\n\r\ndef short_term_forecast() -> str:\r\n \"\"\"Get short term forecast from feed.\"\"\"\r\n for item in FEED.entries:\r\n desc = html.escape(item.description)\r\n\r\n sep = \"/font>\"\r\n desc = desc.split(sep, 1)[1]\r\n sep = \"תחזית לימים הקרובים\"\r\n desc = desc.split(sep, 1)[0]\r\n\r\n desc = clean(desc)\r\n\r\n short_term = desc.strip()\r\n\r\n return short_term\r\n\r\n\r\ndef long_term_forecast() -> str:\r\n \"\"\"Get long term forecast from feed.\"\"\"\r\n for item in FEED.entries:\r\n desc = html.escape(item.description)\r\n\r\n sep = \"תחזית לימים הקרובים\"\r\n desc = desc.split(sep, 1)[1]\r\n\r\n desc = clean(desc)\r\n\r\n long_term = desc.strip()\r\n\r\n return long_term\r\n\r\n\r\ndef get_attributes() -> dict:\r\n \"\"\"Get all atrributes.\"\"\"\r\n attrs = json.dumps(\r\n {\r\n \"short_term\": short_term_forecast(),\r\n \"long_term\": long_term_forecast(),\r\n \"link\": link(),\r\n \"last_fetched\": str(dt.now().strftime(\"%d/%m %H:%M\")),\r\n },\r\n ensure_ascii=False,\r\n indent=2,\r\n )\r\n\r\n return attrs\r\n\r\n\r\n@service\r\ndef ims_sensor():\r\n \"\"\"Send IMS data over MQTT.\"\"\"\r\n client.connect(BROKER)\r\n log.info(f\"Connected\")\r\n\r\n client.publish(\"homeassistant/ims\", state())\r\n client.publish(\"homeassistant/ims/attrs\", get_attributes())\r\n log.info(f\"Published\")\r\n\r\n sleep(3)\r\n\r\n client.disconnect()\r\n log.debug(f\"Disconnected\")\r\n","sub_path":"homeassistant/config/pyscript/ims2mqtt.py","file_name":"ims2mqtt.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347265614","text":"from os import environ, mkdir, name\nfrom shutil import copy2 as copia\nimport crypt\n\nimport funcoesPrincipais as fPrn, funcoesAuxiliares as fAux\n\ndef iniciaProcedimento():\n #caminhoArquivoOriginal = fAux.loopPergunta(\"Qual arquivo devo abrir? \", False, str)\n caminhoArquivoOriginal = \"/home/lucas/passow/passwd.txt\"\n arquivoLeitura = open(caminhoArquivoOriginal, 'r+')\n\n print(\"Bem-vindo a este utilitário, selecione o que deseja fazer com os usuários:\")\n acao = fAux.loopPergunta(\" 1. Listar \\n 2. Adicionar \\n 3. Editar \\n 4. Remover \\n Escolha: \", False)\n if(acao == \"1\" or acao.upper().find(\"LIS\") != -1):\n fPrn.listaUsuarios(arquivoLeitura)\n elif(acao == \"2\" or acao.upper().find(\"AD\") != -1):\n if(fPrn.criaUsuario(arquivoLeitura, caminhoArquivoOriginal) == \"erro\"):\n fPrn.criaUsuario(arquivoLeitura, caminhoArquivoOriginal)\n elif(acao == \"3\" or acao.upper().find(\"ED\") != -1):\n string = fAux.loopPergunta(\"Informe o username ou UID do usuário a ser editado: \", False)\n fPrn.editaUsuario(string, arquivoLeitura, caminhoArquivoOriginal)\n elif(acao == \"4\" or acao.upper().find(\"rem\".upper()) != -1):\n string = fAux.loopPergunta(\"Informe o username ou UID do usuário a ser excluído: \", False)\n fPrn.excluirUsuario(string, arquivoLeitura, caminhoArquivoOriginal)\n\n\niniciaProcedimento()\n","sub_path":"passwd.py","file_name":"passwd.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"332156422","text":"#\n# Copyright (c) 2023 Airbyte, Inc., all rights reserved.\n#\n\n\nfrom typing import Any, List, Mapping, Tuple\n\nfrom airbyte_cdk.models import SyncMode\nfrom airbyte_cdk.sources import AbstractSource\nfrom airbyte_cdk.sources.streams import Stream\nfrom source_lemlist.auth import HttpBasicAuthenticator\n\nfrom .streams import Activities, Campaigns, Team, Unsubscribes\n\n\nclass SourceLemlist(AbstractSource):\n def check_connection(self, logger, config) -> Tuple[bool, any]:\n try:\n auth = HttpBasicAuthenticator(\n (\n \"\",\n config[\"api_key\"],\n ),\n )\n\n team_stream = Team(authenticator=auth)\n team_gen = team_stream.read_records(sync_mode=SyncMode.full_refresh)\n\n next(team_gen)\n return True, None\n except Exception as error:\n return False, f\"The provided API key {config['api_key']} is invalid. - {repr(error)}\"\n\n def streams(self, config: Mapping[str, Any]) -> List[Stream]:\n auth = HttpBasicAuthenticator(\n (\n \"\",\n config[\"api_key\"],\n ),\n )\n return [Team(authenticator=auth), Campaigns(authenticator=auth), Activities(authenticator=auth), Unsubscribes(authenticator=auth)]\n","sub_path":"dts/airbyte/airbyte-integrations/connectors/source-lemlist/source_lemlist/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243225361","text":"import os\nimport shutil\nimport subprocess\nimport sys\n\nimport click\nimport userpath\n\nfrom hatch.commands.utils import (\n CONTEXT_SETTINGS, echo_failure, echo_info, echo_success, echo_waiting,\n echo_warning\n)\nfrom hatch.conda import get_conda_new_exe_path\nfrom hatch.config import get_python_dir\nfrom hatch.settings import copy_default_settings, load_settings, save_settings\nfrom hatch.utils import ON_WINDOWS, conda_available, resolve_path\n\n\n@click.command(context_settings=CONTEXT_SETTINGS, short_help='Manages Python installations')\n@click.argument('version')\n@click.argument('name', required=False)\n@click.option('--head/--tail', is_flag=True, default=None,\n help='Adds the installation to the head or tail of the user PATH.')\ndef python(version, name, head): # no cov\n if not conda_available():\n echo_failure('Conda is unavailable. You can install it by doing `hatch conda`.')\n sys.exit(1)\n\n exe_name = 'py{}'.format(name or version) + ('.exe' if ON_WINDOWS else '')\n name = name or version\n path = os.path.join(get_python_dir(), name)\n command = ['conda', 'create', '--yes', '-p', path, 'python={}'.format(version)]\n\n if os.path.exists(path):\n echo_failure('The path `{}` already exists.'.format(path))\n sys.exit(1)\n\n settings = load_settings(lazy=True)\n if 'pypaths' not in settings:\n updated_settings = copy_default_settings()\n updated_settings.update(settings)\n settings = updated_settings\n echo_success('Settings were successfully updated to include `pypaths` entry.')\n\n old_path = settings['pypaths'].get(name)\n if old_path:\n echo_failure('The Python path `{}` already points to `{}`.'.format(name, old_path))\n sys.exit(1)\n\n echo_waiting('Installing Python {}...'.format(version))\n try:\n subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n except subprocess.CalledProcessError as e:\n echo_failure('The installation was seemingly unsuccessful.')\n click.echo(e.stdout)\n click.echo(e.stderr)\n sys.exit(e.returncode)\n\n conda_path = get_conda_new_exe_path(path)\n python_path = resolve_path(shutil.which('python', path=conda_path))\n settings['pypaths'][name] = python_path\n save_settings(settings)\n echo_success('Successfully saved Python `{}` located at `{}`.'.format(name, python_path))\n\n if head is not None:\n add_to_path = userpath.prepend if head else userpath.append\n success = add_to_path(conda_path, app_name='Hatch')\n shutil.copy(python_path, os.path.join(os.path.dirname(python_path), exe_name))\n\n if success:\n echo_info(\n 'Please restart your shell for PATH changes to take effect.'\n )\n else:\n echo_warning(\n 'It appears that we were unable to modify PATH. Please '\n 'do so using the following: ', nl=False\n )\n echo_info(conda_path)\n","sub_path":"hatch/commands/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381220269","text":"from simple_vector_library import Py_Vector\nimport numpy as np\nimport math\nfrom random import *\nimport global_settings as gls\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nclass Bubble:\n def __init__(self, radius, mass, ID, resolution):\n #self.pos = Py_Vector(randint(radius, gls.SCREENWIDTH - radius), randint(radius, gls.SCREENHEIGHT - radius))\n self.pos = Py_Vector(0, 0)\n self.vel = Py_Vector(randint(-5, 5), randint(-4, 4))\n self.accel = Py_Vector(0, 0)\n\n self.resolution = resolution\n\n self.preExpansivePos = Py_Vector(0, 0)\n self.expansiveVelocity = Py_Vector(0, 0)\n\n self.radius = radius\n self.mass = mass\n\n self.ID = ID\n\n self.noteList = []\n\n self.vertList = []\n self.shineVertList = []\n self.calculateVerticies()\n\n '''\n def draw(self):\n glLineWidth(4)\n glBegin(GL_LINE_LOOP)\n for i in range(self.resolution):\n theta = 2.0 * 3.1415926 * i/self.resolution\n x = self.radius * math.cos(theta)\n y = self.radius * math.sin(theta)\n glVertex2f(self.pos.x_component + x, self.pos.y_component + y)\n glEnd()\n\n #Bubble shine\n glBegin(GL_LINE_LOOP)\n for i in range(math.ceil(self.resolution/8)):\n theta = 2.0 * 3.1415926 * i/(self.resolution)\n x = (self.radius * 0.75) * np.cos(theta)\n y = (self.radius * 0.75) * np.sin(theta)\n glVertex2f(self.pos.x_component + x, self.pos.y_component + y)\n glEnd()\n '''\n\n def draw(self):\n glLineWidth(5)\n glBegin(GL_LINE_LOOP)\n for i in range(0, len(self.vertList,), 2):\n glVertex2f(self.pos.x_component + self.vertList[i],\n self.pos.y_component + self.vertList[i + 1])\n\n glEnd()\n\n glBegin(GL_LINE_LOOP)\n for i in range(0, len(self.shineVertList), 2):\n glVertex2f(self.pos.x_component + self.shineVertList[i],\n self.pos.y_component + self.shineVertList[i + 1])\n glEnd()\n\n def calculateVerticies(self):\n for i in range(self.resolution):\n theta = 2.0 * 3.1415926 * (i/self.resolution)\n x = self.radius * math.cos(theta)\n y = self.radius * math.sin(theta)\n self.vertList.append(math.ceil(x))\n self.vertList.append(math.ceil(y))\n\n for i in range(math.ceil(self.resolution/8)):\n theta = 2.0 * 3.145926 * i/(self.resolution)\n x = (self.radius * 0.75) * math.cos(theta)\n y = (self.radius * 0.75) * math.sin(theta)\n self.shineVertList.append(math.ceil(x))\n self.shineVertList.append(math.ceil(y))\n\n\n def update(self, STATE):\n if(STATE == 'floating'):\n #this.vel.add(this.accel)\n self.pos.add(self.vel)\n if(self.pos.x_component >= gls.SCREENWIDTH - (self.radius + 3)):\n self.vel.x_component *= -1\n self.pos.x_component = (gls.SCREENWIDTH - (self.radius + 3))\n\n if(self.pos.x_component <= self.radius + 3):\n self.vel.x_component *= -1\n self.pos.x_component = (self.radius + 3)\n\n if(self.pos.y_component >= gls.SCREENHEIGHT - (self.radius+3)):\n self.vel.y_component *= -1\n self.pos.y_component = (gls.SCREENHEIGHT - (self.radius + 3))\n\n if(self.pos.y_component <= self.radius+3):\n self.vel.y_component *= -1\n self.pos.y_component = (self.radius + 3)\n elif(STATE == 'expansion'):\n self.pos.add(self.expansiveVelocity)\n elif(STATE == 'closing'):\n self.pos.sub(self.expansiveVelcoity)\n\n self.vel.limit(5)\n\n def expansiveDraw(self):\n glLineWidth(4)\n glBegin(GL_LINE_LOOP)\n for i in range(self.resolution):\n theta = 2.0 * 3.1415926 * i/self.resolution\n x = self.radius * math.cos(theta)\n y = self.radius * math.sin(theta)\n glVertex2f(self.pos.x_component + x, self.pos.y_component + y)\n glEnd()\n\n #Removing the shine as the bubbles are bouncing speeds up\n # the expansion animation\n '''\n #Bubble shine\n glBegin(GL_TRIANGLES)\n for i in range(math.ceil(self.resolution/8)):\n theta = 2.0 * 3.1415926 * i/(self.resolution)\n x = (self.radius * 0.75) * np.cos(theta)\n y = (self.radius * 0.75) * np.sin(theta)\n glVertex2f(self.pos.x_component + x, self.pos.y_component + y)\n glEnd()\n '''\n","sub_path":"Floating_Note_OpenGL/Bubble.py","file_name":"Bubble.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129094441","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.utils.text import slugify\nfrom django.urls import reverse\nfrom time import time\nfrom math import ceil\n# from geopy.geocoders import Nominatim # Nominatim - geocoder OpenStreetMaps\nfrom geopy.geocoders import GoogleV3\nfrom django_countries.fields import CountryField\nfrom django.conf import settings\nimport PIL\nfrom io import BytesIO\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nimport sys\nfrom .managers import OfferManager\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=200,\n db_index=True)\n slug = models.SlugField(max_length=200,\n db_index=True,\n unique=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name = 'category'\n verbose_name_plural = 'categories'\n\n # def save(self, *args, **kwargs):\n # if not self.slug:\n # self.slug = slugify(self.name)\n # super(Category, self).save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('offer:offer_list_by_category',\n args=[self.slug])\n\n def __str__(self):\n return self.name\n\n\nclass Offer(models.Model):\n STATUS_CHOICES = (\n ('draft', 'Draft'),\n ('active', 'Active'),\n )\n CURRENCY_CHOICES = (\n ('USD', 'USD'),\n ('EUR', 'EUR'),\n ('PLN', 'PLN'),\n ('CHF', 'CHF'),\n ('GBP', 'GBP'),\n ('AUD', 'AUD'),\n ('CAD', 'CAD'),\n ('JPY', 'JPY'),\n ('SEK', 'SEK'),\n ('NZD', 'NZD'),\n ('CNH', 'CNH'),\n )\n title = models.CharField(max_length=250)\n slug = models.SlugField(max_length=300)\n category = models.ForeignKey(Category,\n related_name='offers',\n on_delete=models.CASCADE)\n user = models.ForeignKey(User,\n related_name='user_offers',\n on_delete=models.CASCADE)\n description = models.TextField()\n\n max_participants = models.PositiveIntegerField(default=1)\n price_per_participant = models.DecimalField(max_digits=10, decimal_places=2)\n currency = models.CharField(max_length=3,\n choices=CURRENCY_CHOICES,\n default='EUR')\n\n start_date = models.DateTimeField(default=timezone.now)\n duration = models.PositiveIntegerField(default=1)\n\n publish = models.DateTimeField(default=timezone.now)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n status = models.CharField(max_length=10,\n choices=STATUS_CHOICES,\n default='draft')\n address_1 = models.CharField(max_length=120, default=\"\", blank=True)\n address_2 = models.CharField(max_length=120, blank=True)\n city = models.CharField(max_length=120, blank=True)\n state = models.CharField(max_length=120, blank=True)\n country = CountryField(blank=True)\n zip_code = models.CharField(max_length=6, blank=True)\n latitude = models.FloatField(default=0.0)\n longitude = models.FloatField(default=0.0)\n\n objects = OfferManager()\n\n # objects = models.Manager() # Manager domyslny (obiekty w queryset bez filtrowania)\n\n class Meta:\n ordering = ('-publish',)\n index_together = (('id', 'slug'),)\n\n def __str__(self):\n return self.title\n\n def save(self, *args, **kwargs):\n if self.id:\n self.slug = slugify(str(self.title) + \"-\" + str(self.id))\n else:\n self.slug = slugify(str(self.title) + \"-\" + str(ceil(time() * 10)) + \"a\")\n\n geolocator = GoogleV3(api_key=settings.GOOGLE_API_KEY, domain='maps.googleapis.com')\n location = geolocator.geocode(str(self.address_1) + ' '\n + str(self.address_2) + ' '\n + str(self.zip_code) + ' '\n + str(self.city) + ' '\n + str(self.country))\n if location:\n self.longitude = location.longitude\n self.latitude = location.latitude\n\n super(Offer, self).save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('offer:offer_detail',\n args=[self.id,\n self.slug])\n\n def get_edit_url(self):\n return f\"{self.get_absolute_url()}edit\"\n\n def get_delete_url(self):\n return f\"{self.get_absolute_url()}delete\"\n\n @property\n def owner(self):\n return self.user\n\n\ndef get_image_filename(instance, filename):\n title = instance.offer.title\n slug = slugify(title)\n user = instance.offer.user\n image_id = instance.offer.id\n created_date = instance.offer.created\n return \"offer_images/%s/%s/%s-%s-%s\" % (user, image_id, created_date, slug, filename)\n\n\nclass Images(models.Model):\n offer = models.ForeignKey(Offer, default=None, on_delete=models.CASCADE)\n image = models.ImageField(upload_to=get_image_filename,\n verbose_name='Image')\n\n def save(self, *args, **kwargs):\n # Opening the uploaded image\n im = PIL.Image.open(self.image)\n\n output = BytesIO()\n base_size = 600\n width, height = im.size\n if width > base_size or height > base_size:\n ratio = width / height\n if ratio > 1:\n width = base_size\n height = round(base_size / ratio)\n else:\n height = base_size\n width = round(base_size * ratio)\n # Resize/modify the image\n im = im.resize((width, height), PIL.Image.ANTIALIAS)\n\n # Keep the exif data\n exif = None\n if 'exif' in im.info:\n exif = im.info['exif']\n # after modifications, save it to the output\n im.save(output, format='JPEG', exif=exif, quality=90)\n else:\n im.save(output, format='JPEG', quality=90)\n\n output.seek(0)\n\n # change the imagefield value to be the newley modifed image value\n self.image = InMemoryUploadedFile(output, 'ImageField', \"%s.jpg\" % self.image.name.split('.')[0], 'image/jpeg',\n sys.getsizeof(output), None)\n\n super(Images, self).save(*args, **kwargs)\n","sub_path":"offer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259405560","text":"\"\"\"\n我这里是直接使用 sqlalchemy ,其实 flask 是有 sqlalchemy 专门的拓展,但是我也是刚弄博客,就先用 sqlalchemy 了。\n其实两者都差不多,关于 sqlalchemy 的学习资料也有很多。官方文档讲的也非常详细,对于英语掌握不熟练的用谷歌翻译看也比很多博客强很多。\n用 mysql 数据库也是一样,或则用别的方式操作数据库都一样,只要需求能实现,不必太在意使用的是什么技术。\n官方文档地址:https://www.sqlalchemy.org/\n \n\"\"\"\n\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import Column\nfrom sqlalchemy.types import Integer, String, DATETIME, TEXT\nfrom sqlalchemy.ext.declarative import declarative_base\nimport datetime\n\n# 数据基类模型\nBaseModel = declarative_base()\n\n# echo 参数为 True 时,会显示每条执行的 SQL 语句,生产环境下可关闭\n# engine = create_engine('sqlite:///memory.db', echo=True)\nengine = create_engine('sqlite:///databases/message.db', echo=True)\nDB_Session = sessionmaker(bind=engine)\nsession = DB_Session()\n\n\n# init database(创建数据库)\ndef init_db():\n BaseModel.metadata.create_all(engine)\n\n\n# drop database(删除数据库)\ndef drop_db():\n BaseModel.metadata.drop_all()\n\n\n# 设置数据库的字段(创建数据库时的初始化对象)\nclass MassageInfo(BaseModel):\n __tablename__ = 'message'\n id = Column(Integer, primary_key=True)\n name = Column(String(10))\n title = Column(String(10))\n content = Column(TEXT)\n date_time = Column(DATETIME)\n\n\n# 操作数据库(插入、删除)\nclass MassageDb(object):\n def __init__(self):\n self.engine = create_engine('sqlite:///databases/message.db', echo=True)\n self.DB_Session = sessionmaker(bind=engine)\n self.session = DB_Session()\n self.query = session.query(MassageInfo)\n\n # 插入数据到 sqlite3\n def insert_data(self, name, title, content):\n session1 = self.DB_Session()\n date_time = datetime.datetime.now()\n print(date_time)\n msg = MassageInfo(name=name, title=title, content=content, date_time=date_time)\n session1.add(msg)\n session1.commit()\n session1.close()\n\n # 从 sqlite3 查询数据\n def query_all(self):\n session2 = self.DB_Session()\n msg = session2.query(MassageInfo)\n session2.close()\n return msg # 返回的是一个类似列表的对象\n\n def close(self):\n self.session.close()\n\n\ndef main():\n query = MassageDb()\n query.query_all()\n\n\ndef insert():\n msg = MassageDb()\n msg.insert_data(name=\"c\", title=\"c\", content=\"c\")\n msg.query_all()\n msg.close()\n\n\nif __name__ == \"__main__\":\n init_db()\n","sub_path":"flask/chapter2/sqllite3_db.py","file_name":"sqllite3_db.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590755486","text":"\"\"\"\nStudents are asked to stand in non-decreasing order of heights for an annual photo.\n\nReturn the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.\n\n\"\"\"\n\ndef solution(height):\n step = 0\n for i, j in zip(heights, sorted(heights)):\n step += i != j\n return step\n\nheights = [1,1,4,2,1,3]\nprint(solution(heights))","sub_path":"daily-coding-challenge/18022020.py","file_name":"18022020.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"135078721","text":"__author__ = 'yinyanhe'\n\"\"\"\nGiven n points on a 2D plane, find the maximum number of points that lie on the same straight line\n\"\"\"\nclass Point(object):\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\nclass Solution(object):\n def maxPoints(self, points):\n \"\"\"\n :type points: List[Point]\n :rtype: int\n \"\"\"\n lg=len(points)\n if lg<2: return lg\n rst=0\n dict={}#key is slope\n for i in range(lg):\n localMax=overLap=vertical=0\n for j in range(i+1, lg):\n a=points[j].x-points[i].x\n b=points[j].y-points[i].y\n if a==0 and b==0:\n overLap+=1\n continue\n elif a==0:\n vertical+=1\n else:\n gcd=self.GCD(a, b)\n a/=gcd\n b/=gcd\n dict[(a, b)]+=1\n localMax=max(dict[(a, b)],localMax)\n localMax=max(localMax, vertical)\n rst=max(rst, localMax+overLap+1)\n return rst\n def GCD(self, a, b):\n if b==0: return a\n else:\n return self.GCD(b, a%b)\n\n\n def maxPoints1(self, points):\n lg, m=len(points), 0\n for i in range(lg):\n dict={'i':1}\n same=0\n for j in range(i+1, lg):\n a=points[i].x-points[j].x\n b=points[i].y-points[j].y\n if a==0 and b==0:\n same+=1\n continue\n if a==0:\n slope='i'\n else:\n slope=b*1.0/a\n if slope not in dict:\n dict[slope]=1\n dict[slope]+=1\n m=max(m, max(dict.values())+same)\n return m\n","sub_path":"Algo/MaxPointInALine.py","file_name":"MaxPointInALine.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"460784881","text":"import os\nimport numpy as np\nimport cv2\nfrom PIL import Image\n\nimport geojson\nimport shapely.wkt\nimport rasterio as rio\nimport geopandas\nimport wwtool\nimport mmcv\n\nfrom multiprocessing import Pool\nfrom functools import partial\nfrom shapely.geometry import Polygon\n\nimport tqdm\n\nImage.MAX_IMAGE_PIXELS = int(2048 * 2048 * 2048 // 4 // 3)\n\n\nclass SplitImage():\n def __init__(self, \n core_dataset_name='buildchange',\n src_version='v0',\n dst_version='v1',\n imageset='shanghai',\n sub_imageset_fold='arg',\n subimage_size=1024,\n gap=512,\n multi_processing=False,\n num_processor=16,\n show=False):\n self.core_dataset_name = core_dataset_name\n self.src_version = src_version\n self.dst_version = dst_version\n self.imageset = imageset\n self.sub_imageset_fold = sub_imageset_fold\n self.subimage_size = subimage_size\n self.gap = gap\n self.image_path = './data/{}/{}/{}/{}/images'.format(core_dataset_name, src_version, imageset, sub_imageset_fold)\n self.roof_shp_path = './data/{}/{}/{}/{}/roof_shp_4326'.format(core_dataset_name, src_version, imageset, sub_imageset_fold)\n self.geo_path = './data/{}/{}/{}/{}/geo_info'.format(core_dataset_name, src_version, imageset, sub_imageset_fold)\n self.pixel_anno_v2_path = './data/{}/{}/{}/{}/pixel_anno_v2'.format(core_dataset_name, src_version, imageset, sub_imageset_fold)\n\n self.image_save_path = './data/{}/{}/{}/{}/images'.format(core_dataset_name, dst_version, imageset, sub_imageset_fold)\n wwtool.mkdir_or_exist(self.image_save_path)\n self.label_save_path = './data/{}/{}/{}/{}/labels'.format(core_dataset_name, dst_version, imageset, sub_imageset_fold)\n wwtool.mkdir_or_exist(self.label_save_path)\n\n self.shp_parser = wwtool.ShpParse()\n self.multi_processing = multi_processing\n self.pool = Pool(num_processor)\n self.show = show\n\n def drop_subimage(self, \n subimages, \n subimage_coordinate, \n subimage_masks,\n center_area=2, \n small_object=64,\n show=False):\n \"\"\"judge whether to drop the overlap image\n\n Arguments:\n subimages {dict} -- dict which contains all subimages (value)\n subimage_coordinate {tuple} -- the coordinate of subimage in original image\n subimage_masks {list} -- list of masks in subimages\n\n Keyword Arguments:\n center_area {int} -- the area of center line (default: {2})\n show {bool} -- whether to show center line (default: {False})\n\n Returns:\n drop flag -- True: drop the subimage, False: keep the subimage\n \"\"\"\n # black image\n if np.mean(subimages[subimage_coordinate]) == 0:\n return True\n\n # no object\n if len(subimage_masks) == 0:\n return True\n\n # keep the main subimage, just drop the overlap part\n if abs(subimage_coordinate[0] - subimage_coordinate[1]) in (0, 1024) and (subimage_coordinate[0] != 512 and subimage_coordinate[1] != 512):\n return False\n\n subimage_mask_area = []\n subimage_mask_polygons = []\n for subimage_mask in subimage_masks:\n subimage_mask_polygon = wwtool.mask2polygon(subimage_mask)\n subimage_mask_polygons.append(subimage_mask_polygon)\n subimage_mask_area.append(subimage_mask_polygon.area)\n\n # (horizontal, vertical)\n center_lines = [Polygon([(0, 512 - center_area), \n (0, 512 + center_area), \n (1023, 512 + center_area), \n (1023, 512 - center_area), \n (0, 512 - center_area)]), \n Polygon([(512 - center_area, 0), \n (512 + center_area, 0), \n (512 + center_area, 1023), \n (512 - center_area, 1023), \n (512 - center_area, 0)])]\n\n if subimage_coordinate[0] == 512 and subimage_coordinate[1] != 512:\n center_lines = [center_lines[1]]\n elif subimage_coordinate[0] != 512 and subimage_coordinate[1] == 512:\n center_lines = [center_lines[0]]\n else:\n center_lines = center_lines\n\n subimage_mask_polygons = wwtool.clean_polygon(subimage_mask_polygons)\n subimage_mask_df = geopandas.GeoDataFrame({'geometry': subimage_mask_polygons, 'submask_df':range(len(subimage_mask_polygons))})\n center_line_df = geopandas.GeoDataFrame({'geometry': center_lines, 'center_df':range(len(center_lines))})\n\n image_border_polygon = [Polygon([(0, 0), (1024-1, 0), (1024-1, 1024-1), (0, 1024-1), (0, 0)])]\n border_line_df = geopandas.GeoDataFrame({'geometry': image_border_polygon, 'border_df':range(len(image_border_polygon))})\n\n if show:\n fig, ax = plt.subplots() \n\n subimage_mask_df.plot(ax=ax, color='red')\n center_line_df.plot(ax=ax, facecolor='none', edgecolor='g')\n border_line_df.plot(ax=ax, facecolor='none', edgecolor='k')\n ax.set_title('{}_{}'.format(subimage_coordinate[0], subimage_coordinate[1]))\n plt.xticks([])\n plt.yticks([])\n plt.axis('off')\n\n # plt.show()\n plt.savefig('./{}_{}_{}.png'.format(self.image_fn.replace('.jpg', ''), subimage_coordinate[0], subimage_coordinate[1]), bbox_inches='tight', dpi=600, pad_inches=0.0)\n\n res_intersection = geopandas.overlay(subimage_mask_df, center_line_df, how='intersection')\n inter_dict = res_intersection.to_dict()\n ignore_indexes = list(set(inter_dict['submask_df'].values()))\n\n inter_areas = []\n for ignore_index in ignore_indexes:\n inter_areas.append(subimage_mask_polygons[ignore_index].area)\n\n if len(inter_areas) == 0 or max(inter_areas) < small_object * small_object:\n return True\n else:\n return False\n\n def split_image(self, image_fn):\n if not image_fn.endswith('.jpg'):\n return\n image_file = os.path.join(self.image_path, image_fn)\n shp_file = os.path.join(self.roof_shp_path, image_fn.replace('jpg', 'shp'))\n geo_file = os.path.join(self.geo_path, image_fn.replace('jpg', 'png'))\n ignore_file = os.path.join(self.pixel_anno_v2_path, image_fn.replace('jpg', 'png'))\n \n file_name = os.path.splitext(os.path.basename(image_file))[0]\n\n if not os.path.exists(shp_file):\n return\n\n img = cv2.imread(image_file)\n geo_info = rio.open(geo_file)\n\n objects = self.shp_parser(shp_fn=shp_file, \n geom_img=geo_info,\n ignore_file=ignore_file,\n return_ignore_index=True)\n\n masks = np.array([obj['segmentation'] for obj in objects])\n ignore_indexes = np.array([obj['ignore_index'] for obj in objects])\n\n subimages = wwtool.split_image(img, subsize=self.subimage_size, gap=self.gap)\n subimage_coordinates = list(subimages.keys())\n\n if masks.shape[0] == 0:\n return\n\n mask_centroids = []\n for obj in objects:\n geometry = obj['converted_polygon'].centroid\n geo = geojson.Feature(geometry=geometry, properties={})\n coordinate = geo.geometry[\"coordinates\"]\n coordinate[0], coordinate[1] = abs(coordinate[0]), abs(coordinate[1])\n mask_centroids.append(coordinate)\n\n mask_centroids = np.array(mask_centroids)\n mask_centroids_ = mask_centroids.copy()\n \n for subimage_coordinate in subimage_coordinates:\n objects = []\n\n mask_centroids_[:, 0] = mask_centroids[:, 0] - subimage_coordinate[0]\n mask_centroids_[:, 1] = mask_centroids[:, 1] - subimage_coordinate[1]\n\n\n cx_bool = np.logical_and(mask_centroids_[:, 0] >= 0, mask_centroids_[:, 0] < subimage_size)\n cy_bool = np.logical_and(mask_centroids_[:, 1] >= 0, mask_centroids_[:, 1] < subimage_size)\n\n subimage_masks = masks[np.logical_and(cx_bool, cy_bool)]\n \n\n subimage_masks_ = []\n for subimage_mask in subimage_masks:\n if wwtool.mask2polygon(subimage_mask).area < 5:\n continue\n subimage_mask_np = np.array(subimage_mask)\n subimage_mask_np[0::2] = subimage_mask_np[0::2] - subimage_coordinate[0]\n subimage_mask_np[1::2] = subimage_mask_np[1::2] - subimage_coordinate[1]\n\n subimage_masks_.append(subimage_mask_np.tolist())\n \n\n subimage_masks = subimage_masks_\n # cut the polygons by image boundary\n subimage_masks = wwtool.clip_mask(subimage_masks, image_size=(1024, 1024))\n\n # judge whether to drop this subimage\n drop_flag = self.drop_subimage(subimages, \n subimage_coordinate, \n subimage_masks,\n show=self.show)\n if drop_flag:\n continue\n\n img = subimages[subimage_coordinate]\n\n label_save_file = os.path.join(self.label_save_path, '{}_{}__{}_{}.txt'.format(self.sub_imageset_fold, file_name, subimage_coordinate[0], subimage_coordinate[1]))\n image_save_file = os.path.join(self.image_save_path, '{}_{}__{}_{}.png'.format(self.sub_imageset_fold, file_name, subimage_coordinate[0], subimage_coordinate[1]))\n cv2.imwrite(image_save_file, img)\n \n for subimage_mask in subimage_masks:\n subimage_objects = dict()\n subimage_objects['mask'] = subimage_mask\n subimage_objects['label'] = 'building'\n objects.append(subimage_objects)\n wwtool.simpletxt_dump(objects, label_save_file, encode='mask')\n\n def core(self):\n if self.multi_processing:\n image_fn_list = os.listdir(self.image_path)\n num_image = len(image_fn_list)\n worker = partial(self.split_image)\n # self.pool.map(worker, image_fn_list)\n ret = list(tqdm.tqdm(self.pool.imap(worker, image_fn_list), total=num_image))\n else:\n image_fn_list = os.listdir(self.image_path)\n progress_bar = mmcv.ProgressBar(len(image_fn_list))\n for _, image_fn in enumerate(image_fn_list):\n self.split_image(image_fn)\n progress_bar.update()\n\n def __getstate__(self):\n self_dict = self.__dict__.copy()\n del self_dict['pool']\n return self_dict\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n\n\nif __name__ == '__main__':\n core_dataset_name = 'buildchange'\n src_version = 'v0'\n dst_version = 'v2'\n # imagesets = ['shanghai']\n # sub_imageset_folds = {'shanghai': ['arg']}\n imagesets = ['shanghai', 'beijing', 'jinan', 'haerbin', 'chengdu']\n sub_imageset_folds = {'beijing': ['arg', 'google', 'ms', 'tdt'],\n 'chengdu': ['arg', 'google', 'ms', 'tdt'],\n 'haerbin': ['arg', 'google', 'ms'],\n 'jinan': ['arg', 'google', 'ms', 'tdt'],\n 'shanghai': ['google', 'ms', 'tdt', 'PHR2016', 'PHR2017']}\n # sub_imageset_folds = {'beijing': ['arg', 'google', 'ms', 'tdt'],\n # 'chengdu': ['arg', 'google', 'ms', 'tdt'],\n # 'haerbin': ['arg', 'google', 'ms'],\n # 'jinan': ['arg', 'google', 'ms', 'tdt'],\n # 'shanghai': ['arg', 'google', 'ms', 'tdt', 'PHR2016', 'PHR2017']}\n subimage_size = 1024\n gap = subimage_size // 2\n\n for imageset in imagesets:\n for sub_imageset_fold in sub_imageset_folds[imageset]:\n print(\"Begin processing {} {} set.\".format(imageset, sub_imageset_fold))\n split_image = SplitImage(core_dataset_name=core_dataset_name,\n src_version=src_version,\n dst_version=dst_version,\n imageset=imageset,\n sub_imageset_fold=sub_imageset_fold,\n subimage_size=subimage_size,\n gap=gap,\n multi_processing=True,\n num_processor=8)\n\n split_image.core()\n print(\"Finish processing {} {} set.\".format(imageset, sub_imageset_fold))\n\n \n","sub_path":"tools/datasets/buildchange/split_image_with_roof_shp_4326.py","file_name":"split_image_with_roof_shp_4326.py","file_ext":"py","file_size_in_byte":12960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"434744495","text":"import numpy as np\nfrom scipy.signal import periodogram\nimport matplotlib.pyplot as plt\nimport threading\nfrom collections import deque\n\nimport u6\nfrom LabJackPython import *\n\nCHANNELS = [0,2]\nSAMPLERATE = 10000\n\nclass StreamReader():\n def __init__(self):\n # A buffer for incoming data. Use deque for fast writes.\n self.buffer = deque()\n # Integration time in seconds\n self.t_integrate = 1\n self._device = u6.U6()\n self._device.getCalibrationData()\n self._barrier = threading.Barrier(2)\n self.data_ready = threading.Event()\n\n def __del__(self):\n if self._device is not None:\n try:\n self._device.streamStop()\n except:\n pass\n self._device.close()\n\n def trigger_acquisition(self):\n self.data_ready.clear()\n self._barrier.wait()\n\n def start_acquisition(self):\n self._acq_thread = threading.Thread(target=self._acquire_loop)\n self._barrier.reset()\n self._acq_thread.start()\n\n def stop_acquisition(self):\n self._barrier.abort()\n self._acq_thread.join()\n\n def fetch_data(self, another=True):\n self.data_ready.wait()\n data = {}\n dropped = 0\n while len(self.buffer) > 0:\n raw = self.buffer.popleft()\n dropped += raw['missed']\n processed = self._device.processStreamData(raw['result'])\n for k,v in processed.items():\n if k in data:\n data[k].extend(v)\n else:\n data[k] = v\n nchannels = len(data.keys())\n npoints = max(map(len, data.values()))\n x = np.linspace(0, npoints/SAMPLERATE, npoints)\n print (\"Dropped %d of %d samples.\" % (dropped, npoints * nchannels))\n if another:\n self.trigger_acquisition()\n return x, data\n\n def _acquire_loop(self):\n dev = self._device\n while True:\n # wait for barrier\n try:\n self._barrier.wait()\n except threading.BrokenBarrierError:\n break\n # do acquisition\n n = len(CHANNELS)\n dev.streamConfig(NumChannels=n, ChannelNumbers=CHANNELS, \n ChannelOptions=[0]*n, \n ResolutionIndex=0, ScanFrequency=SAMPLERATE)\n count = 0\n stream = dev.streamData(convert=False)\n dev.streamStart()\n while count < self.t_integrate * SAMPLERATE * n:\n if self._barrier.broken:\n # Check for abort.\n break\n raw = next(stream)\n # if (raw['errors'] + raw['missed']) > 0:\n # print(raw['errors'], raw['missed'])\n # for pkt, err in enumerate(raw['result'][11::64]):\n # errNum = err\n # if errNum != 0:\n # #Error detected in this packet\n # print (\"Packet\", pkt, \"error:\", errNum)\n count += raw['numPackets'] * self._device.streamSamplesPerPacket\n self.buffer.append(raw)\n self._device.streamStop()\n # set event\n self.data_ready.set()\n\n\ndef do_plot(x, data, lines, axs):\n if not lines:\n plt.ion()\n axs[1].set_yscale('log')\n for k,v in data.items():\n lines[k] = axs[0].plot(x, v)[0]\n f, p = periodogram(v, fs=(1 / (x[1] - x[0])), window='hann', scaling='density')\n lines['f_' + k] = axs[1].plot(f, p)[0]\n else:\n for k,l in lines.items():\n if k.startswith('f_'):\n f, p = periodogram(data[k[2:]], fs=(1 / (x[1] - x[0])), window='hann', scaling='density')\n l.set_xdata(f)\n l.set_ydata(p)\n else:\n l.set_xdata(x)\n l.set_ydata(data[k])\n return lines\n\n\n\n#global RUN_FLAG \nRUN_FLAG = True\n\ndef on_close(evt):\n global RUN_FLAG\n RUN_FLAG = False\n\nif __name__ == '__main__':\n s = StreamReader()\n lines = {}\n\n fig, axs = plt.subplots(2,1)\n fig.canvas.mpl_connect('close_event', on_close)\n\n d = s._device\n d.configIO(NumberTimersEnabled=1)\n d.configTimerClock(4, 0)\n d.getFeedback(u6.Timer0Config(7, 1))\n div = 0\n \n\n import time\n time.sleep(2)\n s.start_acquisition()\n s.trigger_acquisition()\n while True:\n d.getFeedback(u6.Timer0Config(LJ_tmFREQOUT, 127))\n #div = (div + 32) % 256\n while not s.data_ready.is_set() and RUN_FLAG:\n plt.pause(0.2)\n if not RUN_FLAG:\n # Break to prevent trying to update a plot that has been closed.\n break\n x, data = s.fetch_data()\n lines = do_plot(x, data, lines, axs)\n\n\n s.stop_acquisition()","sub_path":"labjacksa.py","file_name":"labjacksa.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"298478027","text":"'''\nA basic port scanner in python. Used to test out knowledge for security\n'''\n\nimport socket\nimport sys\n\n'''\nThe min and max is the range of ports you want to test on the given host (The host is given as a parameter on the command\nline.\n'''\nmin = 1\nmax = 1024\nif len(sys.argv) < 2 or len(sys.argv) >= 5:\n print(\"Must pass a ip address\")\n exit()\n\n'''\nIf the user provides more than the hostname we check to see if it is a range or not a number.\n'''\nif 2 < len(sys.argv) < 5:\n if sys.argv[2].isdigit():\n min = int(sys.argv[2])\n if len(sys.argv) == 4:\n max = int(sys.argv[3])\n else:\n '''\n If it is not a number then we think of it as wanting to search for a common ports\n (I will probably change this later to add more parameters\n '''\n common_ports = {80, 443, 20, 21, 22, 23, 25, 69, 110, 995, 143, 902, 993,\n 385, 587, 3306, 2082, 2083, 2086, 2087,\n 2095, 2096, 2077, 2078, 3389}\n print(\"Scanning: {} for common open ports\".format(sys.argv[1]))\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n for port in common_ports:\n try:\n s.settimeout(1000)\n s.connect((sys.argv[1], port))\n\n print(\"OPEN: {}\".format(port))\n s.close()\n except:\n continue\n print(\"Finished Scan\")\n exit()\n\n'''\nPerform a normal scan based off of min and max values\n'''\nprint(\"Scanning: {} from {} to {}\".format(sys.argv[1], min, max))\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nfor port in range(min, max):\n try:\n s.settimeout(1000)\n s.connect((sys.argv[1], port))\n\n print(\"OPEN: {}\".format(port))\n s.close()\n except:\n continue\nprint(\"Finished Scan\")\n","sub_path":"Port Scanner/portScanner.py","file_name":"portScanner.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152598974","text":"# coding:utf-8\r\nimport os\r\nimport datetime\r\nfrom math import ceil\r\n\r\nfrom car.models import CarsAll, CarsIn\r\nfrom parking_management_system.main import extract_license_plate\r\n\r\n\r\n# 获取car文件夹下的car_img文件夹的地址\r\nCAR_IMG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'car_img')\r\n\r\n\r\ndef update_model(img_name):\r\n plate_name = '%s_plate%s' % os.path.splitext(img_name)\r\n # 准备参数\r\n car_img_path = os.path.join(CAR_IMG_DIR, img_name)\r\n license_plate_path = os.path.join(CAR_IMG_DIR, plate_name)\r\n # 提取车牌号\r\n car_license_plate = extract_license_plate(car_img_path,\r\n license_plate_path,\r\n '/Users/gangwei/desktop/web1127/svc.pkl')\r\n\r\n # 从图片名中获取拍摄时间\r\n year, month, day, hour, minute, second = map(int, os.path.splitext(img_name)[0].split('_'))\r\n upd_time = datetime.datetime(year, month, day, hour, minute, second)\r\n\r\n # 查询对应的车是否已经存在数据表cars_all中,没有的话,此次为入库,有的话此次为出库\r\n query_result = CarsAll.objects.filter(license_id=car_license_plate).filter(exit_time=datetime.datetime(1970, 1, 1))\r\n if query_result:\r\n # 出库\r\n query_result.update(exit_time=upd_time, image_path=car_img_path)\r\n CarsIn.objects.filter(license_id=car_license_plate).delete()\r\n else:\r\n # 入库\r\n CarsAll.objects.create(license_id=car_license_plate,\r\n entry_time=upd_time,\r\n exit_time=datetime.datetime(1970, 1, 1),\r\n image_path=car_img_path)\r\n CarsIn.objects.create(license_id=car_license_plate, entry_time=upd_time)\r\n\r\n\r\ndef cost(entry_time, exit_time):\r\n \"\"\"\r\n 根据入库和出库时间计算停车费用,每分钟$1/60,不满一分钟,按照一分钟算\r\n :param entry_time: datetime.datetime 入库时间,UTC\r\n :param exit_time: datetime.datetime 出库时间,当出库时间为1970年时,出库时间设定为timezone.now() UTC\r\n :return: float 停车费用\r\n \"\"\"\r\n if exit_time.year == 1970:\r\n exit_time = datetime.datetime.now()\r\n return ceil((exit_time - entry_time).total_seconds() / 60) * (1 / 60)\r\n","sub_path":"car/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"104734348","text":"\"\"\"\nConfig settings loaded from exe.conf\nIs responsible for the system-wide settings we use\nO/S specific config classes are derieved from here\n\"\"\"\nfrom exe.engine.configparser import ConfigParser\nfrom exe.engine.path import Path\nfrom exe.engine.locales import chooseDefaultLocale\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport sys\nimport os\nimport gettext\nimport tempfile\nclass Config:\n \"\"\"\n The Config class contains the configuration information for eXe.\n \"\"\"\n optionNames = {\n 'system': ('webDir', 'xulDir', 'port', 'dataDir', \n 'configDir', 'localeDir', 'browserPath'),\n 'user': ('locale',)\n }\n def __init__(self):\n \"\"\"\n Initialise\n \"\"\"\n self.configPath = None\n self.configParser = ConfigParser()\n self.exePath = Path(sys.argv[0]).abspath()\n self.webDir = self.exePath.dirname()\n self.xulDir = self.exePath.dirname()\n self.localeDir = self.exePath.dirname()/\"locale\"\n self.port = 8081\n self.dataDir = Path(\".\")\n self.configDir = Path(\".\")\n self.browserPath = Path(\"firefox\")\n self.locale = chooseDefaultLocale(self.localeDir)\n self.styles = []\n self._overrideDefaultVals()\n self.webDir = Path(self.webDir)\n if not (self.webDir/'scripts').isdir() \\\n and (self.webDir/'webui').isdir():\n self.webDir /= 'webui'\n self.xulDir = Path(self.xulDir)\n if not (self.xulDir/'scripts').isdir() \\\n and (self.xulDir/'xului').isdir():\n self.xulDir /= 'xului'\n self.__setConfigPath()\n self._writeDefaultConfigFile()\n self.loadSettings()\n self.setupLogging()\n self.loadStyles()\n self.loadLocales()\n def _overrideDefaultVals(self):\n \"\"\"\n Override this to override the\n default config values\n \"\"\"\n def _getConfigPathOptions(self):\n \"\"\"\n Override this to give a list of\n possible config filenames\n in order of preference\n \"\"\"\n return ['exe.conf']\n def _writeDefaultConfigFile(self):\n \"\"\"\n [Over]writes 'self.configPath' with a default config file \n (auto write is on so we don't need to write the file at the end)\n \"\"\"\n for sectionName, optionNames in self.optionNames.items():\n for optionName in optionNames:\n defaultVal = getattr(self, optionName)\n self.configParser.setdefault(sectionName, \n optionName, \n defaultVal)\n self.configParser.setdefault('logging', 'root', 'INFO')\n def __setConfigPath(self):\n \"\"\"\n sets self.configPath to the filename of the config file that we'll\n use.\n In descendant classes set self.configFileOptions to a list\n of directories where the configDir should be in order of preference.\n If no config files can be found in these dirs, it will\n force creation of the config file in the top dir\n \"\"\"\n self.configPath = None\n configFileOptions = map(Path, self._getConfigPathOptions())\n if \"EXECONF\" in os.environ:\n envconf = Path(os.environ[\"EXECONF\"])\n if envconf.isfile():\n self.configPath = os.environ[\"EXECONF\"]\n if self.configPath is None:\n for confPath in configFileOptions:\n if confPath.isfile():\n self.configPath = confPath\n break\n else:\n self.configPath = configFileOptions[0]\n folder = self.configPath.abspath().dirname()\n if not folder.exists():\n folder.makedirs()\n self.configPath.touch()\n self.configParser.read(self.configPath)\n self.configParser.autoWrite = True\n def upgradeFile(self):\n \"\"\"\n Called before loading the config file,\n removes or upgrades any old settings.\n \"\"\"\n if self.configParser.has_section('system'):\n system = self.configParser.system\n if system.has_option('appDataDir'):\n self.configDir = Path(system.appDataDir)\n system.configDir = self.configDir\n del system.appDataDir\n if system.has_option('greDir'):\n del system.greDir\n def loadSettings(self):\n \"\"\"\n Loads the settings from the exe.conf file.\n Overrides the defaults set in __init__\n \"\"\"\n def defVal(dummy, option):\n \"\"\"If something is not in the config file, just use the default in\n 'self'\"\"\"\n return getattr(self, option)\n self.configParser.defaultValue = defVal\n self.upgradeFile()\n if self.configParser.has_section('system'):\n system = self.configParser.system\n self.webDir = Path(system.webDir)\n self.xulDir = Path(system.xulDir)\n self.localeDir = Path(system.localeDir)\n self.port = int(system.port)\n self.browserPath = Path(system.browserPath)\n self.dataDir = Path(system.dataDir)\n self.configDir = Path(system.configDir)\n if not self.dataDir.isdir():\n self.dataDir = tempfile.gettempdir()\n self.webDir = self.webDir.expand().abspath()\n if not self.configDir.exists():\n self.configDir.mkdir()\n if self.configParser.has_section('user'):\n if self.configParser.user.has_option('locale'):\n self.locale = self.configParser.user.locale\n return\n self.locale = chooseDefaultLocale(self.localeDir)\n def setupLogging(self):\n \"\"\"\n setup logging file\n \"\"\"\n try:\n hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a', \n 500000, 10)\n hdlr.doRollover()\n except OSError:\n hdlr = logging.FileHandler(self.configDir/'exe.log')\n format = \"%(asctime)s %(name)s %(levelname)s %(message)s\"\n log = logging.getLogger()\n hdlr.setFormatter(logging.Formatter(format))\n log.addHandler(hdlr)\n loggingLevels = {\"DEBUG\" : logging.DEBUG,\n \"INFO\" : logging.INFO,\n \"WARNING\" : logging.WARNING,\n \"ERROR\" : logging.ERROR,\n \"CRITICAL\" : logging.CRITICAL }\n if self.configParser.has_section('logging'):\n for logger, level in self.configParser._sections[\"logging\"].items():\n if logger == \"root\":\n logging.getLogger().setLevel(loggingLevels[level])\n else:\n logging.getLogger(logger).setLevel(loggingLevels[level])\n log.info(\"************** eXe logging started **************\")\n log.info(\"configPath = %s\" % self.configPath)\n log.info(\"exePath = %s\" % self.exePath)\n log.info(\"browserPath = %s\" % self.browserPath)\n log.info(\"webDir = %s\" % self.webDir)\n log.info(\"xulDir = %s\" % self.xulDir)\n log.info(\"localeDir = %s\" % self.localeDir)\n log.info(\"port = %d\" % self.port)\n log.info(\"dataDir = %s\" % self.dataDir)\n log.info(\"configDir = %s\" % self.configDir)\n log.info(\"locale = %s\" % self.locale)\n def loadStyles(self):\n \"\"\"\n Scans the eXe style directory and builds a list of styles\n \"\"\"\n log = logging.getLogger()\n self.styles = []\n styleDir = self.webDir/\"style\"\n log.debug(\"loadStyles from %s\" % styleDir)\n for subDir in styleDir.dirs():\n styleSheet = subDir/'content.css'\n log.debug(\" checking %s\" % styleSheet)\n if styleSheet.exists():\n style = subDir.basename()\n log.debug(\" loading style %s\" % style)\n self.styles.append(style)\n def loadLocales(self):\n \"\"\"\n Scans the eXe locale directory and builds a list of locales\n \"\"\"\n log = logging.getLogger()\n log.debug(\"loadLocales\")\n gettext.install('exe', self.localeDir, True)\n self.locales = {}\n for subDir in self.localeDir.dirs():\n if (subDir/'LC_MESSAGES'/'exe.mo').exists():\n self.locales[subDir.basename()] = \\\n gettext.translation('exe', \n self.localeDir, \n languages=[str(subDir.basename())])\n if subDir.basename() == self.locale:\n locale = subDir.basename()\n log.debug(\" loading locale %s\" % locale)\n self.locales[locale].install(unicode=True)\n","sub_path":"eXe/rev2283-2366/right-branch-2366/exe/engine/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"589390134","text":"assignments = []\n\n\nrows = 'ABCDEFGHI'\ncols = '123456789' \n\ndef cross(A, B):\n \"Cross product of elements in A and elements in B.\"\n return [a+b for a in A for b in B]\n\nall_boxes = [r+c for r in rows for c in cols]\nrow_units = [ [r+c for c in cols] for r in rows] \ncol_units = [ [r+c for r in rows] for c in cols]\nsqu_units = [ cross(r, c) for r in ['ABC', 'DEF', 'GHI'] for c in ['123', '456', '789']]\n\ndiag_units= []\nl1 = []\nl2 = []\nfor i in range(9):\n l1.append(rows[i] + cols[i])\n l2.append(rows[i] + cols[8-i])\n\ndiag_units.append(l1)\ndiag_units.append(l2)\n\nunitlist = row_units + col_units + squ_units + diag_units\nunits = dict((s, [u for u in unitlist if s in u]) for s in all_boxes)\npeers = dict((s, set(sum(units[s],[]))-set([s])) for s in all_boxes)\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n\n # Don't waste memory appending actions that don't actually change any values\n if values[box] == value:\n return values\n\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\n\ndef naked_twins_helper(values, units):\n for unit in units:\n count = {}\n for x in unit:\n if values[x] in count:\n count[values[x]] += 1\n else:\n count[values[x]] = 1\n\n for num in count:\n if len(num) > 1 and len(num) == count[num]: \n for x in unit:\n if values[x] != num:\n for c in num:\n assign_value(values, x, values[x].replace(c, ''))\n return values\n\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n\n # Find all instances of naked twins\n # Eliminate the naked twins as possibilities for their peers\n\n # Eliminate naked twins from each of row, col and square units\n values = naked_twins_helper(values, row_units)\n values = naked_twins_helper(values, col_units)\n values = naked_twins_helper(values, squ_units)\n\n return values\n \n\ndef grid_values(values):\n \"\"\"\n Convert values into a dict of {square: char} with '123456789' for empties.\n Args:\n values(string) - A grid in string form.\n Returns:\n A values in dictionary form\n Keys: The boxes, e.g., 'A1'\n Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.\n \"\"\"\n values = dict((rows[r] + cols[c], values[r * 9 + c]) for c in range(9) for r in range(9))\n\n for v in values:\n if values[v] == '.':\n values[v] = '123456789'\n\n return values\n\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D values.\n Args:\n values(dict): The sudoku in dictionary form\n \"\"\"\n for r in rows:\n for c in cols:\n print('{0: <10}'.format(values[r + c]), end='')\n print('')\n\n\ndef eliminate(values):\n singles = []\n for b in values:\n if len(values[b]) == 1:\n singles.append(b)\n \n for s in singles:\n for p in peers[s]:\n #print(\"Eliminating {0} from {1} at location {2}\".format(values[s], grid[p], p))\n values[p] = values[p].replace(values[s], '')\n return values\n\n\ndef only_choice(values):\n for unit in unitlist:\n for box in unit:\n v = values[box]\n if len(v) > 1:\n for d in '123456789':\n if d in v:\n update = True\n for box1 in unit:\n if box != box1 and d in values[box1]:\n update = False\n if update:\n #print(\"Assigning {0} to {1}\".format(d, values[box]))\n values[box] = d\n \n return values\n \n\ndef reduce_puzzle(values):\n stagnent = False\n while not stagnent:\n #print('.')\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n values = eliminate(values)\n values = only_choice(values)\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n \n if solved_values_before == solved_values_after:\n stagnent = True\n \n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\n\ndef search(values):\n values = reduce_puzzle(values)\n \n if values == False:\n return False\n \n index = None\n for b in values:\n if len(values[b]) > 1:\n index = b\n break\n \n if index is None:\n return values\n \n elements = values[index]\n \n for e in elements:\n values_copy = values.copy()\n values_copy[index] = e\n attempt = search(values_copy)\n if attempt:\n return attempt\n \n\ndef solve(values):\n \"\"\"\n Find the solution to a Sudoku values.\n Args:\n values(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku values. False if no solution exists.\n \"\"\"\n values = grid_values(values)\n values = search(values)\n return values\n\n\nif __name__ == '__main__':\n diag_sudoku_values = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(solve(diag_sudoku_values))\n\n try:\n from visualize import visualize_assignments\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","sub_path":"term1/AIND-Sudoku/temp/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"553204599","text":"import datetime\r\nimport requests\r\n\r\nlocations = {\r\n \"Newark, DE\": '337531',\r\n \"Wilmington, DE\": '327535',\r\n \"Clementon, NJ\": '2175028',\r\n \"West Berlin, NJ\": '2208734'\r\n }\r\n\r\nparameters = {\"apikey\": ''} # <- Your API key goes here\r\nhourly = requests.get('http://dataservice.accuweather.com/forecasts/v1/hourly/12hour/'\r\n +locations[\"Wilmington, DE\"],\r\n params=parameters)\r\ndata = hourly.json()\r\n\r\nif __name__ == \"__main__\":\r\n for i in data:\r\n time_tag = datetime.datetime.fromtimestamp(i['EpochDateTime'])\r\n time_tag = time_tag.strftime(\"%I:%M %p\")\r\n print('[{}] Weather: {}, Precipitation: {}%, Type: {}'.format(\r\n time_tag, i['Temperature']['Value'],\r\n i['PrecipitationProbability'], i['IconPhrase']))\r\n\r\n\t\r\n","sub_path":"hourly_weather.py","file_name":"hourly_weather.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605200918","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport urllib\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\n\nimport jinja2\nimport webapp2\n\nstations = {0: u'Девяткино', \n 1: u'Гражданский проспект',\n 2: u'Академическая',\n 3: u'Политехническая',\n 4: u'Площадь Мужества',\n 5: u'Лесная',\n 6: u'Выборгская',\n 7: u'Площадь Ленина',\n 8: u'Чернышевская',\n 9: u'Площадь Восстания',\n 10: u'Владимирская',\n 11: u'Пушкинская',\n 12: u'Технологический институт-1',\n 13: u'Балтийская',\n 14: u'Нарвская',\n 15: u'Кировский завод',\n 16: u'Автово',\n 17: u'Ленинский проспект',\n 18: u'Проспект Ветеранов',\n 19: u'Парнас',\n 20: u'Проспект Просвещения',\n 21: u'Озерки',\n 22: u'Удельная',\n 23: u'Пионерская',\n 24: u'Чёрная речка',\n 25: u'Петроградская',\n 26: u'Горьковская',\n 27: u'Невский проспект',\n 28: u'Сенная площадь',\n 29: u'Технологический институт-2',\n 30: u'Фрунзенская',\n 31: u'Московские ворота',\n 32: u'Электросила',\n 33: u'Парк Победы',\n 34: u'Московская',\n 35: u'Звёздная',\n 36: u'Купчино',\n 37: u'Приморская',\n 38: u'Василеостровская',\n 39: u'Гостиный двор',\n 40: u'Маяковская',\n 41: u'Площадь Александра Невского-1',\n 42: u'Елизаровская',\n 43: u'Ломоносовская',\n 44: u'Пролетарская',\n 45: u'Обухово',\n 46: u'Рыбацкое',\n 47: u'Спасская',\n 48: u'Достоевская',\n 49: u'Лиговский проспект',\n 50: u'Площадь Александра Невского-2',\n 51: u'Новочеркасская',\n 52: u'Ладожская',\n 53: u'Проспект Большевиков',\n 54: u'Улица Дыбенко',\n 55: u'Комендантский проспект',\n 56: u'Старая Деревня',\n 57: u'Крестовский остров',\n 58: u'Чкаловская',\n 59: u'Спортивная',\n 60: u'Адмиралтейская',\n 61: u'Садовая',\n 62: u'Звенигородская',\n 63: u'Обводный канал',\n 64: u'Волковская',\n 65: u'Бухарестская',\n 66: u'Международная'\n }\n\ng = {0: {1: 3},\n 1: {0: 3, 2: 3},\n 2: {1: 3, 3: 2},\n 3: {2: 2, 4: 3},\n 4: {3: 3, 5: 3},\n 5: {4: 3, 6: 3},\n 6: {5: 3, 7: 2},\n 7: {6: 2, 8: 3},\n 8: {7: 3, 9: 2},\n 9: {8: 2, 40: 2, 10: 2},\n 10: {9: 2, 11: 2, 48: 2},\n 11: {10: 2, 12: 2, 62: 2},\n 12: {11: 2, 13: 2, 29: 1},\n 13: {12: 2, 14: 3},\n 14: {13: 3, 15: 4},\n 15: {14: 4, 16: 2},\n 16: {15: 2, 17: 3},\n 17: {16: 3, 18: 2},\n 18: {17: 2},\n 19: {20: 3},\n 20: {19: 3, 21: 2},\n 21: {20: 2, 22: 3},\n 22: {21: 3, 23: 3},\n 23: {22: 3, 24: 3},\n 24: {23: 3, 25: 4},\n 25: {24: 4, 26: 2},\n 26: {25: 2, 27: 4},\n 27: {26: 4, 28: 2, 39: 2},\n 28: {27: 2, 29: 3, 47: 3, 61: 3},\n 29: {28: 3, 30: 2, 12: 1},\n 30: {29: 2, 31: 2},\n 31: {30: 2, 32: 2},\n 32: {31: 2, 33: 2},\n 33: {32: 2, 34: 3},\n 34: {33: 3, 35: 4},\n 35: {34: 4, 36: 3},\n 36: {35: 3},\n 37: {38: 4},\n 38: {37: 4, 39: 4},\n 39: {38: 4, 40: 3, 27: 2},\n 40: {39: 3, 41: 3, 9: 2},\n 41: {40: 3, 42: 5, 50: 2},\n 42: {41: 5, 43: 3},\n 43: {42: 3, 44: 3},\n 44: {43: 3, 45: 3},\n 45: {44: 3, 46: 4},\n 46: {45: 4},\n 47: {48: 4, 28: 3, 61: 3},\n 48: {47: 4, 49: 2, 10: 2},\n 49: {48: 2, 50: 2},\n 50: {49: 2, 51: 3, 41: 2},\n 51: {50: 3, 52: 3},\n 52: {51: 3, 53: 3},\n 53: {52: 3, 54: 2},\n 54: {53: 2},\n 55: {56: 3},\n 56: {55: 3, 57: 3},\n 57: {56: 3, 58: 4},\n 58: {57: 4, 59: 2},\n 59: {58: 2, 60: 3},\n 60: {59: 3, 61: 3},\n 61: {60: 3, 62: 4, 47: 3, 28: 3},\n 62: {61: 4, 63: 3, 11: 2},\n 63: {62: 3, 64: 3},\n 64: {63: 3, 65: 3},\n 65: {64: 3, 66: 3},\n 66: {65: 3}\n }\n\nn = 67\n\nstations_rev_lower = {}\nfor i in range(n):\n stations_rev_lower[stations[i].lower()] = i\n\nstations_alph = []\nfor i in range(n):\n stations_alph.append(stations[i])\nstations_alph.sort()\n\ndef color(v):\n if v <= 18:\n return '#BC021E' # красная\n else:\n if v <= 36:\n return '#0E7EA3' # синяя\n else:\n if v <= 46:\n return '#088B1C' # зеленая\n else:\n if v <= 54:\n return '#C28C04' # желтая\n else:\n return '#9C1995' # фиолетовая\n\ndef norm_path(path):\n ans = []\n transfer = 0\n for i in range(len(path)):\n if i != 0 and color(path[i]) != color(path[i - 1]):\n transfer += 1\n ans.append((stations[path[i]], color(path[i])))\n return ans, transfer\n\ndef dijkstra(s, r):\n if s == r:\n return 0, []\n \n d = [float('inf')] * n\n p = [-1] * n\n d[s] = 0\n u = [False] * n\n \n for i in range(n):\n v = -1\n for j in range(n):\n if (not u[j]) and (v == -1 or d[j] < d[v]):\n v = j\n if d[v] == float('inf'):\n break\n u[v] = True\n if v == r:\n path = []\n while r != s:\n path.append(r)\n r = p[r]\n path.append(s)\n path = list(reversed(path))\n return d[v], path\n \n for j in range(len(g[v])):\n to = g[v].items()[j][0]\n length = g[v].items()[j][1]\n if d[v] + length < d[to]:\n d[to] = d[v] + length\n p[to] = v\n\ndef transfer_text(transfer):\n if transfer == 0:\n return u'Без пересадок'\n if transfer == 1:\n return u'1 пересадка'\n return str(transfer) + u' пересадки'\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n template_values = {\n 'stations': stations_alph,\n }\n\n template = JINJA_ENVIRONMENT.get_template('index.html')\n self.response.write(template.render(template_values))\n\n def post(self):\n begin = self.request.get('begin').strip().lower()\n end = self.request.get('end').strip().lower()\n try:\n u = stations_rev_lower[begin]\n v = stations_rev_lower[end]\n path = []\n res, path = dijkstra(u, v)\n path, transfer = norm_path(path)\n transfer = transfer_text(transfer)\n\n template_values = {\n 'result': res,\n 'stations': stations_alph,\n 'st_begin': stations[u],\n 'st_end': stations[v],\n 'path': path,\n 'transfer': transfer,\n 'check': False,\n }\n except:\n template_values = {\n 'stations': stations_alph,\n 'check': True,\n # 'error': begin + ' - ' + end,\n }\n template = JINJA_ENVIRONMENT.get_template('index.html')\n self.response.write(template.render(template_values))\n\napp = webapp2.WSGIApplication([\n ('/', MainPage),\n], debug=True)","sub_path":"metro.py","file_name":"metro.py","file_ext":"py","file_size_in_byte":8364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129174319","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ncap = cv2.VideoCapture('chaplin.mp4')\n\nif not cap.isOpened():\n raise IOError(\"Could not open video\")\n\ndef get_adjacent_pixels(img, x, y):\n h = img.shape[0]\n w = img.shape[1]\n pixels = []\n if x > 0: #it isn't at the first column\n pixels.append(img[y][x-1])\n if x < w-1: #it isn't at the last column\n pixels.append(img[y][x+1])\n if y > 0: #it isn't at the first row\n pixels.append(img[y-1][x])\n if y < h-1: #it isn't at the first row\n pixels.append(img[y+1][x])\n return pixels\n\ndef compute_contrast(image):\n h = image.shape[0]\n w = image.shape[1]\n contrast = 0\n for y in range(0, h):\n for x in range(0, w):\n contrast += (1/(h*w))*(np.abs(image[y,x]-np.mean(get_adjacent_pixels(image,x,y))))\n return contrast\n\nframe_mean = []\nframe_stddv = []\nframe_contrast = []\ncount = 0;\nwhile True:\n ret, frame = cap.read()\n\n if ret:\n count = count + 1;\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n mean_stddv = cv2.meanStdDev(frame)\n m = float(mean_stddv[0][0])\n s = float(mean_stddv[1][0])\n c = compute_contrast(frame)\n frame_mean.append(m)\n frame_stddv.append(s)\n frame_contrast.append(c)\n print(count,(count/150)*100)\n else:\n break\n\ncap.release()\n\nplt.plot(frame_mean, color='b')\nplt.plot(frame_stddv, color='r')\nplt.plot(frame_contrast, color='g')\nplt.xlim([0,150])\nplt.show()\n","sub_path":"2-b.py","file_name":"2-b.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"529694922","text":"# -*- coding: utf-8 -*-\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\nimport logging\nimport textwrap\nfrom unittest import mock\n\nimport fixtures\nimport yaml\n\nfrom reno import config\nfrom reno import loader\nfrom reno.tests import base\n\n\nclass TestValidate(base.TestCase):\n\n scanner_output = {\n '0.0.0': [('note', 'shaA')],\n }\n\n versions = ['0.0.0']\n\n def setUp(self):\n super(TestValidate, self).setUp()\n self.logger = self.useFixture(\n fixtures.FakeLogger(\n format='%(message)s',\n level=logging.WARNING,\n )\n )\n self.c = config.Config('reporoot')\n\n def _make_loader(self, note_bodies):\n def _load(ldr):\n ldr._scanner_output = self.scanner_output\n ldr._cache = {\n 'file-contents': {'note1': note_bodies},\n }\n\n with mock.patch('reno.loader.Loader._load_data', _load):\n return loader.Loader(\n self.c,\n ignore_cache=False,\n )\n\n def test_note_with_non_prelude_string_converted_to_list(self):\n \"\"\"Test behavior when a non-prelude note is not structured as a list.\n\n We should silently convert it to list.\n \"\"\"\n note_bodies = yaml.safe_load(textwrap.dedent(\"\"\"\n issues: |\n This is a single string. It should be converted to a list.\n \"\"\"))\n self.assertIsInstance(note_bodies['issues'], str)\n with self._make_loader(note_bodies) as ldr:\n parse_results = ldr.parse_note_file('note1', None)\n self.assertIsInstance(parse_results['issues'], list)\n\n def test_invalid_note_with_prelude_as_list(self):\n note_bodies = yaml.safe_load(textwrap.dedent('''\n prelude:\n - The prelude should not be a list.\n '''))\n self.assertIsInstance(note_bodies['prelude'], list)\n with self._make_loader(note_bodies) as ldr:\n ldr.parse_note_file('note1', None)\n self.assertIn('does not parse as a single string', self.logger.output)\n\n def test_invalid_note_with_colon_as_dict(self):\n note_bodies = yaml.safe_load(textwrap.dedent('''\n issues:\n - This line is fine.\n - dict: But this is parsed as a mapping (dictionary), which is bad.\n '''))\n self.assertIsInstance(note_bodies['issues'][-1], dict)\n with self._make_loader(note_bodies) as ldr:\n ldr.parse_note_file('note1', None)\n self.assertIn('instead of a string', self.logger.output)\n\n def test_invalid_note_with_unrecognized_key(self):\n \"\"\"Test behavior when note contains an unrecognized section.\"\"\"\n note_bodies = yaml.safe_load(textwrap.dedent('''\n foobar:\n - |\n This is an issue but we're using an unrecognized section key.\n '''))\n self.assertIsInstance(note_bodies, dict)\n with self._make_loader(note_bodies) as ldr:\n ldr.parse_note_file('note1', None)\n self.assertIn(\n 'The foobar section of note1 is not a recognized section.',\n self.logger.output)\n\n def test_invalid_note_with_missing_key(self):\n \"\"\"Test behavior when note is not structured as a mapping.\n\n This one should be an error since we can't correct the input.\n \"\"\"\n note_bodies = yaml.safe_load(textwrap.dedent('''\n - |\n This is an issue but we're missing the top-level 'issues' key.\n '''))\n self.assertIsInstance(note_bodies, list)\n with self._make_loader(note_bodies) as ldr:\n self.assertRaises(ValueError, ldr.parse_note_file, 'note1', None)\n self.assertIn(\n 'does not appear to be structured as a YAML mapping',\n self.logger.output)\n","sub_path":"reno/tests/test_loader.py","file_name":"test_loader.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110844210","text":"from __future__ import print_function\nfrom maya import cmds\nimport inspect\nimport json\nimport sys\nimport imp\nimport os\n\n\ndef loadConfig():\n \"\"\" Load config file\n\n Return:\n config(list): List of path module paths\n\n \"\"\"\n configFilePath = os.path.normpath(os.path.join(\n cmds.internalVar(userScriptDir=True), 'rush.json'))\n\n defaultModulePath = os.path.normpath(os.path.join(\n cmds.internalVar(userScriptDir=True), 'rush', 'module'))\n\n config = [defaultModulePath]\n\n # Use only default module path if config file does not exist\n if not os.path.exists(configFilePath):\n print(\"Additional config file not found: %s\" % configFilePath)\n return config\n\n # Open and load config file in use home dir and append it to the\n # config list\n try:\n f = open(configFilePath, 'r')\n extra_config = json.load(f)\n additionalPaths = extra_config[\"path\"]\n f.close()\n except IOError:\n print(\"Failed to load config file\")\n\n config.extend(additionalPaths)\n\n return config\n\n\ndef getModulePath(path):\n \"\"\" Create and return a list of module paths\n\n Args:\n path (str): directory path to search modules\n\n Return:\n mods (list): List of module paths\n None: if the path doesn't exist\n\n \"\"\"\n if not os.path.exists(path):\n return None\n\n # Get all files in the directory\n allFiles = [os.path.join(root, f) for root, _, files in os.walk(path)\n for f in files]\n\n # Get only python files\n pythonFiles = [i for i in allFiles if i.endswith(\".py\")]\n\n # Remove __init__ and main plugin file\n mods = [f for f in pythonFiles\n if not f.endswith(\"__init__.py\") and not f.endswith(\"Rush.py\")]\n\n return mods\n\n\ndef loadModule(path):\n \"\"\" Load module\n\n Args:\n path (str): Full path to the python module\n\n Return:\n mod (module object): command module\n None: if path doesn't exist\n\n \"\"\"\n # Create module names for import, for exapmle ...\n #\n # \"rush/template\"\n # \"animation/animate\"\n # \"common/create\"\n # \"common/display\"\n\n normpath = os.path.normpath(path)\n\n if sys.platform == \"win32\":\n name = os.path.splitext(normpath)[0].split(\"\\\\\")\n else:\n name = os.path.splitext(normpath)[0].split(\"/\")\n\n name = \"/\".join(name[-2:])\n\n # If arnold is not loaded or installed, ignore modules for arnold\n if name.startswith(\"Arnold\"):\n hasArnold = cmds.pluginInfo(\"mtoa\", q=True, loaded=True)\n if not hasArnold:\n return None\n\n try:\n mod = imp.load_source(name, path)\n return mod\n except Exception:\n print(\"Failed to load module : %s\" % path)\n return None\n\n\nclass TempClass(object):\n commandDict = {}\n\n\nmodules = []\n\n\nfor path in loadConfig():\n normpath = os.path.normpath(path)\n if os.path.exists(normpath):\n module_paths = getModulePath(path)\n for module_path in module_paths:\n m = loadModule(module_path)\n try:\n tempDict = {}\n for cmd in m.commandDict:\n displayName = cmd[:1].capitalize() + cmd[1:]\n command_data = {}\n command_data[displayName] = {}\n command_data[displayName]['icon'] = m.commandDict[cmd]\n command_data[displayName]['path'] = module_path\n command_data[displayName]['command'] = cmd\n tempDict.update(command_data)\n TempClass.commandDict.update(tempDict)\n except AttributeError:\n pass\n fs = inspect.getmembers(m, inspect.isfunction)\n for f in fs:\n setattr(TempClass, f[0], staticmethod(f[1]))\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238405817","text":"from bot.model.Result import Result\nimport requests\nfrom bs4 import BeautifulSoup\n\nclass ResultService():\n\n @staticmethod\n def addResult(local, visit, rlocal, rvisit):\n try:\n result = Result()\n result.setTeamLocal(local)\n result.setTeamVisit(visit)\n result.setResultLocal(rlocal)\n result.setResultVisit(rvisit)\n result.save()\n return True\n except:\n return False\n\n @staticmethod\n def getResult(id):\n\n try:\n result = Result.get(Result.id == id)\n except:\n return None\n return result\n\n @staticmethod\n def getResultByLocal(local):\n\n try:\n result = Result.get(Result.teamLocal == local)\n except:\n return None\n return result\n\n @staticmethod\n def getResultByVisit(visit):\n\n try:\n result = Result.get(Result.teamVisit == visit)\n except:\n return None\n return result\n\n @staticmethod\n def getAll():\n\n try:\n listResults =[]\n result = Result.select()\n for r in result:\n listResults.append(r)\n result = listResults\n except:\n return None\n return result\n\n @staticmethod\n def getResultLocal(id):\n try:\n result = Result.get(Result.id == id)\n except:\n return None\n return result.getResultLocal()\n\n @staticmethod\n def inserDataResult():\n \"\"\"Funcion que scrapea de la web la información de los resultados de la jornada de la liga española de fútbol.\n \"\"\"\n url = \"http://resultados.as.com/resultados/futbol/primera/jornada/\"\n\n req = requests.get(url)\n\n v_tlocal = [] # vector equipos locales\n v_tvisit = [] # vector equipos visitantes\n v_result = [] # vector resultados\n v_result_local = []\n v_result_visit = []\n v_fecha = [] # vecto fechas\n\n statusCode = req.status_code\n if statusCode == 200:\n\n # Pasamos el contenido HTML de la web a un objeto BeautifulSoup()\n html = BeautifulSoup(req.text, \"html.parser\")\n\n # Obtenemos todos los divs donde estan las entradas de los equipos locales\n entradas = html.find_all('div', {'class': 'equipo-local'})\n for i, entrada in enumerate(entradas):\n equipo_local = entrada.find('span', {'class': 'nombre-equipo'}).getText()\n v_tlocal.insert(i, equipo_local)\n\n # Obtenemos todos los divs donde estan las entradas de los equipos visitantes\n entradas2 = html.find_all('div', {'class': 'equipo-visitante'})\n for i, entrada in enumerate(entradas2):\n equipo_visit = entrada.find('span', {'class': 'nombre-equipo'}).getText()\n v_tvisit.insert(i, equipo_visit)\n\n # Obtenemos todos los divs donde estan los resultados finalizados\n entradas3 = html.find_all('a', {'class': 'resultado'})\n for i, entrada in enumerate(entradas3):\n # resultado = entrada.find('a', {'class' : 'resultado'}).getText()\n v_result.insert(i, entrada.text)\n print(entrada.text)\n result = entrada.text\n position = result.find('-')\n v_result_local.insert(i, int(\"\"+result[position-2]))\n v_result_visit.insert(i, int(\"\"+result[position + 2]))\n\n if len(v_result) < 10:\n for i in range(len(v_result), 10):\n v_result.insert(i, \"-\")\n\n # Obtenemos todos los divs donde estan las fechas\n entradas4 = html.find_all('span', {'class': 'fecha'})\n for i, entrada in enumerate(entradas4):\n # resultado = entrada.find('a', {'class' : 'resultado'}).getText()\n v_fecha.insert(i, entrada.text)\n\n # print (entradas)\n\n for i in range(10):\n # fun_bd.insertResultados(v_tlocal[i], v_result[i], v_tvisit[i], i + 1)\n try:\n result = Result.select().where(Result.id == i).get()\n result.setTeamLocal(v_tlocal[i])\n result.setTeamVisit(v_tvisit[i])\n result.setResultLocal(int(v_result_local[i]))\n result.setResultVisit(int(v_result_visit[i]))\n result.save()\n except:\n result = Result()\n result.setTeamLocal(v_tlocal[i])\n result.setTeamVisit(v_tvisit[i])\n result.setResultLocal(int(v_result_local[i]))\n result.setResultVisit(int(v_result_visit[i]))\n result.save()\n\n else:\n print (\"Status Code %d\" % statusCode)\n","sub_path":"Ejercicios-tema4/microservicio_python/bot/service/ResultService.py","file_name":"ResultService.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306266999","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport six\nimport tensorflow as tf\n\nfrom copy import deepcopy\nfrom edward.models.random_variable import RandomVariable\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.framework.ops import set_shapes_for_outputs\nfrom tensorflow.python.util import compat\n\ndistributions = tf.contrib.distributions\n\n\ndef copy(org_instance, dict_swap=None, scope=\"copied\",\n replace_itself=False, copy_q=False):\n \"\"\"Build a new node in the TensorFlow graph from `org_instance`,\n where any of its ancestors existing in `dict_swap` are\n replaced with `dict_swap`'s corresponding value.\n\n The copying is done recursively, so any `Operation` whose output\n is required to evaluate `org_instance` is also copied (if it isn't\n already copied within the new scope). This is with the exception of\n `tf.Variable`s and `tf.placeholder`s, which are reused and not newly copied.\n\n Parameters\n ----------\n org_instance : RandomVariable, tf.Variable, tf.Tensor, or tf.Operation\n Node to add in graph with replaced ancestors.\n dict_swap : dict, optional\n Random variables, variables, tensors, or operations to\n swap with. Its keys are what `org_instance` may depend on,\n and its values are the corresponding object (not necessarily of\n the same type) that is used in exchange.\n scope : str, optional\n A scope for the new node(s). This is used to avoid name\n conflicts with the original node(s).\n replace_itself : bool, optional\n Whether to replace `org_instance` itself if it exists in\n `dict_swap`. (This is used for the recursion.)\n copy_q : bool, optional\n Whether to copy the replaced tensors too (if not already\n copied within the new scope). Otherwise will reuse them.\n\n Returns\n -------\n RandomVariable, tf.Variable, tf.Tensor, or tf.Operation\n The copied node.\n\n Raises\n ------\n TypeError\n If `org_instance` is not one of the above types.\n\n Examples\n --------\n >>> x = tf.constant(2.0)\n >>> y = tf.constant(3.0)\n >>> z = x * y\n >>>\n >>> qx = tf.constant(4.0)\n >>> # The TensorFlow graph is currently\n >>> # `x` -> `z` <- y`, `qx`\n >>>\n >>> # This adds a subgraph with newly copied nodes,\n >>> # `copied/qx` -> `copied/z` <- `copied/y`\n >>> z_new = copy(z, {x: qx})\n >>>\n >>> sess = tf.Session()\n >>> sess.run(z)\n 6.0\n >>> sess.run(z_new)\n 12.0\n \"\"\"\n if not isinstance(org_instance, RandomVariable) and \\\n not isinstance(org_instance, tf.Variable) and \\\n not isinstance(org_instance, tf.Tensor) and \\\n not isinstance(org_instance, tf.Operation):\n raise TypeError(\"Could not copy instance: \" + str(org_instance))\n\n if dict_swap is None:\n dict_swap = {}\n\n # Swap instance if in dictionary.\n if org_instance in dict_swap and replace_itself:\n org_instance = dict_swap[org_instance]\n if not copy_q:\n return org_instance\n elif isinstance(org_instance, tf.Tensor) and replace_itself:\n # Deal with case when `org_instance` is the associated tensor\n # from the RandomVariable, e.g., `z.value()`. If\n # `dict_swap={z: qz}`, we aim to swap it with `qz.value()`.\n for key, value in six.iteritems(dict_swap):\n if isinstance(key, RandomVariable):\n if org_instance == key.value():\n if isinstance(value, RandomVariable):\n org_instance = value.value()\n else:\n org_instance = value\n\n if not copy_q:\n return org_instance\n break\n\n graph = tf.get_default_graph()\n new_name = scope + '/' + org_instance.name\n\n # If an instance of the same name exists, return appropriately.\n # Do this for random variables.\n random_variables = {x.name: x for x in\n graph.get_collection('_random_variable_collection_')}\n if new_name in random_variables:\n return random_variables[new_name]\n\n # Do this for tensors and operations.\n try:\n already_present = graph.as_graph_element(new_name,\n allow_tensor=True,\n allow_operation=True)\n return already_present\n except:\n pass\n\n # If instance is a variable, return it; do not re-copy any.\n # Note we check variables via their name and not their type. This\n # is because if we get variables through an op's inputs, it has\n # type tf.Tensor: we can only tell it is a variable via its name.\n variables = {x.name: x for x in graph.get_collection(tf.GraphKeys.VARIABLES)}\n if org_instance.name in variables:\n return graph.get_tensor_by_name(variables[org_instance.name].name)\n\n # Do the same for placeholders. Same logic holds.\n # Note this assumes that placeholders are all in this collection.\n placeholders = {x.name: x for x in graph.get_collection('PLACEHOLDERS')}\n if org_instance.name in placeholders:\n return graph.get_tensor_by_name(placeholders[org_instance.name].name)\n\n if isinstance(org_instance, RandomVariable):\n rv = org_instance\n\n # If it has copiable arguments, copy them.\n dist_args = {}\n for key, value in six.iteritems(rv._dist_args):\n if isinstance(value, RandomVariable) or \\\n isinstance(value, tf.Variable) or \\\n isinstance(value, tf.Tensor) or \\\n isinstance(value, tf.Operation):\n value = copy(value, dict_swap, scope, True, copy_q)\n\n dist_args[key] = value\n\n dist_args['name'] = new_name + rv.distribution.name\n\n # Copy a new `rv` with any newly copied arguments.\n # We do this by creating an empty class object and setting\n # its attributes. (This is to avoid a throwaway tensor in the\n # graph, during instantiation of DistributionTensor.)\n new_rv = Empty()\n new_rv.__class__ = rv.__class__\n for key, value in six.iteritems(rv.__dict__):\n if key not in ['_name', '_dist_args', '_dist', '_value']:\n setattr(new_rv, key, deepcopy(value))\n\n setattr(new_rv, '_name', new_name)\n setattr(new_rv, '_dist_args', dist_args)\n setattr(new_rv, '_dist', new_rv._dist_cls(**new_rv._dist_args))\n setattr(new_rv, '_value', new_rv._dist.sample())\n return new_rv\n elif isinstance(org_instance, tf.Tensor):\n tensor = org_instance\n\n # A tensor is one of the outputs of its underlying\n # op. Therefore copy the op itself.\n op = tensor.op\n new_op = copy(op, dict_swap, scope, True, copy_q)\n\n output_index = op.outputs.index(tensor)\n new_tensor = new_op.outputs[output_index]\n\n # Add copied tensor to collections that the original one is in.\n for name, collection in tensor.graph._collections.items():\n if tensor in collection:\n graph.add_to_collection(name, new_tensor)\n\n return new_tensor\n else: # tf.Operation\n op = org_instance\n\n # If it has an original op, copy it.\n if op._original_op is not None:\n new_original_op = copy(op._original_op, dict_swap, scope, True, copy_q)\n else:\n new_original_op = None\n\n # If it has control inputs, copy them.\n new_control_inputs = []\n for x in op.control_inputs:\n elem = copy(x, dict_swap, scope, True, copy_q)\n if not isinstance(elem, tf.Operation):\n elem = tf.convert_to_tensor(elem)\n\n new_control_inputs += [elem]\n\n # If it has inputs, copy them.\n new_inputs = []\n for x in op.inputs:\n elem = copy(x, dict_swap, scope, True, copy_q)\n if not isinstance(elem, tf.Operation):\n elem = tf.convert_to_tensor(elem)\n\n new_inputs += [elem]\n\n # Make a copy of the node def.\n # As an instance of tensorflow.core.framework.graph_pb2.NodeDef, it\n # stores string-based info such as name, device, and type of the op.\n # It is unique to every Operation instance.\n new_node_def = deepcopy(op.node_def)\n new_node_def.name = new_name\n\n # Copy the other inputs needed for initialization.\n output_types = op._output_types[:]\n input_types = op._input_types[:]\n\n # Make a copy of the op def.\n # It is unique to every Operation type.\n op_def = deepcopy(op.op_def)\n\n ret = tf.Operation(new_node_def,\n graph,\n new_inputs,\n output_types,\n new_control_inputs,\n input_types,\n new_original_op,\n op_def)\n\n # Use Graph's private methods to add the op, following\n # implementation of `tf.Graph().create_op()`.\n compute_shapes = True\n compute_device = True\n op_type = new_name\n\n if compute_shapes:\n set_shapes_for_outputs(ret)\n graph._add_op(ret)\n graph._record_op_seen_by_control_dependencies(ret)\n\n if compute_device:\n graph._apply_device_functions(ret)\n\n if graph._colocation_stack:\n all_colocation_groups = []\n for colocation_op in graph._colocation_stack:\n all_colocation_groups.extend(colocation_op.colocation_groups())\n if colocation_op.device:\n # Make this device match the device of the colocated op, to\n # provide consistency between the device and the colocation\n # property.\n if ret.device and ret.device != colocation_op.device:\n logging.warning(\"Tried to colocate %s with an op %s that had \"\n \"a different device: %s vs %s. \"\n \"Ignoring colocation property.\",\n name, colocation_op.name, ret.device,\n colocation_op.device)\n else:\n ret._set_device(colocation_op.device)\n\n all_colocation_groups = sorted(set(all_colocation_groups))\n ret.node_def.attr[\"_class\"].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(s=all_colocation_groups)))\n\n # Sets \"container\" attribute if\n # (1) graph._container is not None\n # (2) \"is_stateful\" is set in OpDef\n # (3) \"container\" attribute is in OpDef\n # (4) \"container\" attribute is None\n if (graph._container and\n op_type in graph._registered_ops and\n graph._registered_ops[op_type].is_stateful and\n \"container\" in ret.node_def.attr and\n not ret.node_def.attr[\"container\"].s):\n ret.node_def.attr[\"container\"].CopyFrom(\n attr_value_pb2.AttrValue(s=compat.as_bytes(graph._container)))\n\n return ret\n\n\ndef cumprod(xs):\n \"\"\"Cumulative product of a tensor along its outer dimension.\n\n https://github.com/tensorflow/tensorflow/issues/813\n\n Parameters\n ----------\n xs : tf.Tensor\n A 1-D or higher tensor.\n\n Returns\n -------\n tf.Tensor\n A tensor with `cumprod` applied along its outer dimension.\n\n Raises\n ------\n InvalidArgumentError\n If the input has Inf or NaN values.\n \"\"\"\n xs = tf.convert_to_tensor(xs)\n dependencies = [tf.verify_tensor_all_finite(xs, msg='')]\n xs = control_flow_ops.with_dependencies(dependencies, xs)\n\n values = tf.unpack(xs)\n out = []\n prev = tf.ones_like(values[0])\n for val in values:\n s = prev * val\n out.append(s)\n prev = s\n\n result = tf.pack(out)\n return result\n\n\ndef dot(x, y):\n \"\"\"Compute dot product between a 2-D tensor and a 1-D tensor.\n\n If x is a ``[M x N]`` matrix, then y is a ``M``-vector.\n\n If x is a ``M``-vector, then y is a ``[M x N]`` matrix.\n\n Parameters\n ----------\n x : tf.Tensor\n A 1-D or 2-D tensor (see above).\n y : tf.Tensor\n A 1-D or 2-D tensor (see above).\n\n Returns\n -------\n tf.Tensor\n A 1-D tensor of length ``N``.\n\n Raises\n ------\n InvalidArgumentError\n If the inputs have Inf or NaN values.\n \"\"\"\n x = tf.convert_to_tensor(x)\n y = tf.convert_to_tensor(y)\n dependencies = [tf.verify_tensor_all_finite(x, msg=''),\n tf.verify_tensor_all_finite(y, msg='')]\n x = control_flow_ops.with_dependencies(dependencies, x)\n y = control_flow_ops.with_dependencies(dependencies, y)\n\n if len(x.get_shape()) == 1:\n vec = x\n mat = y\n return tf.reshape(tf.matmul(tf.expand_dims(vec, 0), mat), [-1])\n else:\n mat = x\n vec = y\n return tf.reshape(tf.matmul(mat, tf.expand_dims(vec, 1)), [-1])\n\n\nclass Empty(object):\n \"\"\"Empty class.\"\"\"\n pass\n\n\ndef get_dims(x):\n \"\"\"Get values of each dimension.\n\n Parameters\n ----------\n x : float, int, tf.Tensor, np.ndarray, or RandomVariable\n A n-D tensor.\n\n Returns\n -------\n list of int\n Python list containing dimensions of ``x``.\n \"\"\"\n if isinstance(x, float) or isinstance(x, int):\n return []\n elif isinstance(x, tf.Tensor) or isinstance(x, tf.Variable):\n return x.get_shape().as_list()\n elif isinstance(x, np.ndarray):\n return list(x.shape)\n elif isinstance(x, RandomVariable):\n return x.get_batch_shape().as_list()\n else:\n raise NotImplementedError()\n\n\ndef get_session():\n \"\"\"Get the globally defined TensorFlow session.\n\n If the session is not already defined, then the function will create\n a global session.\n\n Returns\n -------\n _ED_SESSION : tf.InteractiveSession\n \"\"\"\n global _ED_SESSION\n if tf.get_default_session() is None:\n _ED_SESSION = tf.InteractiveSession()\n else:\n _ED_SESSION = tf.get_default_session()\n\n return _ED_SESSION\n\n\ndef hessian(y, xs):\n \"\"\"Calculate Hessian of y with respect to each x in xs.\n\n Parameters\n ----------\n y : tf.Tensor\n Tensor to calculate Hessian of.\n xs : list of tf.Variable\n List of TensorFlow variables to calculate with respect to.\n The variables can have different shapes.\n\n Returns\n -------\n tf.Tensor\n A 2-D tensor where each row is\n .. math:: \\partial_{xs} ( [ \\partial_{xs} y ]_j ).\n\n Raises\n ------\n InvalidArgumentError\n If the inputs have Inf or NaN values.\n \"\"\"\n y = tf.convert_to_tensor(y)\n dependencies = [tf.verify_tensor_all_finite(y, msg='')]\n dependencies.extend([tf.verify_tensor_all_finite(x, msg='') for x in xs])\n\n with tf.control_dependencies(dependencies):\n # Calculate flattened vector grad_{xs} y.\n grads = tf.gradients(y, xs)\n grads = [tf.reshape(grad, [-1]) for grad in grads]\n grads = tf.concat(0, grads)\n # Loop over each element in the vector.\n mat = []\n d = grads.get_shape()[0]\n if not isinstance(d, int):\n d = grads.eval().shape[0]\n\n for j in range(d):\n # Calculate grad_{xs} ( [ grad_{xs} y ]_j ).\n gradjgrads = tf.gradients(grads[j], xs)\n # Flatten into vector.\n hi = []\n for l in range(len(xs)):\n hij = gradjgrads[l]\n # return 0 if gradient doesn't exist; TensorFlow returns None\n if hij is None:\n hij = tf.zeros(xs[l].get_shape(), dtype=tf.float32)\n\n hij = tf.reshape(hij, [-1])\n hi.append(hij)\n\n hi = tf.concat(0, hi)\n mat.append(hi)\n\n # Form matrix where each row is grad_{xs} ( [ grad_{xs} y ]_j ).\n return tf.pack(mat)\n\n\ndef kl_multivariate_normal(loc_one, scale_one, loc_two=0.0, scale_two=1.0):\n \"\"\"Calculate the KL of multivariate normal distributions with\n diagonal covariances.\n\n Parameters\n ----------\n loc_one : tf.Tensor\n A 0-D tensor, 1-D tensor of length n, or 2-D tensor of shape M\n x n where each row represents the mean of a n-dimensional\n Gaussian.\n scale_one : tf.Tensor\n A tensor of same shape as ``loc_one``, representing the\n standard deviation.\n loc_two : tf.Tensor, optional\n A tensor of same shape as ``loc_one``, representing the\n mean of another Gaussian.\n scale_two : tf.Tensor, optional\n A tensor of same shape as ``loc_one``, representing the\n standard deviation of another Gaussian.\n\n Returns\n -------\n tf.Tensor\n For 0-D or 1-D tensor inputs, outputs the 0-D tensor\n ``KL( N(z; loc_one, scale_one) || N(z; loc_two, scale_two) )``\n For 2-D tensor inputs, outputs the 1-D tensor\n ``[KL( N(z; loc_one[m,:], scale_one[m,:]) || ``\n ``N(z; loc_two[m,:], scale_two[m,:]) )]_{m=1}^M``\n\n Raises\n ------\n InvalidArgumentError\n If the location variables have Inf or NaN values, or if the scale\n variables are not positive.\n \"\"\"\n loc_one = tf.convert_to_tensor(loc_one)\n scale_one = tf.convert_to_tensor(scale_one)\n loc_two = tf.convert_to_tensor(loc_two)\n scale_two = tf.convert_to_tensor(scale_two)\n dependencies = [tf.verify_tensor_all_finite(loc_one, msg=''),\n tf.verify_tensor_all_finite(loc_two, msg=''),\n tf.assert_positive(scale_one),\n tf.assert_positive(scale_two)]\n loc_one = control_flow_ops.with_dependencies(dependencies, loc_one)\n scale_one = control_flow_ops.with_dependencies(dependencies, scale_one)\n\n if loc_two == 0.0 and scale_two == 1.0:\n # With default arguments, we can avoid some intermediate computation.\n out = tf.square(scale_one) + tf.square(loc_one) - \\\n 1.0 - 2.0 * tf.log(scale_one)\n else:\n loc_two = control_flow_ops.with_dependencies(dependencies, loc_two)\n scale_two = control_flow_ops.with_dependencies(dependencies, scale_two)\n out = tf.square(scale_one / scale_two) + \\\n tf.square((loc_two - loc_one) / scale_two) - \\\n 1.0 + 2.0 * tf.log(scale_two) - 2.0 * tf.log(scale_one)\n\n if len(out.get_shape()) <= 1: # scalar or vector\n return 0.5 * tf.reduce_sum(out)\n else: # matrix\n return 0.5 * tf.reduce_sum(out, 1)\n\n\ndef log_mean_exp(input_tensor, reduction_indices=None, keep_dims=False):\n \"\"\"Compute the ``log_mean_exp`` of elements in a tensor, taking\n the mean across axes given by ``reduction_indices``.\n\n Parameters\n ----------\n input_tensor : tf.Tensor\n The tensor to reduce. Should have numeric type.\n reduction_indices : int or list of int, optional\n The dimensions to reduce. If `None` (the default), reduces all\n dimensions.\n keep_dims : bool, optional\n If true, retains reduced dimensions with length 1.\n\n Returns\n -------\n tf.Tensor\n The reduced tensor.\n\n Raises\n ------\n InvalidArgumentError\n If the input has Inf or NaN values.\n \"\"\"\n input_tensor = tf.convert_to_tensor(input_tensor)\n dependencies = [tf.verify_tensor_all_finite(input_tensor, msg='')]\n input_tensor = control_flow_ops.with_dependencies(dependencies, input_tensor)\n\n x_max = tf.reduce_max(input_tensor, reduction_indices, keep_dims=True)\n return tf.squeeze(x_max) + tf.log(tf.reduce_mean(\n tf.exp(input_tensor - x_max), reduction_indices, keep_dims))\n\n\ndef log_sum_exp(input_tensor, reduction_indices=None, keep_dims=False):\n \"\"\"Compute the ``log_sum_exp`` of elements in a tensor, taking\n the sum across axes given by ``reduction_indices``.\n\n Parameters\n ----------\n input_tensor : tf.Tensor\n The tensor to reduce. Should have numeric type.\n reduction_indices : int or list of int, optional\n The dimensions to reduce. If `None` (the default), reduces all\n dimensions.\n keep_dims : bool, optional\n If true, retains reduced dimensions with length 1.\n\n Returns\n -------\n tf.Tensor\n The reduced tensor.\n\n Raises\n ------\n InvalidArgumentError\n If the input has Inf or NaN values.\n \"\"\"\n input_tensor = tf.convert_to_tensor(input_tensor)\n dependencies = [tf.verify_tensor_all_finite(input_tensor, msg='')]\n input_tensor = control_flow_ops.with_dependencies(dependencies, input_tensor)\n\n x_max = tf.reduce_max(input_tensor, reduction_indices, keep_dims=True)\n return tf.squeeze(x_max) + tf.log(tf.reduce_sum(\n tf.exp(input_tensor - x_max), reduction_indices, keep_dims))\n\n\ndef logit(x):\n \"\"\"Evaluate :math:`\\log(x / (1 - x))` elementwise.\n\n Parameters\n ----------\n x : tf.Tensor\n A n-D tensor.\n\n Returns\n -------\n tf.Tensor\n A tensor of same shape as input.\n\n Raises\n ------\n InvalidArgumentError\n If the input is not between :math:`(0,1)` elementwise.\n \"\"\"\n x = tf.convert_to_tensor(x)\n dependencies = [tf.assert_positive(x),\n tf.assert_less(x, 1.0)]\n x = control_flow_ops.with_dependencies(dependencies, x)\n\n return tf.log(x) - tf.log(1.0 - x)\n\n\ndef multivariate_rbf(x, y=0.0, sigma=1.0, l=1.0):\n \"\"\"Squared-exponential kernel\n\n .. math:: k(x, y) = \\sigma^2 \\exp{ -1/(2l^2) \\sum_i (x_i - y_i)^2 }\n\n Parameters\n ----------\n x : tf.Tensor\n A n-D tensor.\n y : tf.Tensor, optional\n A tensor of same shape as ``x``.\n sigma : tf.Tensor, optional\n A 0-D tensor, representing the standard deviation of radial\n basis function.\n l : tf.Tensor, optional\n A 0-D tensor, representing the lengthscale of radial basis\n function.\n\n Returns\n -------\n tf.Tensor\n A tensor of one less dimension than the input.\n\n Raises\n ------\n InvalidArgumentError\n If the mean variables have Inf or NaN values, or if the scale\n and length variables are not positive.\n \"\"\"\n x = tf.convert_to_tensor(x)\n y = tf.convert_to_tensor(y)\n sigma = tf.convert_to_tensor(sigma)\n l = tf.convert_to_tensor(l)\n dependencies = [tf.verify_tensor_all_finite(x, msg=''),\n tf.verify_tensor_all_finite(y, msg=''),\n tf.assert_positive(sigma),\n tf.assert_positive(l)]\n x = control_flow_ops.with_dependencies(dependencies, x)\n y = control_flow_ops.with_dependencies(dependencies, y)\n sigma = control_flow_ops.with_dependencies(dependencies, sigma)\n l = control_flow_ops.with_dependencies(dependencies, l)\n\n return tf.pow(sigma, 2.0) * \\\n tf.exp(-1.0 / (2.0 * tf.pow(l, 2.0)) * tf.reduce_sum(tf.pow(x - y, 2.0)))\n\n\ndef placeholder(*args, **kwargs):\n \"\"\"A wrapper around ``tf.placeholder``. It adds the tensor to the\n ``PLACEHOLDERS`` collection.\"\"\"\n x = tf.placeholder(*args, **kwargs)\n tf.add_to_collection(\"PLACEHOLDERS\", x)\n return x\n\n\ndef rbf(x, y=0.0, sigma=1.0, l=1.0):\n \"\"\"Squared-exponential kernel element-wise\n\n .. math:: k(x, y) = \\sigma^2 \\exp{ -1/(2l^2) (x - y)^2 }\n\n Parameters\n ----------\n x : tf.Tensor\n A n-D tensor.\n y : tf.Tensor, optional\n A tensor of same shape as ``x``.\n sigma : tf.Tensor, optional\n A 0-D tensor, representing the standard deviation of radial\n basis function.\n l : tf.Tensor, optional\n A 0-D tensor, representing the lengthscale of radial basis\n function.\n\n Returns\n -------\n tf.Tensor\n A tensor of one less dimension than the input.\n\n Raises\n ------\n InvalidArgumentError\n If the mean variables have Inf or NaN values, or if the scale\n and length variables are not positive.\n \"\"\"\n x = tf.convert_to_tensor(x)\n y = tf.convert_to_tensor(y)\n sigma = tf.convert_to_tensor(sigma)\n l = tf.convert_to_tensor(l)\n dependencies = [tf.verify_tensor_all_finite(x, msg=''),\n tf.verify_tensor_all_finite(y, msg=''),\n tf.assert_positive(sigma),\n tf.assert_positive(l)]\n x = control_flow_ops.with_dependencies(dependencies, x)\n y = control_flow_ops.with_dependencies(dependencies, y)\n sigma = control_flow_ops.with_dependencies(dependencies, sigma)\n l = control_flow_ops.with_dependencies(dependencies, l)\n\n return tf.pow(sigma, 2.0) * \\\n tf.exp(-1.0 / (2.0 * tf.pow(l, 2.0)) * tf.pow(x - y, 2.0))\n\n\ndef set_seed(x):\n \"\"\"Set seed for both NumPy and TensorFlow.\n\n Parameters\n ----------\n x : int, float\n seed\n \"\"\"\n node_names = list(six.iterkeys(tf.get_default_graph()._nodes_by_name))\n if len(node_names) > 0 and node_names != ['keras_learning_phase']:\n raise RuntimeError(\"Seeding is not supported after initializing \"\n \"part of the graph. \"\n \"Please move set_seed to the beginning of your code.\")\n\n np.random.seed(x)\n tf.set_random_seed(x)\n\n\ndef tile(input, multiples, *args, **kwargs):\n \"\"\"Constructs a tensor by tiling a given tensor.\n\n This extends ``tf.tile`` to features available in ``np.tile``.\n Namely, ``inputs`` and ``multiples`` can be a 0-D tensor. Further,\n if 1-D, ``multiples`` can be of any length according to broadcasting\n rules (see documentation of ``np.tile`` or examples below).\n\n Parameters\n ----------\n input : tf.Tensor\n The input tensor.\n multiples : tf.Tensor\n The number of repetitions of ``input`` along each axis. Has type\n ``tf.int32``. 0-D or 1-D.\n *args :\n Passed into ``tf.tile``.\n **kwargs :\n Passed into ``tf.tile``.\n\n Returns\n -------\n tf.Tensor\n Has the same type as ``input``.\n\n Examples\n --------\n >>> a = tf.constant([0, 1, 2])\n >>> sess.run(ed.tile(a, 2))\n array([0, 1, 2, 0, 1, 2], dtype=int32)\n >>> sess.run(ed.tile(a, (2, 2)))\n array([[0, 1, 2, 0, 1, 2],\n [0, 1, 2, 0, 1, 2]], dtype=int32)\n >>> sess.run(ed.tile(a, (2, 1, 2)))\n array([[[0, 1, 2, 0, 1, 2]],\n [[0, 1, 2, 0, 1, 2]]], dtype=int32)\n >>>\n >>> b = tf.constant([[1, 2], [3, 4]])\n >>> sess.run(ed.tile(b, 2))\n array([[1, 2, 1, 2],\n [3, 4, 3, 4]], dtype=int32)\n >>> sess.run(ed.tile(b, (2, 1)))\n array([[1, 2],\n [3, 4],\n [1, 2],\n [3, 4]], dtype=int32)\n >>>\n >>> c = tf.constant([1, 2, 3, 4])\n >>> sess.run(ed.tile(c, (4, 1)))\n array([[1, 2, 3, 4],\n [1, 2, 3, 4],\n [1, 2, 3, 4],\n [1, 2, 3, 4]], dtype=int32)\n\n Notes\n -----\n Sometimes this can result in an unknown shape. The core reason for\n this is the following behavior:\n\n >>> n = tf.constant([1])\n >>> tf.tile(tf.constant([[1.0]]),\n ... tf.concat(0, [n, tf.constant([1.0]).get_shape()]))\n \n >>> n = tf.reshape(tf.constant(1), [1])\n >>> tf.tile(tf.constant([[1.0]]),\n ... tf.concat(0, [n, tf.constant([1.0]).get_shape()]))\n \n\n For this reason, we try to fetch ``multiples`` out of session if\n possible. This can be slow if ``multiples`` has computationally\n intensive dependencies in order to perform this fetch.\n \"\"\"\n input = tf.convert_to_tensor(input)\n multiples = tf.convert_to_tensor(multiples)\n\n # 0-d tensor\n if len(input.get_shape()) == 0:\n input = tf.expand_dims(input, 0)\n\n # 0-d tensor\n if len(multiples.get_shape()) == 0:\n multiples = tf.expand_dims(multiples, 0)\n\n try:\n get_session()\n multiples = tf.convert_to_tensor(multiples.eval())\n except:\n pass\n\n # broadcasting\n diff = len(input.get_shape()) - get_dims(multiples)[0]\n if diff < 0:\n input = tf.reshape(input, [1] * np.abs(diff) + get_dims(input))\n elif diff > 0:\n multiples = tf.concat(0, [tf.ones(diff, dtype=tf.int32), multiples])\n\n return tf.tile(input, multiples, *args, **kwargs)\n\n\ndef to_simplex(x):\n \"\"\"Transform real vector of length ``(K-1)`` to a simplex of dimension ``K``\n using a backward stick breaking construction.\n\n Parameters\n ----------\n x : tf.Tensor\n A 1-D or 2-D tensor.\n\n Returns\n -------\n tf.Tensor\n A tensor of same shape as input but with last dimension of\n size ``K``.\n\n Raises\n ------\n InvalidArgumentError\n If the input has Inf or NaN values.\n\n Notes\n -----\n x as a 3-D or higher tensor is not guaranteed to be supported.\n \"\"\"\n x = tf.cast(x, dtype=tf.float32)\n dependencies = [tf.verify_tensor_all_finite(x, msg='')]\n x = control_flow_ops.with_dependencies(dependencies, x)\n\n if isinstance(x, tf.Tensor) or isinstance(x, tf.Variable):\n shape = get_dims(x)\n else:\n shape = x.shape\n\n if len(shape) == 1:\n n_rows = ()\n K_minus_one = shape[0]\n eq = -tf.log(tf.cast(K_minus_one - tf.range(K_minus_one), dtype=tf.float32))\n z = tf.sigmoid(eq + x)\n pil = tf.concat(0, [z, tf.constant([1.0])])\n piu = tf.concat(0, [tf.constant([1.0]), 1.0 - z])\n S = cumprod(piu)\n return S * pil\n else:\n n_rows = shape[0]\n K_minus_one = shape[1]\n eq = -tf.log(tf.cast(K_minus_one - tf.range(K_minus_one), dtype=tf.float32))\n z = tf.sigmoid(eq + x)\n pil = tf.concat(1, [z, tf.ones([n_rows, 1])])\n piu = tf.concat(1, [tf.ones([n_rows, 1]), 1.0 - z])\n # cumulative product along 1st axis\n S = tf.pack([cumprod(piu_x) for piu_x in tf.unpack(piu)])\n return S * pil\n","sub_path":"edward/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":27673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567169876","text":"from collegeapp.models import Info\nfrom rest_framework.generics import ListAPIView\nfrom django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.generics import ListAPIView\nfrom rest_framework.filters import SearchFilter, OrderingFilter\nfrom collegeapp.api.serializers import InfoSerializer,InfoCreateSerializer,InfoUpdateSerializer\n# Create your views here.\n##############################\nSUCCESS = 'success'\nERROR = 'error'\nDELETE_SUCCESS = 'deleted'\nUPDATE_SUCCESS = 'updated'\nCREATE_SUCCESS = 'created'\n\n@api_view(['DELETE',])\n#@permission_classes((IsAuthenticated, ))\ndef api_delete_collegeapp_view(request, pk):\n\n\ttry:\n\t\tinfo_user = Info.objects.get(pk=pk)\n\texcept Info.DoesNotExist:\n\t\treturn Response(status=status.HTTP_404_NOT_FOUND)\n\n\n\tif request.method == 'DELETE':\n\t\toperation = info_user.delete()\n\t\tdata = {}\n\t\tif operation:\n\t\t\tdata['response'] = DELETE_SUCCESS\n\t\treturn Response(data=data)\n\n@api_view(['PUT'])\ndef api_update_collegeapp_view(request,pk):\n\n\ttry:\n\t\tinfo_user = Info.objects.get(pk=pk)\n\t\t#print (info_user.image_file)\n\texcept Info.DoesNotExist:\n\t\treturn Response(status=status.HTTP_404_NOT_FOUND)\n\n\tif request.method == 'PUT':\n\t\tserializer = InfoUpdateSerializer(info_user, data=request.data, partial=True)\n\t\tdata = {}\n\t\tif serializer.is_valid():\n\t\t\tserializer.save()\n\t\t\tdata['response'] = UPDATE_SUCCESS\n\t\t\tdata['pk'] = info_user.pk\n\t\t\tdata['reg_number'] = info_user.reg_number\n\t\t\tdata['ein1'] = info_user.ein1\n\t\t\tdata['ein2'] = info_user.ein2\n\t\t\tdata['ein3'] = info_user.ein3\n\t\t\tdata['nid'] = info_user.nid\n\t\t\tdata['amount'] = info_user.amount\n\t\t\treturn Response(data=data)\n\t\treturn Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef api_create_collegeapp_view(request):\n\n\tif request.method == 'POST':\n\t\tprint(\"inside create method!!!!!\")\n\t\tdata = request.data\n\t\tserializerboard = InfoCreateSerializer(data=data)\n\n\t\tdata = {}\n\t\tif serializerboard.is_valid():\n\t\t\tinfo_user = serializerboard.save()\n\t\t\tdata['response'] = CREATE_SUCCESS\n\t\t\t# data['pk'] = info_user.pk\n\t\t\t# data['reg_number'] = info_user.reg_number\n\t\t\t# data['ein1'] = info_user.ein1\n\t\t\t# data['ein2'] = info_user.ein2\n\t\t\t# data['ein3'] = info_user.ein3\n\t\t\t# data['nid'] = info_user.nid\n\t\t\t# data['amount'] = info_user.amount\n\t\t\treturn Response(data=data)\n\t\treturn Response(serializerboard.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass InfoListView(ListAPIView):\n\tqueryset = Info.objects.all()\n\tserializer_class = InfoSerializer\n\tpagination_class = PageNumberPagination\n\tfilter_backends = (SearchFilter, OrderingFilter)\n\tsearch_fields = ('reg_number', 'nid')\n","sub_path":"college/collegeapp/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432670470","text":"class GSP(object):\n\n def __init__(\n self,\n startState,\n goalState,\n actionStore,\n ss,\n gg,\n blocklist=['A', 'B', 'C', 'D']\n ):\n\n self.counter = 0\n self.blockList = blocklist\n self.startState=self.state_2_conjunct(ss)\n self.goalState=self.state_2_conjunct(gg)\n self.actionStore=actionStore\n\n\n\n\n\n\n def generateConjunct(self, preCondList, args):\n c = []\n for p in preCondList:\n t = []\n t.append(p[0])\n for a in p[1:]:\n # print a\n t.append(args[int(a[1])])\n t1 = tuple(t)\n c.append(tuple(['predicate', t1]))\n return tuple(['conjunct', c])\n\n\n def generate_and_set_blocks_list(self, state):\n bList = set()\n on = state['on']\n for t in on:\n bList = bList.union(list(t))\n\n bList = bList.union(state['onTable'] + state['holding'] + state['clear'])\n self.blockList = list(bList)\n return bList\n\n\n def plan_to_states_list(self, plan, start):\n out = []\n state = start\n s = self.conjunct_2_state(state)\n out.append(s)\n\n for action in plan:\n state = self.progress(state, action)\n s = self.conjunct_2_state(state)\n out.append(s)\n\n return out\n\n\n def progress(self, state, action):\n # sanity checks have been assumed\n # ie the fact that the action _can_ be done is assumed by this function\n currentState = self.conjunct_2_state(state)\n name = action[1][0]\n args = action[1][1:]\n\n add = self.actionStore[name]['A']\n for a in add:\n if a[0] == 'on': # two args, put as tuple\n currentState[a[0]].append(tuple([args[int(a[1][1])], args[int(a[2][1])]]))\n elif a[0] == 'armEmpty':\n currentState[a[0]] = True\n else: # one arg\n currentState[a[0]].append(args[int(a[1][1])])\n\n delete = actionStore[name]['D']\n for d in delete:\n if d[0] == 'on':\n currentState[d[0]].remove(tuple(args))\n elif d[0] == 'armEmpty':\n currentState[d[0]] = False\n else:\n currentState[d[0]].remove(args[int(d[1][1])])\n\n return self.state_2_conjunct(currentState)\n\n\n # return only a _list_ of actions and no conjuncts\n def get_actions_for_predicate(self, pred):\n p = pred[1]\n name = p[0]\n args = p[1:]\n actions = []\n if name == 'on':\n actions = [('action', ('stack', args[0], args[1]))]\n\n elif name == 'onTable':\n actions = [('action', ('putDown', args[0]))]\n\n elif name == 'clear':\n\n for b in self.blockList:\n if b != args[0]:\n actions.append(('action', ('stack', args[0], b)))\n for b in self.blockList:\n if b != args[0]:\n actions.append(('action', ('unStack', b, args[0])))\n\n elif name == 'holding':\n\n actions.append(('action', ('pickup', args[0])))\n for b in self.blockList:\n if b != args[0]:\n actions.append(('action', ('unStack', args[0], b)))\n\n elif name == 'armEmpty':\n\n for b in self.blockList:\n actions.append(('action', ('putDown', b)))\n\n for b1 in self.blockList:\n for b2 in self.blockList:\n if b1 != b2:\n actions.append(('action', ('stack', b1, b2)))\n\n return actions\n\n\n def is_in_state(self, pred, state):\n return pred in state[1]\n p = pred[1]\n name = p[0]\n if name == 'on':\n return p[1:] in state[name]\n elif name == 'armEmpty':\n return state[name]\n else:\n return p[1:] in state[name]\n\n\n def check_sovled(self, predList, state):\n for p in predList:\n if not self.is_in_state(p, state):\n return False\n return True\n\n\n # convert from state dict to a conjuct form\n def state_2_conjunct(self, state):\n conjunct = []\n\n if state['onTable']:\n for t in state['onTable']:\n p = ['predicate', ]\n o = ['onTable', ]\n o.append(t)\n p.append(tuple(o))\n conjunct.append(tuple(p))\n\n if state['clear']:\n for t in state['clear']:\n p = ['predicate', ]\n o = ['clear', ]\n o.append(t)\n p.append(tuple(o))\n conjunct.append(tuple(p))\n\n if state['holding']:\n for t in state['holding']:\n p = ['predicate', ]\n o = ['holding', ]\n o.append(t)\n p.append(tuple(o))\n conjunct.append(tuple(p))\n\n if state['armEmpty']:\n p = ['predicate', ]\n o = ['armEmpty', ]\n p.append(tuple(o))\n conjunct.append(tuple(p))\n\n if state['on']:\n for t in state['on']:\n p = ['predicate', ]\n o = ['on', ]\n o.extend(t)\n p.append(tuple(o))\n conjunct.append(tuple(p))\n\n return tuple(['conjunct', conjunct])\n\n def conjunct_2_state(self, conjunct):\n state = {\n 'on': [],\n 'onTable': [],\n 'clear': [],\n 'holding': [],\n 'armEmpty': False\n }\n for c in conjunct[1]:\n a = c[1]\n if a[0] == 'on':\n state['on'].append(a[1:])\n elif a[0] == 'onTable':\n state['onTable'].append(a[1])\n elif a[0] == 'clear':\n state['clear'].append(a[1])\n elif a[0] == 'holding':\n state['holding'].append(a[1])\n elif a[0] == 'armEmpty':\n state['armEmpty'] = True\n return state\n\n\n def gsp_recursive(self, state, goal, openList): # return plan, new-state\n plan = []\n g_type = goal[0]\n self.counter += 1\n print('GOAL: ', goal)\n # print state\n if g_type == 'conjunct':\n predList = goal[1]\n ## print predList\n if not self.check_sovled(predList, state):\n plan1, state1 = [], state\n for p in predList:\n ## print p\n g = self.gsp_recursive(state1, p, openList)\n if g:\n plan1, state1 = g\n plan.extend(plan1)\n else:\n\n # # print goal\n self.counter -= 1\n\n return False\n\n if not self.check_sovled(predList, state1):\n change = True\n while change:\n for p in predList:\n if not self.is_in_state(p, state1):\n g = self.gsp_recursive(state1, p, openList)\n if g:\n plan1, state1 = g\n plan.extend(plan1)\n break # changed, start over\n else:\n # we need a better way to handle this.\n return False\n else:\n change = False\n # all solved, peace\n self.counter -= 1\n\n return plan, state1\n\n else: # if all are already solved\n self.counter -= 1\n\n return [], state\n\n else: # goal is a predicate\n if self.is_in_state(goal, state):\n self.counter -= 1\n\n return [], state\n elif goal in openList:\n self.counter -= 1\n\n return False\n else:\n openList.append(goal)\n actions = self.get_actions_for_predicate(goal)\n plan1, state1 = [], state\n\n for a in actions:\n name = a[1][0]\n args = a[1][1:]\n precondList = self.actionStore[name]['P']\n conjunct = self.generateConjunct(precondList, args)\n\n g = self.gsp_recursive(state1, conjunct, openList)\n if g:\n plan1, state1 = g\n plan1.append(a)\n self.counter -= 1\n rr = plan1, self.progress(state1, a)\n\n return rr\n else:\n continue\n else:\n self.counter -= 1\n return False\n\n\n# print(json.dumps(ss))\n# sys.exit()\n\nstartState = {\n 'on': [],\n 'onTable': ['A', 'B'],\n 'clear': ['A', 'B'],\n 'holding': [],\n 'armEmpty': True\n}\ngoalState = {\n 'on': [('B', 'A')],\n 'onTable': ['A'],\n 'clear': ['B'],\n 'holding': [],\n 'armEmpty': True\n}\n\nactionStore = {\n 'pickup': {\n 'P': [('onTable', '_0'), ('clear', '_0'), ('armEmpty',)],\n 'A': [('holding', '_0')],\n 'D': [('onTable', '_0'), ('armEmpty',)]\n },\n\n 'putDown': {\n 'P': [('holding', '_0')],\n 'A': [('onTable', '_0'), ('armEmpty',)],\n 'D': [('holding', '_0')]\n },\n\n 'unStack': {\n 'P': [('on', '_0', '_1'), ('clear', '_0'), ('armEmpty',)],\n 'A': [('holding', '_0'), ('clear', '_1')],\n 'D': [('on', '_0', '_1'), ('armEmpty',)]\n },\n 'stack': {\n 'P': [('holding', '_0'), ('clear', '_1')],\n 'A': [('on', '_0', '_1'), ('clear', '_0'), ('armEmpty',)],\n 'D': [('holding', '_0'), ('clear', '_1')]\n }\n}\n\n\n\ndef conjunct_2_state(conjunct):\n state = {\n 'on': [],\n 'onTable': [],\n 'clear': [],\n 'holding': [],\n 'armEmpty': False\n }\n for c in conjunct[1]:\n a = c[1]\n if a[0] == 'on':\n state['on'].append(a[1:])\n elif a[0] == 'onTable':\n state['onTable'].append(a[1])\n elif a[0] == 'clear':\n state['clear'].append(a[1])\n elif a[0] == 'holding':\n state['holding'].append(a[1])\n elif a[0] == 'armEmpty':\n state['armEmpty'] = True\n return state\n\n\nss = {\n 'on': [('B', 'A'), ],\n 'onTable': ['A', 'C', 'D'],\n 'clear': ['B', 'C', 'D'],\n 'holding': [],\n 'armEmpty': True\n}\n\ngg = {\n 'on': [('C', 'A'), ('B', 'D')],\n 'onTable': ['A', 'D'],\n 'clear': ['C', 'B'],\n 'holding': [],\n 'armEmpty': True\n}\nss = {\n 'on': [('B', 'A'),],\n 'onTable': ['A', 'C', 'D'],\n 'clear': ['B', 'C', 'D'],\n 'holding': [],\n 'armEmpty': True\n}\n\ngg = {\n 'on': [('C', 'A'),],\n 'onTable': ['A', 'D', 'B'],\n 'clear': ['A', 'B', 'D'],\n 'holding': [],\n 'armEmpty': True\n}\n\nss = {\n 'on': [('C', 'A'), ('A', 'B')],\n 'onTable': ['B'],\n 'clear': ['C'],\n 'holding': [],\n 'armEmpty': True\n}\n\ngg = {\n 'on': [],\n 'onTable': ['A', 'B', 'C', ],\n 'clear': ['A', 'B', 'C'],\n 'holding': [],\n 'armEmpty': True\n}\n\ngsp = GSP(startState=startState, goalState=goalState, actionStore=actionStore, ss=ss, gg=gg)\nplan, state = gsp.gsp_recursive(gsp.startState, gsp.goalState, [])\n# plan, state = gsp_recursive(s, g, [])\nstate = conjunct_2_state(state)\n\nprint('STATE', state)","sub_path":"task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":11584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"205809887","text":"from flask import Flask, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///email.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False \ndb = SQLAlchemy(app)\n\ndrop_table = 'DROP TABLE IF EXISTS users;'\nusers_table = \"\"\"\nCREATE TABLE users(\nusername VARCHAR NOT NULL PRIMARY KEY,\nemail VARCHAR);\n\"\"\"\ndata = \"\"\"\nINSERT INTO users\nVALUES\n (\"Buddy Rich\", \"buddy@clarusway.com\" ),\n (\"Candido\", \"candido@clarusway.com\"),\n (\"Charlie Byrd\", \"charlie.byrd@clarusway.com\");\n\"\"\"\ndb.session.execute(drop_table)\ndb.session.execute(users_table)\ndb.session.execute(data)\ndb.session.commit()\n\ndef find_emails(keyword):\n query = f'''\n SELECT * FROM users\n WHERE username LIKE '%{keyword}%';\n '''\n result = db.session.execute(query)\n user_emails = [(row[0], row[1]) for row in result]\n if not any(user_emails):\n user_emails = [('Not Found', 'Not Found')]\n return user_emails\n\ndef insert_email(name, email):\n query = f'''\n SELECT * FROM users\n WHERE username LIKE '{name}';\n '''\n result = db.session.execute(query)\n response = 'Error occured ...'\n\n if name == '' or email == '':\n response = 'Username or email cannot be empty!!!'\n elif not any(result):\n insert = f'''\n INSERT INTO users\n VALUES ('{name}', '{email}');\n '''\n result = db.session.execute(insert)\n db.session.commit()\n response = f'User {name} added successfully !'\n else:\n response = f'User {name} already exists !'\n return response\n\n@app.route('/', methods = ['GET', 'POST'])\ndef emails():\n if request.method == 'POST':\n user_name = request.form['username']\n user_emails = find_emails(user_name)\n return render_template('emails.html', name_emails = user_emails,\n keyword = user_name, show_result = True)\n else:\n return render_template('emails.html', show_result = False)\n\n@app.route('/add', methods = ['GET', 'POST'])\ndef add_email():\n if request.method == 'POST':\n user_name = request.form['username']\n user_email = request.form['useremail']\n result = insert_email(user_name, user_email)\n return render_template('add-email.html', result = result, show_result = True)\n else:\n return render_template('add-email.html', show_result = False)\n\nif __name__ == '__main__':\n app.run(debug = True)\n","sub_path":"flask-03-handling-forms-and-sql-on-ec2-linux2/app-with-sqlite.py","file_name":"app-with-sqlite.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"642176189","text":"\"\"\"\nThis is ninth task from Python Course - Basic (Day 13 of the course)\nDone by DirtySiwy12\n\nTask 9.5: Create an Asteroid game. Use provided code and add three things:\n - Create a score counter.\n - Create multiple meteors and make them reappear.\n - Load shooting and explosion sounds when needed.\n\"\"\"\n\nimport os\nimport random\nimport pygame\nfrom pygame.locals import *\n\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nDARK_BLUE = (0, 0, 128)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nPINK = (255, 200, 200)\nYELLOW = (255, 255, 0)\n\n\n# Creating classes for bullets and meteors\nclass Ghost:\n def __init__(self, g_x, g_y, image):\n self.g_x = g_x\n self.g_y = g_y\n self.image = image\n self.height = self.image.get_height()\n self.width = self.image.get_width()\n\n def draw(self, _screen):\n _screen.blit(self.image, (self.g_x, self.g_y))\n\n\nclass Bullets(Ghost):\n image = pygame.image.load(os.path.join('../images', 'shot.gif'))\n\n def __init__(self, g_x, g_y):\n super().__init__(g_x, g_y, Bullets.image)\n\n def collision(self, _sprite):\n if abs(self.g_x - _sprite.g_x) < self.width + _sprite.width:\n if abs(self.g_y - _sprite.g_y) < self.height + _sprite.height:\n return True\n\n return False\n\n\nclass Meteor(Ghost):\n image = pygame.image.load(os.path.join(\"../images\", \"asteroid.gif\"))\n\n def __init__(self, g_x, g_y, vel_x, vel_y):\n super().__init__(g_x, g_y, Meteor.image)\n self.vel_x = vel_x\n self.vel_y = vel_y\n\n\npygame.mixer.pre_init(44100, -16, 2, 512)\npygame.mixer.init()\npygame.init()\n\n# Setting up game\nclock = pygame.time.Clock()\nscreen = pygame.display.set_mode((640, 480), 0, 32)\npygame.display.set_caption('Asteroids')\nfont = pygame.font.SysFont('calibri', 40)\nbg = pygame.image.load(os.path.join(\"../images\", \"space.jpg\"))\nshot_sound = pygame.mixer.Sound(os.path.join('../sounds', 'shot.wav'))\nexplosion_sound = pygame.mixer.Sound(os.path.join('../sounds', 'explosion.wav'))\npygame.mouse.set_visible(0)\n\n# Load a ship\nship = pygame.image.load(os.path.join('../images', 'ship.gif'))\nship_top = screen.get_height() - ship.get_height()\nship_left = screen.get_width() / 2 - ship.get_width() / 2\nscreen.blit(ship, (ship_left, ship_top))\n\n# Helping variables\nbullets = []\nmeteors = []\nmeteor_control = 0\nscore = 0\nloop_end = False\n\n# Creating first meteor\nmeteor = Meteor(random.randint(10, 630), random.randint(10, 450), random.uniform(0.1, 1), random.uniform(0.1, 1))\nmeteors.append(meteor)\n\n# Game loop\nwhile not loop_end:\n\n # Ship location\n counter = clock.tick(60)\n screen.blit(bg, (0, 0))\n x, y = pygame.mouse.get_pos()\n screen.blit(ship, (x - ship.get_width() / 2, ship_top))\n\n # Creating next meteors\n meteor_control += counter\n if meteor_control > 1500 and len(meteors) <= 3:\n meteor = Meteor(random.randint(10, 630), random.randint(10, 450),\n random.uniform(0.1, 1), random.uniform(0.1, 1))\n meteors.append(meteor)\n meteor_control = 0\n\n # Printing score\n score_text = font.render('Score -', True, WHITE)\n score_count = font.render(str(score), True, WHITE)\n screen.blit(score_text, (10, 20))\n screen.blit(score_count, (110, 20))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n loop_end = True\n break\n\n elif event.type == KEYDOWN:\n if event.key == K_q:\n loop_end = True\n break\n\n # Firing\n elif event.type == MOUSEBUTTONDOWN:\n pygame.mixer.Sound.play(shot_sound)\n shot_y = 466\n shot_x = x\n bullets.append(Bullets(shot_x, shot_y))\n\n # Erasing objects out of screen\n objects_to_remove = []\n for bullet in bullets:\n if bullet.g_y > 0:\n bullet.g_y -= 10\n else:\n objects_to_remove.append(bullet)\n\n for meteor in meteors:\n if meteor.g_x < 640 and meteor.g_y > 0:\n meteor.g_x += meteor.vel_x\n meteor.g_y -= meteor.vel_y\n else:\n objects_to_remove.append(meteor)\n\n for bullet in bullets:\n for meteor in meteors:\n if bullet.collision(meteor):\n pygame.mixer.Sound.play(explosion_sound)\n objects_to_remove.append(bullet)\n objects_to_remove.append(meteor)\n score += 1\n\n if len(objects_to_remove) > 0:\n for element in objects_to_remove:\n if element in bullets:\n bullets.remove(element)\n elif element in meteors:\n meteors.remove(element)\n\n for bullet in bullets:\n bullet.draw(screen)\n\n for meteor in meteors:\n meteor.draw(screen)\n\n pygame.display.update()\n\npygame.quit()\n","sub_path":"Task_09_Games/Game_05_Asteroids/Asteroids.py","file_name":"Asteroids.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494603183","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 16 14:41:09 2019\r\n\r\n@author: Zhong.Lianzhen\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nimport os\r\nimport logging\r\nimport scipy.io\r\nimport SimpleITK as sitk\r\nimport pandas as pd\r\nimport radiomics\r\nfrom radiomics import featureextractor\r\n\r\nInput_dir = r'I:\\research\\ICT-NPC\\all_postprocessing_data'\r\nOutput_dir = r'I:\\research\\ICT-NPC\\Pyradiomics-feature_LL'\r\nif not os.path.exists(Output_dir):\r\n os.mkdir(Output_dir)\r\nsequence_spacing = {\r\n 'DWI': [1.2,1.2],\r\n 'data1': [0.5,0.5],\r\n 'data1c': [0.5,0.5],\r\n 'data2': [0.5,0.5]}\r\nxlsx_path = os.path.join(Output_dir,'DWI_feature.csv')\r\nxlsx_path1 = os.path.join(Output_dir,'T1_feature.csv')\r\nxlsx_path2 = os.path.join(Output_dir,'T2_feature.csv')\r\nxlsx_path3 = os.path.join(Output_dir,'T1C_feature.csv')\r\n\r\nparams = r'E:\\Spyder_file\\experiment_test\\radiomics\\example_MR_for_wavelet_LL.yaml'\r\n\r\ndef extract_feature(sub_dir2,sequence,name,extractor):\r\n data1 = scipy.io.loadmat(sub_dir2)\r\n data1 = data1[sequence]\r\n v_o = data1['v_o']\r\n v_o = v_o[0][0]\r\n# import pdb; pdb.set_trace()\r\n v_s = data1['v_s']\r\n v_s = v_s[0][0][0][0]\r\n v_o = v_o.transpose((2,1,0))\r\n v_s = v_s.transpose((2,1,0))\r\n # plt.imshow(v_o1[0,:,:], cmap=plt.cm.bone) #plt.cm.bone\r\n # plt.show()\r\n# import pdb;pdb.set_trace()\r\n z_spacing = float(data1['SliceThickness'][0][0][0])\r\n spacing = list(sequence_spacing[sequence])\r\n# import pdb; pdb.set_trace()\r\n spacing.append(z_spacing)\r\n spacing = tuple(spacing)\r\n img = sitk.GetImageFromArray(v_o)\r\n img_mask = sitk.GetImageFromArray(v_s)\r\n #set PixelSapcing (1.0,1.0,1.0)\r\n img.SetSpacing(spacing)\r\n img_mask.SetSpacing(spacing)\r\n featureVector = extractor.execute(img, img_mask)\r\n aFeature = pd.Series(featureVector)\r\n aFeature = aFeature.to_frame()\r\n aFeature.columns = [name]\r\n \r\n return aFeature\r\n \r\ndef main():\r\n \r\n extractor = featureextractor.RadiomicsFeatureExtractor(params)\r\n \r\n # Get the PyRadiomics logger (default log-level = INFO)\r\n logger = radiomics.logger\r\n logger.setLevel(logging.DEBUG) # set level to DEBUG to include debug log messages in log file\r\n \r\n # Set up the handler to write out all log entries to a file\r\n handler = logging.FileHandler(filename=os.path.join(Output_dir,'testLog.txt'), mode='w')\r\n formatter = logging.Formatter(\"%(levelname)s:%(name)s: %(message)s\")\r\n handler.setFormatter(formatter)\r\n logger.addHandler(handler)\r\n \r\n start_row = 1\r\n go_row = 1\r\n batch = 100\r\n featureVector1 = pd.DataFrame()\r\n featureVector2 = pd.DataFrame()\r\n featureVector3 = pd.DataFrame()\r\n featureVector4 = pd.DataFrame()\r\n sub_dirs = os.listdir(Input_dir)\r\n num_file = len(sub_dirs)\r\n for sub_dir in sub_dirs:\r\n if start_row < go_row:\r\n start_row += 1\r\n continue\r\n name = sub_dir\r\n print('#####################')\r\n print('Read %d-th file_ID: %s' % (start_row,name))\r\n sub_dir1 = os.path.join(Input_dir,sub_dir)\r\n sub_dirs_2 = os.listdir(sub_dir1)\r\n for sub_dir2 in sub_dirs_2:\r\n sequence = sub_dir2[:-4]\r\n sub_dir2 = os.path.join(sub_dir1,sub_dir2)\r\n result = extract_feature(sub_dir2,sequence,name,extractor)\r\n if sequence == 'DWI':\r\n featureVector1 = featureVector1.append(result.T)\r\n if ((start_row % batch) == 0) or (start_row == num_file):\r\n div = start_row // batch\r\n if div == 1:\r\n featureVector1.to_csv(path_or_buf = xlsx_path,encoding='utf-8',index = True,header = True)\r\n print('Read DWI')\r\n featureVector1 = pd.DataFrame()\r\n else:\r\n featureVector1.to_csv(path_or_buf = xlsx_path,encoding='utf-8',index = True,header = False,mode = 'a')\r\n print('Read DWI')\r\n featureVector1 = pd.DataFrame()\r\n \r\n if sequence == 'data1':\r\n featureVector2 = featureVector2.append(result.T)#不能写featureVector2.append(result.T)\r\n if ((start_row % batch) == 0) or (start_row == num_file):\r\n div = start_row // batch\r\n if div == 1:\r\n featureVector2.to_csv(path_or_buf = xlsx_path1,encoding='utf-8',index = True,header = True)\r\n print('Read data1')\r\n featureVector2 = pd.DataFrame()\r\n else:\r\n featureVector2.to_csv(path_or_buf = xlsx_path1,encoding='utf-8',index = True,header = False,mode = 'a')\r\n print('Read data1')\r\n featureVector2 = pd.DataFrame()\r\n if sequence == 'data1c':\r\n featureVector3 = featureVector3.append(result.T)\r\n if ((start_row % batch) == 0) or (start_row == num_file):\r\n div = start_row // batch\r\n if div == 1:\r\n featureVector3.to_csv(path_or_buf = xlsx_path2,encoding='utf-8',index = True,header = True)\r\n print('Read data1c')\r\n featureVector3 = pd.DataFrame()\r\n else:\r\n featureVector3.to_csv(path_or_buf = xlsx_path2,encoding='utf-8',index = True,header = False,mode = 'a')\r\n print('Read data1c')\r\n featureVector3 = pd.DataFrame()\r\n if sequence == 'data2':\r\n featureVector4 = featureVector4.append(result.T)\r\n if ((start_row % batch) == 0) or (start_row == num_file):\r\n div = start_row // batch\r\n if div == 1:\r\n featureVector4.to_csv(path_or_buf = xlsx_path3,encoding='utf-8',index = True,header = True)\r\n print('Read data2')\r\n featureVector4 = pd.DataFrame()\r\n else:\r\n featureVector4.to_csv(path_or_buf = xlsx_path3,encoding='utf-8',index = True,header = False,mode = 'a')\r\n print('Read data2')\r\n featureVector4 = pd.DataFrame()\r\n start_row += 1\r\n \r\n logger.removeHandler(handler)\r\n handler.close()\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"naso_cancer/_ref/main_featureExtractor1.py","file_name":"main_featureExtractor1.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"134387652","text":"# Copyright 2015 Mirantis, Inc.\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\nimport logging\nimport six\nimport time\n\nfrom oslo_messaging._drivers.zmq_driver.client.publishers.dealer \\\n import zmq_dealer_call_publisher\nfrom oslo_messaging._drivers.zmq_driver.client.publishers.dealer \\\n import zmq_reply_waiter\nfrom oslo_messaging._drivers.zmq_driver.client.publishers \\\n import zmq_publisher_base\nfrom oslo_messaging._drivers.zmq_driver import zmq_address\nfrom oslo_messaging._drivers.zmq_driver import zmq_async\nfrom oslo_messaging._drivers.zmq_driver import zmq_names\n\nzmq = zmq_async.import_zmq()\n\nLOG = logging.getLogger(__name__)\n\n\nclass DealerPublisherProxy(object):\n \"\"\"Used when publishing to a proxy. \"\"\"\n\n def __init__(self, conf, matchmaker, socket_to_proxy):\n self.sockets_manager = zmq_publisher_base.SocketsManager(\n conf, matchmaker, zmq.ROUTER, zmq.DEALER)\n self.socket = socket_to_proxy\n self.routing_table = RoutingTable(conf, matchmaker)\n\n def send_request(self, request):\n if request.msg_type == zmq_names.CALL_TYPE:\n raise zmq_publisher_base.UnsupportedSendPattern(\n request.msg_type)\n\n routing_key = self.routing_table.get_routable_host(request.target) \\\n if request.msg_type in zmq_names.DIRECT_TYPES else \\\n zmq_address.target_to_subscribe_filter(request.target)\n\n self.socket.send(b'', zmq.SNDMORE)\n self.socket.send(six.b(str(request.msg_type)), zmq.SNDMORE)\n self.socket.send(six.b(routing_key), zmq.SNDMORE)\n self.socket.send(six.b(request.message_id), zmq.SNDMORE)\n self.socket.send_pyobj(request.context, zmq.SNDMORE)\n self.socket.send_pyobj(request.message)\n\n LOG.debug(\"->[proxy:%(addr)s] Sending message_id %(message)s to \"\n \"a target %(target)s\",\n {\"message\": request.message_id,\n \"target\": request.target,\n \"addr\": list(self.socket.connections)})\n\n def cleanup(self):\n self.socket.close()\n\n\nclass DealerCallPublisherProxy(zmq_dealer_call_publisher.DealerCallPublisher):\n\n def __init__(self, conf, matchmaker, sockets_manager):\n reply_waiter = ReplyWaiterProxy(conf)\n sender = CallSenderProxy(conf, matchmaker, sockets_manager,\n reply_waiter)\n super(DealerCallPublisherProxy, self).__init__(\n conf, matchmaker, sockets_manager, sender, reply_waiter)\n\n\nclass CallSenderProxy(zmq_dealer_call_publisher.CallSender):\n\n def __init__(self, conf, matchmaker, sockets_manager, reply_waiter):\n super(CallSenderProxy, self).__init__(\n sockets_manager, reply_waiter)\n self.socket = self.outbound_sockets.get_socket_to_publishers()\n self.reply_waiter.poll_socket(self.socket)\n self.routing_table = RoutingTable(conf, matchmaker)\n\n def _connect_socket(self, target):\n return self.socket\n\n def _do_send_request(self, socket, request):\n routing_key = self.routing_table.get_routable_host(request.target)\n\n # DEALER socket specific envelope empty delimiter\n socket.send(b'', zmq.SNDMORE)\n socket.send(six.b(str(request.msg_type)), zmq.SNDMORE)\n socket.send(six.b(routing_key), zmq.SNDMORE)\n socket.send(six.b(request.message_id), zmq.SNDMORE)\n socket.send_pyobj(request.context, zmq.SNDMORE)\n socket.send_pyobj(request.message)\n\n LOG.debug(\"Sent message_id %(message)s to a target %(target)s\",\n {\"message\": request.message_id,\n \"target\": request.target})\n\n\nclass ReplyWaiterProxy(zmq_reply_waiter.ReplyWaiter):\n\n def receive_method(self, socket):\n empty = socket.recv()\n assert empty == b'', \"Empty expected!\"\n reply_id = socket.recv()\n assert reply_id is not None, \"Reply ID expected!\"\n message_type = int(socket.recv())\n assert message_type == zmq_names.REPLY_TYPE, \"Reply is expected!\"\n message_id = socket.recv()\n reply = socket.recv_pyobj()\n LOG.debug(\"Received reply %s\", message_id)\n return reply\n\n\nclass RoutingTable(object):\n \"\"\"This class implements local routing-table cache\n taken from matchmaker. Its purpose is to give the next routable\n host id (remote DEALER's id) by request for specific target in\n round-robin fashion.\n \"\"\"\n\n def __init__(self, conf, matchmaker):\n self.conf = conf\n self.matchmaker = matchmaker\n self.routing_table = {}\n self.routable_hosts = {}\n\n def get_routable_host(self, target):\n self._update_routing_table(target)\n hosts_for_target = self.routable_hosts[str(target)]\n host = hosts_for_target.pop(0)\n if not hosts_for_target:\n self._renew_routable_hosts(target)\n return host\n\n def _is_tm_expired(self, tm):\n return 0 <= self.conf.zmq_target_expire <= time.time() - tm\n\n def _update_routing_table(self, target):\n routing_record = self.routing_table.get(str(target))\n if routing_record is None:\n self._fetch_hosts(target)\n self._renew_routable_hosts(target)\n elif self._is_tm_expired(routing_record[1]):\n self._fetch_hosts(target)\n\n def _fetch_hosts(self, target):\n self.routing_table[str(target)] = (self.matchmaker.get_hosts(\n target, zmq_names.socket_type_str(zmq.DEALER)), time.time())\n\n def _renew_routable_hosts(self, target):\n hosts, _ = self.routing_table[str(target)]\n self.routable_hosts[str(target)] = list(hosts)\n","sub_path":"oslo_messaging/_drivers/zmq_driver/client/publishers/dealer/zmq_dealer_publisher_proxy.py","file_name":"zmq_dealer_publisher_proxy.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346446423","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import find_peaks\nfrom scipy.io import wavfile\n\n# recording/logging duration (in seconds)\n# This number can be found from the Crimson_thresing_test.py file\nt = 40\n\n# load data\nax = np.genfromtxt(\"ax.csv\", delimiter=\",\")\nay = np.genfromtxt(\"ay.csv\", delimiter=\",\")\naz = np.genfromtxt(\"az.csv\", delimiter=\",\")\n\nfs, y = wavfile.read(\"output.wav\")\n\n# width= , distance=20, prominence= , threshold=\npeaks_ax, _ = find_peaks(ax, prominence=0.75)\npeaks_ay, _ = find_peaks(ay, prominence=0.75)\npeaks_az, _ = find_peaks(az, prominence=0.75)\npeaks_mic, _ = find_peaks(y, height=2, distance=2000)\n\n# plotting\nfig = plt.figure()\n\nax1 = fig.add_subplot(4, 1, 1)\n\nax1.set(xticks=(np.arange(0, len(ax), len(ax) / t)), ylabel=\"Ax\")\nax1.set_xticklabels(np.arange(0, t, 1))\n\nax2 = fig.add_subplot(4, 1, 2, sharex=ax1)\nax2.set(ylabel=\"Ay\")\n\nax3 = fig.add_subplot(4, 1, 3, sharex=ax1)\nax3.set(ylabel=\"Az\")\n\nax4 = fig.add_subplot(4, 1, 4)\nax4.set(xticks=(np.arange(0, len(y), len(y) / t)), ylabel=\"MIC\")\nax4.set_xticklabels(np.arange(0, t, 1))\n\nax1.plot(peaks_ax, ax[peaks_ax], \"xr\")\nax1.plot(ax)\nax2.plot(peaks_ay, ay[peaks_ay], \"xr\")\nax2.plot(ay)\nax3.plot(peaks_az, az[peaks_az], \"xr\")\nax3.plot(az)\nax4.plot(peaks_mic, y[peaks_mic], \"xr\")\nax4.plot(y)\n\n# print(peaks_ax)\n# print(peaks_ay)\n# print(peaks_az)\n# print(peaks_mic)\n\n# convert peak values from sample number to time\nevents_ax = (peaks_ax) * t / len(ax)\n# print(events_ax)\nevents_ay = (peaks_ay) * t / len(ay)\n# print(events_ay)\nevents_az = (peaks_az) * t / len(az)\n# print(events_az)\nevents_mic = peaks_mic * t / len(y)\n# print(events_mic)\n\n# show plot\nplt.show()\n\n# ------------------------------------#\n# signal preprocessing:\n# algo to determine if it's an action:\n\n# STEP 1:\n# In each signal average out cluster of peaks:\n# Assumption 1: sensor and microphone data for each drilling motion is close to a normal distribution,\n# the center of the motion should be close to the average value of x-coordinates\n# Therefore, to find the center we can calculate the average x-coordinate of a cluster of peaks\n# Assumption 2: there's at least 1 second in between two drilling actions\n\n# do it for ax\npeak_counter = 1\navg_peaks = events_ax[0]\navg_peaks_ax = []\n\nfor i in range(1, len(events_ax)):\n # if two consecutive peaks are less than a second apart, add them up and increase the peak counter\n if (events_ax[i] - events_ax[i - 1]) <= 1:\n avg_peaks = avg_peaks + events_ax[i]\n peak_counter = peak_counter + 1\n\n # if the gap between two consecutive peaks is larger than 1s or the list of peaks is finished, log the average value of the group of peaks\n if ((events_ax[i] - events_ax[i - 1]) > 1) or (i == (len(events_ax) - 1)):\n # average the average peaks (yea I know it sounds redundant)\n avg_peaks = avg_peaks / peak_counter\n # add the averaged value to the ax valid peaks list\n avg_peaks_ax.append(avg_peaks)\n # put back the first non successive peak into the peak average value\n avg_peaks = events_ax[i]\n # reset peak counter\n peak_counter = 1\n\nprint(avg_peaks_ax)\n\n# do it for ay\navg_peaks = events_ay[0]\navg_peaks_ay = []\n\nfor i in range(1, len(events_ay)):\n # if two consecutive peaks are less than a second apart, add them up and increase the peak counter\n if (events_ay[i] - events_ay[i - 1]) <= 1:\n avg_peaks = avg_peaks + events_ay[i]\n peak_counter = peak_counter + 1\n\n # if the gap between two consecutive peaks is larger than 1s or the list of peaks is finished, log the average value of the group of peaks\n if ((events_ay[i] - events_ay[i - 1]) > 1) or (i == (len(events_ay) - 1)):\n # average the average peaks (yea I know it sounds redundant)\n avg_peaks = avg_peaks / peak_counter\n # add the averaged value to the ax valid peaks list\n avg_peaks_ay.append(avg_peaks)\n # put back the first non successive peak into the peak average value\n avg_peaks = events_ay[i]\n # reset peak counter\n peak_counter = 1\n\nprint(avg_peaks_ay)\n\n# do it for az\npeak_counter = 1\navg_peaks = events_az[0]\navg_peaks_az = []\n\nfor i in range(1, len(events_az)):\n # if two consecutive peaks are less than half a second apart, add them up and increase the peak counter\n if (events_az[i] - events_az[i - 1]) <= 1:\n avg_peaks = avg_peaks + events_az[i]\n peak_counter = peak_counter + 1\n\n # if the gap between two consecutive peaks is larger than 1s or the list of peaks is finished, log the average value of the group of peaks\n if ((events_az[i] - events_az[i - 1]) > 1) or (i == (len(events_az) - 1)):\n # average the average peaks (yea I know it sounds redundant)\n avg_peaks = avg_peaks / peak_counter\n # add the averaged value to the ax valid peaks list\n avg_peaks_az.append(avg_peaks)\n # put back the first non successive peak into the peak average value\n avg_peaks = events_az[i]\n # reset peak counter\n peak_counter = 1\n\nprint(avg_peaks_az)\n\n# do it for microphone\npeak_counter = 1\navg_peaks = events_mic[0]\navg_peaks_mic = []\n\nfor i in range(1, len(events_mic)):\n # if two consecutive peaks are less than a half a second apart, add them up and increase the peak counter\n if (events_mic[i] - events_mic[i - 1]) <= 0.5:\n avg_peaks = avg_peaks + events_mic[i]\n peak_counter = peak_counter + 1\n\n # if the gap between two consecutive peaks is larger than 1s or the list of peaks is finished, log the average value of the group of peaks\n if ((events_mic[i] - events_mic[i - 1]) > 0.5) or (i == (len(events_mic) - 1)):\n # average the average peaks (yea I know it sounds redundant)\n avg_peaks = avg_peaks / peak_counter\n # add the averaged value to the ax valid peaks list\n avg_peaks_mic.append(avg_peaks)\n # put back the first non successive peak into the peak average value\n avg_peaks = events_mic[i]\n # reset peak counter\n peak_counter = 1\n\nprint(avg_peaks_mic)\n\n# STEP 2: eliminate false positives from accelerometer data.\n# Assuming the worker doesn't move much between two overhead drilling actions, accelerometer peaks\n# represent the vibration from the drill/tool: all axes of the accelerometer should detect some vibration\n# To eliminate noise peaks from the averaging phase in step 1, we only consider an average peak valid if\n# it is detected by at least 2 sensors.\n# we consider average peaks within 0.5s of each other to belong to the same motion\n\n# container for the loop\nvalid_peaks = []\navg_selected = 0\nd1 = 0\nd2 = 0\n\nfor i in range(len(avg_peaks_ax)):\n for j in range(len(avg_peaks_ay)):\n d1 = 0\n d = avg_peaks_ax[i] - avg_peaks_ay[j]\n if abs(d) <= 0.5:\n d1 = 1\n for k in range(len(avg_peaks_az)):\n d2 = 0\n # compare elements in peaks set\n e = avg_peaks_ax[i] - avg_peaks_az[k]\n # the peaks are considered to belong to the same action if they are less than half a second apart\n if (abs(e) <= 0.5) or (abs(d - e) <= 0.5):\n d2 = 1\n if (d1 == 1) and (d2 == 1):\n avg_selected = (avg_peaks_ax[i] + avg_peaks_ay[j] + avg_peaks_az[k]) / 3\n # add this value to a list of validated peaks\n valid_peaks.append(avg_selected)\n\nprint(valid_peaks)\n\n# STEP 3:\n# Compare accelerometer peaks to microphone peaks\n# one action should have matching microphone and accelerometer peaks\n# Assumption: peaks are considered matching if they are within half a second from each other\nx = 0\nactions_count = 0\n\nfor i in range(len(valid_peaks)):\n for j in range(len(avg_peaks_mic)):\n x = abs(valid_peaks[i] - avg_peaks_mic[j])\n if x <= 0.5:\n actions_count = actions_count + 1\n\nprint(\"Number of tasks completed: \", actions_count)\n\n","sub_path":"REV1 - IMU BREAKOUT/Crimson_action_count.py","file_name":"Crimson_action_count.py","file_ext":"py","file_size_in_byte":7928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"277800424","text":"#2 player Resource Simulation Game\n\n#Definiton of interaction pf 2 players\n\nclass Game(): \n\tdef __init__(self):\n\t\tself.strategies=['fight','coop']\n\t\tself.traits=['strength','discount','humanity','consumption_cost']\n\t\t#['fight','coop']\n\n\tdef __fighting_chance(strength1, strength2):\n\t\treturn pow(strength1,2)/(pow(strength1,2)+pow(strength2,2))\n\n\tdef payoff(my_strategy, opp_strategy, resource_value):\n\t\t(strategy_vec1,strength1,discount1)=my_strategy\n\t\t(strategy_vec2,strength2,discount2)=opp_strategy\n\n\t\tif strategy_vec1==[0,1]: # If my_strategy is to coop\n\t\t\tif strategy_vec2==[0,1]:\n\t\t\t\treturn resource_value*discount1/2\n\t\t\telse: \n\t\t\t\treturn 0\n\t\t\t#return resource_value*strategy_vec2[1]*discount1/2 #return d/2 only if opp_strategy== coop\n\n\t\telif strategy_vec1==[1,0]: # If my_strategy is to fight\n\t\t\tif strategy_vec2 == [1,0]: # opponent is also 'fight'\n\t\t\t\treturn resource_value*Game.__fighting_chance(strength1,strength2)*discount1\n\t\t\telif strategy_vec2 == [0,1]: # opponent is 'coop'\n\t\t\t\treturn resource_value*discount1\n","sub_path":"Resource Game/v1.1/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"64240941","text":"# encoding:utf-8\r\nimport json\r\n\r\n\r\ndef find_bfs(city, src_station, dst_station, rejected_system=[], only_one_line=False):\r\n data = load_data(city, \"Stations\")\r\n\r\n graph = {}\r\n for station in data:\r\n graph[station] = set()\r\n neighbors = data[station][\"neighbors\"]\r\n for key in neighbors:\r\n if only_one_line is False:\r\n flag = True\r\n if neighbors[key][\"type\"] in rejected_system:\r\n flag = False\r\n if data[key][\"system\"] in rejected_system:\r\n flag = False\r\n if flag is True:\r\n graph[station].add(key)\r\n elif station.split(\"_\")[0] == key.split(\"_\")[0]:\r\n graph[station].add(key)\r\n\r\n visited_station = []\r\n path_length = []\r\n queue = [(src_station, [src_station], 1)]\r\n while queue:\r\n vertex, path, length = queue.pop(0)\r\n if vertex == dst_station:\r\n yield path\r\n elif vertex not in visited_station:\r\n visited_station.append(vertex)\r\n path_length.append(length)\r\n elif path_length[visited_station.index(vertex)] < length:\r\n continue\r\n queue += [\r\n (candidate, path + [candidate], length + 1)\r\n for candidate in graph[vertex] - set(visited_station)\r\n ]\r\n\r\n\r\ndef load_data(city, key=\"all\"):\r\n with open(\"MetroData/data/{0}.json\".format(city), encoding=\"utf-8\") as w:\r\n k = json.load(w)\r\n if key == \"all\":\r\n return k\r\n else:\r\n return k[key]\r\n return None\r\n\r\n\r\ndef generate_ids(city, station_name, lang=\"zh\", rejected_system=[]):\r\n data = load_data(city, \"Stations\")\r\n return set(\r\n [\r\n station\r\n for station in data\r\n if data[station][\"name\"][lang] == station_name\r\n and data[station][\"system\"] not in rejected_system\r\n ]\r\n )\r\n\r\n\r\ndef get_name_from_id(city, station_id, lang=\"zh\"):\r\n return load_data(city, \"Stations\")[station_id][\"name\"][lang]\r\n\r\n\r\ndef add_route_info(city, route):\r\n data = load_data(city, \"Stations\")\r\n directs = []\r\n i = 1\r\n while i < len(route):\r\n src, dst = route[i - 1], route[i]\r\n connection = data[src][\"neighbors\"][dst]\r\n if connection[\"type\"] == \"train\":\r\n line = connection[\"line\"]\r\n direction = connection[\"direction\"]\r\n else:\r\n line = connection[\"type\"]\r\n direction = dst\r\n directs.append([line, direction, 1])\r\n i += 1\r\n return directs\r\n\r\n\r\ndef handle_routes(city, routes):\r\n c = []\r\n for route in routes:\r\n directs = add_route_info(city, route)\r\n i = 1\r\n while i < len(directs):\r\n if directs[i][0:2] == directs[i - 1][0:2]:\r\n route.pop(i)\r\n directs.pop(i)\r\n directs[i - 1][2] += 1\r\n else:\r\n i += 1\r\n x = [1] * (len(route) + len(directs))\r\n for i in range(len(route)):\r\n x[2 * i] = [route[i], \"\"]\r\n for i in range(len(directs)):\r\n x[2 * i + 1] = directs[i]\r\n x[0][1] = \"src\"\r\n x[-1][1] = \"dst\"\r\n\r\n i = 0\r\n while 2 * i + 2 < len(x):\r\n name_a = get_name_from_id(city, x[2 * i][0])\r\n name_b = get_name_from_id(city, x[2 * i + 2][0])\r\n if x[2 * i + 1][0] == \"walk-in\" and name_a == name_b:\r\n x.pop(2 * i + 1)\r\n x.pop(2 * i + 1)\r\n else:\r\n if x[2 * i + 1][0] in set([\"walk-out\", \"walk-transfer\"]):\r\n x[2 * i][1] = \"dst\" if 2 * i != 0 else \"\"\r\n x[2 * i + 2][1] = \"src\" if 2 * i + 2 != len(x) - 1 else \"\"\r\n i += 1\r\n c.append(x)\r\n c.sort(key=len)\r\n return c\r\n\r\n\r\ndef search(city, src_station, dst_station, lang=\"zh\", rejected_system=[]):\r\n src_list = generate_ids(city, src_station, lang, rejected_system)\r\n dst_list = generate_ids(city, dst_station, lang, rejected_system)\r\n routes = []\r\n for src_id in src_list:\r\n for dst_id in dst_list:\r\n routes += list(find_bfs(city, src_id, dst_id, rejected_system))\r\n if len(routes) == 0:\r\n return []\r\n else:\r\n min_length = min(map(len, routes))\r\n routes = [i for i in routes if len(i) == min_length]\r\n return handle_routes(city, routes)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n city = \"上海\"\r\n stations = [\r\n \"富锦路\",\r\n \"徐泾东\",\r\n \"浦东国际机场\",\r\n \"江杨北路\",\r\n \"奉贤新城\",\r\n \"闵行开发区\",\r\n \"港城路\",\r\n \"美兰湖\",\r\n \"花木路\",\r\n \"市光路\",\r\n \"松江南站\",\r\n \"曹路\",\r\n \"新江湾城\",\r\n \"航中路\",\r\n \"嘉定北\",\r\n \"迪士尼\",\r\n \"花桥\",\r\n \"七莘路\",\r\n \"金运路\",\r\n \"张江路\",\r\n \"滴水湖\",\r\n \"东方绿舟\",\r\n \"汇臻路\",\r\n ]\r\n p = load_data(city)\r\n for i in range(len(stations)):\r\n for j in range(i + 1, len(stations)):\r\n s = search(\"上海\", stations[i], stations[j], \"zh\", [\"磁悬浮\"])\r\n for route in s:\r\n u = []\r\n for step in route:\r\n if len(step) == 2:\r\n u.append(p[\"Stations\"][step[0]][\"name\"][\"zh\"])\r\n elif len(step) == 3:\r\n if step[0] == \"walk-out\":\r\n pass\r\n else:\r\n if step[1] == \"cw\":\r\n u.append(p[\"Lines\"][step[0]][\"name\"][\"zh\"] + \"顺时针\")\r\n elif step[1] == \"ccw\":\r\n u.append(p[\"Lines\"][step[0]][\"name\"][\"zh\"] + \"逆时针\")\r\n else:\r\n u.append(\r\n p[\"Lines\"][step[0]][\"name\"][\"zh\"]\r\n + p[\"Stations\"][step[1]][\"name\"][\"zh\"]\r\n )\r\n print(\"->\".join(u))\r\n # print(p[\"Lines\"])\r\n # break\r\n # break\r\n","sub_path":"MetroRouteFinder/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"78652667","text":"\"\"\"\n nbttreewidget\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport logging\n\nfrom PySide import QtGui\nfrom PySide.QtCore import Qt\n\nfrom mcedit2.widgets.nbttree.nbttreemodel import NBTFilterProxyModel\nfrom mcedit2.util.load_ui import registerCustomWidget\nfrom mcedit2.widgets.layout import Row\n\n\nlog = logging.getLogger(__name__)\n\n@registerCustomWidget\nclass NBTTreeView(QtGui.QWidget):\n def __init__(self, *args, **kwargs):\n super(NBTTreeView, self).__init__(*args, **kwargs)\n self.treeView = QtGui.QTreeView()\n self.setLayout(Row(self.treeView))\n\n def setModel(self, model):\n self.model = model\n\n proxyModel = NBTFilterProxyModel(self)\n proxyModel.setSourceModel(model)\n proxyModel.setDynamicSortFilter(True)\n\n self.treeView.setModel(model)\n\n self.treeView.sortByColumn(0, Qt.AscendingOrder)\n self.treeView.expandToDepth(0)\n self.treeView.resizeColumnToContents(0)\n self.treeView.resizeColumnToContents(1)\n","sub_path":"src/mcedit2/widgets/nbttree/nbttreeview.py","file_name":"nbttreeview.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115936868","text":"import json\nimport urllib3\n\nfrom flask import Flask, request, make_response, jsonify\n\nhttpgetter = urllib3.PoolManager()\napp = Flask(__name__)\nlog = app.logger\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef webhook():\n req = request.get_json()\n try:\n action = req.get('queryResult').get('action')\n except AttributeError:\n return \"wrong json\"\n \n if action == 'joke.get':\n res = joke()\n #res = ''\n else:\n res = \"action not found\"\n return make_response(jsonify({'fulfillmentText': res}))\n\n\ndef joke():\n baseurl = \"http://api.icndb.com/jokes/random\"\n result = httpgetter.request('GET', baseurl).data\n data = json.loads(result)\n joke = data.get('value').get('joke')\n return joke\n\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471578432","text":"from PIL import Image, ImageDraw, ImageFont\nimport sys\n\nif __name__ == \"__main__\":\n fileNames = sys.argv[1:]\n count = len(sys.argv)\n for name in fileNames:\n img = Image.open(name).convert(\"RGBA\")\n\n nsize = (int(img.size[0] * 0.4),int(img.size[1] * 0.4))\n img = img.resize(nsize,Image.BILINEAR)\n\n text = \"YSLucida\"\n txtImage = Image.new(\"RGBA\",nsize,(0,0,0,0))\n fnt = ImageFont.truetype(\"C:\\Windows\\Fonts\\msyhbd.ttc\",100)\n d = ImageDraw.Draw(txtImage)\n size = txtImage.size\n d.text((size[0] - 400,size[1] - 150),text,(255,255,255,100),fnt)\n\n out = Image.alpha_composite(img,txtImage)\n out.convert(\"RGB\").save(name + \"_wm.jpg\")\n #layer = img.convert('RGBA')\n","sub_path":"src/bicow/video/wm.py","file_name":"wm.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470205757","text":"import numpy as np\nfrom astropy.io import fits\nfrom scipy.interpolate import interp1d\nimport time\n\nfrom . import utils, read_files, bias, convert, RSD, DLA, independent, absorber, absorber_data, stats\n\nlya = utils.lya_rest\n\n#Function to create a SimulationData object given a specific pixel, information about the complete simulation, and the filenames.\ndef make_gaussian_pixel_object(pixel,base_filename,input_format,MOCKID_lookup,lambda_min=0,IVAR_cutoff=lya):\n\n #Determine which file numbers we need to look at for the current pixel.\n relevant_keys = [key for key in MOCKID_lookup.keys() if key[1]==pixel]\n files_included = 0\n\n #For each relevant file, extract the data and aggregate over all files into a 'combined' object.\n for key in relevant_keys:\n #Get the MOCKIDs of the relevant quasars: those that are located in the current pixel, stored in the current file.\n file_number = key[0]\n relevant_MOCKIDs = MOCKID_lookup[key]\n N_relevant_qso = len(relevant_MOCKIDs)\n\n #If there are some relevant quasars, open the data file and make it into a SimulationData object.\n #We use SimulationData.get_reduced_data to avoid loading all of the file's data into the object.\n if N_relevant_qso > 0:\n filename = base_filename+'{}.fits'.format(file_number)\n working = SimulationData.get_gaussian_skewers_object(filename,file_number,input_format,MOCKIDs=relevant_MOCKIDs,lambda_min=lambda_min,IVAR_cutoff=IVAR_cutoff)\n\n #Combine the data from the working file with that from the files already looked at.\n if files_included > 0:\n combined = SimulationData.combine_files(combined,working,gaussian_only=True)\n files_included += 1\n else:\n combined = working\n files_included += 1\n\n pixel_object = combined\n\n return pixel_object\n\n#Definition of a generic SimulationData class, from which it is easy to save in new formats.\nclass SimulationData:\n #Initialisation function.\n def __init__(self,N_qso,N_cells,SIGMA_G,TYPE,RA,DEC,Z_QSO,DZ_RSD,MOCKID,PLATE,MJD,FIBER,GAUSSIAN_DELTA_rows,DENSITY_DELTA_rows,VEL_rows,IVAR_rows,R,Z,D,V,LOGLAM_MAP):\n\n self.N_qso = N_qso\n self.N_cells = N_cells\n self.SIGMA_G = SIGMA_G\n\n # catalog information\n self.TYPE = TYPE\n self.RA = RA\n self.DEC = DEC\n self.Z_QSO = Z_QSO\n self.DZ_RSD = DZ_RSD\n self.MOCKID = MOCKID\n self.PLATE = PLATE\n self.MJD = MJD\n self.FIBER = FIBER\n\n # skewer information used by all absorbers\n self.GAUSSIAN_DELTA_rows = GAUSSIAN_DELTA_rows\n self.DENSITY_DELTA_rows = DENSITY_DELTA_rows\n self.VEL_rows = VEL_rows\n\n # used in picca files to mask outside Lya region\n self.LOGLAM_MAP = LOGLAM_MAP\n self.IVAR_rows = IVAR_rows\n\n # coordinates for the skewer cells (might get rid of some of these)\n self.R = R\n self.Z = Z\n self.D = D\n self.V = V\n\n # these will store the absorbing fields (Lya, Lyb, metals...)\n self.lya_absorber = absorber.AbsorberData(name='Lya',rest_wave=lya,flux_transform_m=1.0)\n self.lyb_absorber = None\n self.metals = None\n\n # these will store the DLA (if asked for)\n self.DLA_table = None\n\n # these will store the RSD weights (if asked for)\n self.RSD_weights = None\n\n return\n\n def setup_Lyb_absorber(self):\n\n self.lyb_absorber = absorber_data.get_lyb_absorber()\n\n return\n\n def setup_metal_absorbers(self):\n\n # get a dictionary with multiple absorbers, one for each metal line\n self.metals = absorber_data.get_metal_dict()\n\n return\n\n #Method to extract reduced data from an input file of a given format, with a given list of MOCKIDs.\n @classmethod\n def get_gaussian_skewers_object(cls,filename,file_number,input_format,MOCKIDs=None,lambda_min=0,IVAR_cutoff=lya,SIGMA_G=None):\n\n h = fits.open(filename)\n\n #Get data about the catalog and cosmology.\n h_MOCKID = read_files.get_MOCKID(h,input_format,file_number)\n h_R, h_Z, h_D, h_V = read_files.get_COSMO(h,input_format)\n h_lya_lambdas = read_files.get_lya_lambdas(h,input_format)\n h_lya_lambdas_edges = utils.get_edges(h_lya_lambdas)\n\n #Work out which rows in the hdulist we are interested in.\n if MOCKIDs is not None:\n rows = []\n s = set(MOCKIDs)\n for i, qso in enumerate(h_MOCKID):\n if qso in s:\n rows += [i]\n else:\n rows = list(range(h_MOCKID.shape[0]))\n\n #Calculate the first_relevant_cell.\n first_relevant_cell = np.searchsorted(h_lya_lambdas_edges[1:],lambda_min)\n\n if input_format == 'physical_colore':\n\n #Extract data from the HDUlist.\n TYPE = h[1].data['TYPE'][rows]\n RA = h[1].data['RA'][rows]\n DEC = h[1].data['DEC'][rows]\n Z_QSO = h[1].data['Z_COSMO'][rows]\n DZ_RSD = h[1].data['DZ_RSD'][rows]\n DENSITY_DELTA_rows = h[2].data[rows,:][:,first_relevant_cell:]\n VEL_rows = h[3].data[rows,:][:,first_relevant_cell:]\n Z = h[4].data['Z'][first_relevant_cell:]\n R = h[4].data['R'][first_relevant_cell:]\n D = h[4].data['D'][first_relevant_cell:]\n V = h[4].data['V'][first_relevant_cell:]\n\n #Derive the number of quasars and cells in the file.\n N_qso = RA.shape[0]\n N_cells = Z.shape[0]\n if SIGMA_G == None:\n SIGMA_G = h[4].header['SIGMA_G']\n\n #Derive the MOCKID and LOGLAM_MAP.\n MOCKID = read_files.get_MOCKID(h,input_format,file_number)\n LOGLAM_MAP = np.log10(lya*(1+Z))\n\n #Calculate the Gaussian skewers.\n GAUSSIAN_DELTA_rows = convert.lognormal_delta_to_gaussian(DENSITY_DELTA_rows,SIGMA_G,D)\n\n #Make binary IVAR_rows for picca.\n IVAR_rows = utils.make_IVAR_rows(IVAR_cutoff,Z_QSO,LOGLAM_MAP)\n\n #Insert placeholder values for remaining variables.\n DENSITY_DELTA_rows = None\n PLATE = MOCKID\n MJD = np.zeros(N_qso)\n FIBER = np.zeros(N_qso)\n\n elif input_format == 'gaussian_colore':\n\n #Extract data from the HDUlist.\n TYPE = h[1].data['TYPE'][rows]\n RA = h[1].data['RA'][rows]\n DEC = h[1].data['DEC'][rows]\n Z_QSO = h[1].data['Z_COSMO'][rows]\n DZ_RSD = h[1].data['DZ_RSD'][rows]\n GAUSSIAN_DELTA_rows = h[2].data[rows,:][:,first_relevant_cell:]\n VEL_rows = h[3].data[rows,:][:,first_relevant_cell:]\n Z = h[4].data['Z'][first_relevant_cell:]\n R = h[4].data['R'][first_relevant_cell:]\n D = h[4].data['D'][first_relevant_cell:]\n V = h[4].data['V'][first_relevant_cell:]\n\n #Derive the number of quasars and cells in the file.\n N_qso = RA.shape[0]\n N_cells = Z.shape[0]\n if SIGMA_G == None:\n SIGMA_G = h[4].header['SIGMA_G']\n\n #Derive the MOCKID and LOGLAM_MAP.\n if MOCKIDs != None:\n MOCKID = MOCKIDs\n else:\n MOCKID = read_files.get_MOCKID(h,input_format,file_number)\n LOGLAM_MAP = np.log10(lya*(1+Z))\n\n #Make binary IVAR_rows for picca.\n IVAR_rows = utils.make_IVAR_rows(IVAR_cutoff,Z_QSO,LOGLAM_MAP)\n\n #Insert placeholder values for remaining variables.\n DENSITY_DELTA_rows = None\n PLATE = MOCKID\n MJD = np.zeros(N_qso)\n FIBER = np.zeros(N_qso)\n else:\n print('Input format not recognised: current options are \"colore\" and \"picca\".')\n print('Please choose one of these options and try again.')\n\n h.close()\n\n return cls(N_qso,N_cells,SIGMA_G,TYPE,RA,DEC,Z_QSO,DZ_RSD,MOCKID,PLATE,MJD,FIBER,GAUSSIAN_DELTA_rows,DENSITY_DELTA_rows,VEL_rows,IVAR_rows,R,Z,D,V,LOGLAM_MAP)\n\n #Function to trim skewers according to a minimum value of lambda. QSOs with no relevant cells are removed.\n def trim_skewers(self,lambda_min=0.,min_catalog_z=0.,extra_cells=0,lambda_max=None,whole_lambda_range=False,remove_irrelevant_QSOs=False):\n\n #Find the first relevant cell, and the last one if desired.\n #We make sure to include all frequencies within (lambda_min,lambda_max).\n lambdas = 10**(self.LOGLAM_MAP)\n lambda_edges = utils.get_edges(lambdas)\n first_relevant_cell = np.searchsorted(lambda_edges[1:],lambda_min)\n if lambda_max:\n last_relevant_cell = np.searchsorted(lambda_edges[1:],lambda_max) - 1\n else:\n last_relevant_cell = -1 % self.N_cells\n\n #Calculate the actual values of lambda min and max.\n actual_lambda_min = lambda_edges[:-1][first_relevant_cell]\n actual_lambda_max = lambda_edges[:-1][last_relevant_cell]\n\n #If we want to keep any extra_cells, we subtract from the first_relevant_cell.\n #If we cannot add enough extra cells, then we just set the first relevant cell to 0.\n if first_relevant_cell>extra_cells:\n first_relevant_cell -= extra_cells\n else:\n first_relevant_cell = 0\n\n #Determine which QSOs have any relevant cells to keep.\n relevant_QSOs = (self.Z_QSO>min_catalog_z)\n if remove_irrelevant_QSOs:\n relevant_QSOs *= (np.sum(self.IVAR_rows,axis=1)>0)\n\n #If we want the entirety of the lambda range to be relevant (i.e. with IVAR=1), we must remove skewers that do not have this\n if whole_lambda_range:\n relevant_QSOs *= (self.IVAR_rows[:,first_relevant_cell] == 1) * (self.IVAR_rows[:,last_relevant_cell] == 1)\n\n #Remove QSOs no longer needed.\n self.N_qso = np.sum(relevant_QSOs)\n\n self.TYPE = self.TYPE[relevant_QSOs]\n self.RA = self.RA[relevant_QSOs]\n self.DEC = self.DEC[relevant_QSOs]\n self.Z_QSO = self.Z_QSO[relevant_QSOs]\n self.DZ_RSD = self.DZ_RSD[relevant_QSOs]\n self.MOCKID = self.MOCKID[relevant_QSOs]\n self.PLATE = self.PLATE[relevant_QSOs]\n self.MJD = self.MJD[relevant_QSOs]\n self.FIBER = self.FIBER[relevant_QSOs]\n\n self.GAUSSIAN_DELTA_rows = self.GAUSSIAN_DELTA_rows[relevant_QSOs,:]\n if self.DENSITY_DELTA_rows is not None:\n self.DENSITY_DELTA_rows = self.DENSITY_DELTA_rows[relevant_QSOs,:]\n self.VEL_rows = self.VEL_rows[relevant_QSOs,:]\n self.IVAR_rows = self.IVAR_rows[relevant_QSOs,:]\n if self.lya_absorber.tau_computed():\n self.lya_absorber.tau = self.lya_absorber.tau[relevant_QSOs,:]\n if self.lya_absorber.RSDs_applied:\n self.lya_absorber.tau_noRSD = self.lya_absorber.tau_noRSD[relevant_QSOs,:]\n if self.lyb_absorber:\n if self.lyb_absorber.tau_computed():\n self.lyb_absorber.tau = self.lyb_absorber.tau[relevant_QSOs,:]\n if self.lyb_absorber.RSDs_applied:\n self.lyb_absorber.tau_noRSD = self.lyb_absorber.tau_noRSD[relevant_QSOs,:]\n if self.metals:\n for metal in iter(self.metals.values()):\n if metal.tau_computed():\n metal.tau = metal.tau[relevant_QSOs,:]\n if metal.RSDs_applied:\n metal.tau_noRSD = metal.tau_noRSD[relevant_QSOs,:]\n\n #Now trim the skewers of the remaining QSOs.\n self.N_cells = last_relevant_cell - first_relevant_cell + 1\n\n self.GAUSSIAN_DELTA_rows = self.GAUSSIAN_DELTA_rows[:,first_relevant_cell:last_relevant_cell + 1]\n if self.DENSITY_DELTA_rows is not None:\n self.DENSITY_DELTA_rows = self.DENSITY_DELTA_rows[:,first_relevant_cell:last_relevant_cell + 1]\n self.VEL_rows = self.VEL_rows[:,first_relevant_cell:last_relevant_cell + 1]\n self.IVAR_rows = self.IVAR_rows[:,first_relevant_cell:last_relevant_cell + 1]\n if self.lya_absorber.tau_computed():\n self.lya_absorber.tau = self.lya_absorber.tau[:,first_relevant_cell:last_relevant_cell + 1]\n if self.lya_absorber.RSDs_applied:\n self.lya_absorber.tau_noRSD = self.lya_absorber.tau_noRSD[:,first_relevant_cell:last_relevant_cell + 1]\n if self.lyb_absorber:\n if self.lyb_absorber.tau_computed():\n self.lyb_absorber.tau = self.lyb_absorber.tau[:,first_relevant_cell:last_relevant_cell + 1]\n if self.lyb_absorber.RSDs_applied:\n self.lyb_absorber.tau_noRSD = self.lyb_absorber.tau_noRSD[:,first_relevant_cell:last_relevant_cell + 1]\n if self.metals:\n for metal in iter(self.metals.values()):\n if metal.tau_computed():\n metal.tau = metal.tau[:,first_relevant_cell:last_relevant_cell + 1]\n if metal.RSDs_applied:\n metal.tau_noRSD = metal.tau_noRSD[:,first_relevant_cell:last_relevant_cell + 1]\n\n self.R = self.R[first_relevant_cell:last_relevant_cell + 1]\n self.Z = self.Z[first_relevant_cell:last_relevant_cell + 1]\n self.D = self.D[first_relevant_cell:last_relevant_cell + 1]\n self.V = self.V[first_relevant_cell:last_relevant_cell + 1]\n self.LOGLAM_MAP = self.LOGLAM_MAP[first_relevant_cell:last_relevant_cell + 1]\n if not isinstance(self.SIGMA_G,float):\n self.SIGMA_G = self.SIGMA_G[first_relevant_cell:last_relevant_cell + 1]\n if hasattr(self,'sample_SIGMA_G'):\n self.sample_SIGMA_G = self.sample_SIGMA_G[first_relevant_cell:last_relevant_cell + 1]\n\n #Modify the RSD weights to remove QSOs and cut off cells simultaneously\n if self.RSD_weights:\n trimmed_RSD_weights = {}\n k = 0\n for i in self.RSD_weights.keys():\n if relevant_QSOs[i]:\n #Extract the matrix from the old dictionary.\n weights = self.RSD_weights[i]\n\n #Trim in both dimensions.\n weights = weights[first_relevant_cell:last_relevant_cell + 1,:]\n weights = weights[:,first_relevant_cell:last_relevant_cell + 1]\n\n #Add the new weights to a new dictionary.\n trimmed_RSD_weights[k] = weights\n k += 1\n\n #Add the new dictionary to the object.\n self.RSD_weights = trimmed_RSD_weights\n\n #Remove DLAs that are no longer relevant, either because their QSO has\n #been removed, or they are outside the wavelength range.\n if self.DLA_table is not None:\n DLA_lambdas = lya*(1+self.DLA_table['Z_DLA_NO_RSD'])\n relevant_DLAs = [id for id in range(self.DLA_table['MOCKID'].shape[0]) if self.DLA_table['MOCKID'][id] in self.MOCKID and DLA_lambdas[id]>actual_lambda_min and DLA_lambdas[id]0\n mean[cells] = np.average(skewer_rows[:,cells],axis=0,weights=self.IVAR_rows[:,cells])\n\n #Else if there's no width, compute the mean of the cells neighbouring the z_value.\n elif not z_width:\n j_value_upper = np.searchsorted(self.Z,z_value)\n\n j_value_lower = max(j_value_upper - 1,0)\n relevant_rows = [i for i in range(self.N_qso) if np.sum(self.IVAR_rows[j_value_lower,j_value_upper]) == 2]\n\n if j_value_lower > -1:\n weight_upper = (z_value - self.Z[j_value_lower])/(self.Z[j_value_upper] - self.Z[j_value_lower])\n weight_lower = (self.Z[j_value_upper] - z_value)/(self.Z[j_value_upper] - self.Z[j_value_lower])\n\n else:\n weight_upper = 1\n weight_lower = 0\n\n weights = np.ones((self.N_qso,2))\n weights[:,0] *= weight_lower\n weights[:,1] *= weight_upper\n\n mean = np.average(skewer_rows[relevant_rows,j_value_lower:j_value_upper+1],weights=weights)\n\n #Else, compute the mean of the chunk of width z_width centred on z_value.\n else:\n j_value_upper = np.searchsorted(self.Z,z_value + z_width/2.) - 1\n j_value_lower = np.max([0,np.searchsorted(self.Z,z_value - z_width/2.)])\n\n if single_value:\n mean = np.average(skewer_rows[:,j_value_lower:j_value_upper+1],weights=self.IVAR_rows[:,j_value_lower:j_value_upper+1])\n else:\n mean = np.average(skewer_rows[:,j_value_lower:j_value_upper+1],weights=self.IVAR_rows[:,j_value_lower:j_value_upper+1],axis=0)\n\n return mean\n\n #Function to measure pdf.\n def get_pdf_quantity(self,quantity,z_value=None,z_width=None,single_value=True,bins=100,power=1):\n\n if type(bins) != float:\n N_bins = bins.shape[0]\n\n if quantity == 'gaussian':\n skewer_rows = self.GAUSSIAN_DELTA_rows ** power\n elif quantity == 'density':\n skewer_rows = (self.DENSITY_DELTA_rows + 1) ** power\n elif quantity == 'tau':\n skewer_rows = self.lya_absorber.tau ** power\n elif quantity == 'flux':\n skewer_rows = self.lya_absorber.transmission() ** power\n elif quantity == 'FlnF':\n #Use that ln(F)=-tau so FlnF = -F*tau\n skewer_rows = (-self.lya_absorber.transmission() * self.lya_absorber.tau) ** power\n elif quantity == 'FlnFlnF':\n #Use that ln(F)=-tau so FlnFlnF = F*tau**2\n skewer_rows = (self.lya_absorber.transmission() * (self.lya_absorber.tau)**2) ** power\n\n #If no z value, then compute the pdf as a function of redshift.\n if not z_value:\n hist = np.zeros(N_bins,self.N_cells)\n edges = np.zeros(N_bins+1,self.N_cells)\n for i in range(self.N_cells):\n hist_i,edges_i = np.histogram(skewer_rows[:,i],bins=bins,weights=self.IVAR_rows[:,i],density=True)\n hist[:,i] = hist_i\n edges[:,i] = edges_i\n\n #Else if there's no width, compute the pef of the cells neighbouring the z_value.\n elif not z_width:\n j_value_upper = np.searchsorted(self.Z,z_value)\n j_value_lower = max(j_value_upper - 1,0)\n relevant_rows = [i for i in range(self.N_qso) if np.sum(self.IVAR_rows[j_value_lower,j_value_upper]) == 2]\n\n if j_value_lower > -1:\n weight_upper = (z_value - self.Z[j_value_lower])/(self.Z[j_value_upper] - self.Z[j_value_lower])\n weight_lower = (self.Z[j_value_upper] - z_value)/(self.Z[j_value_upper] - self.Z[j_value_lower])\n\n else:\n weight_upper = 1\n weight_lower = 0\n\n weights = np.ones((self.N_qso,2))\n weights[:,0] *= weight_lower\n weights[:,1] *= weight_upper\n\n hist,edges = np.histogram(skewer_rows[relevant_rows,j_value_lower,j_value_upper+1],bins=bins,weights=weights,density=True)\n\n #Else, compute the mean of the chunk of width z_width centred on z_value.\n else:\n j_value_upper = np.searchsorted(self.Z,z_value + z_width/2.) - 1\n j_value_lower = np.max([0,np.searchsorted(self.Z,z_value - z_width/2.)])\n if single_value:\n hist,edges = np.histogram(skewer_rows[:,j_value_lower:j_value_upper+1],bins=bins,weights=self.IVAR_rows[:,j_value_lower:j_value_upper+1],density=True)\n else:\n hist = np.zeros(N_bins,j_value_upper+1-j_value_lower)\n edges = np.zeros(N_bins+1,j_value_upper+1-j_value_lower)\n for i in range(j_value_upper+1-j_value_lower):\n hist_i,edges_i = np.histogram(skewer_rows[:,i],bins=bins,weights=self.IVAR_rows[:,i],density=True)\n hist[:,i] = hist_i\n edges[:,i] = edges_i\n\n return hist,edges\n\n #Function to measure sigma dF.\n def get_sigma_dF(self,absorber,z_value=None,z_width=None,mean_F=None):\n\n if not mean_F:\n mean_F = self.get_mean_quantity('flux',z_value=z_value,z_width=z_width)\n\n F = absorber.transmission()\n dF = F/mean_F\n\n if not z_value:\n # TODO: there's no weighting in here?\n sigma_dF = np.std(dF,axis=0)\n\n elif not z_width:\n j_value_upper = np.searchsorted(self.Z,z_value)\n\n j_value_lower = np.max([j_value_upper - 1,0])\n relevant_rows = [i for i in range(self.N_qso) if np.sum(self.IVAR_rows[j_value_lower,j_value_upper]) == 2]\n\n sigma_dF = np.std(dF[relevant_rows,j_value_lower:j_value_upper+1])\n\n else:\n j_value_upper = np.searchsorted(self.Z,z_value + z_width/2.)\n j_value_lower = np.max([0,np.searchsorted(self.Z,z_value - z_width/2.) - 1])\n\n sigma_dF = np.std(dF[:,j_value_lower:j_value_upper+1])\n\n #print('gsd return',sigma_dF)\n return sigma_dF\n\n #Method to combine data from two objects into one.\n # TODO: add something to check that we can just take values from 1 of the objects\n @classmethod\n def combine_files(cls,object_A,object_B,gaussian_only=False):\n\n N_qso = object_A.N_qso + object_B.N_qso\n\n \"\"\"\n something to check N_cells is the same in both files\n \"\"\"\n\n N_cells = object_A.N_cells\n SIGMA_G = object_A.SIGMA_G\n\n TYPE = np.concatenate((object_A.TYPE,object_B.TYPE),axis=0)\n RA = np.concatenate((object_A.RA,object_B.RA),axis=0)\n DEC = np.concatenate((object_A.DEC,object_B.DEC),axis=0)\n Z_QSO = np.concatenate((object_A.Z_QSO,object_B.Z_QSO),axis=0)\n DZ_RSD = np.concatenate((object_A.DZ_RSD,object_B.DZ_RSD),axis=0)\n MOCKID = np.concatenate((object_A.MOCKID,object_B.MOCKID),axis=0)\n PLATE = np.concatenate((object_A.PLATE,object_B.PLATE),axis=0)\n MJD = np.concatenate((object_A.MJD,object_B.MJD),axis=0)\n FIBER = np.concatenate((object_A.FIBER,object_B.FIBER),axis=0)\n\n GAUSSIAN_DELTA_rows = np.concatenate((object_A.GAUSSIAN_DELTA_rows,object_B.GAUSSIAN_DELTA_rows),axis=0)\n VEL_rows = np.concatenate((object_A.VEL_rows,object_B.VEL_rows),axis=0)\n IVAR_rows = np.concatenate((object_A.IVAR_rows,object_B.IVAR_rows),axis=0)\n if gaussian_only:\n DENSITY_DELTA_rows = None\n else:\n DENSITY_DELTA_rows = np.concatenate((object_A.DENSITY_DELTA_rows,object_B.DENSITY_DELTA_rows),axis=0)\n\n \"\"\"\n Something to check this is ok?\n \"\"\"\n\n Z = object_A.Z\n LOGLAM_MAP = object_A.LOGLAM_MAP\n R = object_A.R\n D = object_A.D\n V = object_A.V\n\n return cls(N_qso,N_cells,SIGMA_G,TYPE,RA,DEC,Z_QSO,DZ_RSD,MOCKID,PLATE,MJD,FIBER,GAUSSIAN_DELTA_rows,DENSITY_DELTA_rows,VEL_rows,IVAR_rows,R,Z,D,V,LOGLAM_MAP)\n\n #Function to save in the colore format.\n def save_as_colore(self,quantity,filename,header,overwrite=False,cell_size=None,compress=True):\n t = time.time()\n\n #Organise the catalog data into a colore-format array.\n colore_1_data = []\n for i in range(self.N_qso):\n colore_1_data += [(self.TYPE[i],self.RA[i],self.DEC[i],self.Z_QSO[i],self.DZ_RSD[i],self.MOCKID[i])]\n dtype = [('TYPE', 'f4'), ('RA', 'f4'), ('DEC', 'f4'), ('Z_COSMO', 'f4'), ('DZ_RSD', 'f4'), ('MOCKID', int)]\n colore_1 = np.array(colore_1_data,dtype=dtype)\n\n #Choose the right skewers according to input quantity.\n if quantity == 'gaussian':\n colore_2 = self.GAUSSIAN_DELTA_rows\n elif quantity == 'density':\n colore_2 = self.DENSITY_DELTA_rows + 1\n elif quantity == 'tau':\n colore_2 == self.lya_absorber.tau\n elif quantity == 'flux':\n colore_2 = self.lya_absorber.transmission()\n colore_2 = colore_2.astype('float32')\n\n #Add the velocity skewers and cosmology data\n colore_3 = self.VEL_rows.astype('float32')\n colore_4_data = []\n for i in range(self.N_cells):\n colore_4_data += [(self.R[i],self.Z[i],self.D[i],self.V[i])]\n dtype = [('R', 'f4'), ('Z', 'f4'), ('D', 'f4'), ('V', 'f4')]\n colore_4 = np.array(colore_4_data,dtype=dtype)\n\n #Construct HDUs from the data arrays.\n prihdr = fits.Header()\n prihdu = fits.PrimaryHDU(header=prihdr)\n cols_CATALOG = fits.ColDefs(colore_1)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n hdu_GAUSSIAN = fits.ImageHDU(data=colore_2,header=header,name=quantity.upper())\n hdu_VEL = fits.ImageHDU(data=colore_3,header=header,name='VELOCITY')\n cols_COSMO = fits.ColDefs(colore_4)\n hdu_COSMO = fits.BinTableHDU.from_columns(cols_COSMO,header=header,name='COSMO')\n\n #Combine the HDUs into an HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([prihdu, hdu_CATALOG, hdu_GAUSSIAN, hdu_VEL, hdu_COSMO])\n hdulist.writeto(filename,overwrite=overwrite)\n hdulist.close()\n\n #print('--> saving takes {:2.3f}s'.format(time.time()-t))\n t = time.time()\n #Compress the file if desired.\n if compress:\n utils.compress_file(filename)\n #print('--> compressing takes {:2.3f}s'.format(time.time()-t))\n\n return\n\n #Function to save in the picca format.\n def save_as_picca_delta(self,quantity,filename,header,mean_data=None,overwrite=False,min_number_cells=2,cell_size=None,notnorm=False,add_QSO_RSDs=True,compress=True,all_absorbers=False):\n\n t = time.time()\n lya_lambdas = 10**self.LOGLAM_MAP\n\n #If not normalising:\n if notnorm:\n if quantity == 'gaussian':\n skewer_rows = self.GAUSSIAN_DELTA_rows\n elif quantity == 'density':\n skewer_rows = self.DENSITY_DELTA_rows\n elif quantity == 'tau':\n skewer_rows = self.lya_absorber.tau\n #If desired, add all metal absorbers.\n if all_absorbers:\n if self.lyb_absorber is not None:\n #Shift the skewers according to absorber rest wavelength.\n lyb_lam = (10**self.LOGLAM_MAP)*self.lyb_absorber.rest_wave/lya\n lyb_skewers = interp1d(lyb_lam,self.lyb_absorber.tau,axis=1,fill_value=(0.,0.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows += lyb_skewers\n header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n if self.metals is not None:\n for metal in iter(self.metals.values()):\n #Shift the skewers according to absorber rest wavelength.\n metal_lam = (10**self.LOGLAM_MAP)*metal.rest_wave/lya\n metal_skewers = interp1d(metal_lam,metal.tau,axis=1,fill_value=(0.,0.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows += metal_skewers\n header[metal.HDU_name] = metal.rest_wave\n elif quantity == 'flux':\n skewer_rows = self.lya_absorber.transmission()\n #If desired, add all metal absorbers.\n if all_absorbers:\n if self.lyb_absorber is not None:\n #Shift the skewers according to absorber rest wavelength.\n lyb_lam = (10**self.LOGLAM_MAP)*self.lyb_absorber.rest_wave/lya\n lyb_skewers = interp1d(lyb_lam,self.lyb_absorber.transmission(),axis=1,fill_value=(1.,1.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows *= lyb_skewers\n header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n if self.metals is not None:\n for metal in iter(self.metals.values()):\n #Shift the skewers according to absorber rest wavelength.\n metal_lam = (10**self.LOGLAM_MAP)*metal.rest_wave/lya\n metal_skewers = interp1d(metal_lam,metal.transmission(),axis=1,fill_value=(1.,1.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows *= metal_skewers\n header[metal.HDU_name] = metal.rest_wave\n\n #If normalising:\n else:\n if quantity == 'gaussian':\n skewer_rows = self.GAUSSIAN_DELTA_rows\n elif quantity == 'density':\n skewer_rows = self.DENSITY_DELTA_rows\n elif quantity == 'tau':\n skewer_rows = np.zeros(self.lya_absorber.tau.shape)\n cells = np.sum(self.IVAR_rows,axis=0)>0\n #print('min mean tau:',np.min(mean[cells]))\n skewer_rows[:,cells] = self.lya_absorber.tau[:,cells]\n #If desired, add all metal absorbers.\n if all_absorbers:\n if self.lyb_absorber is not None:\n #Shift the skewers according to absorber rest wavelength.\n lyb_lam = (10**self.LOGLAM_MAP)*self.lyb_absorber.rest_wave/lya\n lyb_skewers = interp1d(lyb_lam,self.lyb_absorber.tau,axis=1,fill_value=(0.,0.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows += lyb_skewers\n header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n if self.metals is not None:\n for metal in iter(self.metals.values()):\n #Shift the skewers according to absorber rest wavelength.\n metal_lam = (10**self.LOGLAM_MAP)*metal.rest_wave/lya\n metal_skewers = interp1d(metal_lam,metal.tau,axis=1,fill_value=(0.,0.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows += metal_skewers\n header[metal.HDU_name] = metal.rest_wave\n #Get mean with redshift.\n if mean_data is None:\n mean = self.get_mean_quantity('tau',all_absorbers=all_absorbers)\n else:\n mean = np.interp(self.Z,mean_data['z'],mean_data['mean'])\n #Normalise to get deltas\n skewer_rows[:,cells] = skewer_rows[:,cells]/mean[cells] - 1\n elif quantity == 'flux':\n skewer_rows = np.zeros(self.lya_absorber.transmission().shape)\n cells = np.sum(self.IVAR_rows,axis=0)>0\n #print('min mean flux:',np.min(mean[cells]))\n skewer_rows[:,cells] = self.lya_absorber.transmission()[:,cells]\n #If desired, add all metal absorbers.\n if all_absorbers:\n if self.lyb_absorber is not None:\n #Shift the skewers according to absorber rest wavelength.\n lyb_lam = (10**self.LOGLAM_MAP)*self.lyb_absorber.rest_wave/lya\n lyb_skewers = interp1d(lyb_lam,self.lyb_absorber.transmission(),axis=1,fill_value=(1.,1.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows *= lyb_skewers\n header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n if self.metals is not None:\n for metal in iter(self.metals.values()):\n #Shift the skewers according to absorber rest wavelength.\n metal_lam = (10**self.LOGLAM_MAP)*metal.rest_wave/lya\n metal_skewers = interp1d(metal_lam,metal.transmission(),axis=1,fill_value=(1.,1.),bounds_error=False)(10**self.LOGLAM_MAP)\n #Add tau contribution and rest wavelength to header.\n skewer_rows *= metal_skewers\n header[metal.HDU_name] = metal.rest_wave\n #Get mean with redshift.\n if mean_data is None:\n mean = self.get_mean_quantity('flux',all_absorbers=all_absorbers)\n else:\n mean = np.interp(self.Z,mean_data['z'],mean_data['mean'])\n #Normalise to get deltas\n skewer_rows[:,cells] = skewer_rows[:,cells]/mean[cells] - 1\n\n #Determine the relevant QSOs: those that have relevant cells (IVAR > 0) beyond the first_relevant_cell.\n #We impose a minimum number of cells per skewer here to avoid problems with picca.\n relevant_QSOs = []\n for i in range(self.N_qso):\n if np.sum(self.IVAR_rows[i,:]) >= min_number_cells:\n relevant_QSOs += [i]\n #relevant_QSOs = np.sum(self.IVAR_rows,axis=1) >= min_number_cells\n non_rel_QSOs = np.sum(self.IVAR_rows,axis=1) < min_number_cells\n\n #Trim data according to the relevant cells and QSOs.\n relevant_skewer_rows = skewer_rows[relevant_QSOs,:]\n relevant_IVAR_rows = self.IVAR_rows[relevant_QSOs,:]\n relevant_LOGLAM_MAP = self.LOGLAM_MAP[:]\n\n #If desired, add in QSO RSDs.\n if add_QSO_RSDs:\n Z_QSO = self.Z_QSO + self.DZ_RSD\n else:\n Z_QSO = self.Z_QSO\n\n #Organise the data into picca-format arrays.\n picca_0 = relevant_skewer_rows.T.astype('float32')\n picca_1 = relevant_IVAR_rows.T\n picca_2 = relevant_LOGLAM_MAP.astype('float32')\n picca_3_data = list(zip(self.RA[relevant_QSOs],self.DEC[relevant_QSOs],Z_QSO[relevant_QSOs],self.PLATE[relevant_QSOs],self.MJD[relevant_QSOs],self.FIBER[relevant_QSOs],self.MOCKID[relevant_QSOs]))\n dtype = [('RA', 'f4'), ('DEC', 'f4'), ('Z', 'f4'), ('PLATE', int), ('MJD', 'f4'), ('FIBER', int), ('THING_ID', int)]\n picca_3 = np.array(picca_3_data,dtype=dtype)\n\n #Add cell size to the header (average)\n dr_hMpc = (self.R[-1] - self.R[0])/(self.N_cells - 1)\n header['dr_hMpc'] = dr_hMpc\n\n #Make the data into suitable HDUs.\n hdu_DELTA = fits.PrimaryHDU(data=picca_0,header=header)\n hdu_iv = fits.ImageHDU(data=picca_1,header=header,name='IV')\n hdu_LOGLAM_MAP = fits.ImageHDU(data=picca_2,header=header,name='LOGLAM_MAP')\n hdu_CATALOG = fits.BinTableHDU(picca_3,header=header,name='CATALOG')\n\n #Combine the HDUs into and HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([hdu_DELTA, hdu_iv, hdu_LOGLAM_MAP, hdu_CATALOG])\n #print('--> organising takes {:2.3f}s'.format(time.time()-t))\n t = time.time()\n hdulist.writeto(filename,overwrite=overwrite)\n #print('--> writing takes {:2.3f}s'.format(time.time()-t))\n t = time.time()\n hdulist.close()\n\n #Compress the file if desired.\n if compress:\n utils.compress_file(filename)\n #print('--> compressing takes {:2.3f}s'.format(time.time()-t))\n\n return\n\n #Compute transmission for a particular absorber, on a particular grid\n def compute_grid_transmission(self,absorber,wave_grid):\n\n #Get data from the absorber.\n F_skewer = absorber.transmission()\n rest_wave = absorber.rest_wave\n wave_skewer = rest_wave*(1+self.Z)\n\n #Create the F_grid.\n N_los = F_skewer.shape[0]\n N_w = wave_grid.shape[0]\n F_grid = np.empty([N_los,N_w])\n\n #Interpolate the skewers.\n for i in range(N_los):\n F_grid[i,] = np.interp(wave_grid,wave_skewer,F_skewer[i],left=1.0,right=1.0)\n\n return F_grid\n\n #Function to save data as a transmission file.\n def save_as_transmission(self,filename,header,overwrite=False,wave_min=3550.,wave_max=6500.,wave_step=0.2,fmt='final',add_QSO_RSDs=True,compress=True):\n\n t = time.time()\n\n # define common wavelength grid to be written in files (in Angstroms)\n wave_grid = np.arange(wave_min,wave_max,wave_step).astype('float32')\n\n # compute Lyman alpha transmission on grid of wavelengths\n F_grid_Lya = self.compute_grid_transmission(self.lya_absorber,wave_grid).astype('float32')\n\n #construct quasar catalog HDU\n if add_QSO_RSDs:\n Z_QSO = self.Z_QSO + self.DZ_RSD\n else:\n Z_QSO = self.Z_QSO\n catalog_data = list(zip(self.RA,self.DEC,Z_QSO,self.Z_QSO,self.MOCKID))\n dtype = [('RA', 'f4'), ('DEC', 'f4'), ('Z', 'f4'), ('Z_noRSD', 'f4'), ('MOCKID', int)]\n catalog_data = np.array(catalog_data,dtype=dtype)\n\n #Construct HDUs from the data arrays.\n prihdr = fits.Header()\n prihdu = fits.PrimaryHDU(header=prihdr)\n cols_METADATA = fits.ColDefs(catalog_data)\n hdu_METADATA = fits.BinTableHDU.from_columns(cols_METADATA,header=header,name='METADATA')\n hdu_WAVELENGTH = fits.ImageHDU(data=wave_grid,header=header,name='WAVELENGTH')\n\n #Combine the HDUs into an HDUlist (including DLAs and metals, if they have been computed)\n list_hdu = [prihdu, hdu_METADATA, hdu_WAVELENGTH]\n\n #Set up the absorber HDUs according to the input format 'fmt'.\n if fmt=='single_HDU':\n\n #Transmission of all absorbers.\n abs_header = header.copy()\n abs_header['LYA'] = self.lya_absorber.rest_wave\n F_grid = F_grid_Lya\n if self.lyb_absorber is not None:\n abs_header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n F_grid *= self.compute_grid_transmission(self.lyb_absorber,wave_grid).astype('float32')\n if self.metals is not None:\n for metal in iter(self.metals.values()):\n abs_header[metal.HDU_name] = metal.rest_wave\n F_grid *= self.compute_grid_transmission(metal,wave_grid).astype('float32')\n hdu_F = fits.ImageHDU(data=F_grid,header=abs_header,name='F')\n list_hdu += [hdu_F]\n\n elif fmt == 'final':\n\n #Gives transmission of Lya only\n lya_header = header\n lya_header['LYA'] = self.lya_absorber.rest_wave\n list_hdu += [fits.ImageHDU(data=F_grid_Lya,header=lya_header,name='F_LYA')]\n\n # compute Lyman beta transmission on grid of wavelengths\n if self.lyb_absorber is not None:\n F_grid_Lyb = self.compute_grid_transmission(self.lyb_absorber,wave_grid).astype('float32')\n HDU_name = 'F_'+self.lyb_absorber.HDU_name\n lyb_header = header.copy()\n lyb_header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n list_hdu += [fits.ImageHDU(data=F_grid_Lyb,header=lyb_header,name=HDU_name)]\n\n #Add an HDU for each metal computed.\n if self.metals is not None:\n F_grid_all_metals = np.ones_like(F_grid_Lya)\n met_header = header.copy()\n # compute metals' transmission on grid of wavelengths\n for metal in iter(self.metals.values()):\n F_grid_all_metals *= self.compute_grid_transmission(metal,wave_grid).astype('float32')\n met_header[metal.HDU_name] = metal.rest_wave\n HDU_name = 'F_METALS'\n list_hdu += [fits.ImageHDU(data=F_grid_all_metals,header=met_header,name=HDU_name)]\n\n elif fmt == 'develop':\n\n #Gives transmission of Lya only\n lya_header = header\n lya_header['LYA'] = self.lya_absorber.rest_wave\n list_hdu += [fits.ImageHDU(data=F_grid_Lya,header=lya_header,name='F_LYA')]\n\n # compute Lyman beta transmission on grid of wavelengths\n if self.lyb_absorber is not None:\n F_grid_Lyb = self.compute_grid_transmission(self.lyb_absorber,wave_grid).astype('float32')\n HDU_name = 'F_'+self.lyb_absorber.HDU_name\n lyb_header = header.copy()\n lyb_header[self.lyb_absorber.HDU_name] = self.lyb_absorber.rest_wave\n list_hdu += [fits.ImageHDU(data=F_grid_Lyb,header=lyb_header,name=HDU_name)]\n\n #Add an HDU for each metal computed.\n if self.metals is not None:\n # compute metals' transmission on grid of wavelengths\n for metal in iter(self.metals.values()):\n F_grid_metal = self.compute_grid_transmission(metal,wave_grid).astype('float32')\n HDU_name = 'F_'+metal.HDU_name\n met_header = header.copy()\n met_header[metal.HDU_name] = metal.rest_wave\n list_hdu += [fits.ImageHDU(data=F_grid_metal,header=met_header,name=HDU_name)]\n\n # add table of DLAs\n if self.DLA_table is not None:\n hdu_DLAs = fits.hdu.BinTableHDU(self.DLA_table,header=header,name='DLA')\n list_hdu.append(hdu_DLAs)\n\n #Save as a new file. Close the HDUlist.\n hdulist = fits.HDUList(list_hdu)\n hdulist.writeto(filename,overwrite=overwrite)\n hdulist.close()\n #print('--> saving takes {:2.3f}s'.format(time.time()-t))\n t = time.time()\n\n #Compress the file if desired.\n if compress:\n utils.compress_file(filename)\n #print('--> compressing takes {:2.3f}s'.format(time.time()-t))\n\n return\n\n #Function to calculate the mean and variance of the different quantities as a function of Z.\n def get_means(self,all_absorbers=True):\n\n #For each cell, determine the number of skewers for which it is relevant.\n N_skewers = np.sum(self.IVAR_rows,axis=0)\n\n #Calculate the mean in each cell of the gaussian delta and its square.\n GM = self.get_mean_quantity('gaussian',all_absorbers=all_absorbers)\n GSM = self.get_mean_quantity('gaussian',power=2.,all_absorbers=all_absorbers)\n\n #Calculate the mean in each cell of the density delta and its square.\n DM = self.get_mean_quantity('density',all_absorbers=all_absorbers)\n DSM = self.get_mean_quantity('density',power=2.,all_absorbers=all_absorbers)\n\n #Calculate the mean in each cell of the tau and its square.\n TM = self.get_mean_quantity('tau',all_absorbers=all_absorbers)\n TSM = self.get_mean_quantity('tau',power=2.,all_absorbers=all_absorbers)\n\n #Calculate the mean in each cell of the flux and its square.\n FM = self.get_mean_quantity('flux',all_absorbers=all_absorbers)\n FSM = self.get_mean_quantity('flux',power=2.,all_absorbers=all_absorbers)\n\n #Calculate the mean in each cell of the flux delta and its square.\n #FDB = np.average(relevant_delta_F,weights=relevant_IVAR+small,axis=0)*relevant_cells\n #FDSB = np.average(relevant_delta_F**2,weights=relevant_IVAR+small,axis=0)*relevant_cells\n\n #Stitch together the means into a binary table.\n dtype = [('Z', 'f4'), ('N', 'int'), ('GAUSSIAN', 'f4'), ('GAUSSIAN_SQUARED', 'f4'), ('DENSITY', 'f4'), ('DENSITY_SQUARED', 'f4'), ('TAU', 'f4'), ('TAU_SQUARED', 'f4'), ('F', 'f4'), ('F_SQUARED', 'f4')]\n #, ('F_DELTA', 'f4'), ('F_DELTA_SQUARED', 'f4')]\n means = np.array(list(zip(self.Z,N_skewers,GM,GSM,DM,DSM,TM,TSM,FM,FSM)),dtype=dtype)\n #,FDB,FDSB\n\n return means\n\n #Function to save the means as a function of z.\n def save_statistics(self,filepath,overwrite=False,compress=True,all_absorbers=True):\n\n means = self.get_means(all_absorbers=all_absorbers)\n statistics = stats.means_to_statistics(means)\n stats.write_statistics(filepath,statistics,overwrite=overwrite,compress=compress)\n\n return statistics\n\n #Function to add DLAs to a set of skewers.\n def add_DLA_table(self,seed,dla_bias=2.0,evol='b_const',method='global'):\n\n #If extrapolate_z_down is set to a value below the skewer, then we extrapolate down to that value.\n #Otherwise, we start placing DLAs at the start of the skewer.\n extrapolate_z_down = None\n DLA_table = DLA.get_DLA_table(self,dla_bias=dla_bias,extrapolate_z_down=extrapolate_z_down,seed=seed,method=method)\n self.DLA_table = DLA_table\n\n return\n\n\n ####\n \"\"\"\n Obsolete functions\n\n #Function to save data as a Gaussian colore file.\n def save_as_gaussian_colore(self,filename,header,overwrite=False):\n\n #Organise the data into colore-format arrays.\n colore_1_data = []\n for i in range(self.N_qso):\n colore_1_data += [(self.TYPE[i],self.RA[i],self.DEC[i],self.Z_QSO[i],self.DZ_RSD[i],self.MOCKID[i])]\n\n dtype = [('TYPE', 'f8'), ('RA', 'f8'), ('DEC', 'f8'), ('Z_COSMO', 'f8'), ('DZ_RSD', 'f8'), ('MOCKID', int)]\n colore_1 = np.array(colore_1_data,dtype=dtype)\n colore_2 = self.GAUSSIAN_DELTA_rows\n colore_3 = self.VEL_rows\n\n colore_4_data = []\n for i in range(self.N_cells):\n colore_4_data += [(self.R[i],self.Z[i],self.D[i],self.V[i])]\n\n dtype = [('R', 'f8'), ('Z', 'f8'), ('D', 'f8'), ('V', 'f8')]\n colore_4 = np.array(colore_4_data,dtype=dtype)\n\n #Construct HDUs from the data arrays.\n prihdr = fits.Header()\n prihdu = fits.PrimaryHDU(header=prihdr)\n cols_CATALOG = fits.ColDefs(colore_1)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n hdu_GAUSSIAN = fits.ImageHDU(data=colore_2,header=header,name='GAUSSIAN_DELTA')\n hdu_VEL = fits.ImageHDU(data=colore_3,header=header,name='VELOCITY')\n cols_COSMO = fits.ColDefs(colore_4)\n hdu_COSMO = fits.BinTableHDU.from_columns(cols_COSMO,header=header,name='COSMO')\n\n #Combine the HDUs into an HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([prihdu, hdu_CATALOG, hdu_GAUSSIAN, hdu_VEL, hdu_COSMO])\n hdulist.writeto(filename,overwrite=overwrite)\n hdulist.close\n\n return\n\n #Function to save data as a picca density file.\n def save_as_picca_gaussian(self,filename,header,overwrite=False,zero_mean_delta=False,min_number_cells=2,mean_DELTA=None):\n\n lya_lambdas = 10**self.LOGLAM_MAP\n\n #Determine the relevant QSOs: those that have relevant cells (IVAR > 0) beyond the first_relevant_cell.\n #We impose a minimum number of cells per skewer here to avoid problems with picca.\n relevant_QSOs = []\n for i in range(self.N_qso):\n if np.sum(self.IVAR_rows[i,:]) >= min_number_cells:\n relevant_QSOs += [i]\n\n #Trim data according to the relevant cells and QSOs.\n relevant_GAUSSIAN_DELTA_rows = self.GAUSSIAN_DELTA_rows[relevant_QSOs,:]\n relevant_IVAR_rows = self.IVAR_rows[relevant_QSOs,:]\n relevant_LOGLAM_MAP = self.LOGLAM_MAP[:]\n\n #If desired, enforce that the Delta rows have zero mean.\n if zero_mean_delta == True:\n relevant_GAUSSIAN_DELTA_rows = utils.normalise_deltas(relevant_GAUSSIAN_DELTA_rows,mean_DELTA)\n\n #Organise the data into picca-format arrays.\n picca_0 = relevant_GAUSSIAN_DELTA_rows.T\n picca_1 = relevant_IVAR_rows.T\n picca_2 = relevant_LOGLAM_MAP\n\n picca_3_data = []\n for i in range(self.N_qso):\n if i in relevant_QSOs:\n picca_3_data += [(self.RA[i],self.DEC[i],self.Z_QSO[i],self.PLATE[i],self.MJD[i],self.FIBER[i],self.MOCKID[i])]\n\n dtype = [('RA', 'f8'), ('DEC', 'f8'), ('Z', 'f8'), ('PLATE', int), ('MJD', 'f8'), ('FIBER', int), ('THING_ID', int)]\n picca_3 = np.array(picca_3_data,dtype=dtype)\n\n #Make the data into suitable HDUs.\n hdu_DELTA = fits.PrimaryHDU(data=picca_0,header=header)\n hdu_iv = fits.ImageHDU(data=picca_1,header=header,name='IV')\n hdu_LOGLAM_MAP = fits.ImageHDU(data=picca_2,header=header,name='LOGLAM_MAP')\n cols_CATALOG = fits.ColDefs(picca_3)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n\n #Combine the HDUs into and HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([hdu_DELTA, hdu_iv, hdu_LOGLAM_MAP, hdu_CATALOG])\n hdulist.writeto(filename,overwrite=overwrite)\n hdulist.close()\n\n return\n\n #Function to save data as a Lognormal colore file.\n def save_as_physical_colore(self,filename,header):\n\n #Organise the data into colore-format arrays.\n colore_1_data = []\n for i in range(self.N_qso):\n colore_1_data += [(self.TYPE[i],self.RA[i],self.DEC[i],self.Z_QSO[i],self.DZ_RSD[i],self.MOCKID[i])]\n\n dtype = [('TYPE', 'f8'), ('RA', 'f8'), ('DEC', 'f8'), ('Z_COSMO', 'f8'), ('DZ_RSD', 'f8'), ('MOCKID', int)]\n colore_1 = np.array(colore_1_data,dtype=dtype)\n\n colore_2 = self.DENSITY_DELTA_rows\n colore_3 = self.VEL_rows\n\n colore_4_data = []\n for i in range(self.N_cells):\n colore_4_data += [(self.R[i],self.Z[i],self.D[i],self.V[i])]\n\n dtype = [('R', 'f8'), ('Z', 'f8'), ('D', 'f8'), ('V', 'f8')]\n colore_4 = np.array(colore_4_data,dtype=dtype)\n\n #Construct HDUs from the data arrays.\n prihdr = fits.Header()\n prihdu = fits.PrimaryHDU(header=prihdr)\n cols_CATALOG = fits.ColDefs(colore_1)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n hdu_DELTA = fits.ImageHDU(data=colore_2,header=header,name='PHYSICAL_DELTA')\n hdu_VEL = fits.ImageHDU(data=colore_3,header=header,name='VELOCITY')\n cols_COSMO = fits.ColDefs(colore_4)\n hdu_COSMO = fits.BinTableHDU.from_columns(cols_COSMO,header=header,name='COSMO')\n\n #Combine the HDUs into an HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([prihdu, hdu_CATALOG, hdu_DELTA, hdu_VEL, hdu_COSMO])\n hdulist.writeto(filename)\n hdulist.close\n\n return\n\n #Function to save data as a picca density file.\n def save_as_picca_density(self,filename,header,zero_mean_delta=False,min_number_cells=2,mean_DELTA=None):\n\n lya_lambdas = 10**self.LOGLAM_MAP\n\n #Determine the relevant QSOs: those that have relevant cells (IVAR > 0) beyond the first_relevant_cell.\n #We impose a minimum number of cells per skewer here to avoid problems with picca.\n relevant_QSOs = []\n for i in range(self.N_qso):\n if np.sum(self.IVAR_rows[i,:]) >= min_number_cells:\n relevant_QSOs += [i]\n\n #Trim data according to the relevant cells and QSOs.\n relevant_DENSITY_DELTA_rows = self.DENSITY_DELTA_rows[relevant_QSOs,:]\n relevant_IVAR_rows = self.IVAR_rows[relevant_QSOs,:]\n relevant_LOGLAM_MAP = self.LOGLAM_MAP[:]\n\n #If desired, enforce that the Delta rows have zero mean.\n if zero_mean_delta == True:\n relevant_DENSITY_DELTA_rows = utils.normalise_deltas(relevant_DENSITY_DELTA_rows,mean_DELTA)\n\n #Organise the data into picca-format arrays.\n picca_0 = relevant_DENSITY_DELTA_rows.T\n picca_1 = relevant_IVAR_rows.T\n picca_2 = relevant_LOGLAM_MAP\n\n picca_3_data = []\n for i in range(self.N_qso):\n if i in relevant_QSOs:\n picca_3_data += [(self.RA[i],self.DEC[i],self.Z_QSO[i],self.PLATE[i],self.MJD[i],self.FIBER[i],self.MOCKID[i])]\n\n dtype = [('RA', 'f8'), ('DEC', 'f8'), ('Z', 'f8'), ('PLATE', int), ('MJD', 'f8'), ('FIBER', int), ('THING_ID', int)]\n picca_3 = np.array(picca_3_data,dtype=dtype)\n\n #Make the data into suitable HDUs.\n hdu_DELTA = fits.PrimaryHDU(data=picca_0,header=header)\n hdu_iv = fits.ImageHDU(data=picca_1,header=header,name='IV')\n hdu_LOGLAM_MAP = fits.ImageHDU(data=picca_2,header=header,name='LOGLAM_MAP')\n cols_CATALOG = fits.ColDefs(picca_3)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n\n #Combine the HDUs into and HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([hdu_DELTA, hdu_iv, hdu_LOGLAM_MAP, hdu_CATALOG])\n hdulist.writeto(filename)\n hdulist.close()\n\n return\n\n #Function to save data as a picca density file.\n def save_as_picca_tau(self,absorber,filename,header,overwrite=False,min_number_cells=2):\n\n lya_lambdas = 10**self.LOGLAM_MAP\n\n #Determine the relevant QSOs: those that have relevant cells (IVAR > 0) beyond the first_relevant_cell.\n #We impose a minimum number of cells per skewer here to avoid problems with picca.\n relevant_QSOs = []\n for i in range(self.N_qso):\n if np.sum(self.IVAR_rows[i,:]) >= min_number_cells:\n relevant_QSOs += [i]\n\n #Trim data according to the relevant cells and QSOs.\n relevant_TAU_rows = absorber.tau[relevant_QSOs,:]\n relevant_IVAR_rows = self.IVAR_rows[relevant_QSOs,:]\n relevant_LOGLAM_MAP = self.LOGLAM_MAP[:]\n\n #Organise the data into picca-format arrays.\n picca_0 = relevant_TAU_rows.T\n picca_1 = relevant_IVAR_rows.T\n picca_2 = relevant_LOGLAM_MAP\n\n picca_3_data = []\n for i in range(self.N_qso):\n if i in relevant_QSOs:\n picca_3_data += [(self.RA[i],self.DEC[i],self.Z_QSO[i],self.PLATE[i],self.MJD[i],self.FIBER[i],self.MOCKID[i])]\n\n dtype = [('RA', 'f8'), ('DEC', 'f8'), ('Z', 'f8'), ('PLATE', int), ('MJD', 'f8'), ('FIBER', int), ('THING_ID', int)]\n picca_3 = np.array(picca_3_data,dtype=dtype)\n\n #Make the data into suitable HDUs.\n hdu_DELTA = fits.PrimaryHDU(data=picca_0,header=header)\n hdu_iv = fits.ImageHDU(data=picca_1,header=header,name='IV')\n hdu_LOGLAM_MAP = fits.ImageHDU(data=picca_2,header=header,name='LOGLAM_MAP')\n cols_CATALOG = fits.ColDefs(picca_3)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n\n #Combine the HDUs into and HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([hdu_DELTA, hdu_iv, hdu_LOGLAM_MAP, hdu_CATALOG])\n hdulist.writeto(filename,overwrite=overwrite)\n hdulist.close()\n\n return\n\n #Function to save data as a picca flux file.\n def save_as_picca_flux(self,filename,header,min_number_cells=2,mean_F_data=None,rebin_size_hMpc=None):\n\n lya_lambdas = 10**self.LOGLAM_MAP\n\n #Determine the relevant QSOs: those that have relevant cells (IVAR > 0) beyond the first_relevant_cell.\n #We impose a minimum number of cells per skewer here to avoid problems with picca.\n relevant_QSOs = []\n for i in range(self.N_qso):\n if np.sum(self.IVAR_rows[i,:]) >= min_number_cells:\n relevant_QSOs += [i]\n\n # get Lya transmission\n F = self.lya_absorber.transmission()\n\n #Trim data according to the relevant cells and QSOs.\n relevant_F = F[relevant_QSOs,:]\n relevant_IVAR = self.IVAR_rows[relevant_QSOs,:]\n relevant_LOGLAM_MAP = self.LOGLAM_MAP[:]\n relevant_Z = self.Z[:]\n\n #Calculate mean F as a function of z for the relevant cells, then delta_F.\n try:\n mean_F_z_values = mean_F_data[:,0]\n mean_F = mean_F_data[:,1]\n relevant_mean_F = np.interp(relevant_Z,mean_F_z_values,mean_F)\n except ValueError:\n #This is done with a 'hack' to avoid problems with weights summing to zero.\n small = 1.0e-10\n relevant_mean_F = np.average(relevant_F,weights=relevant_IVAR+small,axis=0)\n\n relevant_delta_F = ((relevant_F)/relevant_mean_F - 1)*relevant_IVAR\n\n if rebin_size_hMpc:\n grid_start = self.R[0]\n rebin_map = np.array((self.R - self.R[0])//rebin_size_hMpc,dtype='int')\n new_relevant_delta_F = np.zeros((self.N_qso,max(rebin_map)))\n new_relevant_IVAR = np.zeros((self.N_qso,max(rebin_map)))\n new_Z = np.zeros(max(rebin_map))\n for j in range(max(rebin_map)):\n j_lo = np.argmax(rebin_map==j)\n j_hi = np.argmin(rebin_map==j)\n new_relevant_delta_F[:,j] = np.average(relevant_delta_F[:,j_lo:j_hi],axis=1)\n new_relevant_IVAR[:,j] = (relevant_IVAR[:,j_lo:j_hi] == j_hi - j_lo)\n new_Z[j] = np.average(self.Z[j_lo:j_hi])\n new_relevant_LOGLAM_MAP = np.log(lya*(1+new_Z))\n\n picca_0 = new_relevant_delta_F.T\n picca_1 = new_relevant_IVAR.T\n picca_2 = new_relevant_LOGLAM_MAP\n\n else:\n #Organise the data into picca-format arrays.\n picca_0 = relevant_delta_F.T\n picca_1 = relevant_IVAR.T\n picca_2 = relevant_LOGLAM_MAP\n\n picca_3_data = []\n for i in range(self.N_qso):\n if i in relevant_QSOs:\n picca_3_data += [(self.RA[i],self.DEC[i],self.Z_QSO[i],self.PLATE[i],self.MJD[i],self.FIBER[i],self.MOCKID[i])]\n\n dtype = [('RA', 'f8'), ('DEC', 'f8'), ('Z', 'f8'), ('PLATE', int), ('MJD', 'f8'), ('FIBER', int), ('THING_ID', int)]\n picca_3 = np.array(picca_3_data,dtype=dtype)\n\n #Make the data into suitable HDUs.\n hdu_F = fits.PrimaryHDU(data=picca_0,header=header)\n hdu_iv = fits.ImageHDU(data=picca_1,header=header,name='IV')\n hdu_LOGLAM_MAP = fits.ImageHDU(data=picca_2,header=header,name='LOGLAM_MAP')\n cols_CATALOG = fits.ColDefs(picca_3)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n\n #Combine the HDUs into and HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([hdu_F, hdu_iv, hdu_LOGLAM_MAP, hdu_CATALOG])\n hdulist.writeto(filename)\n hdulist.close()\n\n return\n\n # TODO: Do we really want this? Does it make much sense?\n #Function to save data as a picca velocity file.\n def save_as_picca_velocity(self,filename,header,zero_mean_delta=False,min_number_cells=2,overwrite=False):\n\n lya_lambdas = 10**self.LOGLAM_MAP\n\n #Determine the relevant QSOs: those that have relevant cells (IVAR > 0) beyond the first_relevant_cell.\n #We impose a minimum number of cells per skewer here to avoid problems with picca.\n relevant_QSOs = []\n for i in range(self.N_qso):\n if np.sum(self.IVAR_rows[i,:]) >= min_number_cells:\n relevant_QSOs += [i]\n\n #Trim data according to the relevant cells and QSOs.\n relevant_VEL = self.VEL_rows[relevant_QSOs,:]\n relevant_IVAR = self.IVAR_rows[relevant_QSOs,:]\n relevant_LOGLAM_MAP = self.LOGLAM_MAP[:]\n\n #Organise the data into picca-format arrays.\n picca_0 = relevant_VEL.T\n picca_1 = relevant_IVAR.T\n picca_2 = relevant_LOGLAM_MAP\n\n picca_3_data = []\n for i in range(self.N_qso):\n if i in relevant_QSOs:\n picca_3_data += [(self.RA[i],self.DEC[i],self.Z_QSO[i],self.PLATE[i],self.MJD[i],self.FIBER[i],self.MOCKID[i])]\n\n dtype = [('RA', 'f8'), ('DEC', 'f8'), ('Z', 'f8'), ('PLATE', int), ('MJD', 'f8'), ('FIBER', int), ('THING_ID', int)]\n picca_3 = np.array(picca_3_data,dtype=dtype)\n\n #Make the data into suitable HDUs.\n hdu_VEL = fits.PrimaryHDU(data=picca_0,header=header)\n hdu_iv = fits.ImageHDU(data=picca_1,header=header,name='IV')\n hdu_LOGLAM_MAP = fits.ImageHDU(data=picca_2,header=header,name='LOGLAM_MAP')\n cols_CATALOG = fits.ColDefs(picca_3)\n hdu_CATALOG = fits.BinTableHDU.from_columns(cols_CATALOG,header=header,name='CATALOG')\n\n #Combine the HDUs into and HDUlist and save as a new file. Close the HDUlist.\n hdulist = fits.HDUList([hdu_VEL, hdu_iv, hdu_LOGLAM_MAP, hdu_CATALOG])\n hdulist.writeto(filename,overwrite=overwrite)\n hdulist.close()\n\n return\n\n \"\"\"\n","sub_path":"py/simulation_data.py","file_name":"simulation_data.py","file_ext":"py","file_size_in_byte":70909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48447069","text":"import logging\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef plot_density(calibrator, savefig=None, show=None):\n line_colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', ]\n\n plt.figure(figsize=(20,20), dpi=100)\n\n nclasses = len(calibrator.classes_)\n for icls in range(nclasses):\n x_target = np.arange(0, 1, .01)\n x_other = (1 - x_target) / (nclasses - 1)\n X = np.concatenate([\n np.repeat(x_other, icls).reshape(len(x_other), icls),\n x_target.reshape(len(x_target), 1),\n np.repeat(x_other, nclasses-icls-1).reshape(len(x_other), nclasses-icls-1),\n ], axis=1)\n\n p = calibrator.transform(X)\n plt.plot(x_target, p[:,icls], label=calibrator.classes_[icls], c=line_colors[icls])\n\n plt.legend()\n\n if savefig is not None:\n plt.savefig(savefig)\n if show or savefig is None:\n plt.show()\n\n plt.close()\n\n\ndef plot_lr_histogram(X, y, savefig=None, show=None):\n plt.figure(figsize=(10, 7), dpi=100)\n plt.xlabel('LR')\n plt.ylabel('fractie')\n plt.grid(True, axis='y', linestyle=':')\n plt.grid(True, axis='x', linestyle=':')\n\n rangesize = 4\n binsize = .5\n bins = np.arange(-rangesize - binsize/2., rangesize + binsize/2., binsize)\n\n p_target = X[np.arange(len(X)), y]\n\n plots = []\n labels = []\n weights = []\n for label, cnt in zip(*np.unique(y, return_counts=True)):\n p_cls = p_target[y == label]\n plots.append(np.log10(p_cls / (1-p_cls)))\n labels.append(label)\n weights.append(np.ones(cnt) / cnt)\n\n plt.hist(plots,\n label=labels,\n width=.25, alpha=.5, density=True, stacked=True,\n range=(np.min(bins), np.max(bins)),\n bins=bins,\n weights=weights,\n )\n\n ticks = np.arange(-rangesize, rangesize+1, 1.)\n labels = [ str(f) if f < 1 else str(int(f)) for f in np.power(10, ticks) ]\n plt.xticks(ticks=ticks, labels=labels, rotation=0)\n\n plt.legend()\n if savefig is not None:\n plt.savefig(savefig)\n if show or savefig is None:\n plt.show()\n\n plt.close()\n","sub_path":"lib/lrtools/liar/multiclass/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"309179424","text":"class WordDictionary(object):\n\n class Node:\n def __init__(self, key):\n self.children = {}\n self.char = key\n self.wordEndsHere = False\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = self.Node(\"\")\n \n\n def addWord(self, word):\n \"\"\"\n Adds a word into the data structure.\n :type word: str\n :rtype: void\n \"\"\"\n node = self.root\n for c in word:\n if c in node.children:\n node = node.children[c]\n else:\n node.children[c] = self.Node(c)\n node = node.children[c]\n node.wordEndsHere = True\n \n\n def search(self, word):\n \"\"\"\n Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.\n :type word: str\n :rtype: bool\n \"\"\"\n #stack of tuples (indexOfNextChar, NodeForCurrentChar)\n stack = []\n stack.append((0, self.root))\n while len(stack) > 0:\n tup = stack.pop()\n i = tup[0]\n node = tup[1]\n \n #candidate for the end of a word (not the only possibility if there are wildcard '.')\n if i == len(word):\n #if this candidate is valid, we're done and search can return true\n if node.wordEndsHere:\n return True\n else: \n continue #cant return false here because another branch may meet criteria\n\n #if \"next character\" is a wildcard, push all of \"Current character's\" children to stack\n if word[i] == '.':\n for child in node.children:\n stack.append((i+1, node.children[child])) #i+1 because tuple[0] tracks index of next char\n \n # if its not a wildcard only add the proper character to the stack\n else: \n if word[i] not in node.children:\n continue\n else:\n stack.append((i+1, node.children[word[i]]))\n \n # we never found a valid word so return false\n return False\n\ntest = WordDictionary()\n\ntest.addWord(\"testword\")\nprint(test.search(\"te..wor.\"))","sub_path":"python/WordDictionary.py","file_name":"WordDictionary.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"256806007","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nRobust stability of general discrete-time systems using the P-ellipsoidal norm\n\nThis is a low-level interface. Please use generic_matrix if possible.\n\"\"\"\n\nimport scipy.linalg\nimport numpy\nimport mpmath as mp\nfrom mpmath import iv\nimport math\nimport random\nfrom .memoize_simple import matrix_memoize_simple\n\nfrom .iv_matrix_utils import iv_matrix_mid_to_numpy_ndarray, numpy_ndarray_to_mp_matrix, iv_matrix_to_numpy_ndarray, iv_matrix_mid_as_mp, iv_matrix_inv\n\n\n\ndef iv_spectral_norm_rough(M):\n \"\"\"\n Fast but rough interval bound of spectral norm.\n\n 0 <= spectral_norm(M) <= sqrt(sum of all m[i,k]^2)\n \"\"\"\n norm = iv.norm(M, 2)\n return iv.mpf([0, norm.b])\n\n\ndef iv_spectral_norm(M):\n \"\"\"\n Good interval bound of spectral norm of a (interval) matrix\n\n Theorem 3.2 from\n\n Siegfried M. Rump. “Verified bounds for singular values, in particular for the\n spectral norm of a matrix and its inverse”. In: BIT Numerical Mathematics 51.2\n (Nov. 2010), pp. 367–384. DOI : 10.1007/s10543-010-0294-0.\n \"\"\"\n M = iv.matrix(M)\n # imprecise SVD of M (no requirement on precision)\n # _, _, V_T = mp.svd(iv_matrix_mid_to_mp(M)) # <-- configurable precision\n _, _, V_T = scipy.linalg.svd(iv_matrix_mid_to_numpy_ndarray(M)) # <-- faster\n # in [Rump 2010], SVD is defined as M = U @ S @ V.T,\n # in mpmath it is M = U @ S @ V (not transposed) for U,S,V=svd(M)\n # in scipy it is effectively the same as in mpmath, M = U @ S @ Vh for U,S,Vh = svd(M)\n V = numpy_ndarray_to_mp_matrix(V_T).T\n # now, everything is named as in [Rump2010], except that here, A is called M.\n # all following computations are interval bounds\n V = iv.matrix(V)\n B = M @ V\n BTB = B.T @ B\n # split BTB such that DE = diagonal D + rest E\n D = BTB @ 0\n E = BTB @ 0\n for i in range(BTB.rows):\n for j in range(BTB.cols):\n if i == j:\n D[i,j] = BTB[i,j]\n else:\n E[i,j] = BTB[i,j]\n # upper bound of spectral norm of I - V.T @ V\n alpha = iv_spectral_norm_rough(iv.eye(len(M)) - V.T @ V)\n # upper bound of spectral norm of E\n epsilon = iv_spectral_norm_rough(E)\n # maximum of D[i,i] (which are always >= 0)\n d_max = iv.norm(D, mp.inf)\n if alpha.b >= 1:\n # this shouldn't happen - even an imprecise SVD will roughly have V.T @ V = I.\n raise scipy.linalg.LinAlgError(\"Something's numerically wrong - the singular vectors are far from orthonormal\")\n # should this ever happen in reality, a valid return value would be:\n # return iv.mpf([0, mp.inf])\n try:\n lower_bound = iv.sqrt((d_max - epsilon) / (1 + alpha)).a\n except mp.libmp.libmpf.ComplexResult:\n lower_bound=0;\n # note that d_max, epsilon,alpha are intervals, so everything in the following computation is interval arithmetic\n return iv.mpf([lower_bound, iv.sqrt((d_max + epsilon) / (1 - alpha)).b])\n\n\n\n# TODO move to generic_matrix, this doesn't have to depend on the datatype!\ndef iv_P_norm(M, P_sqrt_T):\n \"\"\"\n interval bound on P-ellipsoid norm of M, defined as max_{x in R^n} sqrt(((M x).T P (M x)) / (x.T P x))\n\n with P_sqrt_T.T @ P_sqrt_T = P, where x.T P x typically is a Lyapunov function\n \"\"\"\n P_sqrt_T = iv.matrix(P_sqrt_T)\n M = iv.matrix(M)\n # P_norm(M) = spectral norm (maximum singular value) of P_sqrt_T A P_sqrt_T**(-1)\n return iv_spectral_norm(iv.matrix(P_sqrt_T) @ M @ iv_matrix_inv(iv.matrix(P_sqrt_T)))\n\n\ndef approx_P_norm(M, P_sqrt_T):\n \"\"\"\n approximation of P-ellipsoid norm of M\n\n @see iv_P_norm()\n \"\"\"\n M = iv_matrix_mid_to_numpy_ndarray(M)\n P_sqrt_T = iv_matrix_mid_to_numpy_ndarray(P_sqrt_T)\n return scipy.linalg.norm(numpy.matmul(P_sqrt_T, numpy.matmul(M, np_matrix_inv(P_sqrt_T))), 2)\n\n\ndef approx_P_sqrt_T(A, tolerance=1e-4):\n \"\"\"\n Compute P_sqrt_T such that approximately iv_P_norm(M, P_sqrt_T) < max(abs(eig(A)))\n\n Will raise an AssertionError if approximately max(abs(eig(A))) >= 1.\n\n @param tolerance: relative factor for numerical tolerance. Decrease with caution. Increasing the tolerance will increase robustness.\n \"\"\"\n A = iv_matrix_mid_as_mp(A)\n eigv_A, _= mp.eig(A)\n max_eigv_A = max([abs(i) for i in eigv_A])\n assert max_eigv_A < (1 - tolerance)\n A = iv_matrix_to_numpy_ndarray(A)\n # eigenvalue scaling of A (without this, we could only guarantee iv_P_norm(M, P_sqrt_T) < 1)\n A = A / float(max_eigv_A) * (1 - tolerance)\n Q = numpy.eye(len(A))\n # scipy solves AXA^H - X + Q = 0 for X.\n # We need the solution of A.T P A - P = -Q, so A must be transposed!\n P = scipy.linalg.solve_discrete_lyapunov(a=A.T, q=Q)\n # check validity of the solution\n # Note that there is no guaranteed tolerance bound. For practical reasons we choose the given tolerance.\n assert numpy.allclose(numpy.matmul(numpy.matmul(A.T, P), A) - P, -Q, atol=tolerance), \"Discrete lyapunov solution inaccurate. Try increasing the tolerance.\"\n # numpy.linalg.cholesky returns lower-triangular L such that L*L.T = P\n # Here, L.T is called P_sqrt_T.\n P_sqrt_T = numpy.linalg.cholesky(P).T\n return numpy_ndarray_to_mp_matrix(P_sqrt_T)\n\nIV_NORM_EVAL_ORDER = 10\n\n@matrix_memoize_simple\ndef _iv_matrix_powers(A):\n \"\"\"\n return the first IV_NORM_EVAL_ORDER+1 powers of A:\n [I, A, A**2, ..., A**(IV_NORM_EVAL_ORDER)]\n \"\"\"\n assert isinstance(A, iv.matrix)\n A = iv.matrix(A) + mp.mpi(0,0) # workaround bug\n A_pow = [iv.eye(len(A))]\n for i in range(IV_NORM_EVAL_ORDER+1):\n A_pow.append(A @ A_pow[-1])\n return A_pow\n\ndef iv_P_norm_expm(P_sqrt_T, M1, A, M2, tau):\n \"\"\"\n Bound on P-ellipsoid norm of (M1 (expm(A*t) - I) M2) for |t| < tau\n\n using the theorem in arXiv:1911.02537, section \"Norm bounding of summands\"\n\n @param P_sqrt_T: see iv_P_norm()\n \"\"\"\n P_sqrt_T = iv.matrix(P_sqrt_T)\n M1 = iv.matrix(M1)\n A = iv.matrix(A)\n M2 = iv.matrix(M2)\n # coerce tau to maximum\n tau = abs(iv.mpf(tau)).b\n # P-ellipsoid norms\n M1_p = iv_P_norm(M=M1, P_sqrt_T=P_sqrt_T)\n M2_p = iv_P_norm(M=M2, P_sqrt_T=P_sqrt_T)\n A_p = iv_P_norm(M=A, P_sqrt_T=P_sqrt_T)\n # A_pow[i] = A ** i\n A_pow = _iv_matrix_powers(A)\n # Work around bug in mpmath, see comment in iv_P_norm()\n zero = iv.matrix(mp.zeros(len(A)))\n M1 = zero + M1\n # terms from [arXiv:1911.02537]\n M1_Ai_M2_p = lambda i: iv_P_norm(M=M1 @ A_pow[i] @ M2, P_sqrt_T=P_sqrt_T)\n gamma = lambda i: 1 / math.factorial(i) * (M1_Ai_M2_p(i) - M1_p * A_p ** i * M2_p)\n max_norm = sum([gamma(i) * (tau ** i) for i in range(1, IV_NORM_EVAL_ORDER + 1)]) + M1_p * M2_p * (iv.exp(A_p * tau) - 1)\n # the lower bound is always 0 (for t=0)\n return mp.mpi([0, max_norm.b])\n\n\n@matrix_memoize_simple\ndef np_matrix_inv(M):\n \"\"\"\n interval matrix inverse, with caching\n \"\"\"\n assert isinstance(M, numpy.ndarray)\n return scipy.linalg.inv(M)\n\ndef approx_P_norm_expm(P_sqrt_T, M1, A, M2, tau):\n \"\"\"\n approximate max ( P_norm( M1 (expm(A*t) - I) M2 ) for |t| < tau )\n\n @param P_sqrt_T: see iv_P_norm()\n \"\"\"\n P_sqrt_T = iv_matrix_mid_to_numpy_ndarray(P_sqrt_T)\n M1 = iv_matrix_mid_to_numpy_ndarray(M1)\n A = iv_matrix_mid_to_numpy_ndarray(A)\n M2 = iv_matrix_mid_to_numpy_ndarray(M2)\n # coerce tau to maximum\n tau = float(mp.mpf(abs(iv.mpf(tau)).b))\n max_norm = 0\n for t in numpy.linspace(-tau, tau, 100):\n matrix = numpy.matmul(M1, numpy.matmul(scipy.linalg.expm(A*t) - numpy.eye(len(A)), M2))\n max_norm = max(max_norm, approx_P_norm(M=matrix, P_sqrt_T=P_sqrt_T))\n return max_norm\n\nif __name__ == \"__main__\":\n random.seed(1234565567)\n print(\"Example: random matrix\")\n for i in range(1):\n c = 2\n A = mp.randmatrix(20) - 0.5\n eigv_A, _= mp.eig(iv_matrix_mid_as_mp(A))\n A = 0.5 * A / max([abs(i) for i in eigv_A])\n\n\n eigv_A, _= mp.eig(iv_matrix_mid_as_mp(A))\n #print('eigenvalues(A) = ', eigv_A)\n print('spectral radius(A) = ', max([abs(i) for i in eigv_A]))\n print('interval spectral_norm(A) = ', iv_spectral_norm(A))\n P_sqrt_T = approx_P_sqrt_T(A)\n print('interval P_norm(A) = ',iv_P_norm(A, P_sqrt_T))\n print('interval P_norm(...expm(...)) = ', iv_P_norm_expm(P_sqrt_T, M1=mp.eye(len(A)), A=A, M2=mp.eye(len(A)), tau=0.01))\n print('sampled P_norm(...expm(...)) = ', approx_P_norm_expm(P_sqrt_T, M1=mp.eye(len(A)), A=A, M2=mp.eye(len(A)), tau=0.01))\n print('')\n\n","sub_path":"src/qronos/lis/norms.py","file_name":"norms.py","file_ext":"py","file_size_in_byte":8525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98681527","text":"import torchsnooper\nimport torch\nimport tensorboardX\nimport os\nimport vnet\nimport random\nimport torch.optim as optim\nimport load_data\nimport numpy as np\nimport torch.nn.functional as F\nimport def_loss\nimport losses\n\ndef make_data(name):\n url_data = name + '/original1'\n url_mask = name + '/vein'\n a,b,c = load_data.load_dicom(url_data)\n a = load_data.normalize_ct_array(a)\n a = load_data.set_window(a,255) #对原始数据做normalized\n e,_,_ = load_data.load_dicom(url_mask)\n a_crop = load_data.crop(a) #crop之后,框出了肺部,切成了小个小个的batch[4,208,336]\n e_crop = load_data.crop(e)\n result = []\n for i in range(len(a_crop)):\n ai = a_crop[i][np.newaxis,:]\n ei = e_crop[i][np.newaxis,:]\n # print('ssasa',np.mean(ei))\n if np.mean(ei) != 0: #说明有object\n result.append((ai,ei))\n elif np.mean(ei) == 0 and random.randint(0,9) > 6: #如果没有object则按照一定比例放进去训练\n result.append((ai,ei))\n print('这套数据分成{}个batch'.format(len(result)))\n return result\n\n# @torchsnooper.snoop()\ndef train(this_epoch,name_list,model):\n global log_step\n model.train()\n nll_weight = torch.tensor([1,100]).float().cuda()\n nums_data = len(name_list)\n for i,name in enumerate(name_list):\n #load data and label\n x_y_data = make_data(name) #n,2,1,4,208,336\n random.shuffle(x_y_data)\n check = np.array(x_y_data)\n print('x y data ====== ',check.shape)\n a_nll_loss = 0\n a_dice = 0\n a_focal_loss = 0\n for batch_i,x_y in enumerate(x_y_data):\n data_x = x_y[0][np.newaxis,:] #data\n data_y = x_y[1][np.newaxis,:] #label\n # image = data_x.type(torch.FloatTensor).cuda()\n image = torch.from_numpy(data_x)\n image = image.type(torch.FloatTensor).cuda()\n # target = data_y.type(torch.FloatTensor).long().cuda()\n target = torch.from_numpy(data_y)\n target = target.type(torch.FloatTensor).cuda()\n optimizer.zero_grad() # 梯度清零\n # with torch.no_grad(): #不求梯度,训练是不能写这句的,测试的时候才写\n output = model(image) # n*2维\n # output = torch.tensor(output,requires_grad=True)\n output = output.clone().detach().requires_grad_(True) # 可求导\n target = target.view(target.numel())\n #nll loss\n \"\"\"\n outputcopy = output\n output0 = outputcopy[:,0]\n output1 = outputcopy[:,1] *100\n sss = torch.stack((output0,output1),0)\n sss = torch.t(sss)\n nll_loss = F.nll_loss(sss,target.long()) #,weight=nll_weight) #weight就没起作用\n a_nll_loss += nll_loss\n print('nll loss weight',nll_loss)\n # log.add_scalar('nll lose1', float(nll_loss),batch_i + i * len(name_list) + this_epoch *(batch_i*len(x_y_data)*len(name_list)))\n\n nll_loss1 = F.nll_loss(output, target.long()) #, weight=nll_weight) # weight就没起作用\n # a_nll_loss += nll_loss1\n print('nll loss1 no weight', nll_loss1)\n \"\"\"\n #bce loss + weight\n #sigmoid\n #weight\n # bceloss_func = torch.nn.CrossEntropyLoss()\n\n #focal loss\n pred_ = output[...,1]\n pred = pred_.clone().detach().requires_grad_(True)\n f_loss = def_loss.focal_loss(pred,target)\n print('focal loss',f_loss)\n log.add_scalar('focal loss',float(f_loss),log_step)\n log_step += 1\n # print('global step',log_step)\n # a_focal_loss += f_loss\n\n dice = losses.dice_loss(output,target)\n a_dice += dice\n print('dice',dice)\n # log.add_scalar('dice1', float(dice),batch_i + i * len(name_list) + this_epoch *(batch_i*len(x_y_data)*len(name_list)))\n\n # loss_func = nll_loss\n loss_func = f_loss\n loss_func.backward()\n optimizer.step()\n\n # log.add_scalar('nll loss',a_nll_loss,i + this_epoch*nums_data)\n # a_nll_loss = 0\n # log.add_scalar('focal loss',a_focal_loss, i +this_epoch*nums_data)\n # a_focal_loss = 0\n log.add_scalar('dice',a_dice,i +this_epoch*nums_data)\n a_dice = 0\n\n\ndef make_test_data(url):\n url_data = url + '/original1'\n url_mask = url + '/vein'\n a,b,c = load_data.load_dicom(url_data)\n a = load_data.normalize_ct_array(a)\n a = load_data.set_window(a,255)\n e,_,_ = load_data.load_dicom(url_mask)\n a_crop = load_data.crop(a,mode='test')\n e_crop = load_data.crop(e,mode='test')\n result = []\n for k in range(len(a_crop)):\n ak = a_crop[k][np.newaxis,:]\n ek = e_crop[k][np.newaxis,:]\n result.append((ak,ek))\n print('这套测试数据分成{}个batch'.format(len(result)))\n return result\n\n\ndef test(this_epoch,datalist,model):\n global test_step\n print('====================test=========================')\n model.eval()\n nums_test_data = len(datalist)\n for j,path in enumerate(datalist):\n xydata = make_test_data(path)\n random.shuffle(xydata)\n t_nll_loss = 0\n t_dice = 0\n for batch_k,x_y in enumerate(xydata):\n data_x = x_y[0][np.newaxis,:]\n data_y = x_y[1][np.newaxis,:]\n image = torch.from_numpy(data_x)\n image = image.type(torch.FloatTensor).cuda()\n # target = data_y.type(torch.FloatTensor).long().cuda()\n target = torch.from_numpy(data_y)\n target = target.type(torch.FloatTensor).cuda()\n target = target.view(target.numel())\n optimizer.zero_grad() # 梯度清零\n with torch.no_grad(): #不求梯度,训练是不能写这句的,测试的时候才写\n output = model(image) # n*2维 #sigmoid -> focal loss\n #nll loss\n \"\"\"\n outputcopy = output\n output0 = outputcopy[:, 0]\n output1 = outputcopy[:, 1] * 1000\n sss = torch.stack((output0, output1), 0)\n sss = torch.t(sss)\n nll_loss = F.nll_loss(sss, target.long()) # ,weight=nll_weight) #weight就没起作用\n t_nll_loss += nll_loss\n print('test nll loss weight', nll_loss)\n\n nll_loss1 = F.nll_loss(output, target.long()) # , weight=nll_weight) # weight就没起作用\n # a_nll_loss += nll_loss1\n print('nll loss1 no weight', nll_loss1)\n \"\"\"\n # focal loss\n pred_ = output[..., 1]\n pred = pred_.clone().detach().requires_grad_(True)\n f_loss = def_loss.focal_loss(pred, target)\n print('test focal loss', f_loss)\n log.add_scalar('test focal loss', float(f_loss), test_step)\n test_step += 1\n # print('global step', test_step)\n\n dice = losses.dice_loss(output, target)\n t_dice += dice\n print('test dice', dice)\n\n # print('this data nll loss',t_nll_loss)\n # log.add_scalar('test nll loss', t_nll_loss, j + this_epoch * nums_test_data)\n # t_nll_loss = 0\n print('this data dice ',t_dice)\n log.add_scalar('test dice', t_dice, j + this_epoch * nums_test_data)\n t_dice = 0\n\nif __name__ == '__main__':\n CUDA_VISIBLE_DEVICES = 1\n MIN_BOUND = 0\n MAX_BOUND = 800\n CROP_SIZE = [4, 208, 336]\n EPOCH = 100\n LR = 0.0001 * 5\n model = vnet.VNet(elu=False, nll=False)\n # model.load_state_dict(torch.load('param_save4/vnet_params5.pkl'))\n # model.load_state_dict(torch.load('param_save6/vnet_params36.pkl'))\n # model.load_state_dict(torch.load('param_save8/vnet_params16.pkl'))\n model.load_state_dict(torch.load('param_save9/vnet_params8.pkl'))\n model.cuda()\n\n # log = tensorboardX.SummaryWriter('./logssss/logtry')\n log = tensorboardX.SummaryWriter('./logssss/log10')\n log_step = 0\n test_step = 0\n # global log_step\n #文件list,并打乱\n train_Data_list = '/home/hym/hym/vessel_train_data' #all in\n # train_Data_list ='/home/hym/Documents/vessel_data/train_data' #一套数据\n names = os.listdir(train_Data_list)\n url_list = [train_Data_list + '/' + name for name in names]\n print(url_list)\n print('训练数据{}套'.format(len(url_list)))\n\n #test list\n test_Data_list = '/home/hym/Documents/vessel_data/test_data'\n test_ = os.listdir(test_Data_list)\n test_url = [test_Data_list + '/' + tt for tt in test_]\n print('测试数据{}套'.format(len(test_url)))\n\n\n #train\n # model_save_path = 'param_save_try'\n model_save_path = 'param_save10'\n if not os.path.exists(model_save_path):\n os.makedirs(model_save_path)\n for epo in range(EPOCH):\n model.train()\n print('================================================================')\n print('epoch {}'.format(epo))\n if epo % 5 == 0:\n LR /= 2\n log.add_scalar('learning rate',float(LR),epo)\n optimizer = optim.Adam(model.parameters(), lr=LR)\n random.shuffle(url_list) # 每一个epoch之前打乱数据顺序\n this_list = url_list\n train(epo,this_list,model)\n params = model.state_dict()\n torch.save(params, model_save_path + '/vnet_params{}.pkl'.format(epo))\n\n #test\n testlist = test_url\n test(epo,testlist,model)\n","sub_path":"train_vein.py","file_name":"train_vein.py","file_ext":"py","file_size_in_byte":9524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"175893581","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nfrom operator import itemgetter\n\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom demands import getDMItems\n\nallnumbers = re.compile(\"^[0-9]+$\")\nTHIS_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef Emailer(data, subject, recipient):\n import win32com.client as win32\n env = Environment(loader=FileSystemLoader(THIS_DIR))\n template = env.get_template('New_DM_ProdMgrs.html')\n template.render(data)\n\n outlook = win32.Dispatch('outlook.application')\n mail = outlook.CreateItem(0)\n mail.To = recipient\n mail.Subject = subject\n mail.HtmlBody = template.render(data)\n mail.send\n\n\nDMitems = getDMItems('DM') # fetch DM items from sharepoint\n\nfor dm in DMitems:\n if dm is None:\n continue\n for name in ['Solution', 'Counterparty', 'Next Action Owner', 'Other Clients']:\n dm[name] = dm[name] or ''\n dm['prio'] = re.sub(\"[0-9] - \", '', (dm['Requestor Priority'] or '?'))\n dm['Workload'] = '?' if dm['Workload'] is None else str(float(dm['Workload']))\n dm['Wished Availability Date'] = '?' if dm['Wished Availability Date'] is None else dm['Wished Availability Date'][\n :10]\n for field in ['Domain', 'Counterparty', 'Other Clients', 'Next Action Owner']:\n dm[field + 'list'] = [] if dm[field] is None else [x for x in dm[field].split(\";#\") if\n not (allnumbers.match(x))]\n dm[field + 'listtxt'] = \", \".join(dm[field + 'list'])\n\ndata = {'mid3x': []}\ndms = []\n\n# NEW Mid3x DEMANDS\ndef NewMid3xDMfilter(dm):\n if dm is None:\n return False\n if (dm['Demand Status'][:4] != '0000' or\n dm['Solution'][:14] == 'Platform Large' or\n dm['Counterparty'].find('1001;#La Banque Postale') != -1 or\n dm['Counterparty'].find('202;#BNPP') != -1 or\n dm['Demand Type'] != 'Reactive'):\n return False\n return True\n\n\n\nNewMid3xDMs = [x for x in DMitems if NewMid3xDMfilter(x)]\nNewMid3xDMs = sorted(NewMid3xDMs, key=itemgetter('Domain', 'Next Action Owner', 'ID'))\n\nolddomain = ''\nfor dm in NewMid3xDMs:\n domain = dm['Domainlisttxt']\n if domain != olddomain:\n if olddomain != '':\n data['mid3x'].append({'domains': olddomain, 'demands': dms})\n dms = []\n olddomain = domain\n dms.append(dm)\nif olddomain != '':\n data['mid3x'].append({'domains': olddomain, 'demands': dms})\n\nEmailer(data, 'New MidSize demands per domain', 'koen.beek@soprabanking.com')\n","sub_path":"demands/Send_New_DM_ProdMgrs.py","file_name":"Send_New_DM_ProdMgrs.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128173194","text":"import importlib\nfrom base64 import b64encode\nfrom glob import glob\nfrom json import loads\nfrom random import randint\nfrom shutil import rmtree\n\nimport os\nfrom pymongo import MongoClient\n\nfrom taskman.utils import create_token, fs_name_cleaner\nfrom tests import conf_contents\n\n\ndef init_settings(test_settings_module_name):\n settings_module = importlib.import_module(\"taskman.settings\")\n test_settings_module = importlib.import_module(test_settings_module_name)\n settings = getattr(settings_module, \"settings\")\n test_settings = getattr(test_settings_module, \"settings\")\n settings.update(test_settings)\n return settings\n\n\nclass EveEndpointTestTools(object):\n def __init__(self, extra=None):\n\n self.pilot = dict(\n username=\"pilot\",\n password=\"$2b$12$/3lP7yZ8Rx4O0rmDWW/lbOwO6kNd/VNLl.KNTh/aSmPAdg0zJ3gnC\",\n email=\"pilot@fakemail.ts\",\n roles=\"admin\"\n )\n self.endpoint = os.environ[\"STAGE\"].split(\"_\")[0].lower()\n self.cwd = os.getcwd()\n testing_settings = os.environ[\"STAGE_SETTINGS\"]\n self.settings = init_settings(testing_settings)\n self.fixtures = os.path.join(self.cwd, self.settings[\"CONFIG_DIR\"])\n self.create_conf(extra=extra)\n self.db, self.connection = self.init_db()\n self.app = importlib.import_module(\"taskman.app\").app\n self.pilot_id, self.pilot_token = self.insert_pilot()\n self.auth_url = self.settings[\"TEST_HOST\"] + self.settings[\"TOKEN_URL\"]\n\n def in_fixtures(self, fname):\n return os.path.join(os.getcwd(), self.fixtures, fname)\n\n def api_url(self, endpoint=\"\", embedded=\"\"):\n if embedded:\n embedded = '?embedded={\"%s\":1}' % embedded\n return self.settings[\"TEST_HOST\"] + \"/\" + self.settings[\"URL_PREFIX\"] + \"/\" + (\n endpoint or self.endpoint) + embedded\n\n def item_url(self, lookup, endpoint=\"\", embedded=\"\"):\n if embedded:\n embedded = '?embedded={\"%s\":1}' % embedded\n return self.api_url(endpoint) + \"/\" + lookup + \"/\" + embedded\n\n def auth_header(self, username, password, pilot_id=\"\"):\n return {\n \"Content-Type\": \"application/json\",\n 'Authorization': 'Basic ' + b64encode(\"{0}:{1}\".format(username, password)),\n \"client_id\": pilot_id or self.pilot_id\n }\n\n def token_header(self, token=\"\", item=None):\n header = {\n \"Content-Type\": \"application/json\",\n 'Authorization': 'Basic ' + b64encode(\"{0}:{1}\".format(token or self.pilot_token, \"\"))\n }\n if item:\n header.update(item)\n return header\n\n def make_fixture_dir(self):\n if not os.path.isdir(os.path.join(os.getcwd(), self.fixtures)):\n os.makedirs(os.path.join(os.getcwd(), self.fixtures))\n\n def create_conf(self, extra=None):\n self.make_fixture_dir()\n conf = self.endpoint + \"_conf_content\"\n if hasattr(conf_contents, conf):\n fname = self.endpoint + self.settings[\"CONFIG_EXT\"]\n conf_fh = open(self.in_fixtures(fname), \"w\")\n conf_fh.write(getattr(conf_contents, conf))\n conf_fh.close()\n if extra and len(extra):\n for xconf in extra:\n fname = xconf + self.settings[\"CONFIG_EXT\"]\n xconf += \"_conf_content\"\n conf_fh = open(self.in_fixtures(fname), \"w\")\n if not hasattr(conf_contents, xconf):\n continue\n conf_fh.write(getattr(conf_contents, xconf))\n conf_fh.close()\n\n def clean_conf(self):\n confs = glob(self.in_fixtures(\"*.conf\"))\n for conf in confs:\n os.remove(conf)\n\n def insert_pilot(self):\n users = self.db[\"users\"]\n pilot_id = str(users.insert(self.pilot))\n pilot = users.find_one({\"email\": self.pilot[\"email\"]})\n pilot_token = create_token(pilot, self.settings[\"SECRET_KEY\"])\n users.update({\"email\": pilot[\"email\"]}, {\"$set\": {\"token\": pilot_token}})\n return pilot_id, pilot_token\n\n def init_db(self):\n connection = MongoClient('localhost', 27017)\n dbnames = connection.database_names()\n if self.settings[\"MONGO_DBNAME\"] in dbnames:\n connection.drop_database(\"mongo_test\")\n db = connection[self.settings[\"MONGO_DBNAME\"]]\n return db, connection\n\n def get_db(self, name=\"\"):\n return self.db[name or self.endpoint]\n\n def clean_db(self):\n self.connection.drop_database(self.settings[\"MONGO_DBNAME\"])\n\n def clean_dirs(self, dirs=None):\n if dirs:\n if type(dirs) is str:\n dirs = [dirs]\n for d in dirs:\n if os.path.isdir():\n rmtree(d)\n return\n dirs = glob(self.in_fixtures(\"__*__\"))\n for d in dirs:\n rmtree(d)\n\n @staticmethod\n def parse_response(resp):\n return loads(resp.data) if getattr(resp, \"data\", None) else dict(), resp.status_code\n\n @staticmethod\n def bulk_users(un=4):\n bulk_test_users = []\n roles = [\"admin\", \"superuser\", \"user\"]\n for user_index in range(1, un + 1):\n bulk_test_users.append({\n \"username\": \"test_user \" + str(user_index),\n \"password\": \"test_password\" + str(user_index),\n \"email\": \"test_email\" + str(user_index) + \"@fakemail.ts\",\n \"roles\": roles[randint(0, 2)]\n })\n return bulk_test_users\n\n def insert_bulk_users(self, un=4):\n return self.get_db(\"users\").insert(self.bulk_users(un))\n\n @staticmethod\n def bulk_clients(cn=4, bn=2):\n \"\"\"\n\n :rtype: list\n \"\"\"\n bulk_clients = []\n for client_index in range(1, cn + 1):\n bulk_brands = []\n for brand_index in range(1, bn + 1):\n bulk_brands.append(\n {\n \"name\": \"brand\" + str(brand_index) + \" of client\" + str(client_index),\n \"short\": \"BR\" + str(brand_index)\n }\n )\n current_client = {\n \"name\": \"test_client \" + str(client_index),\n \"short\": \"CL\" + str(client_index),\n \"brands\": list(bulk_brands)\n }\n bulk_clients.append(current_client)\n return bulk_clients\n\n def insert_bulk_clients(self, cn=4, bn=2):\n bulk = self.bulk_clients(cn, bn)\n for c in bulk:\n # noinspection PyTypeChecker\n c[\"root_dir_name\"] = fs_name_cleaner(c[\"name\"])\n return self.get_db(\"clients\").insert(bulk)\n\n def bulk_profiles(self, pn=4):\n bulk_users = self.insert_bulk_users(pn)\n bulk_users_ids = [str(u) for u in bulk_users]\n bulk_test_profiles = []\n position = [\"test_pos1\", \"test_pos2\", \"test_pos3\"]\n department = [\"test_depart1\", \"test_depart2\", \"test_depart3\"]\n for profile_index in range(1, pn + 1):\n bulk_test_profiles.append({\n \"user\": {\n \"_id\": bulk_users_ids[profile_index - 1]\n },\n \"secondary_email\": \"secondary%s@fakemail.ts\" % str(profile_index),\n \"position\": position[randint(0, 2)],\n \"department\": department[randint(0, 2)],\n \"full_name\": {\n \"first_name\": \"test%s\" % str(profile_index),\n \"last_name\": \"profile%s\" % str(profile_index)\n },\n \"phone\": \"070123456%s\" % str(profile_index),\n \"secondary_phone\": \"077654321%s\" % str(profile_index)\n })\n return bulk_test_profiles\n\n def insert_bulk_profiles(self, pn=4):\n return self.get_db().insert(self.bulk_profiles(pn))\n\n def insert_endpoint_pilot(self, data=None, fields=None, endpoint=\"\"):\n if not data:\n data = getattr(self, \"test_\" + (self.endpoint[:-1] if self.endpoint.endswith(\"s\") else self.endpoint))\n if fields:\n for field in fields:\n db = self.get_db(field[\"endpoint\"])\n target = db.find_one(field[\"query\"])\n data[field[\"name\"]] = target[field[\"target\"]]\n return self.get_db(endpoint).insert(data)\n\n def fs_check(self, dirs, root=\"\"):\n for d in dirs:\n if not os.path.isdir(\n os.path.join(self.cwd, root, d)\n ):\n return False\n return True\n\n def create_compound_index(self, asc_field, desc_field):\n from pymongo import ASCENDING, DESCENDING\n self.get_db().create_index(\n [\n (asc_field, ASCENDING),\n (desc_field, DESCENDING)\n ], unique=True)\n\n @staticmethod\n def objId_to_list(lst):\n out = []\n for l in lst:\n out.append({\"_id\": str(l)})\n return out\n\n\nclass EVEFunctionalTestTools(object):\n def __init__(self, settings=\"\"):\n self.target = os.getenv(\"STAGE\", None).split(\"_\")[0].lower()\n self.cwd = os.getcwd()\n self.settings = init_settings(settings)\n self.fixtures = os.path.join(self.cwd, self.settings[\"CONFIG_DIR\"])\n self.create_conf()\n\n def in_fixtures(self, fname):\n return os.path.join(os.getcwd(), self.fixtures, fname)\n\n def create_conf(self, fname=\"\", content=\"\"):\n\n fname = fname or self.target + self.settings[\"CONFIG_EXT\"]\n content = content or getattr(conf_contents, self.target + \"_conf_content\")\n conf_fh = open(self.in_fixtures(fname), \"w\")\n conf_fh.write(content)\n conf_fh.close()\n return\n\n def empty_conf(self):\n confs = glob(self.in_fixtures(\"*.conf\"))\n for conf in confs:\n os.remove(conf)\n\n def replace_in_conf(self, srch, repl, fname=\"\"):\n fname = fname or self.target + self.settings[\"CONFIG_EXT\"]\n fh = open(self.in_fixtures(fname), \"r+\")\n content = fh.read().replace(srch, repl)\n fh.write(content)\n fh.close()\n\n def clean_conf(self):\n confs = glob(self.in_fixtures(\"*.conf\"))\n for conf in confs:\n os.remove(conf)\n","sub_path":"tests/eve_testing_tools.py","file_name":"eve_testing_tools.py","file_ext":"py","file_size_in_byte":10195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"502595949","text":"import re\nimport struct\nfrom enum import IntEnum\nfrom typing import Union, Tuple, List, Optional\nfrom cobs import cobs\nfrom crcmod import crcmod\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass PacketID(IntEnum):\n \"\"\"\n Class containing BPL packet IDs.\n Look in The Serial Protocol Document for comprehensive details on packet ids.\n\n Packet IDs:\n\n \"\"\"\n MODE = 0x01\n \"1 byte - Describes the Mode of a device\"\n VELOCITY = 0x02\n \"1 float - Describes the velocity of a device. Radians/s for angular joints. mm/s for linear joints.\"\n POSITION = 0x03\n \"1 float - Describes the position of a device. In radians or mm\"\n CURRENT = 0x05\n \"1 float - Describes the current drawn by a device in mA\"\n RELATIVE_POSITION = 0x0E\n \"1 float - When sent sets the relative position of actuator. The actuator will move from its current position the amount specified in the data.\"\n INDEXED_POSITION = 0x0D\n \"1 float - On first receiving indexed position an offset is created between the indexed position demand received and the current position. New indexed positions packets then move the actuators relative to the initial indexed position. \"\n REQUEST = 0x60\n \"bytes - Request a packet ID. On receiving the command, the device will send the packet corresponding to the packet IDs in the data field.\"\n SERIAL_NUMBER = 0x61\n \"1 float - The unique serial number of the device\"\n MODEL_NUMBER = 0x62\n \"1 float - The model number of the device\"\n TEMPERATURE = 0x66\n \"1 float - The internal temperature in Celsius\"\n SOFTWARE_VERSION = 0x6C\n \"3 bytes - The software version on the device\"\n KM_END_POS = 0xA1\n \"6 floats - Request the current end effector position. (X, Y, Z, Y, P, R) in mm and radians. Only for kinematic enabled arms.\"\n KM_END_VEL = 0xA2\n \"6 floats - Demand the end effector velocity (XYZ, RZ, RY, RX) in mm/s and rads/s. Only for kinematic enabled arm. Rotation commands (RZ, RY, RX) is only available for 7 function arms.\"\n KM_END_VEL_LOCAL = 0xCB\n \"6 floats - Demand the end effector velocity relative to the end effector. (XYZ, RZ, RY, RX) in mm/s and rads/s. Only fora kinematic enabled arm. Rotation commands (RZ, RY, RX) is only available for 7 function arms.\"\n KM_BOX_OBSTACLE_02 = 0xA5\n \"6 floats - (X1, Y1, Z1, X2, Y2, Z2) mm. Box obstacle defined by 2 opposite corners of a rectangular prism. \"\n KM_BOX_OBSTACLE_03 = 0xA6\n KM_BOX_OBSTACLE_04 = 0xA7\n KM_BOX_OBSTACLE_05 = 0xA8\n KM_CYLINDER_OBSTACLE_02 = 0xAB\n \"7 floats - (X1, Y1, Z1, X2, Y2, Z2, R) mm. Cylinder obstacle defined by 2 opposite centers of a cylinder. R defining the radius of the cylinder\"\n KM_CYLINDER_OBSTACLE_03 = 0xAC\n KM_CYLINDER_OBSTACLE_04 = 0xAD\n KM_CYLINDER_OBSTACLE_05 = 0xAE\n\n VOLTAGE = 0x90\n \"1 float - The supply voltage in Volts\"\n SAVE = 0x50\n \"1 byte - Send this to save user configurable settings on a device\"\n HEARTBEAT_FREQUENCY = 0x92\n \"1 byte - set the frequency of a packet to be sent from a device.\"\n HEARTBEAT_SET = 0x91\n \"10 bytes - Specify the Packet IDs to be sent via heartbeat.\"\n POSITION_LIMITS = 0x10\n \"2 floats - Maximum and Minimum positions of the device\"\n VELOCITY_LIMITS = 0x11\n \"2 floats - Maximum and Minimum velocities of the device\"\n CURRENT_LIMITS = 0x12\n \"2 floats - Maximum and Minimum currents of the device\"\n\n ATI_FT_READING = 0xD8\n \"6 floats - Read force in N and Torque in Nm from the Force torque sensor. (FX, FY, FZ, TX, TY, TZ). Send this packet to the FT Sensor to Tare it\"\n BOOTLOADER = 0xFF\n\n\nclass BPLProtocol:\n \"\"\"Class used to encode and decode BPL packets.\"\"\"\n CRC8_FUNC = crcmod.mkCrcFun(0x14D, initCrc=0xFF, xorOut=0xFF)\n\n @staticmethod\n def packet_splitter(buff: bytes) -> Tuple[List[bytes], Optional[bytes]]:\n \"\"\"\n Split packets coming in along bpl protocol, Packets are split at b'0x00'.\n\n :param buff: input buffer of bytes\n :return: List of bytes separated by 0x00, and a remaining bytes of an incomplete packet.\n \"\"\"\n incomplete_packet = None\n packets = re.split(b'\\x00', buff)\n if buff[-1] != b'0x00':\n incomplete_packet = packets.pop()\n return packets, incomplete_packet\n\n @staticmethod\n def parse_packet(packet_in: Union[bytes, bytearray]) -> Tuple[int, int, bytes]:\n \"\"\"\n Parse the packet returning a tuple of [int, int, bytes].\n If unable to parse the packet, then return 0,0,b''.\n :param packet_in: bytes of a full packet\n :return: device_id, packet_id, data in bytes.\n \"\"\"\n\n packet_in = bytearray(packet_in)\n\n if packet_in and len(packet_in) > 3:\n try:\n decoded_packet: bytes = cobs.decode(packet_in)\n except cobs.DecodeError as e:\n logger.warning(f\"parse_packet(): Cobs Decoding Error, {e}\")\n return 0, 0, b''\n\n if decoded_packet[-2] != len(decoded_packet):\n logger.warning(f\"parse_packet(): Incorrect length: length is {len(decoded_packet)} \"\n f\"in {[hex(x) for x in list(decoded_packet)]}\")\n return 0, 0, b''\n else:\n if BPLProtocol.CRC8_FUNC(decoded_packet[:-1]) == decoded_packet[-1]:\n rx_data = decoded_packet[:-4]\n\n device_id = decoded_packet[-3]\n packet_id = decoded_packet[-4]\n rx_data = rx_data\n return device_id, packet_id, rx_data\n else:\n logger.warning(f\"parse_packet(): CRC error in {[hex(x) for x in list(decoded_packet)]} \")\n return 0, 0, b''\n return 0, 0, b''\n\n @staticmethod\n def encode_packet(device_id: int, packet_id: int, data: Union[bytes, bytearray]):\n \"\"\"\n Encode the packet using the bpl protocol.\n\n :param device_id: Device ID\n :param packet_id: Packet ID\n :param data: Data in bytes\n :return: bytes of the encoded packet.\n \"\"\"\n tx_packet = bytes(data)\n tx_packet += bytes([packet_id, device_id, len(tx_packet)+4])\n tx_packet += bytes([BPLProtocol.CRC8_FUNC(tx_packet)])\n packet: bytes = cobs.encode(tx_packet) + b'\\x00'\n return packet\n\n @staticmethod\n def decode_floats(data: Union[bytes, bytearray]) -> List[float]:\n \"\"\"\n Decode a received byte list, into a float list as specified by the bpl protocol\n\n Bytes are decoded into 32 bit floats.\n\n :param data: bytes, but be divisible by 4.\n :return: decoded list of floats\n \"\"\"\n list_data = list(struct.unpack(str(int(len(data)/4)) + \"f\", data))\n return list_data\n\n @staticmethod\n def encode_floats(float_list: List[float]) -> bytes:\n \"\"\" Encode a list of floats into bytes\n\n Floats are encoded into 32 bits (4 bytes)\n\n :param float_list: list of floats\n :return: encoded bytes\n \"\"\"\n data = struct.pack('%sf' % len(float_list), *float_list)\n return data\n\n\nclass PacketReader:\n \"\"\"\n Packet Reader\n Helper class to read and decode incoming bytes and account for the incomplete packets.\n\n\n\n \"\"\"\n incomplete_packets = b''\n\n def receive_bytes(self, data: bytes) -> List[Tuple[int, int, bytes]]:\n \"\"\"\n Decodes packets.\n Accounts for reading incomplete bytes.\n\n :param data: input bytes\n :return: a list of of decoded packets (Device ID, Packet ID, data (in bytes))\n \"\"\"\n # Receive data, and return a decoded packet\n packet_list = []\n encoded_packets, self.incomplete_packets = BPLProtocol.packet_splitter(self.incomplete_packets + data)\n if encoded_packets:\n for encoded_packet in encoded_packets:\n if not encoded_packet:\n continue\n decoded_packet = BPLProtocol.parse_packet(encoded_packet)\n packet_list.append(decoded_packet)\n return packet_list\n","sub_path":"bplprotocol/bplprotocol/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"439809759","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: quay_mirror\nshort_description: Create a Quay Mirror\ndescription:\n - Create and update a mirror in Quay.io or Quay Enterprise.\nversion_added: \"2.9\"\nauthor: \"Sean nelson (@audiohacked)\"\noptions:\n auth:\n description:\n - Quay OAuth token. Can be specified in C(QUAY_API_KEY), C(QUAY_API_TOKEN), or C(QUAY_OAUTH_TOKEN) environment variables\n aliases: ['API_TOKEN']\n required: True\n state:\n description:\n - Indicate desired state of the target.\n default: enabled\n choices: ['enabled', 'disabled']\n name:\n description:\n - String, this is the name of the repo.\n is_enabled:\n description:\n - Enables the mirror Sync\n external_registry_config:\n options:\n proxy:\n options:\n https_proxy:\n description:\n - String, HTTPS Proxy\n http_proxy:\n description:\n - String, HTTP Proxy\n no_proxy:\n description:\n - String, No Proxy\n external_registry_username:\n description:\n - String, Username for External Registry\n external_registry_password:\n description:\n - String, Password for External Registry\n external_reference:\n description:\n - String, Location to Mirror\n sync_start_date:\n description:\n - String, ISO8601 Datetime\n root_rule:\n options:\n rule_type: \"TAG_GLOB_CSV\",\n description:\n - String, Required, Support\n rule_value:\"string\"\n sync_interval:\n description:\n - Integer, Sync Interval\n robot_username:\n description:\n - String, Robot Username\nrequirements:\n - \"python >= 2.7\"\n'''\n\n\nEXAMPLES = '''\n- name: create a mirror\n quay_mirror:\n auth: XXX\n name: repo_name\n state: present\n register: my_repo\n\n- debug:\n msg: \"ID is {{ my_repo.data.repo.id }}\"\n\n- name: ensure a mirror is present\n quay_repo:\n auth: XXX\n name: repo_name\n state: present\n'''\n\n\nRETURN = '''\n# Quay.io API info https://docs.quay.io/api/swagger/\n\n'''\n\nimport traceback\n\nfrom ansible.module_utils.basic import AnsibleModule, env_fallback\nfrom ansible.module_utils.quay.auth import QuayHelper # pylint: disable=import-error, no-name-in-module\nfrom ansible.module_utils.quay.mirror import QuayMirror # pylint: disable=import-error, no-name-in-module\n\n\ndef main():\n def _enable():\n result[\"original_message\"] = \"Enabling Mirror: %s\" % repo_name\n\n module.params.update(dict(\n is_enabled=True,\n ))\n\n # Make Change\n body = dict(module.params)\n result['data'] = quay_repo.create_mirror(repo_name, body)\n\n # Validate Change\n check = quay_repo.fetch_mirror(repo_name)\n if check['body']['is_enabled'] is False:\n module.fail_json(msg=\"Mirror Enablement Failed!\")\n else:\n result['message'] = \"Mirror Enabled!\"\n result['changed'] = True\n module.exit_json(**result)\n\n def _disable():\n result[\"original_message\"] = \"Disabling Mirror: %s\" % repo_name\n\n module.params.update(dict(\n is_enabled=False,\n ))\n\n # Make Change\n body = dict(module.params)\n result['data'] = quay_repo.update_mirror(repo_name, body)\n\n # Validate Change\n check = quay_repo.fetch_mirror(repo_name)\n if check['body']['is_enabled'] is False:\n result['message'] = \"Mirrror Disabled!\"\n result['changed'] = True\n else:\n module.fail_json(msg=\"Mirror Disablement Failed!\")\n module.exit_json(**result)\n\n argument_spec = dict(\n # Quay API parameters\n auth=dict(type='str', fallback=(env_fallback, ['QUAY_AUTH_TOKEN'])),\n endpoint=dict(type='str', default='quay.io'),\n\n # Ansible parameters\n name=dict(type='str', required=True),\n state=dict(type='str', default='enabled', choices=['disabled', 'enabled']),\n\n # Creation parameters\n # is_enabled: true\n external_registry_config=dict(type='dict', default='{}', options=dict(\n proxy=dict(type='dict', default='{}', options=dict(\n https_proxy=dict(type='str', default=''),\n http_proxy=dict(type='str', default=''),\n no_proxy=dict(type='str', default='')\n ))\n )),\n external_registry_username=dict(type='str', default=''),\n external_registry_password=dict(type='str', default=''),\n external_reference=dict(type='str'),\n sync_start_date=dict(type='str'),\n root_rule=dict(type='dict', options=dict(\n rule_type=dict(type='str', default='TAG_GLOB_CSV'),\n rule_value=dict(type='str', required=True)\n )),\n sync_interval=dict(type='int'),\n robot_username=dict(type='str'),\n )\n\n result = dict(\n changed=False,\n original_message='',\n message='',\n )\n\n module = AnsibleModule(\n argument_spec=argument_spec,\n required_one_of=(['name']),\n required_if=([\n ('state', 'enabled', ['external_reference', 'root_rule']),\n ]),\n supports_check_mode=True,\n )\n\n if module.check_mode:\n module.exit_json(**result)\n\n try:\n state = module.params.pop('state')\n auth = module.params.pop('auth')\n endpoint = module.params.pop('endpoint')\n repo_name = module.params.pop('name')\n\n quay_helper = QuayHelper(module, auth, endpoint)\n quay_repo = QuayMirror(module, quay_helper)\n\n repo_exists = quay_repo.exists(repo_name)\n\n if repo_exists is False:\n module.fail_json(msg=\"Repository Missing!\")\n\n if state == 'enabled':\n _enable()\n elif state == 'disabled':\n _disable()\n else:\n module.fail_json(msg=\"Invalid given state!\")\n except Exception as e:\n module.fail_json(msg=str(e), exception=traceback.format_exc())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"library/quay_mirror.py","file_name":"quay_mirror.py","file_ext":"py","file_size_in_byte":6299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152262796","text":"from .utils import get_data_path\nimport pandas as pd\nimport os\nimport pickle\n\n\ndef read_csv(p_filename, p_io_folder, p_sub_folder=\"\"):\n \"\"\"Read a csv file under given path which is created from params.\n\n e.g. Used for nuremberg.csv, trips.csv, features.csv\n Return the file or an error.\n Args:\n p_filename (str): String of the filename of csv\n p_io_folder (str): String that differentiates between input and output folder\n p_sub_folder (str): String that contains the subfolder after input or output folder => if not given none\n Returns:\n df (DataFrame): DataFrame which is created from the read csv\n \"\"\"\n path = os.path.join(get_data_path(), p_io_folder, p_sub_folder, p_filename)\n try:\n # index_col=0 throws numpy warning,\n # so we set it manually after reading in the file\n df = pd.read_csv(path)\n print(\"Read:\", path)\n if \"Unnamed: 0\" in df.columns:\n df = df.rename({\"Unnamed: 0\": \"index\"}, axis=1)\n if \"index\" in df.columns:\n df = df.set_index(\"index\")\n else:\n df = df.set_index(df.columns[0])\n\n return df\n except FileNotFoundError:\n print(\"Data file not found. Path was \" + path)\n\n\ndef read_object(p_filename):\n \"\"\"Read a pickle file which contains an object and returns it.\n\n e.g. Used for ML models, PCA, Scaler\n Return the file in data/output/models/*p_filename.pkl* or an error.\n Args:\n p_filename (str): String of the filename of pickle\n Returns:\n my_object (Object): Object which is read by pickle\n \"\"\"\n path = os.path.join(get_data_path(), \"output\", \"models\", p_filename)\n with open(path, \"rb\") as f:\n my_object = pickle.load(f)\n print(\"Read:\", path)\n return my_object\n","sub_path":"nextbike/io/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129823687","text":"from PyQt4 import QtGui\r\nimport os, sys\r\nimport ntpath,eyed3\r\n\r\nclass PrettyWidget(QtGui.QWidget):\r\n \r\n def __init__(self):\r\n super(PrettyWidget, self).__init__()\r\n self.initUI()\r\n \r\n \r\n def initUI(self):\r\n self.setGeometry(600, 300, 400, 200)\r\n self.setWindowTitle('Rename Audio File') \r\n \r\n btn = QtGui.QPushButton('BROWSE', self)\r\n btn.resize(btn.sizeHint())\r\n btn.clicked.connect(self.MultipleBrowse)\r\n btn.move(150,100) \r\n\r\n\r\n def MultipleBrowse(self):\r\n filePaths = QtGui.QFileDialog.getOpenFileNames(self, \r\n 'Select Audio Files',\r\n \" \",\r\n '*.mp3')\r\n for filePath in filePaths:\r\n head, tail = os.path.split(str(filePath))\r\n audio_file = eyed3.load(str(filePath))\r\n new_name = audio_file.tag.title + audio_file.tag.artist\r\n\r\n start=end=0\r\n while start != -1 and end != -1:\r\n start = new_name.find('(')\r\n end = new_name.find(')')\r\n if start != -1 and end != -1:\r\n new_name=new_name[0:start] + new_name[end+1:]\r\n changed_name = new_name + \".mp3\"\r\n os.rename(os.path.join(head, tail), os.path.join(head, changed_name))\r\n \r\n \r\ndef main():\r\n app = QtGui.QApplication(sys.argv)\r\n w = PrettyWidget()\r\n w.show()\r\n sys.exit(app.exec_())\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"AutoRename.py","file_name":"AutoRename.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217406718","text":"# Copyright 2017\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_status = {\n 'type': 'string',\n 'enum': ['Success', 'no regions', 'Error', 'Pending', 'Submitted']\n}\n\n_links = {\n 'type': 'object',\n 'properties': {\n 'self': {'type': 'string'}\n },\n 'required': ['self']\n}\n\n_region = {\n 'type': 'object',\n 'properties': {\n 'added': {'type': 'string'},\n 'id': {'type': 'string'},\n 'links': _links\n },\n 'required': ['added', 'id', 'links']\n}\n\n_user = {\n 'type': 'object',\n 'properties': {\n 'added': {'type': 'string', 'format': 'date-time'},\n 'id': {'type': 'string'},\n 'links': _links\n },\n 'required': ['added', 'id', 'links']\n}\n\n_customer = {\n 'type': 'object',\n 'properties': {\n 'id': {'type': 'string'},\n 'links': _links,\n 'created': {'type': 'string', 'format': 'date-time'}\n },\n 'required': ['id', 'links', 'created']\n}\n\ncreate_customer = {\n 'status_code': [201],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'customer': _customer,\n 'transaction_id': {'type': 'string'}\n },\n 'required': ['customer', 'transaction_id']\n }\n}\n\nupdate_customer = {\n 'status_code': [200],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'customer': _customer,\n 'transaction_id': {'type': 'string'}\n },\n 'required': ['customer', 'transaction_id']\n }\n}\n\nadd_regions = {\n 'status_code': [200],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'regions': {\n 'type': 'array',\n 'items': _region\n },\n 'transaction_id': {'type': 'string'}\n },\n 'required': ['regions', 'transaction_id']\n }\n}\n\nadd_users = {\n 'status_code': [200],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'users': {\n 'type': 'array',\n 'items': _user\n },\n 'transaction_id': {'type': 'string'}\n },\n 'required': ['users', 'transaction_id']\n }\n}\n\nreplace_users = add_users\n\nadd_metadata = {\n 'status_code': [200],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'customer': _customer,\n 'transaction_id': {'type': 'string'}\n },\n 'required': ['customer', 'transaction_id']\n }\n}\n\nreplace_metadata = add_metadata\n\nenable_customer = add_metadata\n\nget_customer = {\n 'status_code': [200],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'status': _status,\n 'uuid': {'type': 'string'},\n 'users': {'type': 'array'},\n 'description': {'type': 'string'},\n 'enabled': {'type': 'boolean'},\n 'defaultQuotas': {'type': 'array'},\n 'name': {'type': 'string'},\n 'regions': {'type': 'array'},\n 'custId': {'type': 'string'},\n 'metadata': {'type': 'object'}\n },\n 'required': ['status', 'uuid', 'users', 'description', 'enabled',\n 'defaultQuotas', 'name', 'regions', 'custId', 'metadata']\n }\n}\n\nlist_customer = {\n 'status_code': [200],\n 'response_body': {\n 'type': 'object',\n 'properties': {\n 'customers': {\n 'type': 'array',\n 'items': {\n 'type': 'object',\n 'properties': {\n 'status': _status,\n 'description': {'type': 'string'},\n 'enabled': {'type': 'boolean'},\n 'num_regions': {'type': 'integer'},\n 'regions': {\n 'type': 'array',\n 'items': {'type': 'string'}\n },\n 'id': {'type': 'string'},\n 'name': {'type': 'string'}\n },\n 'required': ['status', 'description', 'enabled',\n 'num_regions', 'regions', 'id', 'name']\n }\n }\n },\n 'required': ['customers']\n }\n}\n\ndelete_customer = {\n 'status_code': [204]\n}\n\ndelete_region_from_customer = delete_customer\n\ndelete_default_user = delete_customer\n\ndelete_user_from_region = delete_customer\n","sub_path":"ranger-tempest-plugin/ranger_tempest_plugin/schemas/customers_schema.py","file_name":"customers_schema.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350486598","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @Filename: download_pictures_by_model_id\n# @Date: 2020/5/10\n# @Author: Mark Wang\n# @Email: wangyouan@gamil.com\n\n\"\"\"\npython -m MeituchaSpider.download_pictures_by_model_id\n\"\"\"\n\nimport os\nimport re\nimport time\nimport logging\nimport requests\n\nfrom bs4 import BeautifulSoup\n\nfrom MeituchaSpider.user_agents import my_user_agent\nfrom MeituchaSpider.download_one_set import download_one_set\n\n\ndef get_page_set_info(page_soup):\n set_box = page_soup.find(class_='hezi')\n li_list = set_box.find_all('li')\n model_url_list = list()\n for li_tag in li_list:\n model_url = 'https://www.meitucha.com{}'.format(li_tag.find('a').get('href'))\n model_url_list.append(model_url)\n\n return model_url_list\n\ndef get_all_model_set(model_id):\n model_page_url = 'https://www.meitucha.com/t/{}'.format(model_id)\n page_req = requests.get(model_page_url, headers={'user_agent': my_user_agent()})\n\n first_page_soup = BeautifulSoup(page_req.content, 'lxml')\n page_req.close()\n\n # Check if multiple page\n pagination_tag = first_page_soup.find(class_='pagination')\n set_url_list = get_page_set_info(first_page_soup)\n if pagination_tag is None:\n logging.debug('Model {} only has one page'.format(model_id))\n else:\n page_link = pagination_tag.find_all('li')\n last_page_index = int(page_link[-2].text)\n logging.debug('There are {} pages'.format(last_page_index))\n for i in range(2, last_page_index + 1):\n logging.debug('Start to download page {} set link'.format(i))\n page_url = '{}?page={}'.format(model_page_url, i)\n next_page_reg = requests.get(page_url, headers={'user_agent': my_user_agent()})\n page_soup = BeautifulSoup(next_page_reg.content, 'lxml')\n next_page_reg.close()\n set_url_list.extend(get_page_set_info(page_soup))\n time.sleep(5)\n\n logging.info('Model {} has {} sets.'.format(model_id, len(set_url_list)))\n for set_url in set_url_list:\n logging.debug('Start downloading {}'.format(set_url))\n download_one_set(set_url)\n logging.debug(\"Set downloaded finished.\")\n time.sleep(1)\n\n logging.info('Model {} downloaded finished'.format(model_id))\n\n\nif __name__ == '__main__':\n import sys\n\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n root.addHandler(handler)\n\n # for model_id in [945, 4044, 4348, 506, 799, 2265, 5482, 624, 289, 292]:\n # for model_id in [292, 3152, 943, 2172, 3172]:\n for model_id in [2172, 3172]:\n get_all_model_set(model_id)\n","sub_path":"MeituchaSpider/download_pictures_by_model_id.py","file_name":"download_pictures_by_model_id.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"200299170","text":"# Secondary side of database operation to retrieve data regularly \n# and place in CSV for graph to render from \n\nimport socket\nimport database\nimport csv\n\nrecent = 0\n\nwhile True:\n\tlatest = database.retrieve_entry() #Take latest entry from MySQL Database\n\tif recent != latest:\n\t\twith open('C:/Users/Sam Holm/Desktop/Quick Access Stuff Mk 4/Massey 2020/Capstone/WebsiteDjango/mysite/CEAL/templates/CEAL/readings.csv', 'a') as csv_file:\n\t\t\tcsv_writer = csv.writer(csv_file, delimiter=',')\n\t\t\tcsv_writer.writerow(latest) #Drop the latest reading into the txt file\n\trecent = latest","sub_path":"retrieve.py","file_name":"retrieve.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26802504","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.\nimport platform\nimport subprocess\nimport sys\n\nfrom airflow_breeze.configure_rich_click import click\nfrom airflow_breeze.utils.common_options import (\n option_airflow_extras,\n option_answer,\n option_backend,\n option_db_reset,\n option_debian_version,\n option_dry_run,\n option_force_build,\n option_forward_credentials,\n option_github_repository,\n option_installation_package_format,\n option_integration,\n option_mount_sources,\n option_mssql_version,\n option_mysql_version,\n option_postgres_version,\n option_python,\n option_use_airflow_version,\n option_use_packages_from_dist,\n option_verbose,\n)\n\n\n@click.group(invoke_without_command=True, context_settings={'help_option_names': ['-h', '--help']})\n@option_verbose\n@option_dry_run\n@option_python\n@option_github_repository\n@option_backend\n@option_postgres_version\n@option_mysql_version\n@option_mssql_version\n@option_debian_version\n@option_forward_credentials\n@option_force_build\n@option_use_airflow_version\n@option_airflow_extras\n@option_use_packages_from_dist\n@option_installation_package_format\n@option_mount_sources\n@option_integration\n@option_db_reset\n@option_answer\n@click.pass_context\ndef main(ctx: click.Context, **kwargs):\n from airflow_breeze.commands.developer_commands import shell\n\n check_for_rosetta_environment()\n check_for_python_emulation()\n\n if not ctx.invoked_subcommand:\n ctx.forward(shell, extra_args={})\n\n\ndef check_for_python_emulation():\n try:\n system_machine = subprocess.check_output([\"uname\", \"-m\"], text=True).strip()\n python_machine = platform.uname().machine\n if system_machine != python_machine:\n from airflow_breeze.utils.console import get_console\n\n get_console().print(\n f'\\n\\n[error]Your Python architecture is {python_machine} and '\n f'system architecture is {system_machine}[/]'\n )\n get_console().print(\n '[warning]This is very bad and your Python is 10x slower as it is emulated[/]'\n )\n get_console().print(\n '[warning]You likely installed your Python wrongly and you should '\n 'remove it and reinstall from scratch[/]\\n'\n )\n from inputimeout import inputimeout\n\n user_status = inputimeout(\n prompt=\"Are you REALLY sure you want to continue? (press y otherwise we exit in 20s) \",\n timeout=20,\n )\n if not user_status.upper() in ['Y', 'YES']:\n sys.exit(1)\n except subprocess.CalledProcessError:\n pass\n except PermissionError:\n pass\n\n\ndef check_for_rosetta_environment():\n if sys.platform != 'darwin':\n return\n try:\n runs_in_rosetta = subprocess.check_output(\n [\"sysctl\", \"-n\", \"sysctl.proc_translated\"],\n text=True,\n stderr=subprocess.DEVNULL,\n ).strip()\n if runs_in_rosetta == '1':\n from airflow_breeze.utils.console import get_console\n\n get_console().print(\n '\\n\\n[error]You are starting breeze in `rosetta 2` emulated environment on Mac[/]'\n )\n get_console().print(\n '[warning]This is very bad and your Python is 10x slower as it is emulated[/]'\n )\n get_console().print(\n '[warning]You likely have wrong architecture-based IDE (PyCharm/VSCode/Intellij) that '\n 'you run it on\\n'\n 'You should download the right architecture for your Mac (Apple Silicon or Intel)[/]\\n'\n )\n from inputimeout import inputimeout\n\n user_status = inputimeout(\n prompt=\"Are you REALLY sure you want to continue? (press y otherwise we exit in 20s) \",\n timeout=20,\n )\n if not user_status.upper() in ['Y', 'YES']:\n sys.exit(1)\n except subprocess.CalledProcessError:\n pass\n except PermissionError:\n pass\n","sub_path":"dev/breeze/src/airflow_breeze/commands/main_command.py","file_name":"main_command.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109699580","text":"#\n# Copyright (c) 2021, NVIDIA 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 annotations\n\nfrom enum import Flag, auto\nfrom typing import Any, List, Optional, Union\n\nfrom nvtabular.columns import ColumnSelector\nfrom nvtabular.columns.schema import Schema\nfrom nvtabular.dispatch import DataFrameType\n\n\nclass Supports(Flag):\n \"\"\"Indicates what type of data representation this operator supports for transformations\"\"\"\n\n # cudf dataframe\n CPU_DATAFRAME = auto()\n # pandas dataframe\n GPU_DATAFRAME = auto()\n # dict of column name to numpy array\n CPU_DICT_ARRAY = auto()\n # dict of column name to cupy array\n GPU_DICT_ARRAY = auto()\n\n\nclass Operator:\n \"\"\"\n Base class for all operator classes.\n \"\"\"\n\n def transform(self, col_selector: ColumnSelector, df: DataFrameType) -> DataFrameType:\n \"\"\"Transform the dataframe by applying this operator to the set of input columns\n\n Parameters\n -----------\n columns: list of str or list of list of str\n The columns to apply this operator to\n df: Dataframe\n A pandas or cudf dataframe that this operator will work on\n\n Returns\n -------\n DataFrame\n Returns a transformed dataframe for this operator\n \"\"\"\n raise NotImplementedError\n\n def compute_output_schema(self, input_schema: Schema, col_selector: ColumnSelector) -> Schema:\n \"\"\"Given a set of schemas and a column selector for the input columns,\n returns a set of schemas for the transformed columns this operator will produce\n Parameters\n -----------\n input_schema: Schema\n The schemas of the columns to apply this operator to\n col_selector: ColumnSelector\n The column selector to apply to the input schema\n Returns\n -------\n Schema\n The schemas of the columns produced by this operator\n \"\"\"\n selected_schema = input_schema.apply(col_selector)\n # TODO: Add a method to Schema to convert to ColumnSelector?\n column_selector = ColumnSelector(selected_schema.column_schemas.keys())\n output_selector = self.output_column_names(column_selector)\n output_names = (\n output_selector.names\n if isinstance(output_selector, ColumnSelector)\n else output_selector\n )\n return Schema(output_names)\n\n def output_column_names(self, col_selector: ColumnSelector) -> ColumnSelector:\n \"\"\"Given a set of columns names returns the names of the transformed columns this\n operator will produce\n\n Parameters\n -----------\n columns: list of str, or list of list of str\n The columns to apply this operator to\n\n Returns\n -------\n list of str, or list of list of str\n The names of columns produced by this operator\n \"\"\"\n return col_selector\n\n def dependencies(self) -> Optional[List[Union[str, Any]]]:\n \"\"\"Defines an optional list of column dependencies for this operator. This lets you consume columns\n that aren't part of the main transformation workflow.\n\n Returns\n -------\n str, list of str or ColumnSelector, optional\n Extra dependencies of this operator. Defaults to None\n \"\"\"\n return None\n\n def __rrshift__(self, other):\n import nvtabular\n\n return nvtabular.ColumnSelector(other) >> self\n\n @property\n def label(self) -> str:\n return self.__class__.__name__\n\n @property\n def supports(self) -> Supports:\n \"\"\"Returns what kind of data representation this operator supports\"\"\"\n return Supports.CPU_DATAFRAME | Supports.GPU_DATAFRAME\n\n def inference_initialize(\n self, col_selector: ColumnSelector, model_config: dict\n ) -> Optional[Operator]:\n \"\"\"Configures this operator for use in inference. May return a different operator to use\n instead of the one configured for use during training\"\"\"\n return None\n","sub_path":"nvtabular/ops/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"247335327","text":"from django.shortcuts import render,redirect\nfrom datetime import datetime\nfrom .models import Slider,Blog,Contact,FilesAdmin,Video\nfrom django.template.loader import get_template\nfrom arogyam.models import Event\nfrom arogyam.models import ArogyamService\n# Create your views here.\nfrom django.http import HttpResponse\n\ndef index(request): \n slider=Slider.objects.all()\n file=Blog.objects.all()\n event=Event.objects.all()\n service=ArogyamService.objects.all()\n context={'slider':slider,'service':service,'file':file,'event':event}\n return render(request,'nutriveda/index.html',context)\n\ndef blogHome(request): \n allBlog= Blog.objects.all()\n context={'allBlog': allBlog}\n return render(request, \"nutriveda/blog/blogHome.html\", context)\n\ndef blogPost(request, slug): \n post=Blog.objects.filter(slug=slug).first()\n context={'post':post}\n return render(request, \"nutriveda/blog/blogPost.html\", context)\n\ndef contactus(request):\n if request.method == \"POST\":\n name = request.POST.get('name')\n mobileno = request.POST.get('mobileno')\n email = request.POST.get('email')\n messages = request.POST.get('messages')\n subject = request.POST.get('subject')\n contact = Contact(name=name, mobileno=mobileno,email=email,messages=messages, subject=subject, createdon=datetime.today())\n contact.save()\n return redirect('contact')\n else: \n return render(request,\"nutriveda/contactus.html\")\n\ndef download(request,path):\n\tfile_path=os.path.join(settings.MEDIA_ROOT,path)\n\tif os.path.exists(file_path):\n\t\twith open(file_path,'rb')as fh:\n\t\t\tresponse=HttpResponse(fh.read(),content_type=\"application/adminfile\")\n\t\t\tresponse['Content-Disposition']='inline;filename='+os.path.basename(file_path)\n\t\t\treturn response\n\n\traise Http404\n\n\ndef fileDownload(request): \n context={'file':FilesAdmin.objects.all()}\n return render(request,'nutriveda/download.html',context)\n\ndef video(request): \n context={'file':Video.objects.all()}\n return render(request,'nutriveda/video.html',context)","sub_path":"nutriveda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117443828","text":"import pandas as pd\nimport os, requests, time\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom tqdm.auto import tqdm\n\n\nBASE_URL = 'https://fantasy.premierleague.com/api/'\n\n\ndef get_player_history(player_id, type):\n '''Get all past season info for a given player_id,\n wait between requests to avoid API rate limit'''\n\n success = False\n # try until a result is returned\n while not success:\n try:\n # send GET request to BASE_URL/api/element-summary/{PID}/\n data = requests.get(\n BASE_URL + 'element-summary/' + str(player_id) + '/').json()\n success = True\n except:\n # wait a bit to avoid API rate limits, if needed\n time.sleep(.3)\n \n # extract 'history_past' data from response into dataframe\n df = pd.json_normalize(data[type])\n\n # season history needs player id column added\n if type == 'history_past':\n df.insert(0, 'id', player_id)\n \n return df\n\n\nclass FplApiData:\n \n def __init__(self, team_id=None, gw=None):\n '''Downloads all relevant data from FPL API'''\n \n # Bootstrap-static data\n api_data = requests.get(BASE_URL+'bootstrap-static/').json()\n \n # player data\n self.players = pd.DataFrame(\n api_data['elements'])[\n ['first_name', 'second_name', 'web_name', 'id', 'team',\n 'total_points', 'element_type', 'now_cost', 'points_per_game',\n 'minutes', 'goals_scored', 'assists', 'clean_sheets',\n 'goals_conceded', 'own_goals', 'penalties_saved', \n 'penalties_missed', 'yellow_cards', 'red_cards', 'saves',\n 'bonus','bps', 'influence', 'creativity', 'threat', 'ict_index']]\n self.players.rename(columns={'id':'player_id',\n 'team':'team_id',\n 'element_type':'position_id'},\n inplace=True)\n # some fields are returned as strings by the api\n self.players = self.players.astype(dtype={'points_per_game': 'float64',\n 'influence': 'float64',\n 'creativity': 'float64',\n 'threat': 'float64',\n 'ict_index': 'float64'})\n self.players.set_index(['player_id'], inplace=True)\n # position data\n self.positions = pd.DataFrame(api_data['element_types'])\n self.positions.drop(\n columns=['plural_name', 'plural_name_short', 'ui_shirt_specific',\n 'sub_positions_locked', 'element_count'],\n axis=1, inplace=True)\n self.positions.rename(columns={'id':'position_id',\n 'singular_name_short':'position_name'},\n inplace=True)\n self.positions.set_index(['position_id'], inplace=True)\n # team data\n self.teams = pd.DataFrame(api_data['teams'])\n self.teams.drop(\n columns=['code', 'played', 'form', 'win', 'draw', 'loss', 'points',\n 'position', 'team_division', 'unavailable', 'pulse_id'],\n axis=1, inplace=True)\n self.teams.rename(columns={'id': 'team_id',\n 'name': 'team_name'},\n inplace=True)\n self.teams.set_index(['team_id'], inplace=True)\n\n # Manager data\n if team_id != None and gw != None:\n manager_data = requests.get(\n f'{BASE_URL}entry/{team_id}/event/{gw}/picks/').json()\n # manager's current squad\n self.current_squad = pd.DataFrame(manager_data['picks'])\n self.current_squad.rename(columns={'element': 'player_id'},\n inplace=True)\n # cash in the bank\n self.bank = manager_data['entry_history']['bank'] / 10\n\n \n def make_opt_df(self, forecasts_file):\n '''Create dataframe with player info and upcoming projections'''\n\n forecasts = pd.read_csv(forecasts_file)\n # rename columns to match api data\n forecasts.rename(columns={'Pos': 'position_name',\n 'Name': 'web_name',\n 'Team': 'team_name'},\n inplace=True)\n forecasts.columns = forecasts.columns.str.lower()\n # replace position names with api names\n forecasts['position_name'].replace(\n {'G':'GKP', 'D':'DEF', 'M':'MID', 'F':'FWD'}, inplace=True)\n\n # player info\n df = self.players[\n ['web_name', 'position_id', 'team_id', 'now_cost']\n # join team names\n ].reset_index().merge(\n self.teams[\n ['team_name']],\n on='team_id'\n # join position names\n ).merge(\n self.positions[\n ['position_name']],\n on='position_id'\n # join forecasts\n ).merge(\n forecasts, on=['team_name', 'web_name', 'position_name']\n )\n\n df.set_index(['player_id'], inplace=True)\n\n return df\n\n\n def make_history_df(self, type):\n '''Create dataframe with all players' gameweek or season histories'''\n\n print(f'Creating player {type} dataframe')\n tqdm.pandas()\n\n # get histories for each player\n df = pd.Series(self.players.index).progress_apply(\n get_player_history, type=type)\n # combine results into single dataframe\n df = pd.concat(p for p in df)\n # rename columns\n df.rename({'element':'player_id'}, axis=1, inplace=True)\n\n return df\n\n\nif __name__ == '__main__':\n\n parser = ArgumentParser(description='Downloads all datasets from FPL API',\n formatter_class=ArgumentDefaultsHelpFormatter)\n parser.add_argument('-o', default=os.path.join('..', 'data', '2022-23'),\n help='relative path to output folder', type=str,\n dest='output_dir', metavar='Output folder')\n args = parser.parse_args()\n\n # make sure using correct separators for path names\n data_dir = args.output_dir.replace('/', os.sep)\n\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n \n # load all data from API into memory\n api_data = FplApiData()\n # save all dataframes as CSVs in chosen folder\n # players\n api_data.players.to_csv(os.path.join(data_dir, 'players.csv'))\n # positions\n api_data.positions.to_csv(os.path.join(data_dir, 'positions.csv'))\n # teams\n api_data.teams.to_csv(os.path.join(data_dir, 'teams.csv'))\n # gameweek histories\n api_data.make_history_df(type='history').to_csv(\n os.path.join(data_dir, 'gameweek_history.csv'), index=False)\n # season histories\n api_data.make_history_df(type='history_past').to_csv(\n os.path.join(data_dir, 'season_history.csv'), index=False)\n","sub_path":"src/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"379292250","text":"import math\nn = int(input())\nl = [1]\ncount = 0\nfor i in range(2, int(math.sqrt(n))+1):\n l.append(i*i)\nlength = len(l)\nready = True\nwhile n != 0:\n for i in range(length-1, 0, -1):\n if n % l[i] == 0:\n print(count+n//l[i])\n ready = False\n break\n else:\n length -= 1\n while n >= l[length]:\n n -= l[length]\n count += 1\n del l[length]\n continue\n break\nif ready:\n print(count)","sub_path":"Code/CodeRecords/2114/60812/261828.py","file_name":"261828.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"254964213","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth import logout,login\nfrom django.contrib import messages\nfrom django.contrib.auth.models import auth,User\nfrom adminpage.models import addemployee,announcement\nfrom . models import leave,salaryemp,salmonth\nfrom ERP.settings import EMAIL_HOST_USER\nfrom django.core.mail import send_mail\nfrom adminpage.forms import announce,EmployeeForm\nfrom datetime import date, datetime\n\n# Create your views here.\n\ndef hrportal(request,username):\n context = {'employees': addemployee.objects.filter(username=username)}\n\n return render(request,'hrportal.html',context)\n\n\ndef logout(request,Employee_id):\n auth.logout(request)\n return redirect('emplogin')\n\ndef view_profile(request,Employee_id):\n context = {'employees': addemployee.objects.filter(Employee_id=Employee_id)}\n return render(request, \"view_profile.html\", context)\n\n\n\ndef new_announhr(request,Employee_id):\n id=0\n if request.method == \"GET\":\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n \n if id == 0:\n form = announce()\n else:\n employee = announcement.objects.get(pk=id)\n form = announce(instance=employee)\n return render(request, \"new_announhr.html\",{'form':form,'employees':employees})\n else:\n \n if id == 0:\n form = announce(request.POST)\n\n else:\n employee = announcement.objects.get(pk=id)\n form = announce(request.POST,instance= employee)\n\n if form.is_valid():\n form.save()\n context=announcement.objects.last()\n\n announcement.objects.filter(id=context.pk).update(announce_by='HR')\n subject = 'New Announcement from Techvolt'\n s=announcement.objects.filter(id=context.pk)\n from_email='techvolt123@gmail.com'\n for i in s:\n message1=i.message\n \n message = \"Welcome, \"+'\\n\\n'+message1+'\\n'+'\\n'+\"Thanks and Regards,\"+'\\n'+\"HR, Techvolt.\"\n if(announcement.objects.filter(id=context.pk,announce_to='All')):\n recievers = []\n for user in addemployee.objects.all():\n recievers.append(user.pemail)\n send_mail(subject, message, from_email, recievers)\n elif(announcement.objects.filter(id=context.pk,announce_to='Technical')):\n recievers = []\n for user in addemployee.objects.filter(dept='Technical'):\n recievers.append(user.pemail)\n send_mail(subject, message, from_email, recievers)\n elif(announcement.objects.filter(id=context.pk,announce_to='Marketing')):\n recievers = []\n for user in addemployee.objects.filter(dept='Marketing'):\n recievers.append(user.pemail)\n send_mail(subject, message, from_email, recievers)\n elif(announcement.objects.filter(id=context.pk,announce_to='Finance')):\n recievers = []\n for user in addemployee.objects.filter(dept='Marketing'):\n recievers.append(user.pemail)\n send_mail(subject, message, from_email, recievers)\n elif(announcement.objects.filter(id=context.pk,announce_to='HR')):\n recievers = []\n for user in addemployee.objects.filter(dept='Human Resource'):\n recievers.append(user.pemail)\n send_mail(subject, message, from_email, recievers)\n \n return redirect('view_announhr',Employee_id=Employee_id)\n\n\n\ndef view_announhr(request,Employee_id):\n if request.method=='GET':\n\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n announces=announcement.objects.all().order_by('-date')[:5]\n return render(request, \"view_announhr.html\", {'announces':announces,'employees':employees})\n\n\ndef view_leavehr(request,Employee_id):\n if request.method=='GET':\n\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n leaves=leave.objects.filter(branch='Human Resource')\n return render(request, \"view_leavehr.html\", {'leaves':leaves,'employees':employees})\n\ndef view_approvehr(request,Employee_id):\n if request.method=='GET':\n\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n leaves=leave.objects.filter(status='Accepted',branch='Finance')|leave.objects.filter(status='Accepted',branch='Marketing')|leave.objects.filter(status='Accepted',branch='Technical')\n leavesm=leave.objects.filter(status='Rejected',branch='Finance')|leave.objects.filter(status='Rejected',branch='Marketing')|leave.objects.filter(status='Rejected',branch='Technical')\n return render(request, \"view_approvehr.html\", {'leaves':leaves,'leavesm':leavesm,'employees':employees})\n\n\ndef new_approvehr(request,Employee_id):\n if request.method=='GET':\n\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n leaves=leave.objects.filter(status='Pending',branch='Finance')|leave.objects.filter(status='Pending',branch='Marketing')|leave.objects.filter(status='Pending',branch='Technical')\n return render(request, \"new_approvehr.html\", {'leaves':leaves,'employees':employees})\n\ndef approvehr(request,emp_id,id):\n if request.method=='GET':\n leave.objects.filter(id=id).update(status='Accepted')\n employees =addemployee.objects.filter(Employee_id=emp_id)\n leaves=leave.objects.filter(status='Pending',branch='Finance')|leave.objects.filter(status='Pending',branch='Marketing')|leave.objects.filter(status='Pending',branch='Technical')\n return render(request, \"new_approvehr.html\", {'leaves':leaves,'employees':employees})\n\ndef rejecthr(request,emp_id,id):\n if request.method=='GET':\n leave.objects.filter(id=id).update(status='Rejected')\n employees =addemployee.objects.filter(Employee_id=emp_id)\n leaves=leave.objects.filter(status='Pending',branch='Finance')|leave.objects.filter(status='Pending',branch='Marketing')|leave.objects.filter(status='Pending',branch='Technical')\n return render(request, \"new_approvehr.html\", {'leaves':leaves,'employees':employees})\n\ndef exist_emphr(request,id):\n employees =addemployee.objects.filter(pk=id)\n exist_emp= addemployee.objects.all()\n print(exist_emp)\n return render(request, \"exist_emphr.html\", {'exist_emp':exist_emp,'employees':employees})\n\ndef addemphr(request,Employee_id):\n empid=Employee_id\n \n if(request.method=='POST'):\n empid=Employee_id\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n \n id=len(addemployee.objects.all())+1\n eid='EM' +str(id)\n Employee_id=eid\n username = eid\n image='pics/person.png'\n full_name = request.POST['full_name']\n password = eid +full_name[:4]\n father_name = request.POST['father_name']\n contact = request.POST['contact']\n aadhar = request.POST['aadhar']\n pan = request.POST['pan']\n whrs = request.POST['whrs']\n oemail = request.POST['oemail']\n pemail = request.POST['pemail']\n designation = request.POST['designation']\n dept = request.POST['dept']\n Gender = request.POST['Gender']\n doj = request.POST['doj']\n address = request.POST['address']\n job_loc = request.POST['job_loc']\n bank_name = request.POST['bank_name']\n ba_no = request.POST['ba_no']\n pfno = request.POST['pfno']\n salary = request.POST['salary']\n oemail=oemail.lower()\n pemail=pemail.lower()\n\n \n if not addemployee.objects.filter(oemail=oemail).exists():\n user=addemployee.objects.create(username=username,Employee_id=Employee_id,image=image,password=password,full_name=full_name,oemail=oemail,pemail=pemail,father_name=father_name,pan=pan,pfno=pfno,whrs=whrs,salary=salary,ba_no=ba_no,bank_name=bank_name,job_loc=job_loc,aadhar=aadhar,address=address,dept=dept,designation=designation,doj=doj,contact=contact,Gender=Gender)\n user.save()\n\n else:\n messages.info(request,'User Exists')\n return redirect('addemphr',Employee_id=Employee_id)\n\n else:\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n id=len(addemployee.objects.all())+1\n eid='EM' +str(id)\n return render(request,'addemphr.html',{'empid':eid,'employees':employees})\n \n\n\n\ndef employee_form1(request,id=0):\n if request.method == \"GET\":\n employees =addemployee.objects.filter(pk=id)\n print(id)\n if id == 0:\n form = EmployeeForm()\n else:\n employee = addemployee.objects.get(pk=id)\n \n form = EmployeeForm(instance=employee)\n return render(request, \"employee_form1.html\", {'form': form,'employees':employees})\n else:\n employees = addemployee.objects.get(pk=id)\n form = EmployeeForm(request.POST,instance= employees)\n print(form)\n if form.is_valid():\n form.save()\n \n return redirect('exist_emphr',id=id)\n else:\n return redirect('exist_emphr',id=id)\n\ndef leave_requesthr(request,Employee_id):\n \n if request.method == \"GET\":\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n\n return render(request, \"leave_requesthr.html\",{'employees':employees})\n else:\n \n from_date=request.POST.get('from_date')\n to_date=request.POST.get('to_date')\n numdays=request.POST['numdays']\n leave_type=request.POST['leave_type']\n reason=request.POST['reason']\n \n\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n for employee in employees:\n emp_name=employee.full_name\n emp_id=employee.Employee_id\n desgn=employee.designation\n branch=employee.dept\n \n user=leave.objects.create(status='Pending',from_date=from_date,to_date=to_date,emp_id=emp_id,emp_name=emp_name,desgn=desgn,branch=branch,numdays=numdays,leave_type=leave_type,reason=reason)\n user.save()\n\n return redirect('leave_requesthr',Employee_id=Employee_id)\n\ndef viewsalhr(request,Employee_id):\n Empoyee_id=request.POST.getlist('employee')\n Empoyee=request.POST.getlist('present_days')\n print(Empoyee_id,Empoyee)\n rt=salmonth.objects.all().last()\n st=rt.month\n r=str(st)\n y=r[5:7]\n \n \n exist_emp = addemployee.objects.filter(id__in=Empoyee_id)\n print(exist_emp)\n for i in exist_emp:\n m=i.dept\n print(m)\n qw=salaryemp.objects.filter(status='Generated') \n l=[]\n for i in qw:\n v=str(i.date_of_generate)\n if(v[5:7]==r[5:7]):\n l.append(i.emid)\n exist = addemployee.objects.filter(dept=str(m))\n print(exist)\n qr=addemployee.objects.filter(dept=m) \n print(l)\n print('qr',qr)\n l1=[]\n for i in qr:\n l1.append(i.Employee_id)\n print(l1)\n l2=list(set(l1)-set(l))\n print(l2)\n o=[]\n r= addemployee.objects.filter(Employee_id__in=l2)\n print(r)\n for i in r:\n o.append(int(i.id))\n q=[]\n print('o is',o)\n print(Empoyee)\n for i in Empoyee_id:\n i=int(i)\n if i in o:\n s=addemployee.objects.filter(id=i)\n print('hellow')\n for u in s:\n emp_name=u.full_name\n dept=u.dept\n acno=u.ba_no\n emid=u.Employee_id\n q.append(u.Employee_id)\n sal=u.salary\n working_days=30\n p=o.index(i)\n e=Empoyee[p]\n gross=((int(e)/30)*sal)\n pf=round(gross*0.4*0.12,3)\n esi=round(gross*0.4*0.0075,3)\n basic_pay=0.4*gross\n hra=0.5*basic_pay\n special_allowance=gross-basic_pay-hra\n month=rt.month\n gross=round(gross, 3)\n \n if(salaryemp.objects.filter(month=month,emid=emid).exists()):\n \n salaryemp.objects.filter(emid=emid).update(present_days=e,hra=hra,special_allowance=special_allowance,basic_pay=basic_pay,gross=gross,pf=pf,esi=esi)\n else:\n \n salaryemp.objects.create(present_days=e,month=month,acno=acno,emp_name=emp_name,dept=dept,sal=sal,emid=emid,working_days=working_days,hra=hra,special_allowance=special_allowance,basic_pay=basic_pay,gross=gross,pf=pf,esi=esi)\n \n sala = salaryemp.objects.filter(emid__in=q,month=rt.month) \n \n employees= addemployee.objects.filter(Employee_id=Employee_id)\n\n return render(request, \"viewsalhr.html\", {'sala':sala,'employees':employees})\n\ndef gensal(request,Employee_id):\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n if request.method=='POST':\n month=request.POST['month']\n dept=request.POST['dept']\n salmonth.objects.create(month=month,dept=dept)\n \n m=salaryemp.objects.filter(dept=dept)\n e=[]\n for i in m:\n date=i.month\n d=str(date)\n print(d)\n if(str(month)==d[:7]):\n if(i.status=='Generated' or i.status=='Paid'):\n e.append(i.emid)\n \n exist_emp= addemployee.objects.filter(dept=dept)\n o=[]\n for i in exist_emp:\n o.append(i.Employee_id)\n emp=list(set(o) - set(e))\n print(emp)\n exist_emp= addemployee.objects.filter(dept=dept,Employee_id__in=emp)\n return render(request, \"gensalhr.html\", {'exist_emp':exist_emp,'employees':employees})\n else:\n return render(request,'gensal.html',{'employees':employees})\n\n\ndef salaryslip(request,Employee_id):\n\n Empoyee_id=request.POST.getlist('employee')\n Empoyee=request.POST.getlist('it')\n exist_emp = salaryemp.objects.filter(emid__in=Empoyee_id)\n r=[]\n for i in salaryemp.objects.filter(status=''):\n r.append(i.emid)\n for i in Empoyee_id:\n m=r.index(i)\n empsal=salaryemp.objects.filter(emid=i)\n for i in empsal:\n emid=i.emid\n gross=i.gross\n pf=i.pf\n esi=i.esi\n it=Empoyee[m]\n total_dedu=round(float(pf)+float(esi)+float(it),2)\n payable=round(float(gross)-total_dedu,2)\n status='Generated'\n salaryemp.objects.filter(emid=emid).update(it=it,total_dedu=total_dedu,payable=payable,status=status)\n\n sala=salaryemp.objects.all().order_by(\"-month\")\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n return render(request,'view_salaryhr.html',{'employees':employees,'sala':sala})\n\ndef view_salaryhr(request,Employee_id):\n sala=salaryemp.objects.all().order_by(\"-month\")\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n return render(request,'view_salaryhr.html',{'employees':employees,'sala':sala})\n\n\ndef Salaryhr(request,Employee_id):\n sala=salaryemp.objects.filter(emid=Employee_id).order_by(\"-month\")\n employees =addemployee.objects.filter(Employee_id=Employee_id)\n return render(request,'Salaryhr.html',{'employees':employees,'sala':sala})\n\ndef salary_slip(request,id):\n sala=salaryemp.objects.filter(id=id)\n for i in sala:\n emp=i.emid\n employees =addemployee.objects.filter(Employee_id=emp)\n \n return render(request,'salary_slip.html',{'employees':employees,'sala':sala})\n\ndef salary_down(request,id):\n sala=salaryemp.objects.filter(id=id)\n for i in sala:\n emp=i.emid\n employees =addemployee.objects.filter(Employee_id=emp)\n \n return render(request,'salary_down.html',{'employees':employees,'sala':sala})\n","sub_path":"hr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"473814643","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport time\nimport itertools\nimport hashlib\nimport zlib\nimport gzip\nimport bz2\nimport sys\nimport re\nimport logging\nimport functools\nfrom GoogleScraper.config import Config\n\n\"\"\"\nGoogleScraper is a complex application and thus searching is error prone. While developing,\nyou may need to repeat the same searches several times and you might end being banned by\nGoogle. This is why all searches are chached by default.\n\nEvery SERP page is cached in a separate file. In the future, it might be more straightforward to\nmerge several logically adjacent search result HTML code together.\n\"\"\"\n\nlogger = logging.getLogger('GoogleScraper')\n\nALLOWED_COMPRESSION_ALGORITHMS = ('zip', 'gz', 'bz2')\n\nclass InvalidConfigurationFileException(Exception):\n \"\"\"\n Used when the cache module cannot\n determine the kind (compression for instance) of a\n configuration file\n \"\"\"\n pass\n\n\nclass CompressedFile(object):\n \"\"\"Open and return the data of a compressed file\n\n Supported algorithms: zlib, gz, bz2\n\n >>> import os\n >>> f = CompressedFile('zip', '/tmp/test.txt')\n >>> f.write('hello world')\n >>> assert os.path.exists('/tmp/test.txt.zip')\n\n >>> f2 = CompressedFile('zip', '/tmp/test.txt.zip')\n >>> assert f2.read() == 'hello world'\n \"\"\"\n\n def __init__(self, algorithm, path):\n \"\"\"Create a new compressed file to read and write data to.\n\n Args:\n algorithm: Which algorithm to use.\n path: A valid file path to the file to read/write. Depends\n on the action called.\n \"\"\"\n\n assert algorithm in ALLOWED_COMPRESSION_ALGORITHMS, algorithm\n\n self.algorithm = algorithm\n if path.endswith(algorithm):\n self.path = path\n else:\n self.path = '{path}.{ext}'.format(path=path, ext=algorithm)\n\n self.data = b''\n self.readers = {\n 'zip': self.read_zlib,\n 'gz': self.read_gz,\n 'bzw': self.read_bz2\n }\n self.writers = {\n 'zip': self.write_zlib,\n 'gz': self.write_gz,\n 'bzw': self.write_bz2\n }\n\n def _read(self):\n if not self.data:\n with open(self.path, 'rb') as fd:\n self.data = fd.read()\n\n def _write(self, data):\n with open(self.path, 'wb') as f:\n f.write(data)\n\n def read_zlib(self):\n self._read()\n try:\n data = zlib.decompress(self.data).decode()\n return data\n except zlib.error as e:\n raise e\n\n def read_gz(self):\n try:\n file = gzip.GzipFile(self.path)\n return file.read()\n except Exception as e:\n raise\n\n def read_bz2(self):\n raise NotImplemented('yet')\n\n def write_zlib(self, data):\n if not isinstance(data, bytes):\n data = data.encode()\n\n try:\n self._write(zlib.compress(data, 5))\n except zlib.error as e:\n raise e\n\n def write_gz(self):\n pass\n\n def write_bz2(self):\n pass\n\n def read(self):\n assert os.path.exists(self.path)\n return self.readers[self.algorithm]()\n\n def write(self, data):\n return self.writers[self.algorithm](data)\n\n\n\ndef maybe_create_cache_dir():\n if Config['GLOBAL'].getboolean('do_caching'):\n cd = Config['GLOBAL'].get('cachedir', '.scrapecache')\n if not os.path.exists(cd):\n os.mkdirs(cd)\n\n\ndef if_caching(f):\n @functools.wraps(f)\n def wraps(*args, **kwargs):\n if Config['GLOBAL'].getboolean('do_caching'):\n maybe_create_cache_dir()\n return f(*args, **kwargs)\n\n return wraps\n\n\ndef maybe_clean_cache():\n \"\"\"Clean the cache.\n\n Clean all cached searches (the obtained html code) in the cache directory iff\n the respective files are older than specified in the configuration. Defaults to 12 hours.\n \"\"\"\n for fname in os.listdir(Config['GLOBAL'].get('cachedir', '.scrapecache')):\n path = os.path.join(Config['GLOBAL'].get('cachedir'), fname)\n if time.time() > os.path.getmtime(path) + (60 * 60 * Config['GLOBAL'].getint('clean_cache_after', 12)):\n # Remove the whole directory if necessary\n if os.path.isdir(path):\n import shutil\n\n shutil.rmtree(path)\n else:\n os.remove(os.path.join(Config['GLOBAL'].get('cachedir'), fname))\n\n\ndef cached_file_name(kw, url, params={}):\n \"\"\"Make a unique file name from the Google search request.\n\n Important! The order of the sequence is darn important! If search queries have the same\n words but in a different order, they are unique searches.\n\n Args:\n kw: The search keyword\n url: The url for the search (without params)\n params: The parameters used in the search url without the \"q\" parameter. Optional and may be empty.\n\n Returns:\n A unique file name based on the parameters of the search request.\n\n \"\"\"\n assert isinstance(kw, str), kw\n assert isinstance(url, str), url\n assert isinstance(params, dict)\n\n unique = list(itertools.chain([kw, ], url, params.keys(), params.values()))\n\n sha = hashlib.sha256()\n sha.update(b''.join(str(s).encode() for s in unique))\n return '{file_name}.{extension}'.format(file_name=sha.hexdigest(), extension='cache')\n\n\n@if_caching\ndef get_cached(kw, url, params={}):\n \"\"\"Loads a cached SERP result.\n\n Args:\n kw: The keyword used in the search request. Value of \"q\" parameter.\n url: The base search url used while requesting.\n params: The search parameters as a dictionary, optional.\n\n Returns:\n The contents of the HTML that was shipped while searching. False if there couldn't\n be found a file based on the above params.\n\n \"\"\"\n fname = cached_file_name(kw, url, params)\n\n cdir = Config['GLOBAL'].get('cachedir', '.scrapecache')\n\n if fname in os.listdir(cdir):\n # If the cached file is older than 12 hours, return False and thus\n # make a new fresh request.\n try:\n modtime = os.path.getmtime(os.path.join(cdir, fname))\n except FileNotFoundError as err:\n return False\n\n if (time.time() - modtime) / 60 / 60 > Config['GLOBAL'].getint('clean_cache_after', 12):\n return False\n\n path = os.path.join(cdir, fname)\n return read_cached_file(path)\n else:\n return False\n\n\n@if_caching\ndef read_cached_file(path):\n \"\"\"Read a zipped or unzipped.\n\n The compressing schema is determined by the file extension. For example\n a file that ends with .zip needs to be unzipped.\n\n Supported algorithms:\n zlib, gzip, and bzip2\n\n Args:\n path: The path to the cached file.\n\n Returns:\n The data of the cached file.\n\n Raises:\n InvalidConfigurationFileException: When the type of the cached file\n cannot be determined.\n \"\"\"\n\n ext = path.split('.')[-1]\n\n # The path needs to have an extension in any case.\n # When uncompressed, ext is 'cache', else it is the\n # compressing scheme file ending like .gz or .zip ...\n assert ext\n\n if ext == 'cache':\n with open(path, 'r') as fd:\n try:\n data = fd.read()\n return data\n except UnicodeDecodeError as e:\n # If we get this error, the cache files are probably\n # compressed but the 'compress_cached_files' flag was\n # set to False. Try to decompress them, but this may\n # lead to a infinite recursion. This isn't proper coding,\n # but convenient for the end user.\n Config.set('GLOBAL', 'compress_cached_files', True)\n elif ext in ALLOWED_COMPRESSION_ALGORITHMS:\n f = CompressedFile(ext)\n return f.read(path)\n else:\n raise InvalidConfigurationFileException('\"{path}\" is a invalid configuration file.')\n\n\n@if_caching\ndef cache_results(data, kw, url, params={}):\n \"\"\"Stores the data in a file.\n\n The file name is determined by the parameters kw, url and params.\n See cached_file_name() for more information.\n\n This will always write(overwrite) the cached file. If compress_cached_files is\n True, the page is written in bytes (obviously).\n\n Args:\n data: The data to cache.\n kw: The search keyword\n url: The search url for the search request\n params: The search params, Optional\n \"\"\"\n fname = cached_file_name(kw, url, params)\n cachedir = Config['GLOBAL'].get('cachedir', '.scrapecache')\n path = os.path.join(cachedir, fname)\n\n if Config['GLOBAL'].getboolean('compress_cached_files'):\n algorithm = Config['GLOBAL'].get('compressing_algorithm', 'zip')\n f = CompressedFile(algorithm, path)\n f.write(data)\n else:\n with open(path, 'w') as fd:\n if isinstance(data, bytes):\n fd.write(data.decode())\n else:\n fd.write(data)\n\n\ndef _get_all_cache_files():\n \"\"\"Return all files found in the cachedir.\n\n Returns:\n All files that have the string \"cache\" in it within the cache directory.\n Files are either uncompressed filename.cache or are compressed with a\n compresssion algorithm: \"filename.cache.zip\"\n \"\"\"\n files = set()\n for dirpath, dirname, filenames in os.walk(Config['GLOBAL'].get('cachedir')):\n for name in filenames:\n if 'cache' in name:\n files.add(os.path.join(dirpath, name))\n return files\n\n\ndef _caching_is_one_to_one(keywords, url):\n \"\"\"Check whether all keywords map to a unique file name.\n\n Args:\n keywords: All keywords for which to check the uniqueness of the hash\n url: The search url\n\n Returns:\n True if all keywords map to a unique hash and False if not.\n \"\"\"\n mappings = {}\n for kw in keywords:\n hash = cached_file_name(kw, url)\n if hash not in mappings:\n mappings.update({hash: [kw, ]})\n else:\n mappings[hash].append(kw)\n\n duplicates = [v for k, v in mappings.items() if len(v) > 1]\n if duplicates:\n logger.info('Not one-to-one. {}'.format(duplicates))\n return False\n else:\n logger.info('one-to-one')\n return True\n\n\ndef parse_all_cached_files(keywords, conn, url, try_harder=True):\n \"\"\"Walk recursively through the cachedir (as given by the Config) and parse all cached files.\n\n Args:\n keywords: A sequence of keywords which were used as search query strings.\n conn: A sqlite3 database connection.\n try_harder: If there is a cache file that cannot be mapped to a keyword, read it and try it again with the query.\n\n Returns:\n A list of keywords that couldn't be parsed and which need to be scraped anew.\n \"\"\"\n r = re.compile(r'(?P<kw>.*?) - Google Search')\n files = _get_all_cache_files()\n mapping = {cached_file_name(kw, url): kw for kw in keywords}\n diff = set(mapping.keys()).difference({os.path.split(path)[1] for path in files})\n logger.info('{} cache files found in {}'.format(len(files), Config['GLOBAL'].get('cachedir')))\n logger.info('{}/{} keywords have been cached and are ready to get parsed. {} remain to get scraped.'.format(\n len(keywords) - len(diff), len(keywords), len(diff)))\n\n if Config['GLOBAL'].getboolean('simulate'):\n sys.exit(0)\n\n for path in files:\n fname = os.path.split(path)[1]\n query = mapping.get(fname)\n data = read_cached_file(path)\n if not query and try_harder:\n m = r.search(data)\n if m:\n query = m.group('kw').strip()\n if query in mapping.values():\n logger.debug('The request with the keywords {} was wrongly cached.'.format(query))\n else:\n continue\n else:\n continue\n # TODO: Push to database\n mapping.pop(fname)\n conn.commit()\n\n # return the remaining keywords to scrape\n return mapping.values()\n\n\ndef fix_broken_cache_names(url):\n \"\"\"Fix broken cache names.\n\n Args:\n url: A list of strings to add to each cached_file_name() call.\n \"\"\"\n files = _get_all_cache_files()\n logger.debug('{} cache files found in {}'.format(len(files), Config['GLOBAL'].get('cachedir', '.scrapecache')))\n r = re.compile(r'(?P<kw>.*?) - Google Search')\n\n for i, path in enumerate(files):\n fname = os.path.split(path)[1].strip()\n data = read_cached_file(path)\n infilekws = r.search(data).group('kw')\n realname = cached_file_name(infilekws, url)\n if fname != realname:\n logger.debug(\n 'The search query in the title element in file {} differ from that hash of its name. Fixing...'.format(\n path))\n src = os.path.abspath(path)\n dst = os.path.abspath(os.path.join(os.path.split(path)[0], realname))\n logger.debug('Renamed from {} => {}'.format(src, dst))\n os.rename(src, dst)\n logger.debug('Renamed {} files.'.format(i))\n\n\ndef cached(f, attr_to_cache=None):\n \"\"\"Decoator that makes return value of functions cachable.\n \n Any function that returns a value and that is decoratated with \n cached will be supplied with the previously calculated result of\n an earlier call. The parameter name with the cached value may \n be set with attr_to_cache.\n \n Args:\n attr_to_cache: The name of attribute whose data\n is cachable.\n \n Returns: The modified and wrapped function.\n \"\"\"\n def wraps(*args, **kwargs):\n cached_value = get_cached(*args, params=kwargs)\n if cached_value:\n value = f(*args, attr_to_cache=cached_value, **kwargs)\n else:\n # Nothing was cached for this attribute\n value = f(*args, attr_to_cache=None, **kwargs)\n cache_results(value, *args, params=kwargs)\n return wraps\n \nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","sub_path":"GoogleScraper/caching.py","file_name":"caching.py","file_ext":"py","file_size_in_byte":14151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"625653764","text":"import sqlite3\n\nwith sqlite3.connect('cars.db') as connection:\n c = connection.cursor()\n\n cars = [\n ('Ford', 'Focus', 2),\n ('Ford', 'Lacta', 3),\n ('Ford', 'Cak', 1),\n ('Honda', 'Civic', 8),\n ('Honda', 'CB', 4),\n ]\n\n c.executemany(\"INSERT INTO inventory VALUES (?, ?, ?)\", cars)\n","sub_path":"sql/carsa.py","file_name":"carsa.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"468365045","text":"import pandas as pd\nfrom utils.database import config as cfg, io\n\nengine_base = cfg.load_engine()[\"2Gb\"]\n\n\ndef fetch_stockvaluation(start, end):\n sql = \"SELECT * FROM ( \\\n SELECT p.stock_id ,p.date ,v.`market_price` ,v.`circulated_price` ,v.`pe_ttm` , \\\n v.`pe_deducted_ttm` ,v.`pe_lyr`,v.`pb`,v.pb_lf,v.`pb_mrq`,v.`beta_24m` , \\\n p.`last_trading_day`,p.`status`,p.`close` \\\n FROM base_finance.stock_price as p \\\n LEFT JOIN base_finance.stock_valuation v \\\n ON p.stock_id = v.stock_id AND p.date = v.date \\\n WHERE (p.date between '{before}' AND '{now}')) T1 \\\n UNION (SELECT p.stock_id ,p.date ,v.`market_price` ,v.`circulated_price` ,v.`pe_ttm` , \\\n v.`pe_deducted_ttm` ,v.`pe_lyr`,v.`pb`,v.pb_lf,v.`pb_mrq`,v.`beta_24m` , \\\n p.`last_trading_day`,p.`status`,p.`close` \\\n FROM base_finance.stock_price as p \\\n LEFT JOIN base_finance.stock_valuation v \\\n ON p.stock_id = v.stock_id AND p.date = v.date \\\n WHERE (p.update_time between '{before}' AND '{now}')) \\\n UNION (SELECT p.stock_id ,p.date ,v.`market_price` ,v.`circulated_price` ,v.`pe_ttm` , \\\n v.`pe_deducted_ttm` ,v.`pe_lyr`,v.`pb`,v.pb_lf,v.`pb_mrq`,v.`beta_24m` , \\\n p.`last_trading_day`,p.`status`,p.`close` \\\n FROM base_finance.stock_price as p \\\n LEFT JOIN base_finance.stock_valuation v \\\n ON p.stock_id = v.stock_id AND p.date = v.date \\\n WHERE (v.update_time between '{before}' AND '{now}'))\".format(before=start, now=end)\n\n sql2 = \"SELECT stock_id as subject_id, `name` as subject_name FROM base_finance.stock_info\"\n\n name = pd.read_sql(sql2, engine_base)\n df = pd.read_sql(sql, engine_base)\n if len(df) == 0:\n return pd.DataFrame()\n df.rename(columns={\"stock_id\": \"subject_id\", \"close\": \"closing_price\"}, inplace=True)\n df_all = pd.merge(df, name, how='inner', on='subject_id')\n\n return df_all\n\n\ndef sync_stock_price(start, end):\n data = fetch_stockvaluation(start, end)\n io.to_sql(\"security_price\", engine_base, data, type=\"update\")\n\n\ndef main():\n a = input(\"输入1或者天数拿取数据,默认一周\\n\")\n is_checked = int(a)\n\n if is_checked == 1:\n I = 7\n data = fetch_stockvaluation(I)\n print(data)\n a1 = input(\"输入1确认入库\\n\")\n if a1 == \"1\":\n io.to_sql(\"security_price\", engine_base, data, type=\"update\")\n else:\n print(\"失败\")\n else:\n data = fetch_stockvaluation(is_checked)\n print(data)\n a1 = input(\"输入1确认入库\\n\")\n if a1 == \"1\":\n io.to_sql(\"security_price\", engine_base, data, type=\"update\")\n else:\n print(\"失败\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"SCRIPT/OTHER/desktop/sync_stock_price.py","file_name":"sync_stock_price.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"602344429","text":"#!/usr/bin/env python\n# \n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\n\n# Basic Operational methods and convenience wrappers to cut down on unnecessary repetition in the code\ndef connect():\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n return psycopg2.connect(\"dbname=swiss_tournament\")\n\ndef __commit_and_close(query, params=None):\n \"\"\"Convenience wrapper for insert/update statements\"\"\"\n db = connect()\n cur = db.cursor()\n if params:\n cur.execute(query, params)\n else:\n cur.execute(query)\n db.commit()\n db.close()\n\ndef __get_scalar(query):\n \"\"\"Convenience wrapper for retrieving a single column from a single row in a given query\"\"\"\n db = connect()\n cur = db.cursor()\n cur.execute(query)\n result = cur.fetchone()\n db.close()\n if result is not None:\n return result[0]\n\ndef __get_results(query):\n \"\"\"Convenience wrapper for a multi-column and/or multi-row result set for a given query\"\"\"\n db = connect()\n cur = db.cursor()\n cur.execute(query)\n results = cur.fetchall()\n db.close()\n return results\n\ndef __get_current_tournament():\n return __get_scalar(\"SELECT id FROM tournaments WHERE is_won IS FALSE AND is_closed IS FALSE;\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n __commit_and_close(\n \"DELETE FROM matches \"\n \"WHERE winner IN (\"\n \"SELECT p.id FROM players p \"\n \"INNER JOIN tournaments t ON p.tournament_id = t.id AND t.is_won IS FALSE);\"\n )\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n __commit_and_close(\"DELETE FROM players WHERE tournament_id IN (SELECT id FROM tournaments WHERE is_won IS FALSE);\")\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n return __get_scalar(\"SELECT * FROM number_of_players_in_tournament;\")\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n \n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n \n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n\n # Get or create the current tournament\n tournament_id = __get_current_tournament()\n if not tournament_id:\n __commit_and_close(\"INSERT INTO tournaments (is_won) VALUES (FALSE);\")\n tournament_id = __get_current_tournament()\n\n # Register this new player to the current tournament\n __commit_and_close(\"INSERT INTO players (name, tournament_id) VALUES (%s, %s)\", (name, tournament_id))\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place, or a player\n tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n\n # Retrieve the players with their win and match counts\n return __get_results(\"SELECT * FROM player_standings;\")\n\ndef reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n\n # Close the tournament to which these players belong from any further players registering to it\n __commit_and_close(\n \"UPDATE tournaments SET is_closed = TRUE \"\n \"WHERE is_closed IS FALSE AND id IN (\"\n \"SELECT tournament_id FROM players \"\n \"WHERE id IN (%s, %s) \"\n \"GROUP BY tournament_id);\",\n (winner, loser)\n )\n\n # Report this particular match-up (only if these players are part of an active tournament)\n __commit_and_close(\n \"INSERT INTO matches (winner, loser) \"\n \"SELECT %s, %s FROM tournaments \"\n \"WHERE id IN (\"\n \"SELECT tournament_id FROM players \"\n \"WHERE is_closed IS TRUE AND is_won IS FALSE AND id IN (%s, %s));\",\n (winner, loser, winner, loser)\n )\n\n # If the tournament has a winner (only one player with all wins and no losses), close the tournament\n __commit_and_close(\n \"UPDATE tournaments SET is_won = TRUE \"\n \"WHERE is_won IS FALSE \"\n \"AND (SELECT * FROM current_tournament_is_won) IS TRUE;\"\n )\n\ndef swissPairings():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n \n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n \n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n\n pairings = []\n\n # Check to see if any matches have occurred yet, if none, just mix the pairings arbitrarily\n if __get_scalar(\"SELECT SUM(match_count) FROM player_standings;\") == 0:\n player_count = countPlayers()\n # Here, we're just cutting the list into two equal halves\n player1s = __get_results(\"SELECT id, name FROM player_standings LIMIT {0};\".format(player_count/2))\n player2s = __get_results(\"SELECT id, name FROM player_standings LIMIT {0} OFFSET {0};\".format(player_count/2))\n\n if player1s and player2s:\n # now the two halves are zipped together into a new list of tuples\n pairings.extend(map(tuple.__add__, player1s, player2s))\n else:\n # Here, we have a grouping available, by wins and losses, so teams in each group are paired against each other\n groups = __get_results(\"SELECT * FROM win_loss_groups;\")\n for w, l in groups:\n # Find the players that match this particular win/loss group (there will be at least two)\n player_standings = __get_results(\n \"SELECT id, name FROM player_standings WHERE wins = {0} AND (match_count - wins) = {1}\".format(w, l)\n )\n\n # now the list of players that fit this win/loss group are zipped together into a new list of tuples\n pairings.extend(\n map(\n tuple.__add__,\n player_standings[:len(player_standings)/2],\n player_standings[len(player_standings)/2:len(player_standings)]\n )\n )\n\n return pairings\n","sub_path":"vagrant/tournament/tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546180056","text":"import random\nimport simpy\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nrandom.seed(7)\n\n# Grand totals hold the results at each\n# iteration of the for loop\nGRAND_TOTAL_SERVER_TIME = []\nGRAND_TOTAL_CHECKER_TIME = []\nGRAND_TOTAL_WAIT_TIME = []\nGRAND_TOTAL_SYSTEM_TIME = []\n\nfor numCheckers in range(1, 5):\n random.seed(7)\n ARRIVAL_RATE_LAMBDA = 50 # passengers per minute (lambda)\n\n NUM_SERVERS = 1 # ID/boarding-pass queue servers\n SERVICE_TIME = 0.75 # minutes per passenger at ID/boarding pass queue\n averageServeTime = []\n\n NUM_CHECKERS = numCheckers # personal-check queue checkers\n MIN_SCAN_TIME = 0.5\n MAX_SCAN_TIME = 1.0\n averageCheckTime = []\n\n SIM_RUN_TIME = 3000 # minutes to run the simulation\n\n averageTotalWaitTime = []\n averageSystemTime = []\n\n\n class Airport(object):\n def __init__(self, env):\n self.env = env\n self.serverQueue = simpy.Resource(env, capacity=NUM_SERVERS)\n self.checkQueue = simpy.Resource(env, capacity=NUM_CHECKERS)\n\n def serve(self): # boarding-pass/id check\n yield self.env.timeout(SERVICE_TIME)\n\n def check(self): # personal check\n checkerTime = random.uniform(MIN_SCAN_TIME, MAX_SCAN_TIME)\n yield self.env.timeout(checkerTime)\n\n\n def passenger(env, name, airport):\n # passenger arrives\n enterSystemTime = env.now\n\n # passenger enters ID/boarding-pass queue\n with airport.serverQueue.request() as requestForServer:\n startWaitingForServer = env.now\n yield requestForServer\n waitTimeForServer = env.now - startWaitingForServer\n averageServeTime.append(waitTimeForServer)\n\n yield env.process(airport.serve())\n\n # passenger enters personal-check queue\n with airport.checkQueue.request() as requestForChecker:\n startWaitingForChecker = env.now\n yield requestForChecker\n waitTimeForChecker = env.now - startWaitingForChecker\n averageCheckTime.append(waitTimeForChecker)\n\n yield env.process(airport.check())\n\n averageTotalWaitTime.append(waitTimeForServer + waitTimeForChecker)\n averageSystemTime.append(env.now - enterSystemTime)\n\n\n def startSimulation(env):\n airport = Airport(env)\n\n # Create initial passengers at time 0.0\n for i in range(ARRIVAL_RATE_LAMBDA):\n env.process(passenger(env, 'Passenger %d' % i, airport))\n\n # Create more passengers while the simulation is running\n arrivalNumber = ARRIVAL_RATE_LAMBDA - 1\n while True:\n # time between successive arrivals (exponential distribution)\n yield env.timeout(np.random.exponential(ARRIVAL_RATE_LAMBDA))\n\n # arriving passengers\n for i in range(ARRIVAL_RATE_LAMBDA):\n arrivalNumber += 1\n env.process(passenger(env, 'Passenger %d' % arrivalNumber, airport))\n\n\n # Setup and start the simulation\n env = simpy.Environment()\n env.process(startSimulation(env))\n\n env.run(until=SIM_RUN_TIME)\n\n print(\"\\n\")\n print('Number of Servers in id/boarding-pass queue:', NUM_SERVERS)\n print('Number of Checkers in personal-check queue:', NUM_CHECKERS)\n print('Avg wait in serve queue:', np.mean(averageServeTime))\n print('Avg wait in check queue:', np.mean(averageCheckTime))\n print('Avg total wait time:', np.mean(averageTotalWaitTime))\n print('Avg time in system:', np.mean(averageSystemTime))\n\n GRAND_TOTAL_WAIT_TIME.append(np.mean(averageTotalWaitTime))\n GRAND_TOTAL_CHECKER_TIME.append(np.mean(averageCheckTime))\n GRAND_TOTAL_SERVER_TIME.append(np.mean(averageServeTime))\n GRAND_TOTAL_SYSTEM_TIME.append(np.mean(averageSystemTime))\n\n\n# Plot the results\nplt.plot(range(1, 5), GRAND_TOTAL_SERVER_TIME)\nplt.plot(range(1, 5), GRAND_TOTAL_CHECKER_TIME)\nplt.plot(range(1, 5), GRAND_TOTAL_WAIT_TIME)\nplt.plot(range(1, 5), GRAND_TOTAL_SYSTEM_TIME)\nplt.xticks([1, 2, 3, 4])\nplt.xlabel(\"Number of Checkers\")\nplt.ylabel(\"Total Wait Time\")\nplt.title(\"Effects of Increasing Checkers on Wait Times\")\nplt.legend(['Server Wait',\n 'Checker Wait',\n 'Total Wait',\n 'Time in System'],\n loc='upper right')\nplt.show()\n\n","sub_path":"IncreasingCheckers.py","file_name":"IncreasingCheckers.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115490467","text":"\n# coding: utf-8\n\n# In this program we use Scikit-learn package to do logistic regression on two different datasets details of which are given below. \n\n# Importing dependencies \n\n# In[22]:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\n\n\n# When the data is not linearly spearable, mapFeature can be used to generate additional fearures.\n\n# In[23]:\n\ndef mapFeature(X1, X2, degree):\n out = np.ones(( X1.shape[0], sum(range(degree + 2)) )) # could also use ((degree+1) * (degree+2)) / 2 instead of sum\n curr_column = 1\n for i in range(1, degree + 1):\n for j in range(i+1):\n out[:,curr_column] = np.power(X1,i-j) * np.power(X2,j)\n curr_column += 1\n return out\n\n\n# Print scores\n\n# In[24]:\n\ndef print_score(X,Y,logreg):\n predictions=logreg.predict(X)\n print('Accuracy:', accuracy_score(Y, predictions))\n print('Precision:', precision_score(Y, predictions, average='macro'))\n print('Recall:', recall_score(Y, predictions, average='macro'))\n\n\n# Plot the decision boundaries\n\n# In[25]:\n\ndef plot_boundary(X,y,degree,logreg):\n x_min, x_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n y_min, y_max = X[:, 2].min() - .5, X[:, 2].max() + .5\n xs, ys = np.meshgrid(np.linspace(x_min, x_max, 200),np.linspace(y_min, y_max, 200))\n xys = mapFeature(xs.ravel(),ys.ravel(),degree)\n Z = logreg.predict(xys).reshape(xs.shape)\n plt.pcolormesh(xs, ys, Z, cmap=plt.cm.Paired)\n plt.scatter(X[:, 1], X[:, 2], c=Y, edgecolors='k', cmap=plt.cm.Paired)\n plt.xlim(xs.min(), xs.max())\n plt.ylim(ys.min(), ys.max())\n plt.xticks(())\n plt.yticks(())\n return plt\n\n\n# Example 1: The two class of data can be seprated using a line.\n\n# In[26]:\n\n#Load the data\ndata = np.loadtxt('data1.txt', delimiter=\",\")\nX = data[:,:2]\nY = data[:,2]\n\n\n# Example specific input parameters\n\n# In[27]:\n\ndegree=1 #Degree of \nlambda_=1e-5 #Rregularaization parameter\n\n\n# Running Logistic Regression and plotting the data and decision boundary\n\n# In[28]:\n\nX = mapFeature(X[:,0], X[:,1],degree)\nlogreg = linear_model.LogisticRegression(C=1/lambda_)\nlogreg.fit(X, Y)\nplt=plot_boundary(X,Y,degree,logreg)\nplt=plot_boundary(X,Y,degree,logreg)\nplt.xlabel('X1')\nplt.ylabel('X2')\nplt.show()\n\n\n# Example 2: When the data is not easy to separate using a line\n\n# In[29]:\n\n#Load the data\ndata = np.loadtxt('data2.txt', delimiter=\",\")\nX = data[:,:2]\nY = data[:,2]\n\n\n# Example specific input parameters\n\n# In[30]:\n\ndegree=6\nlambda_=1e-5\n\n\n# In[31]:\n\nX = mapFeature(X[:,0], X[:,1],degree)\nlogreg = linear_model.LogisticRegression(C=1/lambda_)\nlogreg.fit(X, Y)\nprint_score(X,Y,logreg)\nplt=plot_boundary(X,Y,degree,logreg)\nplt.xlabel('X1')\nplt.ylabel('X2')\nplt.savefig('logistic')\nplt.show()\n\n","sub_path":"LogisticRegression/LogisticRegression_SKLearn.py","file_name":"LogisticRegression_SKLearn.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"295785582","text":"#!/usr/bin/env python\n\n\"\"\"\nThis is a script that:\n\n- runs `git fetch`\n- creates a branch release/ based on origin/develop\n- pushes this branch\n- opens your web browser to the create PR page for the pushed branch (with master as\nthe base branch)\n\nThe script will abort if:\n\n- a tag for the current version already exists\n- there are news fragments on origin/develop\n- there are uncommitted changes\n- the release branch for the current version already exists\n\"\"\"\n\nimport argparse\nimport subprocess\nimport webbrowser\nfrom urllib.parse import quote, urlencode\n\nfrom script_utils.command import CommandError, print_error\nfrom script_utils.git import (\n any_uncommitted_changes,\n local_branch_exists,\n remote_branch_exists,\n remote_tag_exists,\n)\nfrom script_utils.news_fragments import list_news_fragments\nfrom script_utils.versioning import get_current_version\n\nGITHUB_BASE_REPO_URL = 'https://github.com/cgsunkel/data-hub-api'\nRELEASE_GUIDE_URL = (\n 'https://github.com/uktrade/data-hub-api/blob/develop/docs/'\n 'How%20to%20prepare%20a%20release.md'\n)\nPR_BODY_TEMPLATE = \"\"\"This is the release PR for version {version}.\n\nRefer to [How to prepare a release]({release_guide_url}) for further information and the next \\\nsteps.\n\"\"\"\n\n# Currently no real arguments – just used for --help etc.\nparser = argparse.ArgumentParser(\n description='Create and push a release branch for the current version.',\n)\n\n\ndef create_release_branch():\n \"\"\"Create and push a release branch.\"\"\"\n remote = 'origin'\n\n if any_uncommitted_changes():\n raise CommandError(\n 'There are uncommitted changes. Please commit, stash or delete them and try again.',\n )\n\n subprocess.run(['git', 'fetch'], check=True)\n subprocess.run(['git', 'checkout', f'{remote}/develop'], check=True, capture_output=True)\n\n version = get_current_version()\n\n branch = f'release/{version}'\n tag = f'v{version}'\n\n if remote_tag_exists(tag):\n raise CommandError(\n f'A remote tag {tag} currently exists. It looks like version {version} has '\n f'already been released.',\n )\n\n news_fragment_paths = list_news_fragments()\n if news_fragment_paths:\n joined_paths = '\\n'.join(str(path) for path in news_fragment_paths)\n\n raise CommandError(\n 'These are news fragments on origin/develop:\\n\\n'\n f'{joined_paths}\\n\\n'\n 'Is the changelog up to date?',\n )\n\n if local_branch_exists(branch):\n raise CommandError(\n f'Branch {branch} already exists locally. Please delete it and try again.',\n )\n\n if remote_branch_exists(branch):\n raise CommandError(\n f'Branch {branch} already exists remotely. Please delete it on GitHub and try again.',\n )\n\n subprocess.run(['git', 'checkout', '-b', branch, f'{remote}/develop'], check=True)\n subprocess.run(['git', 'push', '--set-upstream', remote, branch], check=True)\n\n params = {\n 'expand': '1',\n 'title': f'Release {version}',\n 'body': PR_BODY_TEMPLATE.format(version=version, release_guide_url=RELEASE_GUIDE_URL),\n }\n encoded_params = urlencode(params)\n escaped_branch_name = quote(branch)\n webbrowser.open(\n f'{GITHUB_BASE_REPO_URL}/compare/master...{escaped_branch_name}?{encoded_params}',\n )\n\n return branch\n\n\ndef main():\n \"\"\"Run the script from the command line.\"\"\"\n parser.parse_args()\n\n try:\n branch_name = create_release_branch()\n except (CommandError, subprocess.CalledProcessError) as exc:\n print_error(exc)\n return\n\n print( # noqa: T001\n f'Branch {branch_name} was created, pushed and opened in your web browser.',\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/create_release_pr.py","file_name":"create_release_pr.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"205909349","text":"\"\"\"\nTetmesh based on cartesian grid for piecewise linear interpolation\n\"\"\"\nimport logging\n\nimport numpy as np\nfrom LoopStructural.interpolators.cython.dsi_helper import cg, constant_norm, fold_cg\nfrom .base_structured_3d_support import BaseStructuredSupport\n\nfrom LoopStructural.utils import getLogger\nlogger = getLogger(__name__)\n\nclass UnStructuredTetMesh:\n \"\"\"\n\n \"\"\"\n def __init__(self, nodes, elements, neighbours,aabb_nsteps=None):\n \"\"\"An unstructured mesh defined by nodes, elements and neighbours\n An axis aligned bounding box (AABB) is used to speed up finding \n which tetra a point is in.\n The aabb grid is calculated so that there are approximately 10 tetra per\n element. \n\n Parameters\n ----------\n nodes : array or array like \n container of vertex locations\n elements : array or array like, dtype cast to long\n container of tetra indicies\n neighbours : array or array like, dtype cast to long\n array containing element neighbours\n aabb_nsteps : list, optional\n force nsteps for aabb, by default None\n \"\"\"\n self.nodes = np.array(nodes)\n self.n_nodes = self.nodes.shape[0]\n self.neighbours = np.array(neighbours,dtype=np.int64)\n self.elements = np.array(elements,dtype=np.int64)\n self.barycentre = np.sum(self.nodes[self.elements][:, :, :],\n axis=1) / 4.\n self.minimum = np.min(self.nodes,axis=0)\n self.maximum = np.max(self.nodes,axis=0)\n length = (self.maximum-self.minimum)\n self.minimum -= length*.1\n self.maximum += length*.1\n if aabb_nsteps==None:\n box_vol = np.product(self.maximum-self.minimum)\n element_volume = box_vol / (len(self.elements)/20)\n # calculate the step vector of a regular cube\n step_vector = np.zeros(3)\n step_vector[:] = element_volume ** (1. / 3.)\n # number of steps is the length of the box / step vector\n aabb_nsteps = np.ceil((self.maximum-self.minimum) / step_vector).astype(int)\n #make sure there is at least one cell in every dimension\n aabb_nsteps[aabb_nsteps<2] =2 \n aabb_nsteps = np.array(aabb_nsteps,dtype=int)\n step_vector = (self.maximum-self.minimum)/(aabb_nsteps-1)\n self.aabb_grid = BaseStructuredSupport(self.minimum,nsteps=aabb_nsteps,step_vector=step_vector)\n # make a big table to store which tetra are in which element.\n # if this takes up too much memory it could be simplified by using sparse matrices or dict but \n # at the expense of speed \n self.aabb_table = np.zeros((self.aabb_grid.n_elements,len(self.elements)),dtype=bool)\n self.aabb_table[:] = False\n self._initialise_aabb()\n \n def _initialise_aabb(self):\n \"\"\"assigns the tetras to the grid cells where the bounding box\n of the tetra element overlaps the grid cell. \n It could be changed to use the separating axis theorem, however this would require \n significantly more calculations. (12 more I think).. #TODO test timing\n \"\"\"\n # calculate the bounding box for all tetraherdon in the mesh\n # find the min/max extents for xyz\n tetra_bb = np.zeros((self.elements.shape[0],19,3))\n minx = np.min(self.nodes[self.elements,0],axis=1)\n maxx = np.max(self.nodes[self.elements,0],axis=1)\n miny = np.min(self.nodes[self.elements,1],axis=1)\n maxy = np.max(self.nodes[self.elements,1],axis=1)\n minz = np.min(self.nodes[self.elements,2],axis=1)\n maxz = np.max(self.nodes[self.elements,2],axis=1)\n ix,iy,iz = self.aabb_grid.global_index_to_cell_index(np.arange(self.aabb_grid.n_elements))\n cix,ciy,ciz = self.aabb_grid.cell_corner_indexes(ix,iy,iz)\n px,py,pz = self.aabb_grid.node_indexes_to_position(cix,ciy,ciz)\n x_boundary = px[:,[0,1]]\n y_boundary = py[:,[0,2]]\n z_boundary = pz[:,[0,3]]\n a = np.logical_and(minx[None,:] > x_boundary[:,None,0],minx[None,:] < x_boundary[:,None,1]) # min point between cell\n b = np.logical_and(maxx[None,:] < x_boundary[:,None,1],maxx[None,:] > x_boundary[:,None,0]) # max point between cell\n c = np.logical_and(minx[None,:] < x_boundary[:,None,0],maxx[None,:] > x_boundary[:,None,0]) # min point < than cell & max point > cell\n\n x_logic = np.logical_or(np.logical_or(a,b),c)\n\n a = np.logical_and(miny[None,:] > y_boundary[:,None,0],miny[None,:] < y_boundary[:,None,1]) # min point between cell\n b = np.logical_and(maxy[None,:] < y_boundary[:,None,1],maxy[None,:] > y_boundary[:,None,0]) # max point between cell\n c = np.logical_and(miny[None,:] < y_boundary[:,None,0],maxy[None,:] > y_boundary[:,None,0]) # min point < than cell & max point > cell\n\n y_logic = np.logical_or(np.logical_or(a,b),c)\n\n\n a = np.logical_and(minz[None,:] > z_boundary[:,None,0],minz[None,:] < z_boundary[:,None,1]) # min point between cell\n b = np.logical_and(maxz[None,:] < z_boundary[:,None,1],maxz[None,:] > z_boundary[:,None,0]) # max point between cell\n c = np.logical_and(minz[None,:] < z_boundary[:,None,0],maxz[None,:] > z_boundary[:,None,0]) # min point < than cell & max point > cell\n\n z_logic = np.logical_or(np.logical_or(a,b),c)\n logic = np.logical_and(x_logic,y_logic)\n logic = np.logical_and(logic,z_logic)\n # inside_x = \n # # add the corners of the cube\n # tetra_bb[:,0,:] = np.array([minx,miny,minz]).T\n # tetra_bb[:,1,:] = np.array([maxx,miny,minz]).T\n # tetra_bb[:,2,:] = np.array([maxx,maxy,minz]).T\n # tetra_bb[:,3,:] = np.array([minx,maxy,minz]).T\n # tetra_bb[:,4,:] = np.array([minx,miny,maxz]).T\n # tetra_bb[:,5,:] = np.array([maxx,miny,minz]).T\n # tetra_bb[:,6,:] = np.array([maxx,maxy,maxz]).T\n # tetra_bb[:,7,:] = np.array([minx,maxy,maxz]).T\n # # add centre\n # tetra_bb[:,8,:] = np.array([(maxx-minx)/2,(maxy-miny)/2,(maxy-miny)/2]).T\n\n \n\n\n # # find which \n # cell_index_ijk = np.array(self.aabb_grid.position_to_cell_index(tetra_bb.reshape((-1,3)))).swapaxes(0,1)\n # cell_index_global = cell_index_ijk[:, 0] + self.aabb_grid.nsteps_cells[ None, 0] \\\n # * cell_index_ijk[:, 1] + self.aabb_grid.nsteps_cells[ None, 0] * \\\n # self.aabb_grid.nsteps_cells[ None, 1] * cell_index_ijk[:, 2]\n # bbcorners_grid_cell = cell_index_global.reshape((tetra_bb.shape[0],tetra_bb.shape[1]))\n # tetra_index = np.arange(self.elements.shape[0],dtype=int)\n # tetra_index = np.tile(tetra_index,(9,1)).T\n self.aabb_table = logic\n #[bbcorners_grid_cell,tetra_index] = True\n\n @property\n def ntetra(self):\n return self.elements.shape[0]\n \n @property\n def n_elements(self):\n return self.ntetra\n\n @property\n def n_cells(self):\n return None\n\n def barycentre(self, elements = None):\n \"\"\"\n Return the barycentres of all tetrahedrons or of specified tetras using\n global index\n\n Parameters\n ----------\n elements - numpy array\n global index\n\n Returns\n -------\n\n \"\"\"\n np.sum(self.nodes[self.elements][:, :, :],\n axis=1) / 4.\n\n\n def evaluate_value(self, pos, property_array):\n \"\"\"\n Evaluate value of interpolant\n\n Parameters\n ----------\n pos - numpy array\n locations\n prop - string\n property name\n\n Returns\n -------\n\n \"\"\"\n values = np.zeros(pos.shape[0])\n values[:] = np.nan\n vertices, c, tetras, inside = self.get_element_for_location(pos)\n values[inside] = np.sum(c[inside,:]*property_array[tetras[inside,:]],axis=1)\n return values\n\n def evaluate_gradient(self, pos, property_array):\n \"\"\"\n Evaluate the gradient of an interpolant at the locations\n\n Parameters\n ----------\n pos - numpy array\n locations\n prop - string\n property to evaluate\n\n\n Returns\n -------\n\n \"\"\"\n values = np.zeros(pos.shape)\n values[:] = np.nan\n vertices, element_gradients, tetras, inside = self.get_element_gradient_for_location(pos)\n #grads = np.zeros(tetras.shape)\n values[inside,:] = (element_gradients[inside,:,:]*property_array[tetras[inside,None,:]]).sum(2)\n length = np.sum(values[inside,:],axis=1)\n # values[inside,:] /= length[:,None]\n return values\n\n def inside(self, pos):\n inside = np.ones(pos.shape[0]).astype(bool)\n for i in range(3):\n inside *= pos[:, i] > self.origin[None, i]\n inside *= pos[:, i] < self.origin[None, i] + \\\n self.step_vector[None, i] * self.nsteps_cells[None, i]\n return inside\n\n def get_elements(self):\n return self.elements\n def get_element_for_location(self, points):\n \"\"\"\n Determine the tetrahedron from a numpy array of points\n\n Parameters\n ----------\n pos : np.array\n\n\n\n Returns\n -------\n\n \"\"\"\n cell_index = np.array(self.aabb_grid.position_to_cell_index(points)).swapaxes(0,1)\n global_index = cell_index[:, 0] + self.aabb_grid.nsteps_cells[ None, 0] \\\n * cell_index[:, 1] + self.aabb_grid.nsteps_cells[ None, 0] * \\\n self.aabb_grid.nsteps_cells[ None, 1] * cell_index[:, 2]\n tetra_indices = self.aabb_table[global_index,:]\n row, col = np.where(tetra_indices)\n vertices = self.nodes[self.elements[col,:]]\n pos = points[row,:]\n vap = pos[:, :] - vertices[:, 0, :]\n vbp = pos[:, :] - vertices[:, 1, :]\n # # vcp = p - points[:, 2, :]\n # # vdp = p - points[:, 3, :]\n vab = vertices[:, 1, :] - vertices[:, 0, :]\n vac = vertices[:, 2, :] - vertices[:, 0, :]\n vad = vertices[:, 3, :] - vertices[:, 0, :]\n vbc = vertices[:, 2, :] - vertices[:, 1, :]\n vbd = vertices[:, 3, :] - vertices[:, 1, :]\n\n va = np.einsum('ij, ij->i', vbp, np.cross(vbd, vbc, axisa=1, axisb=1)) / 6.\n vb = np.einsum('ij, ij->i', vap, np.cross(vac, vad, axisa=1, axisb=1)) / 6.\n vc = np.einsum('ij, ij->i', vap, np.cross(vad, vab, axisa=1, axisb=1)) / 6.\n vd = np.einsum('ij, ij->i', vap, np.cross(vab, vac, axisa=1, axisb=1)) / 6.\n v = np.einsum('ij, ij->i', vab, np.cross(vac, vad, axisa=1, axisb=1)) / 6.\n c = np.zeros((va.shape[0], 4))\n c[:, 0] = va / v\n c[:, 1] = vb / v\n c[:, 2] = vc / v\n c[:, 3] = vd / v\n # inside = np.ones(c.shape[0],dtype=bool)\n mask = np.all(c>=0,axis=1)\n verts = np.zeros((points.shape[0],4,3))\n bc = np.zeros((points.shape[0],4))\n tetras = np.zeros(points.shape[0],dtype='int64')\n inside = np.zeros(points.shape[0],dtype=bool)\n\n verts[row[mask],:,:] = vertices[mask,:,:]\n bc[row[mask],:] = c[mask,:]\n tetras[row[mask]] = col[mask]\n inside[row[mask]]=True\n return verts, bc, self.elements[tetras], inside\n \n\n def get_element_gradients(self, elements = None):\n \"\"\"\n Get the gradients of all tetras\n\n Parameters\n ----------\n elements\n\n Returns\n -------\n\n \"\"\"\n # points = np.zeros((5, 4, self.n_cells, 3))\n # points[:, :, even_mask, :] = nodes[:, even_mask, :][self.tetra_mask_even, :, :]\n # points[:, :, ~even_mask, :] = nodes[:, ~even_mask, :][self.tetra_mask, :, :]\n\n # # changing order to points, tetra, nodes, coord\n # points = points.swapaxes(0, 2)\n # points = points.swapaxes(1, 2)\n if elements is None:\n elements = np.arange(0,self.n_elements,dtype=int)\n ps = self.nodes[self.elements,:]#points.reshape(points.shape[0] * points.shape[1], points.shape[2], points.shape[3])\n #vertices = self.nodes[self.elements[col,:]]\n m = np.array(\n [[(ps[:, 1, 0] - ps[:, 0, 0]), (ps[:, 1, 1] - ps[:, 0, 1]),\n (ps[:, 1, 2] - ps[:, 0, 2])],\n [(ps[:, 2, 0] - ps[:, 0, 0]), (ps[:, 2, 1] - ps[:, 0, 1]),\n (ps[:, 2, 2] - ps[:, 0, 2])],\n [(ps[:, 3, 0] - ps[:, 0, 0]), (ps[:, 3, 1] - ps[:, 0, 1]),\n (ps[:, 3, 2] - ps[:, 0, 2])]])\n I = np.array(\n [[-1., 1., 0., 0.],\n [-1., 0., 1., 0.],\n [-1., 0., 0., 1.]])\n m = np.swapaxes(m, 0, 2)\n element_gradients = np.linalg.inv(m)\n\n element_gradients = element_gradients.swapaxes(1, 2)\n element_gradients = element_gradients @ I\n\n return element_gradients[elements,:,:]\n\n def get_element_gradient_for_location(self, pos):\n \"\"\"\n Get the gradient of the tetra for a location\n\n Parameters\n ----------\n pos\n\n Returns\n -------\n\n \"\"\"\n vertices, bc, tetras, inside = self.get_element_for_location(pos)\n ps = vertices\n m = np.array(\n [[(ps[:, 1, 0] - ps[:, 0, 0]), (ps[:, 1, 1] - ps[:, 0, 1]),(ps[:, 1, 2] - ps[:, 0, 2])],\n [(ps[:, 2, 0] - ps[:, 0, 0]), (ps[:, 2, 1] - ps[:, 0, 1]),(ps[:, 2, 2] - ps[:, 0, 2])],\n [(ps[:, 3, 0] - ps[:, 0, 0]), (ps[:, 3, 1] - ps[:, 0, 1]),(ps[:, 3, 2] - ps[:, 0, 2])]])\n I = np.array(\n [[-1., 1., 0., 0.],\n [-1., 0., 1., 0.],\n [-1., 0., 0., 1.]])\n m = np.swapaxes(m, 0, 2)\n element_gradients = np.linalg.inv(m)\n\n element_gradients = element_gradients.swapaxes(1, 2)\n element_gradients = element_gradients @ I\n return vertices, element_gradients, tetras, inside\n\n\n\n \n\n def get_neighbours(self):\n \"\"\"\n This function goes through all of the elements in the mesh and assembles a numpy array\n with the neighbours for each element\n\n Returns\n -------\n\n \"\"\"\n return self.neighbours\n\n\n\n","sub_path":"LoopStructural/interpolators/unstructured_tetra.py","file_name":"unstructured_tetra.py","file_ext":"py","file_size_in_byte":14186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300229677","text":"from django.urls import path\nfrom . import views\n\napp_name = 'landing'\nurlpatterns = [\n path('', views.index, name= 'index' ),\n path('downloads', views.downloads, name='downloads'),\n path('about', views.about, name='about'),\n path('/',views.CollegeDetailView.as_view(),name='detail')\n]\n","sub_path":"landing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166500527","text":"#!/usr/bin/env python\n\nimport sys\nsys.path.append('/home/sepp/dev/pyHaltija')\nimport wgboard_bbb\n\nfrom flask import Flask, request, Response\napp = Flask(__name__)\n\n\n\n@app.route('/wgcontrol')\ndef api_wgcontrol():\n if 'command' in request.args and 'what' in request.args and 'switchcommand' in request.args:\n if request.args['command']=='switch':\n if request.args['what']=='upper':\n if request.args['switchcommand']=='open':\n wgboard_bbb.wg_win_open_upper()\n return 'opening upper window'\n else:\n if request.args['switchcommand']=='close':\n wgboard_bbb.wg_win_close_upper()\n return 'closing upper window'\n else:\n return 'Usage: switchcommand must be open or close'\n else:\n if request.args['what']=='lower':\n if request.args['switchcommand']=='open':\n wgboard_bbb.wg_win_open_lower()\n return 'opening lower window'\n else:\n if request.args['switchcommand']=='close':\n wgboard_bbb.wg_win_close_lower()\n return 'closing lower window'\n else:\n return 'Usage: switchcommand must be open or close'\n else:\n return 'Usage: what must be lower or upper'\n else:\n return 'Usage: command must be switch'\n\n else:\n resp = Response('Usage: /wgcontrol?command=switch&what=upper/lower&switchcommand=open/close', status=500)\n return resp\n\nif __name__ == '__main__':\n app.run(host= '0.0.0.0')\n","sub_path":"webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497348115","text":"\n# coding: utf-8\n\nfrom pixivpy_async import *\nfrom pixivpy_async.sync import *\nfrom time import sleep\nimport json\nimport os\nimport re\n\n# ログイン処理\n# Log in to pixiv\nf = open(\"client.json\", \"r\")\nclient_info = json.load(f)\nf.close()\napi = PixivAPI()\napi.login(client_info[\"pixiv_id\"], client_info[\"password\"])\naapi = AppPixivAPI()\naapi.login(client_info[\"pixiv_id\"], client_info[\"password\"])\n\n# 入力された絵師IDから絵師情報を取得\n# Enter the Illustrator-Id\nillustrator_pixiv_id = int(input(\"Type illustrator pixiv id number:\\n>>>\"))\n\n# ユーザ情報(作品数、絵師名)を取得\n# get illustratir infomation\nuser_info_json = aapi.user_detail(illustrator_pixiv_id)\ntotal_works = user_info_json.profile.total_illusts + user_info_json.profile.total_manga\nillustrator_name = user_info_json.user.name\n\n# イラスト情報を取得\n# get illustrations information\nworks_info = api.users_works(illustrator_pixiv_id, page = 1, per_page = total_works)\n\n# 渡されたディレクトリが存在しない場合に作成するLambda関数\n# make directories\nmkdirExceptExist = lambda path: \"\" if os.path.exists(path) else os.mkdir(path)\n\nsaving_direcory_path = \"./pixiv_images/\" + illustrator_name + \"/\"\nsaving_direcory_path_R18 = saving_direcory_path + \"R-18/\"\n\n# 保存用フォルダがない場合は生成\n# make directories\nmkdirExceptExist(\"./pixiv_images\")\nmkdirExceptExist(saving_direcory_path) \nmkdirExceptExist(saving_direcory_path_R18)\n\n# ダウンロード開始\n# Display information of illustrator and illustrations & Download \nseparator = \"============================================================\"\nprint(\"Artist: %s\" % illustrator_name)\nprint(\"Works: %d\" % total_works)\nprint(separator)\n\nfor i, work_info in enumerate(works_info.response):\n\n\twork_title = work_info.title\n\tprint(\"Procedure: %d/%d\" % (i + 1,total_works))\n\tprint(\"Title: %s\" % work_title)\n\tprint(separator)\n\n\t# ファイル名に適した形にリネーム\n\t# rename the file \n\twork_title = re.sub(\"[: | \\? | . | \\\" | < | > | \\ | /]\",\"\",work_title)\n\t\n\tif \"R-18\" in work_info.tags: \n\t\tdir = saving_direcory_path_R18\n\telse:\n\t\tdir = saving_direcory_path\n\n\t# 漫画の場合\n\t# illustrations with only one picture\n\tif work_info.is_manga:\n\t\tmanga_info = api.works(work_info.id)\n\t\tfor page_no in range(0, manga_info.response[0].page_count):\n\t\t\tpage_info = manga_info.response[0].metadata.pages[page_no]\n\t\t\tnum = str(page_no) if len(str(page_no)) > 1 else \"0\" + str(page_no)\n\t\t\taapi.download(page_info.image_urls.large, path = dir, name = work_title + num + \".jpg\")\n\n\t# イラストの場合\n\t# illustrations with more than one picture\n\telse:\n\t\taapi.download(work_info.image_urls.large, path = dir, name = work_title + \".jpg\")\n\nprint(\"\\nThat\\\"s all.\")","sub_path":"Python_Pixiv/get_illustrations.py","file_name":"get_illustrations.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306510541","text":"\"\"\"\nDemonstration der Nutzung von inRange im HSV-Farbschema.\n\nZeichnet auf 3 Schnitten im Kamerabild die gefundenen Linienstückchen als grüne\nRechtecke ein.\nWird die eine Linie zu breit, wird das Rechteck rot eingefärbt.\nDas Zentrum aller Linienstückchen in einem Schnitt wird mit einem Punkt markiert.\nGrüne Areale ab einer gewissen Größe werden blau umrandet.\n\nDas Beispielprogramm enthält keine Linienfolgen-Logik.\nEs gibt die Zentren der gefundenen Linienstückchen des untersten Schnittes in der\nKommandozeile aus.\nEs fährt schnell geradeaus, wenn mindestens 1 Linienfragment gesehen wird,\nsonst langsam.\n\nSteuerung:\nPausieren mit p,\nbewegen mit w,a,s,d,\nrotieren mit q,e,\nbeenden mit k\n\nEinstellungen:\nPIXEL_BREITE, PIXEL_HOEHE: Auflösung des Kamerabilds. Lieber nicht verändern, da alle\nPositionen im Kamerabild mit Konstanten gehardcoded sind.\nPARCOURS_PFAD: Pfad zum Parcours-Bild. Zur Auswahl stehen momentan:\n - parcours_cold_RESIZED.JPG und\n - parcours_warm_RESIZED.JPG\nblack_lower_limit, black_lower_limit: schwarz-Grenzen im HSV-Farbschema\ngreen_lower_limit, green_upper_limit: grün-Grenzen im HSV-Farbschema\nkamera_position: \"Größe des Roboters\" - Abstand der Kamera zum Rotationszentrum des Roboters\nkamera_hoehe: Skalierung des Parcours und damit Simulation der Montagehöhe der Kamera (schaut senkrecht nach unten)\nstart_x, start_y: Startposition auf dem Parcours\nsimulator.ROBOT_WIDTH: Abstand der Fahrketten voneinander\nsimulator.SPEED_FACTOR: Fahr- und Rotationsgeschwindigkeit des Roboters\nsimulator.MAXIMUM_ACCELERATION, simulator.MAXIMUM_DECELERATION: Trägheit des Roboters\n\"\"\"\n\nfrom Simulator import Simulator\nimport time\nfrom cv2 import cv2\nimport numpy\n\n#\n# Einstellungen\n#\nPIXEL_BREITE = 320\nPIXEL_HOEHE = 240\nPARCOURS_PFAD = './parcours_cold_RESIZED.JPG'\n\n# H S V\nblack_lower_limit = numpy.uint8([0, 0, 0])\nblack_upper_limit = numpy.uint8([255, 50, 100])\n# R G B\n#black_lower_limit = numpy.uint8([0, 0, 0])\n#black_upper_limit = numpy.uint8([50, 50, 50])\n# H S V\ngreen_lower_limit = numpy.uint8([40, 80, 20])\ngreen_upper_limit = numpy.uint8([80, 255, 255])\n\nGRUEN = (0, 255, 0)\nGELB = (0,255,255)\nROT = (0, 0, 255)\n\ndef line_slice(roi_kreuzung, dieser_frame, offset):\n \"\"\"\n Zeichnet auf auf einem Schnit am gegebenen Y-Offset im Kamerabild die gefundenen\n Linienstückchen als grüne Rechtecke ein.\n Wird die eine Linie zu breit, wird das Rechteck rot eingefärbt.\n Das Zentrum aller Linienstückchen in einem Schnitt wird mit einem Punkt markiert.\n \"\"\"\n yoffset = PIXEL_HOEHE - (PIXEL_HOEHE - 200) - 20 - offset\n # Horizontalen Streifen an y-Position \"offset\" herausschneiden\n roi_line = dieser_frame[PIXEL_HOEHE - 20 - offset:PIXEL_HOEHE - 1 - offset, 0:PIXEL_BREITE - 1]\n # in HSV-Farbschema umwandeln\n hsv = cv2.cvtColor(roi_line, cv2.COLOR_BGR2HSV)\n # Maske erstellen (Monochromes Bild: Linie weiß, alles andere schwarz)\n black_mask = cv2.inRange(hsv, black_lower_limit, black_upper_limit)\n # Konturen extrahieren\n _, konturen, _ = cv2.findContours(black_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cx = 0\n cy = yoffset+5\n cnt = 0\n farbe = GRUEN\n # Liste der X-Positionen der Zentren der gefundenen Linienstücke\n ret = []\n is_kreuzung = False\n for kontur in konturen:\n # Rechteck um die Kontur erhalten\n x, y, w, h = cv2.boundingRect(kontur)\n # zu kleine Konturen wegfiltern\n if w > 10:\n # zu große Konturen rot einfärben\n if w > 150:\n farbe = ROT\n is_kreuzung = True\n # sonst grün einfärben\n else:\n farbe = GRUEN\n # Rechteck um die Kontur zeichnen\n cv2.rectangle(roi_kreuzung, (x, y + yoffset), (x + w, y + yoffset + h), farbe, 2)\n # Summe aller x-Positionen der Zentren der gefundenen Rechtecke bilden\n cx = cx + int(x + w / 2)\n # Anzahl der gefundenen Rechecke mitzählen\n cnt = cnt + 1\n # Rote Rechtecke: X-Position ist 0 (Mitte des Kamerabildes)\n if is_kreuzung:\n ret.append(0)\n # Grüne Rechtecke: Abweichung von Bildmitte an Liste anfügen\n else:\n ret.append(cx - PIXEL_BREITE / 2)\n # keine Linienstücke gefunden: Durchnitt aller X-Positionen ist Bildmitte\n if cx is 0:\n cx = (PIXEL_BREITE - 1) / 2\n # Linienstückchen gefunden: Durchschnitt aller X-Positionen errechnen\n else:\n cx = cx / cnt\n # Kreis zeichnen an durchschnittlicher X-Position aller gefundenen Linienstückchen\n cv2.circle(roi_kreuzung, (int(cx), int(cy)), 5, farbe, -1)\n # Ergebnisliste zurückgeben: Liste der Abweichung der Linie von Mitte in Pixel\n return ret\n\ndef center_line(roi_kreuzung):\n \"\"\"\n Senkrechte Linie in der Bildmitte einzeichnen\n \"\"\"\n cv2.line(roi_kreuzung,(int((PIXEL_BREITE-1)/2),0),(int((PIXEL_BREITE-1)/2),PIXEL_HOEHE-1),GELB,1)\n\ndef green_squares(roi_kreuzung):\n \"\"\"\n Grüne Areale ab einer gewissen Größe werden blau umrandet.\n \"\"\"\n # in HSV-Farbschema konvertieren\n hsv2 = cv2.cvtColor(roi_kreuzung, cv2.COLOR_BGR2HSV)\n # Maske erstellen (Monochromes Bild: grüne Areale weiß, alles andere schwarz)\n green_mask = cv2.inRange(hsv2, green_lower_limit, green_upper_limit)\n # Konturen extrahieren\n _, konturen, _ = cv2.findContours(green_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for kontur in konturen:\n # zu kleine Konturen wegfiltern\n if cv2.contourArea(kontur) > 4000:\n # Rechteck um die Kontur erhalten\n x, y, w, h = cv2.boundingRect(kontur)\n # Rechteck um die Kontur zeichnen\n cv2.rectangle(roi_kreuzung, (x, y), (x + w, y + h), (255, 0, 0), 2)\n\n#\n# 3...2...1 GO!!\n#\ntry:\n # Abstand der Kamera vom Rotationszentrum des Roboters in Pixel:\n # 500 ist halbwegs realistisch, aber da dieser Parcours wesentlich gedrungener daher-\n # kommt als ein echter, ist es denke ich OK wenn man hier auf 300 runter geht.\n kamera_position = 300\n # Skalierungsfaktor für den Parcours (simuliert die Höhe, in der die Kamera montiert ist):\n # Ich denke 0.7 ist halbwegs realistisch.\n kamera_hoehe = 0.7\n start_x = 260\n start_y = 2850\n simulator = Simulator(PARCOURS_PFAD, start_x, start_y, PIXEL_BREITE, PIXEL_HOEHE, kamera_hoehe, kamera_position)\n # Breite des Roboters anpassen:\n #simulator.ROBOT_WIDTH = 200\n # Geschwindigkeit der simulierten Bewegung anpassen:\n #simulator.SPEED_FACTOR = 5.0\n # Trägheit des Roboters anpassen:\n #simulator.MAXIMUM_ACCELERATION = 0.2\n #simulator.MAXIMUM_DECELERATION = 1\n\n # wird zum Testen mit dem richtigen Roboter durch die echte PiCam ersetzt\n kamera = simulator\n\n # wird zum Testen mit dem richtigen Roboter durch das AFMotorShield ersetzt\n motoren = simulator\n\n # CPU quälen:\n bla = 0\n while True:\n # frame lesen\n dieser_frame = kamera.get_frame()\n # kleineren Ausschnitt des Bildes herausschneiden, damit die folgenden Schritte\n # etwas fixer gehen\n roi_kreuzung = dieser_frame[PIXEL_HOEHE - 200:PIXEL_HOEHE - 1, 0:PIXEL_BREITE - 1]\n # grüne Areale blau umranden\n green_squares(roi_kreuzung)\n # Auf Höhe 30 Pixel von Bildunterkante nach schwarzen Arealen suchen, einzeichnen\n # und X-Positionen der gefundenen Linienstückchen als Liste zurückgeben.\n lines = line_slice(roi_kreuzung, dieser_frame, 30)\n # Auf Höhe 90 Pixel von Bildunterkante nach schwarzen Arealen suchen und einzeichnen\n line_slice(roi_kreuzung, dieser_frame, 90)\n # Auf Höhe 150 Pixel von Bildunterkante nach schwarzen Arealen suchen und einzeichnen\n line_slice(roi_kreuzung, dieser_frame, 150)\n # Senkrechte Linie in der Mitte des Bildes zeichnen\n center_line(roi_kreuzung)\n\n # Kamerabild anzeigen\n cv2.imshow(\"Maze Runner\", roi_kreuzung)\n\n # Motoren ansteuern\n if len(lines) > 0:\n # Linienstückchen gefunden\n motoren.set_speed(30, 30)\n # gefundene Linien ausgeben\n print(lines)\n else:\n # keine Linienstückchen gefunden\n motoren.set_speed(10, 10)\n print('No line on Sensor')\n\n # Pausieren mit p, bewegen mit w,a,s,d, rotieren mit q,e, beenden mit k\n # wird zum testen mit dem richtigen Roboter ersetzt durch cv2.waitKey(10)\n simulator.handle_interactive_mode(cv2.waitKey(10))\n\nexcept KeyboardInterrupt:\n print(\"Abbruch durch Benutzer... Tschau!\")\n pass\n\nfinally:\n print(\"Räume auf...\")\n simulator.close()\n","sub_path":"test_mit_inRange.py","file_name":"test_mit_inRange.py","file_ext":"py","file_size_in_byte":8776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398241357","text":"from sklearn.feature_selection import f_regression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\n# loading data\ndata = pd.read_csv('/Users/moshi/Documents/PycharmProjects/train.csv')\n\n# create the regression: declare independent and dependent variable\nfeatures = ['battery_power', 'blue', 'dual_sim', 'fc', 'int_memory', 'mobile_wt',\n 'pc', 'px_height', 'px_width', 'ram', 'sc_h', 'sc_w', 'talk_time', 'three_g', 'touch_screen', 'wifi']\ny = data['price_range']\nx = data[features]\n\n# scaling the data\nscaler = StandardScaler()\nscaler.fit(x)\nscaled_x = scaler.transform(x)\n\n# regression\nreg = LinearRegression()\nreg.fit(scaled_x, y)\ncoefs = reg.coef_\n\nprint(\"This is the intercept: \", reg.intercept_)\n\n# calculate r-squared\nr = reg.score(scaled_x, y)\nprint(\"This is the R^2:\", r)\n\n# calculate adjusted r-squared\n\n\ndef adj_r2(x, y):\n r2 = reg.score(x, y)\n n = x.shape[0]\n p = x.shape[1]\n adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)\n return adjusted_r2\n\n\nrr = adj_r2(scaled_x, y)\nprint('This is the adjusted R^2:', rr)\nprint('')\n\n# calculating p-values\np_values = f_regression(scaled_x, y)[1]\np_values_rounded = p_values.round(3)\n\nreg_summay = pd.DataFrame(data=x.columns.values, columns=['Features'])\nreg_summay['Coefficients'] = coefs\nreg_summay['p-values'] = p_values_rounded\nprint(reg_summay)\n\nprint(\"Removing features with p-values over .5 has slightly increasae the power of this linear regrssion\")\n","sub_path":"moblie-phonesdataset/removing-variables.py","file_name":"removing-variables.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236974153","text":"#!/usr/bin/env python3\n#\n# A script to label images of the form [id],[x-euler],[y-euler],[z-euler]\n#\n\nimport os, random, shutil, math, re, errno\nimport numpy as np\n\n#TODO: holy crap gotta figure out all these frames\ndef cart2sph(x, y, z):\n '''cartesian to spherical coords'''\n hxy = np.hypot(x, y)\n r = np.hypot(hxy, z)\n el = np.arctan2(z, hxy)\n az = np.arctan2(y, x)\n return az, el, r\n\ndef sph2cart(az, el, r):\n '''spherical to cartesian coords'''\n rcos_theta = r * np.cos(el)\n x = rcos_theta * np.cos(az)\n y = rcos_theta * np.sin(az)\n z = r * np.sin(el)\n return x, y, z\n\ndef parse_ln(ln):\n '''simple but might become more complex'''\n return ln.split(',')\n\ndef make_labels(filename):\n '''create dictionary of label: azimuth, elevation correspondence'''\n lbl = 0\n dct_cart = {}\n dct_sph = {}\n with open(filename,'r') as f:\n for line in f:\n x,y,z = parse_ln(line)\n dct_cart[lbl] = [float(x),float(y),float(z)]\n dct_sph[lbl] = cart2sph(float(x),float(y),float(z))\n lbl += 1\n return (dct_cart, dct_sph)\n\ndef dist_sq(v1, v2):\n '''calculate the squared norm since we're doing this just for comparison'''\n return ((v1[0]-v2[0])**2 + \\\n (v1[1]-v2[1])**2 + \\\n (v1[2]-v2[2])**2)\n\ndef closest_cam(x, y, z, dct_cart):\n '''find the camera location closest to the servicer'''\n #TODO: can be done faster with numpy arrays\n minkey = 0\n minval = 2**2 # highest distance in the unit sphere squared\n\n for key, value in dct_cart.items():\n tmp_dist = dist_sq([x,y,z], value)\n if (tmp_dist < minval):\n minval = tmp_dist\n minkey = key\n\n return minkey\n\ndef label_image(filename, dct_cart):\n # Parse the filename\n fn_l = filename.split('.')\n s = '.'.join(fn_l[:len(fn_l)-1]) # get rid of file extension\n s_l = s.split(',')\n s_l = s_l[1:]\n float_l = list(map(float, s_l))\n float_l = list(map(math.radians, float_l))\n float_l[2] = 1 # currently no z-rotation, r = 1\n float_l = sph2cart(*float_l) # change to cartesian\n\n # Find the closest camera\n label = closest_cam(*float_l, dct_cart)\n return str(label)\n\ndef is_png(filename):\n '''check if the file is a png'''\n # can probably find a better way\n file_l = filename.split('.')\n if (file_l[len(file_l)-1] == 'png'):\n return True\n return False\n\ndef main():\n input_dir = \"/media/mannykoum/Data/synthetic_data/AcrimSat_random_no_grain_all/\"\n output_dir = \"/media/mannykoum/Data/synthetic_data/AcrimSat_random_no_grain/\"\n camera_pos_fn = \\\n \"/media/mannykoum/Data/synthetic_data/coords_pts_300_its_10000.txt\"\n\n # Make a dictionary (key=label, val=coordinates)\n dct_cart, dct_sph = make_labels(camera_pos_fn)\n l_files = os.listdir(input_dir)\n for file in l_files:\n # Skip if it isn't a png file\n if not(is_png(file)):\n continue\n\n # Label the image\n label = label_image(file, dct_cart)\n src_path = os.path.join(input_dir, file)\n dst_path = os.path.join(output_dir, label, file)\n\n # Make the dir if it doesn't exist\n if not os.path.exists(os.path.dirname(dst_path)):\n try:\n os.makedirs(os.path.dirname(dst_path))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n # Copy the photo in the appropriate directory\n shutil.copy(src_path, dst_path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"utils/label_and_cp.py","file_name":"label_and_cp.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"367579125","text":"## submit job for lstm_neg\nimport os\n#rs = [20, 100, 500]\nrs = [20]\n#fs = [0]\n#fs = [round(0.01*x, 3) for x in range(1,11)]\nfs = [round(0.01*x, 3) for x in range(1,11)]\npath = \"./\"\n\nfor r in rs:\n for f in fs:\n command = \"python -u ../code/lstm_neg.py {} {} > ../output/lstm_neg_r{}_f{}.pyout\".format(r,f,r,f)\n name = \"lstm_neg_r{}_f{}.sbatch\".format(r,f)\n with open(path + name, \"w\") as rsh:\n with open(path + \"example.sbatch\", \"r\") as exa:\n for item in exa.readlines():\n rsh.write(item)\n #rsh.write(\"\\n\")\n rsh.write(\"echo '{}'\\n\".format(command))\n rsh.write(command)\n\n ## submit job\n print(\"sbatch {}\".format(name))\n os.system(\"sbatch {}\".format(name))\n\n\n","sub_path":"hw1/script/lstm_neg_submit.py","file_name":"lstm_neg_submit.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451823526","text":"import numpy as np\nfrom math import sin, cos, acos, sqrt, atan2, asin\n\nclass Quadrotor:\n \"\"\"\n Higher fidelity quadrotor simulation using quaternion rotations and a second\n order ODE integrator. For a description of the aircraft parameters, please\n see the config file.\n\n -- Sean Morrison, 2018\n \"\"\"\n \n def __init__(self, params):\n self.mass = params[\"mass\"]\n self.prop_radius = params[\"prop_radius\"]\n self.n_motors = params[\"n_motors\"]\n self.hov_p = params[\"hov_p\"]\n self.l = params[\"l\"]\n self.Jxx = params[\"Jxx\"]\n self.Jyy = params[\"Jyy\"]\n self.Jzz = params[\"Jzz\"]\n self.kt = params[\"kt\"]\n self.kq = params[\"kq\"]\n self.kd = params[\"kd\"]\n self.km = params[\"km\"]\n self.g = params[\"g\"]\n self.dt = params[\"dt\"]\n\n # physical parameters\n self.J = np.array([[self.Jxx, 0., 0.],\n [0., self.Jyy, 0.],\n [0., 0., self.Jzz]])\n self.G = np.array([[0.],\n [0.],\n [0.],\n [-self.g]])\n \n # state space. uvw and pqr are 4 element vectors of the form [0, uvw]^T, and [0, pqr]^T\n self.xyz = np.array([[0.],\n [0.],\n [0.]])\n self.zeta = np.array([[0.],\n [0.],\n [0.]])\n self.uvw = np.array([[0.],\n [0.],\n [0.],\n [0.]])\n self.pqr = np.array([[0.],\n [0.],\n [0.],\n [0.]])\n \n # all rotation math handled by quaternions. This is secretly part of the state space.\n self.q = self.euler_to_q(self.zeta)\n \n # action space\n self.rpm = np.array([0.0, 0., 0., 0.])\n\n # accelerations -- memory is required here required for leapfrog integration.\n self.uvw_dot = np.array([[0.],\n [0.],\n [0.]])\n self.pqr_dot = np.array([[0.],\n [0.],\n [0.]])\n\n # we use this matrix to convert from a thrust/moment input to an rpm input.\n self.u_to_rpm = np.linalg.inv(np.array([[self.kt, self.kt, self.kt, self.kt],\n [0., self.l*self.kt, 0., -self.l*self.kt],\n [-self.l*self.kt, 0., self.l*self.kt, 0.],\n [-self.kq, self.kq, -self.kq, self.kq]]))\n \n # important physical limits\n self.hov_rpm = sqrt((self.mass*self.g)/self.n_motors/self.kt)\n self.max_rpm = sqrt(1./self.hov_p)*self.hov_rpm\n self.max_thrust = self.kt*self.max_rpm\n self.terminal_velocity = sqrt((self.max_thrust+self.mass*self.g)/self.kd)\n self.terminal_rotation = sqrt(self.l*self.max_thrust/self.km)\n \n def set_state(self, xyz, zeta, uvw, pqr):\n \"\"\"\n Sets the state space of our vehicle\n \"\"\"\n\n self.xyz = xyz\n self.zeta = zeta\n self.q = self.euler_to_q(zeta)\n self. uvw[1:] = uvw\n self.pqr[1:] = pqr\n \n def get_state(self):\n \"\"\"\n Returns the current state space\n \"\"\"\n\n return self.xyz, self.zeta, self.q, self.uvw[1:], self.pqr[1:]\n \n def reset(self):\n \"\"\"\n Resets the initial state of the quadrotor\n \"\"\"\n\n self.xyz = np.array([[0.],\n [0.],\n [0.]])\n self.q = np.array([[1.],\n [0.],\n [0.],\n [0.]])\n self.uvw[1:] = np.array([[0.],\n [0.],\n [0.]])\n self.pqr[1:] = np.array([[0.],\n [0.],\n [0.]]) \n self.rpm = np.array([0., 0., 0., 0.])\n return self.get_state()\n\n def q_norm(self, q):\n \"\"\"\n Quaternion rotations rely on a unit quaternion. To ensure\n this is the case, we normalize here.\n \"\"\"\n\n return q/np.linalg.norm(q)\n \n def q_mult(self, p):\n \"\"\"\n One way to compute the Hamilton product is usin Q(p)q, where Q(p) is\n the below 4x4 matrix, and q is a 4x1 quaternion. I decided not to do\n the full multiplication here, and instead return Q(p). \n \"\"\"\n\n p0, p1, p2, p3 = p[0,0], p[1,0], p[2,0], p[3,0]\n return np.array([[p0, -p1, -p2, -p3],\n [p1, p0, -p3, p2],\n [p2, p3, p0, -p1],\n [p3, -p2, p1, p0]])\n\n def q_conj(self, q):\n \"\"\"\n Returns the conjugate q* of quaternion q. q* = q'/|q|, where q is the\n magnitude, and q' is the inverse: q' = [p0, -p1, -p2, -p3]^T. Since we\n always normalize after updating q, we should always have a unit\n quaternion. This means we don't have to normalize in this routine. That\n is, for a unit quaternion, q* = q'\n \"\"\"\n\n q0, q1, q2, q3 = q\n return np.array([q0, \n -q1, \n -q2, \n -q3])\n \n def q_to_euler(self, q):\n \"\"\"\n Convert quaternion q to a set of angles zeta. We do all of the heavy\n lifting with quaternions, and then return the Euler angles since they\n are more intuitive.\n \"\"\"\n\n q0, q1, q2, q3 = q\n phi = atan2(2.*(q0*q1+q2*q3),q0**2-q1**2-q2**2+q3**2)\n theta = asin(2.*q0*q2-q3*q1)\n psi = atan2(2.*(q0*q3+q1*q2),q0**2+q1**2-q2**2-q3**2)\n return np.array([[phi],\n [theta],\n [psi]])\n \n def euler_to_q(self, zeta):\n \"\"\"\n Converts a set of Euler angles to a quaternion. We do this at the very\n start, since we initialize the vehicle with Euler angles zeta.\n \"\"\"\n \n phi, theta, psi = zeta\n q0 = cos(phi/2.)*cos(theta/2.)*cos(psi/2.)+sin(phi/2.)*sin(theta/2.)*sin(psi/2.)\n q1 = sin(phi/2.)*cos(theta/2.)*cos(psi/2.)-cos(phi/2.)*sin(theta/2.)*sin(psi/2.)\n q2 = cos(phi/2.)*sin(theta/2.)*cos(psi/2.)+sin(phi/2.)*cos(theta/2.)*sin(psi/2.)\n q3 = cos(phi/2.)*cos(theta/2.)*sin(psi/2.)-sin(phi/2.)*sin(theta/2.)*cos(psi/2.)\n return np.array([[q0],\n [q1],\n [q2],\n [q3]])\n\n def aero_forces(self):\n \"\"\"\n Calculates drag in the body xyz axis (E-N-U) due to linear velocity\n \"\"\"\n\n mag = np.linalg.norm(self.uvw[1:])\n if mag == 0:\n return np.array([[0.],\n [0.],\n [0.]])\n else:\n norm = self.uvw[1:]/mag\n return -(self.kd*mag**2)*norm\n\n def aero_moments(self):\n \"\"\"\n Models aero moments about the body xyz axis (E-N-U) as a function of angular velocity\n \"\"\"\n\n mag = np.linalg.norm(self.pqr[1:])\n if mag == 0:\n return np.array([[0.],\n [0.],\n [0.]])\n else:\n norm = self.pqr[1:]/mag\n return -(self.km*mag**2)*norm\n\n def thrust_forces(self, rpm):\n \"\"\"\n Calculates thrust forces in the body xyz axis (E-N-U)\n \"\"\"\n \n thrust = self.kt*rpm**2\n f_body_x, f_body_y = 0., 0.\n f_body_z = np.sum(thrust)\n return np.array([[f_body_x],\n [f_body_y],\n [f_body_z]])\n \n def thrust_moments(self, rpm):\n \"\"\"\n Calculates moments about the body xyz axis due to motor thrust and torque\n \"\"\"\n\n thrust = self.kt*rpm**2\n t_body_x = self.l*(thrust[1]-thrust[3])\n t_body_y = self.l*(thrust[2]-thrust[0])\n motor_torques = self.kq*rpm**2\n t_body_z = -motor_torques[0]+motor_torques[1]-motor_torques[2]+motor_torques[3]\n return np.array([[t_body_x],\n [t_body_y],\n [t_body_z]])\n \n def step(self, control_signal, rpm_commands=True, return_acceleration=False):\n \"\"\"\n Updating the EOMs using second order leapfrog integration (kick-drift-kick\n form) with quaternion rotations. Should be far more accurate than quadrotor,\n and the quaternion rotations should be both faster and avoid the singularity\n at pitch +-90 degrees.\n \"\"\"\n \n if not rpm_commands:\n rpm_sq = self.u_to_rpm.dot(control_signal)\n rpm_sq = np.clip(rpm_sq, 0, self.max_rpm**2)\n rpm = (rpm_sq**0.5).flatten()\n else:\n rpm = control_signal\n rpm = np.clip(rpm, 0., self.max_rpm)\n \n # thrust forces and moments, aerodynamic forces and moments\n ft = self.thrust_forces(rpm)\n mt = self.thrust_moments(rpm)\n fa = self.aero_forces()\n ma = self.aero_moments()\n\n # calculate angular momentum\n H = self.J.dot(self.pqr[1:])\n \n # rotate gravity vector from inertial frame to body frame using qpq^-1\n Q = self.q_mult(self.q)\n Q_inv = self.q_conj(self.q)\n g_b = Q.dot(self.q_mult(self.G).dot(Q_inv))[1:]\n\n # linear and angular accelerations due to thrust and aerodynamic effects\n uvw_dot = (ft+fa)/self.mass+g_b-np.cross(self.pqr[1:], self.uvw[1:], axis=0)\n pqr_dot = np.linalg.inv(self.J).dot(mt+ma-np.cross(self.pqr[1:], H, axis=0))\n \n # kick: v_{i+0.5} = v_{i}+a_{i}dt/2 -- update velocity by half step\n self.uvw[1:] += self.uvw_dot*self.dt/2.\n self.pqr[1:] += self.pqr_dot*self.dt/2.\n \n # drift: x_{i+1} = x_{i}+v_{i+0.5}dt -- update q using q_dot*dt, and normalize\n q_dot = -0.5*self.q_mult(np.vstack([[0.], y[10:13,:]])).dot(y[3:7])\n self.q = self.q_norm(self.q+q_dot*self.dt)\n \n # update zeta using quaternion to Euler angle conversion\n self.zeta = self.q_to_euler(self.q)\n\n # rotate linear velocity to inertial frame using q^-1pq to get xyz_dot, and update xyz\n Q_inv = self.q_conj(self.q)\n xyz_dot = self.q_mult(Q_inv).dot(self.q_mult(self.uvw).dot(self.q))[1:]\n self.xyz += xyz_dot*self.dt\n\n # kick: v_{i+1} = v_{i+0.5}+a_{i+1}dt/2 -- update velocity by half step\n self.uvw[1:] += uvw_dot*self.dt/2.\n self.pqr[1:] += pqr_dot*self.dt/2.\n self.uvw_dot = uvw_dot\n self.pqr_dot = pqr_dot\n if not return_acceleration:\n return self.xyz, self.zeta, self.q, self.uvw[1:], self.pqr[1:]\n else: \n return self.xyz, self.zeta, self.q, self.uvw[1:], self.pqr[1:], xyz_dot, q_dot, uvw_dot, pqr_dot","sub_path":"simulation/legacy/quadrotor2.py","file_name":"quadrotor2.py","file_ext":"py","file_size_in_byte":11117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"184588624","text":"from gc import collect as gc_collect\nfrom random import random_int\nfrom sys import print_exception\nfrom uio import BytesIO\nfrom ujson import dump as json_dump\nfrom umqtt.simple import MQTTClient\nfrom utime import sleep\nimport wifi\n\nUTF8 = 'utf-8'\n\nclass RxEx(Exception):\n pass\n\nclass MQTT():\n def __init__(self, name, secrets):\n self.name = name\n self.secrets = secrets\n self.state = {}\n self.obj = []\n self.cfg = []\n self.cb = {}\n self.do_pub_cfg = True\n self.reconnect = True\n self.mqtt = None\n self.topic = None\n self.mac = wifi.mac()\n\n def connect(self):\n self.discon()\n\n self.mqtt = MQTTClient(\n self.mac,\n self.secrets.MQTT_SERVER,\n user=self.secrets.MQTT_USER.encode(UTF8),\n password=self.secrets.MQTT_PASSWORD.encode(UTF8)\n )\n\n def rx(tpc, msg):\n msg = msg.decode(UTF8)\n gc_collect()\n try:\n for t, cb in self.cb.items():\n if t == tpc:\n cb(msg)\n break\n except Exception as e:\n print_exception(e)\n raise RxEx()\n \n self.mqtt.set_callback(rx)\n\n self.mqtt.connect()\n sleep(0.5)\n \n if self.do_pub_cfg:\n self.do_pub_cfg = not(self.pub_cfg())\n sleep(0.5)\n \n if self.topic != None:\n self.mqtt.subscribe(self.topic)\n sleep(0.5)\n\n gc_collect()\n \n def discon(self):\n if self.mqtt != None:\n try:\n self.mqtt.disconnect()\n except:\n pass\n self.mqtt = None\n gc_collect()\n\n def add(self, name, cls, key = None, **cfg):\n obj = cls(\n prefix = self.secrets.MQTT_PREFIX,\n dev_name = self.name,\n name = name,\n key = key,\n state = self.state,\n )\n self.obj.append(obj)\n self.cfg.append(cfg)\n return obj\n\n def pub_cfg(self):\n ok = True\n for i, obj in enumerate(self.obj):\n print(obj.__class__.__name__)\n gc_collect()\n if not self.pub_json(obj.cfg_tpc(), obj.cfg(**self.cfg[i]), retain=True):\n ok = False\n print('>fail')\n return ok\n\n def try_pub_cfg(self):\n ok = False\n if wifi.is_connected():\n try:\n if not self.mqtt:\n self.do_pub_cfg = True\n self.connect()\n ok = True\n else:\n ok = self.pub_cfg()\n except Exception as e:\n print_exception(e)\n self.discon()\n self.do_pub_cfg = False\n return ok\n\n def set_attr(self, key, val):\n self.obj[0].set_attr(key, val)\n\n def set_wifi_attr(self):\n self.set_attr(\"ip\", wifi.ip())\n self.set_attr(\"mac\", self.mac)\n self.set_attr(\"rssi\", wifi.rssi())\n\n def pub_json(self, tpc, obj, **kwarg):\n gc_collect()\n print(tpc)\n print(obj)\n if wifi.is_connected() and self.mqtt:\n if type(tpc) != type(b''):\n tpc = tpc.encode(UTF8)\n with BytesIO() as json:\n json_dump(obj, json)\n gc_collect()\n self.mqtt.publish(tpc, json.getvalue(), **kwarg)\n sleep(0.5)\n gc_collect()\n return True\n return False\n \n def pub_state(self):\n gc_collect()\n return self.pub_json(self.obj[0].base_tpc(), self.state)\n gc_collect()\n\n def sub(self, tpc, cb):\n gc_collect()\n self.cb[tpc.encode(UTF8)] = cb\n first = next(iter(self.cb))\n if len(self.cb) == 1:\n self.topic = first\n else:\n self.topic = b''\n for i, char in enumerate(first):\n for t in self.cb.keys():\n if t[i] != char:\n char = None\n break\n if char == None:\n break\n else:\n self.topic += chr(char)\n self.topic += b'#'\n gc_collect()\n\n def wait(self, led=None):\n while self.reconnect:\n try:\n if wifi.is_connected():\n self.connect()\n while True:\n gc_collect()\n try:\n self.mqtt.wait_msg()\n except RxEx:\n pass\n else:\n print('No WiFi')\n except Exception as e:\n print('MQTT' + ':')\n print_exception(e)\n self.discon()\n if self.reconnect:\n if led:\n led.slow_blink()\n sleep(random_int(5))\n led.off()\n else:\n sleep(random_int(8))\n","sub_path":"build/py/environment_sensor/lib/home_assistant/mqtt.py","file_name":"mqtt.py","file_ext":"py","file_size_in_byte":5096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"31453084","text":"# Importing dependencies\nimport os\nimport webbrowser\nimport readline\nimport glob\n\n#Optional. True opens in Firefox after building site.\nsend_output_to_browser = True \n\ndef directoryStatus(folder, fileNames):\n\tprint('The current state of the', folder, 'directory is:')\n\tif len(fileNames) > 1:\n\t\tprint(fileNames)\n\telse:\n\t\tprint('The', folder, 'directory is empty! :)')\n\ndef deleteFileList(files):\n\tfor file in files:\n\t\tos.remove(file)\n\ndef buildMetaData(files, inputDir, outputDir):\n\tpages = []\n\tfor file in files:\n\t\t# print('24', file)\n\t\toutputFile = file.replace(inputDir + '/',outputDir + '/')\n\t\t# print('26', outputFile)\n\t\tcontent = open(file).read()\n\t\tlines = content.splitlines()\n\t\tcount = 1\n\t\tpage = {'file': file, 'outputFile': outputFile,}\n\t\tfor line in lines:\n\t\t\tif line.startswith('***'):\n\t\t\t\tline = line.strip('*')\n\t\t\t\tkey = line.split(\":\", maxsplit=1)[0]\n\t\t\t\tvalue = line.split(\": \", maxsplit=1)[1]\n\t\t\t\tpage[key] = value\n\t\tpages.append(page)\n\t\tcount += 1\n\tif len(pages) > 1:\n\t\treturn pages\n\treturn 'There is no content!'\n\n\t# Extract HTML from input files\ndef extractHTML(file):\n\t# print(file)\n\textracted = ''\n\tlines = file.splitlines()\n\tfor line in lines:\n\t\tif not line.startswith('***'):\n\t\t\textracted = extracted + line\n\treturn extracted\n\n# Build the pages\ndef buildPages(contentMetaData, templates):\n\ttemplate = open(templates[0]).read()\n\tfor item in contentMetaData:\n\t\tfile_content = open(item['file']).read()\n\t\thtml_content = extractHTML(file_content)\n\t\tfinished_page = template.replace(\"{{content}}\", html_content)\n\t\topen(item['outputFile'], 'w+').write(finished_page)\n\n# Optionally open output in web browser\ndef open_firefox(contentMetaData):\n\tif send_output_to_browser == True:\n\t\tdocs_path = \"file://\" + os.path.abspath('') + \"/\"\n\t\tprint(docs_path)\n\t\tfor item in contentMetaData:\n\t\t\twebbrowser.open(docs_path + item['outputFile'])\n\ndef main():\n####################################################\n### Cleansing the output directory ###\n####################################################\n\toutputDir = 'docs'\n\toutputFiles = glob.glob(outputDir+'/'+'*.html')\n\tprint('41',outputFiles)\n\n\t# Print current status of /docs directory.\n\tdirectoryStatus(outputDir, outputFiles)\n\n\t# Remove all HTML files in /docs directory.\n\tdeleteFileList(outputFiles)\n####################################################\n### Building the Content MetaData ###\n####################################################\n\ttemplateDir = 'templates'\n\ttemplates = glob.glob(templateDir+'/'+'*.template')\n\n\tinputDir = 'content'\n\tinputFiles = glob.glob(inputDir+'/'+'*.*')\n\n\t# print('43', inputFiles)\n\t# print('44', templates)\n\n\tcontentMetaData = buildMetaData(inputFiles, inputDir, outputDir)\n\t#print(contentMetaData)\n####################################################\n### Generating the Output ###\n####################################################\n\tbuildPages(contentMetaData, templates)\n####################################################\n### Opening output with Firefox ###\n####################################################\n\topen_firefox(contentMetaData)\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304966468","text":"#!/usr/bin/env python\n#\n# Copyright 2006, Revolution Linux Inc.\n#\n# $Id$\n#\n# Authors : Francis Giraldeau \n# Guillaume Pratte \n# -------------------------------------------------------------------------\n\nimport sys, os, shutil, getopt\nfrom distutils.core import setup, Extension\n\nversion_string = \"1.0.0\"\n\ninit_dir = '/etc/init.d'\nshare_dir = '/usr/share'\netc_dir = '/etc'\nlib_dir = '/var/lib'\n\ndata_files_list = []\ndata_files_list.append((init_dir, [\"svndistup-server\"]))\ndata_files_list.append((etc_dir, [\"svndistup-server.conf\"]))\n\nsetup(name=\"svndistup-client\",\n version=version_string,\n description=\"svn distributed updater client\",\n author=\"Francis Giraldeau\",\n author_email=\"francis.giraldeau@revolutionlinux.com\",\n url=\"http://www.revolutionlinux.com\",\n license=\"GPL\",\n platforms=[\"Linux\"],\n long_description=\"\"\"\nThis is the client of svndistup\n\"\"\",\n scripts=['svndistup-client.py','svndistup-server.py'],\n data_files = data_files_list\n)\n","sub_path":"svndistup/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"226784195","text":"from flask import render_template, jsonify\n\nfrom config import Config\nfrom crudTest import mongo\nfrom datetime import datetime\nfrom bson.objectid import ObjectId\nfrom crudTest.paginator import Paginator\n\ndef makeList(arg):\n return list(arg)\n\ndef insertRecord(data, collectionName='col'):\n data[\"date\"] = datetime.now()\n id = mongo.db[collectionName].insert_one(data).inserted_id\n ido = ObjectId(id)\n mongo.db[collectionName].update_one({'_id': ido}, {'$set': {'id': ido}})\n return id\n\ndef insert_update(data, collectionName='col'):\n if 'id' in data:\n if data['id'] != '':\n query = {'_id': ObjectId(data['id'])}\n del data['id']\n mongo.db.col.update_one(query, {'$set': data})\n return 'updated'\n insertRecord(data)\n return 'inserted'\n\ndef getTable(query={}, request=None):\n data = mongo.db.col.find(query)\n count = data.count()\n\n paginator = Paginator(count, request=request)\n\n if paginator.skip:\n data = data.skip(paginator.skip)\n if paginator.limit :\n data = data.limit(paginator.limit )\n\n data = data.sort('date', Config.sortOrder)\n return { \n 'template': render_template('table.html', data=data, paginator=paginator, list=makeList),\n 'paginator': paginator\n }\n\ndef getRecodr(id, collectionName='col'):\n rec = mongo.db[collectionName].find_one({'id': ObjectId(id)})\n if rec:\n for key in rec:\n if isinstance(rec[key], ObjectId):\n rec[key] = str(rec[key])\n return jsonify(rec)\n return jsonify({})\n\ndef getQeryConditions(request):\n data = request.args.copy()\n if len(data) > 0:\n if 'limit' in data:\n del data['limit']\n if 'skip' in data:\n del data['skip']\n if len(data) > 0:\n if 'date' in data:\n date = data['date']\n dates = date.split('-')\n del data['date']\n dateConditions = {\n '$gte': datetime.strptime(dates[0].strip(), '%d.%m.%Y'),\n '$lt': datetime.strptime(dates[1].strip(), '%d.%m.%Y'),\n }\n\n data['date'] = dateConditions\n\n textCondidions = ['name', 'text']\n for textCondidion in textCondidions:\n if textCondidion in data:\n piceOfData = data[textCondidion]\n del data[textCondidion]\n contition = {'$regex': piceOfData, '$options':'$i'}\n data[textCondidion] = contition\n\n return data\n\ndef deleteRecord(id, collectionName='col'):\n result = mongo.db[collectionName].remove({'_id': ObjectId(id)}, {'justOne': True})\n return result","sub_path":"crudTest/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452065135","text":"from gensim.models import KeyedVectors\nimport numpy as np\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport string\n\ndef tokenize(text, stopwords):\n \"\"\"Tokenizes and removes stopwords from the document\"\"\"\n without_punctuations = text.translate(str.maketrans('', '', string.punctuation))\n tokens = word_tokenize(without_punctuations)\n filtered = [w.lower() for w in tokens if not w in stopwords]\n return filtered\n\ndef extend_tokens(token_list, wv):\n \"\"\"Extends token list summing vector pairs\"\"\"\n tokens = []\n for token in token_list:\n # check if the token is in the vocabulary\n if token in wv.vocab.keys():\n tokens.append(token)\n extention = set()\n for i in range(len(tokens)-1):\n new_token = wv.most_similar(positive=[tokens[i], tokens[i+1]])[0][0]\n extention.add(new_token)\n extention = list(extention)\n return extention\n\ndef candidate_expansion_terms(tokens, k, wv):\n \"\"\"Gets the candidate expansion terms\"\"\"\n candidates = set()\n for token in tokens:\n # check if the token is in the vocabulary\n if token in wv.vocab.keys():\n result = wv.similar_by_word(token)\n limit = k if len(result) > k else len(result)\n # iterate through the most similar words\n for i in range(limit):\n candidates.add(result[i][0])\n # return list of candidates\n candidates = list(candidates)\n return candidates\n\ndef similarity(token, token_list, wv ):\n \"\"\"calculates the similarity between word and list of words\"\"\"\n # calculate the similarity of the token to all tokens\n similarity = 0\n num_of_tokens = 0\n for toks in token_list:\n # check if the token is in the vocabulary\n if toks in wv.vocab.keys():\n num_of_tokens += 1\n similarity += wv.similarity(toks, token)\n return similarity/num_of_tokens\n\ndef get_similarity_pairs(tokens, candidates, wv):\n \"\"\"Gets the actual expansion terms\"\"\"\n similarity_pairs = []\n for candidate in candidates:\n sim = similarity(candidate, tokens, wv)\n similarity_pairs.append((candidate, sim))\n # return the list of expansion terms with their similarities\n return similarity_pairs\n\ndef pre_retrieval_KNN(query, k, wv, n, stop_words,extension=False):\n \"\"\"Find the most similar tokens(candidates) to the given query, optional:query can be extended, then the candidates are found for extended query\"\"\"\n tokens = tokenize(query, stop_words)\n if extension:\n extended = extend_tokens(tokens,wv)\n candidates = candidate_expansion_terms(tokens+extended, k, wv)\n candidates_sim = get_similarity_pairs(tokens+extended, candidates, wv)\n else:\n candidates = candidate_expansion_terms(tokens, k, wv)\n candidates_sim = get_similarity_pairs(tokens, candidates, wv)\n def takeSecond(elem):\n return elem[1]\n sort = sorted(candidates_sim, key=takeSecond)[::-1]\n sort = sort[:n]\n candidate_list = []\n for tupl in sort:\n candidate_list.append(tupl[0])\n return candidate_list","sub_path":"text_embedding/library/query_expansion.py","file_name":"query_expansion.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"95392106","text":"from running_results_fetcher.spider import Spider\nfrom running_results_fetcher.runner import Runner\nfrom running_results_fetcher.spider_config import SpiderConfig\n\n\ndef test_start_urlr_with_injected_configuration():\n runner = Runner('Michał Mojek', 1980)\n config = SpiderConfig(domain_name='enduhub.com')\n config.runner = runner\n config.url_suffix = \"/pl/search/?name={}&page=1\".format(runner.name)\n Spider.set_config(config)\n url_for_test = 'https://enduhub.com/pl/search/?name=Michał Mojek&page=1'\n assert Spider.start_urls[0] == url_for_test\n\n\ndef test_allowed_domain_with_injected_configuration():\n runner = Runner('Michał Mojek', 1980)\n config = SpiderConfig(domain_name='enduhub.com')\n config.runner = runner\n config.url_suffix = \"/pl/search/?name={}&page=1\".format(runner.name)\n Spider.set_config(config)\n assert Spider.allowed_domains[0] == 'enduhub.com'\n","sub_path":"tests/test_spider.py","file_name":"test_spider.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588634010","text":"#Input \n#\t\"task_id\": t_id=7 \n\nimport sys\nt_id=sys.argv[1]\n\nimport datetime\n\nimport kanboard\nkb = kanboard.Client('http://192.168.100.221/kanboard/jsonrpc.php', 'jsonrpc', '392dc75baf66ae2205e9d0655a3e150c5766d011031658c7a1f3d152f5ef')\n\nTaskProperties=kb.getTask(task_id=t_id)\nAllInternalTaskLinks=kb.getAllTaskLinks(task_id=t_id)\nAllTaskComments=kb.getAllComments(task_id=t_id)\nAllTaskFiles=kb.getAllTaskFiles(task_id=t_id)\nUpdateSwitch=0\n\nfor i in range(0,len(AllInternalTaskLinks)):\n\tInternalTaskLinkById=kb.getTaskLinkById(task_link_id=AllInternalTaskLinks[i]['id'])\n\tif InternalTaskLinkById['link_id']=='12' and InternalTaskLinkById['label']=='updatet':\n\t\tUpdateSwitch=1\n\t\tOppositeTask=kb.getTask(task_id=InternalTaskLinkById['opposite_task_id'])\n\t\t#Comment\n\t\ttmp_Comments=[]\n\t\tfor j in range(0,len(AllTaskComments)):\n\t\t\ttmp_Comments.append(\"* \"+datetime.datetime.fromtimestamp(int(AllTaskComments[j][\"date_creation\"])).isoformat()+\" (\"+datetime.datetime.fromtimestamp(int(AllTaskComments[j][\"date_modification\"])).isoformat()+\"):\\n'\"+AllTaskComments[j][\"comment\"]+\"'\\n\\n\")\n\t\ttmp_CommentsMin=min(len(tmp_Comments), 2)\n\t\ttmp_CommentId=kb.createComment(task_id=InternalTaskLinkById['opposite_task_id'], user_id=0, content=''.join(tmp_Comments[::-1][:tmp_CommentsMin]))\n\t\t#Attachment\n\t\ttmp_AllTaskFiles=kb.removeAllTaskFiles(task_id=InternalTaskLinkById['opposite_task_id'])\n\t\tfor j in range(0,len(AllTaskFiles)):\n\t\t\tDownloadTaskFile=kb.downloadTaskFile(file_id=AllTaskFiles[j]['id'])\n\t\t\ttmp_CreatedTaskFile=kb.createTaskFile(project_id=OppositeTask['project_id'], task_id=InternalTaskLinkById['opposite_task_id'], filename=AllTaskFiles[j]['name'], blob=DownloadTaskFile)\n\t\t#CopyInternalLinks\n#\t\tfor j in range(0,len(AllInternalTaskLinks)):\n#\t\t\tif j!=i:\n#\t\t\t\ttmp_InternalTaskLinkById=kb.getTaskLinkById(task_link_id=AllInternalTaskLinks[j]['id'])\n#\t\t\t\tif tmp_InternalTaskLinkById is not None and tmp_InternalTaskLinkById['link_id']!='12':\n##\t\t\t\t\tkb.createTaskLink(task_id=UpdatedTaskID, opposite_task_id=tmp_InternalTaskLinkById['opposite_task_id'], link_id=tmp_InternalTaskLinkById['link_id'])\n \t#Category\n\t\tif TaskProperties['category_id']!=OppositeTask['category_id']:\n\t\t\ttmp_TaskProperties=kb.updateTask(id=InternalTaskLinkById['opposite_task_id'], category_id=TaskProperties['category_id'])\n\t\t#Tag\n\t\tTaskTags=kb.getTaskTags(task_id=t_id)\n#\t\tdictlist=dict.items()\n#\t\tfor key, value in dict.iteritems():\n#\t\t\ttemp=[key, value]\n#\t\t\tdictlist.append(temp)\n\t\tOppositeTaskTags=kb.setTaskTags(project_id=OppositeTask['project_id'], task_id=InternalTaskLinkById['opposite_task_id'], tags=TaskTags)\n#\t\ttmp_AllTaskFiles=kb.getAllTaskFiles(task_id=t_id)\n#\t\tfor j in range(0,len(tmp_AllTaskFiles)):\n#\t\t\ttmp_DownloadTaskFile=kb.downloadTaskFile(file_id=tmp_AllTaskFiles[j]['id'])\n#\t\t\ttmp_CreatedTaskFile=kb.createTaskFile(project_id=OppositeTaskToUpdate['project_id'], task_id=UpdatedTaskID, filename=tmp_AllTaskFiles[j]['name'], blob=tmp_DownloadTaskFile)\n\t\t#RemoveOldTask\n#\t\ttmp_removeTask=kb.removeTask(task_id=InternalTaskLinkById['opposite_task_id'])\nif UpdateSwitch==0:\n\tprint('Keine Karte zum Updaten (interne Verbindung: UPDATET) gefunden.')\nelif UpdateSwitch==1:\n##\ttmp_AllTaskFiles=kb.getAllTaskFiles(task_id=t_id)#InternalTaskLinkById['opposite_task_id'])\n\tprint(TaskTags)#'Alle Karten, die mit UPDATET intern verbunden sind, wurden geupdatet.')\n","sub_path":"UpdateRelatedTaskController.py","file_name":"UpdateRelatedTaskController.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"154045567","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nfs = 50\nN = 100\n\nt = np.arange(0,N/fs,1/fs)\n\nsignalFrec=3\nsignal = np.cos(2*np.pi*signalFrec*t)\n\n\nfig=plt.figure()\nplt.plot(t,signal)\n\n\nmng = plt.get_current_fig_manager()\nmng.full_screen_toggle()\n\n\n\n","sub_path":"material_viejo/untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"566578036","text":"#!/usr/bin/env python \n# -*- coding:utf8 -*- \n# Author:DenisHuang\n# Date:2013/11/7\n# Usage:\nfrom django.db import connections\n\ndb = connections['default']\ncursor = db.cursor()\ncursor._defer_warnings = True\n\nall_types = {}\nall_types[\"integer\"] = [\"tinyint\", \"smallint\", \"mediumint\", \"int\", \"bigint\"]\nall_types[\"decimal\"] = [\"double\", \"float\", \"decimal\"]\nall_types[\"time\"] = [\"time\", \"date\", \"datetime\", \"timestamp\", \"year\"]\nall_types[\"string\"] = [\"char\", \"varchar\", \"text\", \"enum\"]\n\n\ndef genAllFieldTypesTable(cursor, fieldTypes):\n tmp_table = \"tmp_YxbUm87N13F\"\n fs = \",\".join(\n [\"f%s %s\" % (t, t == \"enum\" and \"enum('a')\" or t == \"varchar\" and \"varchar(1)\" or t) for t in fieldTypes])\n cursor.execute(\"create table if not exists %s (%s)\" % (tmp_table, fs))\n cursor.execute(\"select * from %s limit 1\" % tmp_table)\n d = dict([(fd[0][1:], fd[1]) for fd in cursor.description])\n cursor.execute(\"drop table if exists %s \" % tmp_table)\n return d\n\n\n#\n# print genAllFieldTypesTable(cursor,reduce(lambda x,y:x+y,all_types.values())\n#\nfieldTypeCodes = {'smallint': 2,\n 'enum': 254,\n 'varchar': 253,\n 'timestamp': 7,\n 'int': 3,\n 'mediumint': 9,\n 'decimal': 246,\n 'float': 4,\n 'year': 13,\n 'datetime': 12,\n 'char': 254,\n 'tinyint': 1,\n 'bigint': 8,\n 'text': 252,\n 'time': 11,\n 'double': 5,\n 'date': 10}\n\nfieldCodeTypes = dict([(v, k) for k, v in fieldTypeCodes.iteritems()])\n\nfieldCategories = {}\nfor cat, types in all_types.iteritems():\n for type in types:\n fieldCategories[type] = cat\n fieldCategories[fieldTypeCodes[type]] = cat\n\n\ndef cursorDescription2MapList(cursor):\n global fieldCategories\n l = []\n m = {}\n for fd in cursor.description:\n d = {'name': fd[0],\n 'verboseName': fd[0],\n 'category': fieldCategories[fd[1]]}\n l.append(d)\n m[fd[0]] = d\n return m, l\n\n\ndef cursorDescription2SortedDict(cursor):\n from collections import OrderedDict\n #from django.http.request import SortedDict\n m = OrderedDict()\n for fd in cursor.description:\n d = {'name': fd[0],\n 'verboseName': fd[0],\n 'category': fieldCategories[fd[1]]}\n m[fd[0]] = d\n return m\n\n\ndef getDB(dbName='default'):\n return connections[dbName]\n\n\ndef getDBOptionals():\n return [(k, v[\"HOST\"]) for k, v in connections.databases.iteritems()]\n","sub_path":"Documents/backupCode/util/dbutils.py","file_name":"dbutils.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18545760","text":"from db import Book\nfrom sqlalchemy.orm import *\nfrom sqlalchemy import create_engine, and_\nfrom datetime import datetime\nimport os\n\nconnection_string = os.getenv(\"CONNECTION_STR\")\n\n\ndef main():\n engine = create_engine(connection_string)\n i = 0\n session = Session(engine, autoflush=True)\n for e in session.query(Book).filter(and_(Book.publisher_name == None, Book.rank > 0)).with_for_update().all():\n\n if e.publisher:\n p = e.publisher.rfind(\"(\")\n parts = [e.publisher[:p], e.publisher[p + 1:]]\n if len(parts) > 1:\n date_str = parts[1].strip()[:-1]\n try:\n d = datetime.strptime(date_str, '%B %d, %Y')\n except:\n try:\n d = datetime.strptime(date_str, '%B %Y')\n except:\n try:\n d = datetime.strptime(date_str, '%Y')\n except:\n d = None\n e.publish_date = d\n pub_name = parts[0].split(\";\")[0].strip()\n if len(pub_name) < 100:\n e.publisher_name = pub_name\n\n if e.weight_str:\n parts = e.weight_str.split(\" \")\n if len(parts) > 1:\n if parts[1] == \"ounces\":\n e.weigth_grams = float(parts[0]) * 28.3495231\n elif parts[1] == \"pounds\":\n e.weigth_grams = float(parts[0]) * 453.59237\n else:\n raise Exception(\"unsupported weight {}\".format(parts[1]))\n\n if e.dimensions_str:\n parts = e.dimensions_str.split(\" \")\n if len(parts) > 5:\n a = float(parts[0])\n b = float(parts[2])\n c = float(parts[4])\n if parts[5] == \"inches\":\n e.volume_cm3 = (a * 2.54) * (b * 2.54) * (c * 2.54)\n else:\n raise Exception(\"unsupported length {}\".format(parts[5]))\n\n session.add(e)\n session.commit()\n\n print(\"asin {} done i = {}\".format(e.asin, i))\n i += 1\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"fix_data.py","file_name":"fix_data.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236194290","text":"from pyvi import ViTokenizer, ViPosTagger\nimport re \nfrom gensim.models import Word2Vec\nimport string\nimport codecs\nimport pandas as pd\nimport numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, LSTM, Bidirectional\nfrom keras.models import load_model\nimport random\n\nclass Train:\n def __init__(self):\n self.maxlen_sentence = 100\n self.epochs = 10\n self.batch_size = 20\n self.num_class = 2\n self.dropout = 0.2\n self.modelw2v = None\n self.modelLSTM = None\n self.randText = None\n self.label = None\n\n\n def no_marks(self,s):\n VN_CHARS_LOWER = u'ạảãàáâậầấẩẫăắằặẳẵóòọõỏôộổỗồốơờớợởỡéèẻẹẽêếềệểễúùụủũưựữửừứíìịỉĩýỳỷỵỹđð'\n VN_CHARS_UPPER = u'ẠẢÃÀÁÂẬẦẤẨẪĂẮẰẶẲẴÓÒỌÕỎÔỘỔỖỒỐƠỜỚỢỞỠÉÈẺẸẼÊẾỀỆỂỄÚÙỤỦŨƯỰỮỬỪỨÍÌỊỈĨÝỲỶỴỸÐĐ'\n VN_CHARS = VN_CHARS_LOWER + VN_CHARS_UPPER\n __INTAB = [ch for ch in VN_CHARS]\n __OUTTAB = \"a\"*17 + \"o\"*17 + \"e\"*11 + \"u\"*11 + \"i\"*5 + \"y\"*5 + \"d\"*2\n __OUTTAB += \"A\"*17 + \"O\"*17 + \"E\"*11 + \"U\"*11 + \"I\"*5 + \"Y\"*5 + \"D\"*2\n __r = re.compile(\"|\".join(__INTAB))\n __replaces_dict = dict(zip(__INTAB, __OUTTAB))\n result = __r.sub(lambda m: __replaces_dict[m.group(0)], s)\n return result\n def normalize_text(self,text):\n path_nag = './data/nag1.txt'\n path_pos = './data/pos1.txt'\n path_not = './data/not.txt'\n with codecs.open(path_nag, 'r', encoding='UTF-8') as f:\n nag = f.readlines()\n nag_list1 = [' '+n.replace('\\n', ' ') for n in nag]\n nag_list = [n.replace('\\r','') for n in nag_list1]\n with codecs.open(path_pos, 'r', encoding='UTF-8') as f:\n pos = f.readlines()\n pos_list1 = [' '+n.replace('\\n', ' ') for n in pos]\n pos_list = [n.replace('\\r', '') for n in pos_list1]\n with codecs.open(path_not, 'r', encoding='UTF-8') as f:\n not_ = f.readlines()\n not_list1 = [ n.replace('\\n', '') for n in not_]\n not_list = [n.replace('\\r', '') for n in not_list1]\n #Remove các ký tự kéo dài: vd: đẹppppppp\n text = re.sub(r'([A-Z])\\1+', lambda m: m.group(1).upper(), text, flags=re.IGNORECASE)\n # Chuyển thành chữ thường\n text = text.lower()\n\n #Chuẩn hóa tiếng Việt, xử lý emoj, chuẩn hóa tiếng Anh, thuật ngữ\n replace_list = {\n 'òa': 'oà', 'óa': 'oá', 'ỏa': 'oả', 'õa': 'oã', 'ọa': 'oạ', 'òe': 'oè', 'óe': 'oé','ỏe': 'oẻ',\n 'õe': 'oẽ', 'ọe': 'oẹ', 'ùy': 'uỳ', 'úy': 'uý', 'ủy': 'uỷ', 'ũy': 'uỹ','ụy': 'uỵ','ủa':'uả',\n 'ả': 'ả', 'ố': 'ố', 'u´': 'ố','ỗ': 'ỗ', 'ồ': 'ồ', 'ổ': 'ổ', 'ấ': 'ấ', 'ẫ': 'ẫ', 'ẩ': 'ẩ',\n 'ầ': 'ầ', 'ỏ': 'ỏ', 'ề': 'ề','ễ': 'ễ', 'ắ': 'ắ', 'ủ': 'ủ', 'ế': 'ế', 'ở': 'ở', 'ỉ': 'ỉ',\n 'ẻ': 'ẻ', 'àk': u' à ','aˋ': 'à', 'iˋ': 'ì', 'ă´': 'ắ','ử': 'ử', 'e˜': 'ẽ', 'y˜': 'ỹ', 'a´': 'á',\n #Quy các icon về 2 loại emoj: Tích cực hoặc tiêu cực\n \"👹\": \"nagative\", \"👻\": \"positive\", \"💃\": \"positive\",'🤙': ' positive ', '👍': ' positive ',\n \"💄\": \"positive\", \"💎\": \"positive\", \"💩\": \"positive\",\"😕\": \"nagative\", \"😱\": \"nagative\", \"😸\": \"positive\",\n \"😾\": \"nagative\", \"🚫\": \"nagative\", \"🤬\": \"nagative\",\"🧚\": \"positive\", \"🧡\": \"positive\",'🐶':' positive ',\n '👎': ' nagative ', '😣': ' nagative ','✨': ' positive ', '❣': ' positive ','☀': ' positive ',\n '♥': ' positive ', '🤩': ' positive ', 'like': ' positive ', '💌': ' positive ',\n '🤣': ' positive ', '🖤': ' positive ', '🤤': ' positive ', ':(': ' nagative ', '😢': ' nagative ',\n '❤': ' positive ', '😍': ' positive ', '😘': ' positive ', '😪': ' nagative ', '😊': ' positive ',\n '?': ' ? ', '😁': ' positive ', '💖': ' positive ', '😟': ' nagative ', '😭': ' nagative ',\n '💯': ' positive ', '💗': ' positive ', '♡': ' positive ', '💜': ' positive ', '🤗': ' positive ',\n '^^': ' positive ', '😨': ' nagative ', '☺': ' positive ', '💋': ' positive ', '👌': ' positive ',\n '😖': ' nagative ', '😀': ' positive ', ':((': ' nagative ', '😡': ' nagative ', '😠': ' nagative ',\n '😒': ' nagative ', '🙂': ' positive ', '😏': ' nagative ', '😝': ' positive ', '😄': ' positive ',\n '😙': ' positive ', '😤': ' nagative ', '😎': ' positive ', '😆': ' positive ', '💚': ' positive ',\n '✌': ' positive ', '💕': ' positive ', '😞': ' nagative ', '😓': ' nagative ', '️🆗️': ' positive ',\n '😉': ' positive ', '😂': ' positive ', ':v': ' positive ', '=))': ' positive ', '😋': ' positive ',\n '💓': ' positive ', '😐': ' nagative ', ':3': ' positive ', '😫': ' nagative ', '😥': ' nagative ',\n '😃': ' positive ', '😬': ' 😬 ', '😌': ' 😌 ', '💛': ' positive ', '🤝': ' positive ', '🎈': ' positive ',\n '😗': ' positive ', '🤔': ' nagative ', '😑': ' nagative ', '🔥': ' nagative ', '🙏': ' nagative ',\n '🆗': ' positive ', '😻': ' positive ', '💙': ' positive ', '💟': ' positive ',\n '😚': ' positive ', '❌': ' nagative ', '👏': ' positive ', ';)': ' positive ', '<3': ' positive ',\n '🌝': ' positive ', '🌷': ' positive ', '🌸': ' positive ', '🌺': ' positive ',\n '🌼': ' positive ', '🍓': ' positive ', '🐅': ' positive ', '🐾': ' positive ', '👉': ' positive ',\n '💐': ' positive ', '💞': ' positive ', '💥': ' positive ', '💪': ' positive ',\n '💰': ' positive ', '😇': ' positive ', '😛': ' positive ', '😜': ' positive ',\n '🙃': ' positive ', '🤑': ' positive ', '🤪': ' positive ','☹': ' nagative ', '💀': ' nagative ',\n '😔': ' nagative ', '😧': ' nagative ', '😩': ' nagative ', '😰': ' nagative ', '😳': ' nagative ',\n '😵': ' nagative ', '😶': ' nagative ', '🙁': ' nagative ', ':((' : ' nagative ', \n #Chuẩn hóa 1 số sentiment words/English words\n ':))': ' positive ', ':)': ' positive ', 'ô kêi': ' ok ', 'okie': ' ok ', ' o kê ': ' ok ',\n 'okey': ' ok ', 'ôkê': ' ok ', 'oki': ' ok ', ' oke ': ' ok ',' okay':' ok ','okê':' ok ',\n ' tks ': u' cám ơn ', 'thks': u' cám ơn ', 'thanks': u' cám ơn ', 'ths': u' cám ơn ', 'thank': u' cám ơn ',\n '⭐': 'star ', '*': 'star ', '🌟': 'star ', '🎉': u' positive ',\n ' kg ': u' không ',' not ': u' không ', u' kg ': u' không ', '\"k ': u' không ',' kh ':u' không ',' kô ':u' không ',' hok ':u' không ',' kp ': u' không phải ',u' kô ': u' không ', '\"ko ': u' không ', u' ko ': u' không ', u' k ': u' không ', 'khong': u' không ', u' hok ': u' không ',\n 'he he': ' positive ','hehe': ' positive ','hihi': ' positive ', 'haha': ' positive ', 'hjhj': ' positive ',\n ' lol ': ' nagative ',' cc ': ' nagative ',' cute ': u' dễ thương ',' huhu ': ' nagative ', ' vs ': u' với ', ' wa ': ' quá ', ' wá ': u' quá ', ' j ': u' gì ', '“': ' ',\n ' sz ': u' cỡ ', 'size': u' cỡ ', u' đx ': u' được ', 'dk ': u'được ', 'dc': u' được ', 'đk ': u'được ',\n ' đc ': u' được ',' authentic ': u' chuẩn chính hãng ',u' aut ': u' chuẩn chính hãng ', u' auth ': u' chuẩn chính hãng ', ' thick ': u' positive ', ' store ': u' cửa hàng ',\n ' shop ': u' cửa hàng ', ' sp ': u' sản phẩm ', ' gud ': u' tốt ',' god ': u' tốt ',' wel done ':' tốt ', ' good ': u' tốt ', ' gút ': u' tốt ',\n ' sấu' : u' xấu ',' gut' : u' tốt ', u' tot ': u' tốt ', u' nice ': u' tốt ', 'perfect': 'rất tốt', ' bt ': u' bình thường ',\n ' time ': u' thời gian ', ' qá' : u' quá ', u' ship ': u' giao hàng ', u' m ': u' mình ', u' mik ': u' mình ', u'quá hài lòg' : u'positive',\n 'ể': 'ể', 'product': 'sản phẩm', 'quality': 'chất lượng','chat':' chất ', 'excelent': 'hoàn hảo', 'bad': 'tệ','fresh': ' tươi ','sad ': 'tệ ',\n ' date ': u' hạn sử dụng ', ' hsd ': u' hạn sử dụng ',' quickly ': u' nhanh ', ' quick ': u' nhanh ','fast': u' nhanh ',' delivery ': u' giao hàng ',u' síp ': u' giao hàng ',\n ' beautiful ': u' đẹp tuyệt vời ', u' tl ': u' trả lời ', u' r ': u' rồi ', u' shopE ': u' cửa hàng ',u' order ': u' đặt hàng ',\n ' chất lg ': u' chất lượng ',u' sd ': u' sử dụng ',u' dt ': u' điện thoại ',u' nt ': u' nhắn tin ',u' tl ': u' trả lời ',u' sài ': u' xài ',u'bjo':u' bao giờ ',\n ' thik ': u' thích ',u' sop ': u' cửa hàng ', ' fb ': ' facebook ', ' face ': ' facebook ', ' very ': u' rất ',u' quả ng ':u' quảng ',\n ' dep ': u' đẹp ',u' xau ': u' xấu ',' delicious ': u' ngon ', u' hàg ': u' hàng ', u' qủa ': u' quả ',\n ' iu ': u' yêu ',' fake ': u' giả mạo ', 'trl': 'trả lời', '><': u' positive ', u' thích đáng ' : ' nagative ',\n ' por ': u' tệ ',' poor ': u' tệ ', ' ib ':u' nhắn tin ', ' rep ':u' trả lời ',u'fback':' feedback ',' fedback ':' feedback ',\n #dưới 3* quy về 1*, trên 3* quy về 5*\n '6 sao': ' 5star ','6 star': ' 5star ', '5star': ' 5star ','5 sao': ' 5star ','5sao': ' 5star ',\n 'starstarstarstarstar': ' 5star ', '1 sao': ' 1star ', '1sao': ' 1star ','2 sao':' 1star ','2sao':' 1star ',\n '2 starstar':' 1star ','1star': ' 1star ', '0 sao': ' 1star ', '0star': ' 1star ',}\n\n for k, v in replace_list.items():\n text = text.replace(k, v)\n \n # for k, v in replace_list.items():\n # text = text.replace(k, v)\n \n # for k in pos_list :\n # text = text.replace(k, ' positive ')\n # for k in nag_list :\n # text = text.replace(k, ' nagative ')\n text = ViTokenizer.tokenize(text)\n \n # for k, v in replace_list.items():\n # text = text.replace(k, v)\n \n \n text = text.strip()\n texts = text.split()\n len_text = len(texts)\n for i in range(len_text):\n cp_text = texts[i]\n if cp_text in not_list: \n numb_word = 2 if len_text - i - 1 >= 4 else len_text - i - 1\n \n for j in range(numb_word):\n if texts[i + j + 1] in pos_list or texts[i+j+1] == 'positive':\n texts[i] = 'nagative'\n texts[i + j + 1] = ''\n\n if texts[i + j + 1] in nag_list or texts[i+j+1] == 'nagative':\n texts[i] = 'positive'\n texts[i + j + 1] = ''\n # else: \n # if cp_text in pos_list:\n # # texts.append('positive')\n # texts[i] = 'positive'\n # elif cp_text in nag_list:\n # # texts.append('nagative')\n # texts[i] = 'nagative'\n\n text = u' '.join(texts)\n\n \n text = text.replace(u'\"', u' ')\n text = text.replace(u'️', u'')\n text = text.replace('🏻','')\n # text = self.no_marks(text)\n return text\n #load data for word2vec train model \n def load_data_word2vecTrain(self,path):\n X=[]\n result = []\n sentences= u\"\"\n with open(path, encoding=\"utf8\") as fr: \n lines = fr.readlines()\n for line in lines: \n line = re.sub('train_[0-9][0-9][0-9][0-9][0-9][0-9]', '', line)\n line = re.sub('\\n','',line)\n sentences += line\n \n X1 = sentences.strip().split('\"')\n index = 1 \n while index < len(X1) :\n X1[index] = X1[index].strip()\n if X1[index] != '0' and X1[index] != '1' :\n X1[index] = self.normalize_text(X1[index]) \n X1[index] = re.sub('\\{','',X1[index])\n X1[index] = re.sub('\\}','',X1[index])\n X1[index] = re.sub('\\=','',X1[index])\n X1[index] = re.sub('\\(','',X1[index])\n X1[index] = re.sub('\\)','',X1[index])\n X1[index] = re.sub('\\,',' ',X1[index])\n if X1[index] != '' and X1[index] != ' ':\n X.append(X1[index])\n index +=1 \n while X1[index] != '0' and X1[index] != '1' :\n index +=1 \n index += 1\n \n for sentences in X: \n for sentence in sentences.strip().split('.'):\n k = sentence.split()\n if k != []:\n result.append(k)\n return result\n\n\n #load data LSTM for train model \n def load_data_LSTM(self,path, model_path):\n \"\"\"\n input: \n path: data path \n model_path : word2vec model path \n return : \n S: 3D-array data convert to vector by word2vec model loaded in model_path\n L : 2D-array label of data \n \"\"\"\n X = [] \n S = [] \n L = [] \n Z = []\n K = []\n sentences= \"\"\n with open(path,encoding=\"utf8\") as fr: \n lines = fr.readlines()\n for line in lines: \n line = re.sub('\\n','',line)\n line = line.strip()\n sentences += line\n X1 = re.compile('train_[0-9][0-9][0-9][0-9][0-9][0-9]').split(sentences) \n index = 1 \n while index < len(X1) :\n i = 0\n while X1[index][len(X1[index]) - 1-i] != '1' and X1[index][len(X1[index]) - 1-i]!= '0' :\n i +=1 \n tmp = [0,0]\n tmp[int(X1[index][len(X1[index]) - 1-i],10)] = 1\n L.append(tmp)\n \n X1[index] = X1[index][:len(X1[index]) - 1-i]\n K.append(X1[index])\n X1[index] = re.sub('\\.',' ',X1[index])\n X1[index] = self.normalize_text(X1[index]) \n X1[index] = re.sub('\\{','',X1[index])\n X1[index] = re.sub('\\}','',X1[index])\n X1[index] = re.sub('\\=','',X1[index])\n X1[index] = re.sub('\\(','',X1[index])\n X1[index] = re.sub('\\)','',X1[index])\n X1[index] = re.sub('\\,',' ',X1[index])\n \n \n X.append(X1[index])\n index += 1\n \n if self.modelw2v == None:\n self.modelw2v = Word2Vec.load(model_path)\n model = self.modelw2v\n for line in X :\n tmp = []\n for w in line.split():\n if w != ' ' :\n if w in model.wv :\n tmp.append(model.wv[w])\n else :\n tmp.append(np.zeros(shape=(model.wv[model.wv.index2word[0]].shape[0],), dtype=float))\n Z.append(line)\n if len(tmp) > self.maxlen_sentence :\n tmp = tmp[:self.maxlen_sentence]\n elif len(tmp) < self.maxlen_sentence :\n if len(tmp) == 0:\n tmp= np.zeros(shape=(1,100), dtype=float)\n tmp = np.concatenate((tmp, np.zeros(shape=(self.maxlen_sentence - len(tmp),100), dtype=float)),axis=0)\n S.append(tmp)\n \n return np.array(S),np.array(L), Z, K\n #load test data \n def load_data_test(self,path_data, model_path):\n X = [] \n S = [] \n \n sentences= \"\"\n with open(path_data) as fr: \n lines = fr.readlines()\n for line in lines: \n line = re.sub('\\n','',line)\n sentences += line\n \n X1 = re.compile('test_[0-9][0-9][0-9][0-9][0-9][0-9]').split(sentences) \n index = 1 \n while index < len(X1) :\n X1[index] = re.sub('\\\"','',X1[index])\n \n X1[index] = re.sub('\\.',' ',X1[index])\n X1[index] = self.normalize_text(X1[index]) \n X1[index] = re.sub('\\{','',X1[index])\n X1[index] = re.sub('\\}','',X1[index])\n X1[index] = re.sub('\\=','',X1[index])\n X1[index] = re.sub('\\(','',X1[index])\n X1[index] = re.sub('\\)','',X1[index])\n X1[index] = re.sub('\\,',' ',X1[index])\n \n X.append(X1[index])\n index += 1\n \n if self.modelw2v == None:\n self.modelw2v = Word2Vec.load(model_path)\n model = self.modelw2v\n for line in X :\n tmp = []\n for w in line.split():\n if w != ' ' :\n if w in model.wv :\n tmp.append(model.wv[w])\n else :\n tmp.append(np.zeros(shape=(model.wv[model.wv.index2word[0]].shape[0],), dtype=float))\n if len(tmp) > 40:\n tmp = tmp[:40]\n elif len(tmp) < 40:\n if len(tmp) == 0:\n tmp= np.zeros(shape=(1,100), dtype=float)\n tmp = np.concatenate((tmp, np.zeros(shape=(40 - len(tmp),100), dtype=float)),axis=0)\n S.append(tmp)\n \n return np.array(S)\n #train model LSTM \n def train_model_LSTM(self,path_model,X,Y):\n \"\"\"\n path_model : path for save model \n X : 3D-array data content \n Y : 2D-array label \n \"\"\"\n model = Sequential()\n inputdim = (X.shape[1], X.shape[2])\n model.add(LSTM(64, return_sequences=True, input_shape=(X.shape[1], X.shape[2])))\n model.add(Dropout(self.dropout))\n model.add(LSTM(32))\n model.add(Dense(self.num_class, activation=\"softmax\"))\n \n model.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n # model.load_weights('./data/LSTM.model73')\n \n model.fit(X, Y, batch_size=self.batch_size, epochs=self.epochs)\n model.save_weights(path_model)\n\n #predict data \n def predict(self,path_data_test,model_path_word2vec, model_path_LSTM):\n X,Y,Z,K = self.load_data_LSTM(path_data_test, model_path_word2vec)\n X = X[int(len(X)*0.8):]\n Y = Y[int(len(Y)*0.8):]\n Z = Z[int(len(Z)*0.8):]\n K = K[int(len(K)*0.8):]\n inputdim = (X.shape[1], X.shape[2])\n model = Sequential()\n model.add(LSTM(64, return_sequences=True, input_shape=inputdim))\n model.add(Dropout(self.dropout))\n model.add(LSTM(32))\n model.add(Dense(self.num_class, activation=\"softmax\"))\n \n model.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n model.load_weights(model_path_LSTM)\n \n # X = load_data_test(path_data_test,model_path_word2vec)\n \n yhat = model.predict(np.array(X))\n yhat = np.argmax(yhat, axis=1)\n num = 0 \n submit = []\n \n # with open('/content/drive/My Drive/colab/sample_submission.csv') as fr:\n # lines = fr.readlines()\n # for line in lines:\n # line = re.sub('test_[0-9][0-9][0-9][0-9][0-9][0-9]','',line)\n # line = re.sub('\\,','',line)\n # if(int(line) == 0 or int(line) == 1) :\n # submit.append(int(line))\n # for i in range(len(yhat)):\n # if yhat[i] == submit[i] :\n # num += 1\n \n for i in range(len(yhat)):\n if Y[i][yhat[i]] == 1 :\n num += 1 \n else :\n print(i)\n print(Z[i])\n print(K[i])\n print(yhat[i])\n print(Y[i])\n \n print(len(yhat))\n print(len(Y))\n print(len(Z))\n print(len(X))\n print(\"predict : \" + str(num))\n print(num/len(yhat))\n print(yhat[:20])\n #predict sentence \n def convert_sentence_tovec(self,text, model_path_word2vec):\n \n text = re.sub('\\\"','',text)\n text = re.sub('\\.',' ',text)\n text = self.normalize_text(text) \n text = re.sub('\\{','',text)\n text = re.sub('\\}','',text)\n text = re.sub('\\=','',text)\n text = re.sub('\\(','',text)\n text = re.sub('\\)','',text)\n text = re.sub('\\,',' ',text)\n\n if self.modelw2v == None:\n self.modelw2v = Word2Vec.load(model_path_word2vec)\n modelw2v = self.modelw2v\n Wvec = []\n tmp = []\n for w in text.split():\n if w != ' ' :\n if w in modelw2v.wv :\n tmp.append(modelw2v.wv[w])\n else :\n tmp.append(np.zeros(shape=(modelw2v.wv[modelw2v.wv.index2word[0]].shape[0],), dtype=float))\n if len(tmp) > 40:\n tmp = tmp[:40]\n elif len(tmp) < 40:\n if len(tmp) == 0:\n tmp= np.zeros(shape=(1,100), dtype=float)\n tmp = np.concatenate((tmp, np.zeros(shape=(40 - len(tmp),100), dtype=float)),axis=0)\n Wvec.append(tmp)\n return np.array(Wvec)\n\n\n #predic sentence converted to vector by word2vec and return \n def predict_sentence(self, text,model_path_word2vec, model_path_LSTM):\n Wvec = self.convert_sentence_tovec(text,model_path_word2vec)\n if self.modelLSTM == None:\n\n inputdim = (Wvec.shape[1], Wvec.shape[2])\n self.modelLSTM = Sequential()\n self.modelLSTM.add(LSTM(64, return_sequences=True, input_shape=inputdim))\n self.modelLSTM.add(Dropout(self.dropout))\n self.modelLSTM.add(LSTM(32))\n self.modelLSTM.add(Dense(self.num_class, activation=\"softmax\"))\n self.modelLSTM.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n self.modelLSTM.load_weights(model_path_LSTM)\n\n model = self.modelLSTM\n yhat = model.predict(np.array(Wvec))\n yhat = np.argmax(yhat, axis=1)\n return yhat[0] \n\n\n\n #get randomtext \n def get_RanText(self,pathdata):\n if self.randText == None:\n sentences= \"\"\n X =[]\n L = []\n with open(pathdata,encoding=\"utf8\") as fr: \n lines = fr.readlines()\n for line in lines: \n line = re.sub('\\n','',line)\n line = line.strip()\n sentences += line\n X1 = re.compile('train_[0-9][0-9][0-9][0-9][0-9][0-9]').split(sentences)\n X1 = X1[int(0.8*len(X1)) :] \n index = 1 \n while index < len(X1) :\n i = 0\n while X1[index][len(X1[index]) - 1-i] != '1' and X1[index][len(X1[index]) - 1-i]!= '0' :\n i +=1 \n tmp = [0,0]\n tmp[int(X1[index][len(X1[index]) - 1-i],10)] = 1\n L.append(tmp)\n X1[index] = X1[index][:len(X1[index]) - 1-i]\n \n X.append(X1[index])\n index += 1\n self.randText = X\n self.label = L\n index = random.randint(0,len(self.randText))\n return self.randText[index], self.label[index]\n\nif __name__ == \"__main__\":\n mod = Train()\n text = mod.load_data_word2vecTrain('./data/train.crash')\n model = Word2Vec(text, size=100, window=5, min_count=1, workers=4)\n model.save('./data/word2vec.model2')\n X,Y ,Z,K= mod.load_data_LSTM('./data/train.crash','./data/word2vec.model2')\n X = X[:int(len(X)*0.8)]\n Y = Y[:int(len(Y)*0.8)]\n mod.train_model_LSTM('./data/LSTM.model73',X,Y)\n mod.predict('./data/train.crash','./data/word2vec.model2','./data/LSTM.model73')\n # if mod.predict_sentence(\"shop phuc vu kem, san pham khong duoc nhu mong doi :( \",'./data/word2vec.model2','./data/LSTM.model73') == 1:\n # print(\"tieu cuc\")\n # else:\n # print(\"tic cuc\")\n pass","sub_path":"api/trainLSTM.py","file_name":"trainLSTM.py","file_ext":"py","file_size_in_byte":22325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"596493289","text":"import re\r\nimport itertools\r\n\r\nSpacersBaseFileName = \"/home/utkinai2/Project1/Spacers_from_Orphans.txt\"\r\nIslandIDwithCRISPRNeighborsFixedFileName = \"/panfs/pan1/orphancrispr/IslandsCluster/Islands_pfam_3NeighborsSet_fixedID.txt\"\r\n#IslandIDwithCRISPRNeighborsFixedFileName = \"/panfs/pan1/orphancrispr/IslandsCluster/h0.2_2cluster_pfam.txt\"\r\nArrayWithSpacersFileName = \"/panfs/pan1/orphancrispr/OrphanArrays_with_Spacers.txt\"\r\n#ArrayWithClusteredSpacersFileName = \"/panfs/pan1/orphancrispr/SpacersFromArraysCluster/OrphanArrays_with_ClusteredSpacers.txt\"\r\n#ArrayWithSpacersFileName = \"/panfs/pan1/orphancrispr/h0.2_2cluster_spacers.txt\"\r\n\r\n\r\n# PART FOR CLUSTERING BY SPACERS (SEQUENCES)\r\n\r\ndef ReverseComplement(seq):\r\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}\r\n reverse_complement = \"\".join(complement.get(base, base) for base in reversed(seq))\r\n return reverse_complement\r\n\r\nSpacersFromArray = {}\r\n\r\n#run this once\r\nfor line in open(IslandIDwithCRISPRNeighborsFixedFileName , \"r\"):\r\n ID = line[:-1].split(' ')[2].replace('\"','') + '_' + line[:-1].split(' ')[3] + '_' + line[:-1].split(' ')[4]\r\n print(ID)\r\n with open(SpacersBaseFileName, \"r\") as f:\r\n for line1, line2 in itertools.zip_longest(*[f] * 2):\r\n Match = re.findall(ID, line1)\r\n if Match:\r\n # print(Match)\r\n if ID in SpacersFromArray:\r\n SpacersFromArray[ID] += [line2[:-1], ReverseComplement(line2[:-1])]\r\n else:\r\n SpacersFromArray[ID] = [line2[:-1], ReverseComplement(line2[:-1])]\r\n\r\nprint('Length of SpacersFromaArray dict = ', len(SpacersFromArray))\r\nwith open(ArrayWithSpacersFileName, \"w\") as File:\r\n for ID in SpacersFromArray:\r\n File.write(ID + '\\t' + ','.join(SpacersFromArray[ID]) + '\\n')\r\n\r\n\r\n","sub_path":"SpacersIslands_Clustering.py","file_name":"SpacersIslands_Clustering.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318250237","text":"#!/usr/bin/env python3\nimport ase.io\nimport click\n\n@click.command()\n@click.option('--n-slab', default=460, help='Fixed atoms')\n@click.option('--n-adsorbate', default=100, help='Moved atoms')\n@click.option('--distance', default=3.0, help='Distance')\n@click.option('--structure', default='last_geometry.xyz', help='Input')\n@click.option('--output', default='output.xyz', help='Output')\ndef move_it(n_slab, n_adsorbate, distance, structure, output):\n s = ase.io.read(structure)\n slab = s[:n_slab]\n mol = s[n_slab:n_slab+n_adsorbate]\n mol.translate([0, 0, distance])\n ase.io.write(output, slab + mol)\n\nif __name__ == '__main__':\n move_it()\n\n","sub_path":"move_adsorbate.py","file_name":"move_adsorbate.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423799295","text":"\"\"\"\nAdds init/import of BMRB format\n\nMethods:\n\"\"\"\nfrom cing.Libs.AwkLike import AwkLike\nfrom cing.Libs.NTutils import * #@UnusedWildImport\nfrom cing.core.constants import * #@UnusedWildImport\nfrom cing.core.molecule import Chain\nfrom cing.core.molecule import Molecule\n\nbmrbAtomType2spinTypeCingMap = { 'H': '1H', 'C': '13C', 'N': '15N', 'P': '31P' }\nbmrbResType2CingMap = { 'H': '1H', 'C': '13C', 'N': '15N', 'P': '31P' }\n\ndef initBMRB( project, bmrbFile, moleculeName = None ):\n \"\"\"\n Initialize from edited BMRB file\n Return molecule instance\n \"\"\"\n mol = Molecule( name=moleculeName )\n project.appendMolecule( mol )\n\n error = False\n record = None\n for record in AwkLike( bmrbFile, minNF = 8, commentString = '#' ):\n\n resName = record.dollar[3]\n resNum = record.int(2)\n\n atomName = record.dollar[4]\n# shift = record.float(6)\n# serror = record.float(7)\n# ambig = record.int(8)\n res = mol.addResidue( Chain.defaultChainId, resName, resNum, IUPAC )\n\n if (not res):\n nTerror( 'Error initBMRB: invalid residue %s %s line %d (%s)\\n',\n resName, atomName, record.NR, record.dollar[0]\n )\n error = True\n #end if\n #end for\n\n error = error or (project.importBMRB( bmrbFile) == None)\n if error:\n nTmessage( '==> initBMRB: completed with error(s)' )\n else:\n nTmessage( '==> initBMRB: successfully parsed %d lines from %s', record.NR, record.FILENAME )\n #end if\n nTmessage(\"%s\", mol.format() )\n\n if error:\n return None\n return mol\n#end def\n\n#==============================================================================\ndef importFromBMRB( project, bmrbFile ):\n \"\"\"\n Import chemical shifts from edited BMRB file\n No reassigned Pseudo atoms yet;\n Return molecule instance or None on error\n \"\"\"\n\n if not project.molecule:\n nTerror(\"Error importBMRB: no molecule defined\" )\n return None\n #end if\n\n mol = project.molecule\n mol.newResonances(source=bmrbFile)\n\n error = False\n# for f in AwkLike( bmrbFile, minNF = 8, commentString = '#' ):\n#\n# resName = f.dollar[3]\n# resNum = f.int(2)\n#\n# atomName= f.dollar[4]\n# shift = f.float(6)\n# serror = f.float(7)\n# _ambig = f.int(8)\n\n for f in AwkLike( bmrbFile, minNF = 9, commentString = '#' ):\n\n resName = f.dollar[4]\n resNum = f.int(2)\n\n atomName= f.dollar[5]\n shift = f.float(7)\n serror = f.float(8)\n _ambig = f.int(9)\n\n atm = mol.decodeNameTuple( (IUPAC, Chain.defaultChainId, resNum, atomName) )\n\n if not atm:\n nTerror( 'Error initBMRB: invalid atom %s %s line %d (%s)',\n resName, atomName, f.NR, f.dollar[0] )\n error = True\n else:\n atm.resonances().value = shift\n atm.resonances().error = serror\n if _ambig == 1 and atm.isProChiral():\n atm.stereoAssigned = True\n #end if\n #end for\n\n # now fix the assignments;\n for atm in mol.allAtoms():\n # Check if all realAtoms are assigned in case there is a pseudo atom\n if atm.isAssigned(resonanceListIdx=RESONANCE_LIST_IDX_ANY) and not atm.isStereoAssigned() and atm.hasPseudoAtom():\n fix = False\n pseudo = atm.pseudoAtom()\n for a in pseudo.realAtoms():\n if not a.isAssigned(resonanceListIdx=RESONANCE_LIST_IDX_ANY):\n fix = True\n break\n #end if\n #end for\n if fix:\n pseudo.resonances().value = atm.resonances().value\n pseudo.resonances().error = atm.resonances().error\n atm.resonances().value = NaN\n atm.resonances().value = NaN\n nTmessage('Deassigned %s, assigned %s', atm, pseudo)\n #end if\n #end if\n #end for\n\n if error:\n nTerror( '==> importFromBMRB: completed with error(s)' )\n else:\n nr = getDeepByKeysOrAttributes(f, 'NR') # pylint: disable=W0631\n nTmessage( '==> importFromBMRB: successfully parsed %d lines from %s', nr, bmrbFile )\n #end if\n\n if error:\n return None\n return mol\n#end def\n\n# register the functions\nmethods = [(initBMRB, None),\n (importFromBMRB, None)\n ]\nsaves = []\nrestores = []\nexports = []\n","sub_path":"python/cing/PluginCode/BMRB.py","file_name":"BMRB.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11947861","text":"class fTransReconcile:\n def __init__(self,parentForm,FormObj):\n self.form = parentForm\n self.app = parentForm.ClientApplication\n self.FormView = None\n self.oPrint = self.app.GetClientClass('PrintLib','PrintLib')()\n\n def Show(self):\n self.FormContainer.Show()\n\n def CheckClick(self,sender):\n self.form.GetPanelByName('Filter').GetControlByName('LProgam').Visible = not sender.Checked\n\n def TampilkanClick(self,sender):\n app = self.app\n self.uiStatC.ClearData()\n self.uiStatD.ClearData()\n self.uiStatP.ClearData()\n uipFilter = self.uiFilter\n if uipFilter.IsAllProgram == 'F' and (uipFilter.GetFieldValue('LProgam.AccountNo')== None):\n app.ShowMessage('PERINGATAN!! Silahkan pilih Porgram AQH terlebih dahulu')\n return 0\n self.FormObject.CommitBuffer()\n params = self.FormObject.GetDataPacket()\n self.FormObject.SetDataWithParameters(params)\n self.Show()\n\n def ProsesClick(self,sender):\n app = self.app\n if app.ConfirmDialog('Yakin melakukan reconcile transaksi AQH??'):\n pass\n else:\n return 0\n\n self.FormObject.CommitBuffer()\n ph = self.FormObject.GetDataPacket()\n res = self.FormObject.CallServerMethod(\"Proses\", ph)\n\n status = res.FirstRecord\n if status.IsErr :\n app.ShowMessage(status.ErrMessage)\n return 0\n\n self.TampilkanClick(sender)\n #sender.ExitAction = 2\n #self.FormObject.Close(2)\n\n","sub_path":"dialogs/AQH/fTransReconcile_intr.py","file_name":"fTransReconcile_intr.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183102807","text":"name = \"Fractal Plant\"\naxiom = 'X'\nangle = 25\ndistance = 4\ngenerations = 7\nx, y, heading = -325, -350, 70\n\n\ndef orientation(aTurtle):\n aTurtle.up()\n aTurtle.setheading(heading)\n aTurtle.goto(x, y)\n aTurtle.down()\n\n\ndef applyRules(ch):\n if ch == 'X':\n return 'F-[[X]+X]+F[+FX]-X' # Rule 1\n if ch == 'F':\n return 'FF' # Rule 1\n else:\n return ch # no rules apply so keep the character\n\n\nsavedInfoList = []\n\n\ndef lSystem(aTurtle, cmd):\n aTurtle.down()\n if cmd == 'F':\n aTurtle.forward(distance)\n elif cmd == 'B':\n aTurtle.backward(distance)\n elif cmd == '+':\n aTurtle.right(angle)\n elif cmd == '-':\n aTurtle.left(angle)\n elif cmd == '[':\n aTurtle.down()\n savedInfoList.append([aTurtle.xcor(), aTurtle.ycor(), aTurtle.heading()])\n elif cmd == ']':\n aTurtle.up()\n x, y, h = savedInfoList.pop()\n aTurtle.setheading(h)\n aTurtle.setposition(x, y)\n","sub_path":"Lsystems/fractalPlant.py","file_name":"fractalPlant.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93884396","text":"\"\"\"\r\nRead Wafer Config Information From Excel file on Server and store in local database\r\nAuthor: Leon Xiao\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport glob,os,shutil\r\nfrom sqlalchemy import create_engine,select,insert,MetaData,Table\r\nimport sqlite3,time,schedule,pickle\r\n\r\nconfig_dir=r'\\\\30-0001-19146\\spe$\\WafList\\HWY'\r\ndb_dir=r'D:\\06. Software\\SQLiteStudio'\r\nreader=['\\\\SENDAHEAD_READER_WK*.xls','Reader',[1,2,5,6,11],['WAFER','WAFER PART #','Pad Layout','PURPOSE OF WAFER','Feature'],'rConfig.csv']\r\nwriter=['\\\\SENDAHEAD_WRITER_*.xls','Writer',[1,2,5,6,9],['WAFER','WAFER PART #','Pad Layout','PURPOSE OF WAFER','Purpose'],'wConfig.csv']\r\nflw=['\\\\readerprobing*.xlsx','FLW',[1,9,10],['WAFER','FLW','FLW2'],'Flw.csv']\r\ndef scan_new(scheme): #scan xls files from server\r\n __doc__='dfadf'\r\n files=glob.glob(config_dir+scheme[0])\r\n config=pd.DataFrame()\r\n for file in files:\r\n data=pd.read_excel(file,sheet_name=scheme[1],usecols=scheme[2],names=scheme[3])\r\n data['WAFER']=data['WAFER'].map(lambda x: str(x)[:5])\r\n config=config.append(data)\r\n config.drop_duplicates(subset='WAFER',inplace=True,keep='last') #WaferID as Primary Key, ValueError: not enough values to unpack (expected 2, got 0)\r\n #config.dropna().to_csv(scheme[4],index=False)\r\n return config\r\n\r\ndef db_update(db_dir=r'D:\\06. Software\\SQLiteStudio',db='sqlite:///wafer.db'):\r\n os.chdir(db_dir)\r\n metadata = MetaData()\r\n engine=create_engine(db)\r\n connection = engine.connect()\r\n for task in [reader,writer]:\r\n config=scan_new(task)\r\n old=pd.read_sql_table(task[1],engine,index_col=None)['WAFER']\r\n now=config['WAFER']\r\n new=[not i for i in now.isin(old)]\r\n update=config.iloc[new,:]\r\n update.dropna(inplace=True)\r\n config_table = Table(task[1], metadata, autoload=True,autoload_with=engine)\r\n stmt = insert(config_table)\r\n values_list = []\r\n columns=list(update.columns)\r\n print(\"Update %s\" %len(update), task[1] +' Records!')\r\n for row in update.values:\r\n data = {columns[0]: row[0], columns[1]: row[1],columns[2]: row[2],columns[3]: row[3],columns[4]: row[4]}\r\n values_list.append(data)\r\n result_proxy = connection.execute(stmt,values_list)\r\n\r\ndef db_update2(db_dir=r'D:\\06. Software\\SQLiteStudio',db='sqlite:///wafer.db'): #sql delete duplicate results\r\n os.chdir(db_dir)\r\n metadata = MetaData()\r\n engine=create_engine(db)\r\n connection = engine.connect()\r\n for task in [reader,writer]:\r\n config=scan_new(task)\r\n old=set(pd.read_sql_table(task[1],engine,index_col=None)['WAFER'])\r\n now=set(config['WAFER'])\r\n update=config[now-old]\r\n update.to_sql(task[1],connection,if_exists='append',index=False)\r\n\r\n\r\ndef update_table():\r\n fpath=r'D:\\02. Data\\readerprobing summary Dec 18 2018.xlsx'\r\n names=['WAFER','WAFER PART #','Format','Config','BL/SH Design','FLW Target','FLW2 Target','FLW (S2E)','FLW2 (S2E)','FLW (Rmin)','FLW2 (Rmin)']\r\n cols=[1,2,3,4,5,6,7,9,10,69,70]\r\n data=pd.read_excel(fpath,sheet_name='FLW',usecols=cols,names=names,index=False)\r\n data=data.reset_index()\r\n data.columns=names\r\n data.WAFER=data.WAFER.map(lambda x: x[:-1])\r\n os.chdir(db_dir)\r\n metadata = MetaData()\r\n engine=create_engine('sqlite:///test.db')\r\n connection = engine.connect()\r\n data.to_sql('FLW',connection,if_exists='replace',index=False)\r\n connection.close()\r\n data['FLW (S2E)'].astype=float\r\n\r\ndef qst_db():\r\n os.chdir(db_dir)\r\n metadata = MetaData()\r\n engine=create_engine('sqlite:///yield.db')\r\n connection = engine.connect()\r\n os.chdir(r'D:\\00. QST Raw Data\\2019')\r\n ls=os.listdir()\r\n tmr=pd.DataFrame()\r\n tdmr=pd.DataFrame()\r\n for f in ls:\r\n data=pd.read_excel(f)\r\n if 'R2_MRR' in data.columns:\r\n tdmr=tdmr.append(data)\r\n else:\r\n tmr=tmr.append(data)\r\n tmr_col=pd.read_excel('D:\\Python\\RH\\PTP01206_Data.xls').columns\r\n tdmr_col=pd.read_excel('D:\\Python\\RH\\PTP01035_Data.xls').columns\r\n tmr=tmr[tmr_col]\r\n tdmr=tdmr[tdmr_col]\r\n tmr.to_sql('1DMR',connection,if_exists='append',index=False) \r\n tdmr.to_sql('TDMR',connection,if_exists='append',index=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n db_update()\r\n","sub_path":"Python/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129002698","text":"import json\nimport psycopg2\nimport datetime\nimport dateutil.relativedelta\nimport os\nimport zipfile\nimport shutil\nimport schedule, time\nfrom xml.dom import minidom\nfrom xml.parsers import expat\nfrom enum import Enum\n\n#region Classes\n\nclass Log_Message_Type(Enum):\n INFO = 1\n ERROR = 2\n\nclass geopoint(object):\n def __init__(self, id, latitude, longitude, target_date, accquisition_date):\n self.id = id\n self.latitude = latitude\n self.longitude = longitude\n self.target_date = target_date\n self.accquisition_date = accquisition_date\n\nclass database_manager(object):\n def __init__(self, appconfig):\n self.appconfig = appconfig\n\n def create_connection(self):\n \"\"\" This method returns a psycopg2 connection object created \n with the parameters provided to the object. \"\"\"\n return psycopg2.connect(\"dbname={0} user={1} password={2}\".format(self.appconfig.dbName, \n self.appconfig.dbUserName, self.appconfig.dbPassword))\n\n def get_all_not_accquired_geopoints_as_geopoint_collection(self):\n select_geopoints_query = \"\"\"SELECT * FROM geopoints WHERE accquisition_date IS NULL\"\"\"\n\n connection = self.create_connection()\n connection_cursor = connection.cursor()\n connection_cursor.execute(select_geopoints_query)\n result_data = connection_cursor.fetchall()\n connection.close()\n\n result_geopoints = [geopoint(result_item[0], result_item[1], \n result_item[2], result_item[3], result_item[4]) for result_item in result_data]\n\n return result_geopoints\n\n def update_accquisition_date(self, id):\n datetime_now = str(datetime.datetime.today())\n update_accquisition_date_query = \"\"\"UPDATE geopoints SET accquisition_date = now() WHERE id = %d\"\"\"%(id)\n\n connection = self.create_connection()\n connection_cursor = connection.cursor()\n connection_cursor.execute(update_accquisition_date_query)\n connection.commit()\n connection.close()\n\nclass configuration_manager(object):\n def __init__(self, dbName, dbUserName, dbPassword, sentinelUserName, sentinelPassword, wgetLocalization, downloadLocalization):\n self.dbName = dbName\n self.dbUserName = dbUserName\n self.dbPassword = dbPassword\n self.sentinelUserName = sentinelUserName\n self.sentinelPassword = sentinelPassword\n self.wgetLocalization = wgetLocalization\n self.downloadLocalization = downloadLocalization\n\n#endregion\n\n#region Functions\n\ndef get_sentinel_query_results(appconfig, target_date, geo_latitude, geo_longitude):\n main_url = \"https://scihub.copernicus.eu/dhus/search?q=\"\n wget_command = appconfig.wgetLocalization + \" --no-check-certificate\"\n authorization = '--user=%s --password=%s'%(appconfig.sentinelUserName, appconfig.sentinelPassword)\n search_output = \"--output-document=query_results.xml\"\n query_geopoint = 'footprint:\\\\\"Intersects(%s,%s)\\\\\"'%(geo_latitude, geo_longitude)\n start_date = target_date - dateutil.relativedelta.relativedelta(months = 1)\n end_date = target_date\n query_date = \"beginposition:[%sT00:00:00.000Z TO %sT00:00:00.000Z] AND endPosition:[%sT00:00:00.000Z TO %sT00:00:00.000Z]\"%(\n start_date, end_date, start_date, end_date)\n query_paltform_name = \"platformname:Sentinel-2\"\n query_orderby = \"*&orderby=beginposition desc\"\n query = query_geopoint + \" AND \" + query_date + \" AND \" + query_paltform_name + \" AND \" + query_orderby \n\n final_wget_command = '%s %s %s \"%s%s\"'%(wget_command, authorization, search_output, main_url, query)\n\n log_information(Log_Message_Type.INFO, \"Executing command %s\"%(final_wget_command))\n\n os.system(final_wget_command)\n\n log_information(Log_Message_Type.INFO, \"Command %s executed.\"%(final_wget_command))\n\n if not os.path.exists(\"query_results.xml\"):\n log_information(Log_Message_Type.ERROR, \"Something get wrong, wget could not download query result and save it to query_result.xml\")\n return False\n\n return True\n\ndef get_images_from_sentinel(db_manager, appconfig, id, target_date):\n process_query_results_list = process_query_results_xml()\n filename = process_query_results_list[0]\n link = process_query_results_list[1]\n\n if filename == \"\":\n return\n\n wget_command = appconfig.wgetLocalization + \" --no-check-certificate\"\n authorization = '--user=%s --password=%s'%(appconfig.sentinelUserName, appconfig.sentinelPassword)\n downloadPath = appconfig.downloadLocalization + \"\\\\\" + str(id) + \"_\" + str(target_date)\n if not os.path.exists(downloadPath):\n os.makedirs(downloadPath)\n downloadLocalization = downloadPath + \"\\\\\" + filename + \".zip\"\n final_wget_command = '%s %s --output-document=%s \"%s\"'%(wget_command, authorization, downloadLocalization, link)\n \n log_information(Log_Message_Type.INFO, \"Executing command %s\"%(final_wget_command))\n\n os.system(final_wget_command) \n\n log_information(Log_Message_Type.INFO, \"Command %s executed.\"%(final_wget_command))\n\n db_manager.update_accquisition_date(id)\n\n extract_images(downloadLocalization, downloadPath)\n clean_temporary_files(downloadLocalization)\n\ndef extract_images(downloadLocalization, downloadPath):\n if not os.path.exists(downloadLocalization):\n log_information(Log_Message_Type.ERROR, 'Can not unzip file %s becouse that file does not exist.'%(downloadLocalization))\n return\n\n zip_ref = zipfile.ZipFile(downloadLocalization, 'r')\n zip_ref.extractall(downloadPath)\n zip_ref.close()\n\n short_download_localization = downloadLocalization[:-4]\n\n granule_dir = os.listdir(short_download_localization + \"\\\\GRANULE\")[0]\n image_files_localization = short_download_localization + \"\\\\GRANULE\\\\\" + granule_dir + \"\\\\IMG_DATA\"\n for filename in os.listdir(image_files_localization):\n shutil.copy2(image_files_localization + \"\\\\\" + filename, downloadPath)\n \n shutil.copy2(short_download_localization + \"\\\\MTD_MSIL1C.xml\", downloadPath)\n\ndef clean_temporary_files(download_localization):\n os.remove(download_localization)\n shutil.rmtree(download_localization[:-4])\n os.remove(\"query_results.xml\")\n\ndef process_query_results_xml():\n try:\n xml_file = minidom.parse(\"query_results.xml\")\n except expat.ExpatError as e:\n log_information(Log_Message_Type.ERROR, \"Error during parsing query_result.xml: %s\"%(e))\n return \"\"\n\n latest_product = xml_file.getElementsByTagName(\"entry\")[0]\n product_id_number = latest_product.getElementsByTagName(\"id\")[0].firstChild.data\n link = latest_product.getElementsByTagName(\"link\")[0].attributes.items()[0][1]\n\n for node in latest_product.getElementsByTagName(\"str\"):\n (name, value) = node.attributes.items()[0]\n if value == \"filename\":\n filename = str(node.toxml()).split('>')[1].split('<')[0]\n break\n\n return [filename, link] \n\ndef log_information(log_message_type, log_message):\n if log_message_type is Log_Message_Type.INFO:\n log_message_header = \"INFO\"\n\n elif log_message_type is Log_Message_Type.ERROR:\n log_message_header = \"ERROR\"\n\n with open('logfile.txt', 'a') as log_file:\n error_log = '\\n\\n%s at %s\\n%s'%(log_message_header, str(datetime.datetime.today()), log_message)\n log_file.write(error_log)\n \n return\n\n\n#endregion\n\n#region Scheduler jobs\n\ndef sentinel_download_manager_job():\n with open('appconfig.json') as configuration_file:\n configuration_json = json.load(configuration_file)\n\n appconfig = configuration_manager(configuration_json[\"dbName\"], configuration_json[\"dbUserName\"], \n configuration_json[\"dbPassword\"], configuration_json[\"sentinelUserName\"], configuration_json[\"sentinelPassword\"], \n configuration_json[\"wgetLocalization\"], configuration_json[\"downloadLocalization\"])\n\n db_manager = database_manager(appconfig)\n result_data = db_manager.get_all_not_accquired_geopoints_as_geopoint_collection()\n\n for item in result_data:\n is_completed = get_sentinel_query_results(appconfig, item.target_date, item.latitude, item.longitude)\n\n if is_completed:\n get_images_from_sentinel(db_manager, appconfig, item.id, item.target_date)\n\n print(\"DONE!\")\n\n#endregion\n\n#region Main program\n\nwith open('appconfig.json') as configuration_file:\n configuration_json = json.load(configuration_file)\n\nprint(\"Sentinel download manager started.\")\nprint(\"Scheduler configuration.\")\n\nscheduler_mode = configuration_json[\"schedulerMode\"]\n\nif scheduler_mode == \"minutes\":\n minutes = int(configuration_json[\"schedulerMinuteInterval\"])\n schedule.every(minutes).minutes.do(sentinel_download_manager_job)\nelif scheduler_mode == \"days\":\n days = configuration_json[\"schedulerMinuteInterval\"].split(';')\n hour = configuration_json[\"schedulerHour\"]\n\n for day in days:\n if day == \"monday\":\n schedule.every().monday.at(hour).do(sentinel_download_manager_job)\n elif day == \"tuesday\":\n schedule.every().tuesday.at(hour).do(sentinel_download_manager_job)\n elif day == \"wednesday\":\n schedule.every().wednesday.at(hour).do(sentinel_download_manager_job)\n elif day == \"thursday\":\n schedule.every().thursday.at(hour).do(sentinel_download_manager_job)\n elif day == \"friday\":\n schedule.every().friday.at(hour).do(sentinel_download_manager_job)\n elif day == \"saturday\":\n schedule.every().saturday.at(hour).do(sentinel_download_manager_job)\n elif day == \"sunday\":\n schedule.every().sunday.at(hour).do(sentinel_download_manager_job)\n\nprint(\"Scheduler configuration succesfull, starting sentinel download manager.\")\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n\n#endregion\n\n","sub_path":"SentinelDownloadManager.py","file_name":"SentinelDownloadManager.py","file_ext":"py","file_size_in_byte":9812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522346646","text":"import pickle\nfrom numpy.core.defchararray import array\n\nmodel_path = '/Users/arshad_221b/Projects/heart attack /finalized_model.sav'\nmodel = pickle.load(open(model_path, 'rb'))\n\ndef prediction(l):\n l = [float(x) for x in l]\n l = array(l)\n l = l.reshape(1,-1)\n o = model.predict(l)\n if o[0] == 1:\n return('Heart Attack!')\n else:\n return('No Heart Attack!')\n\n\n\n","sub_path":"model2_prediction.py","file_name":"model2_prediction.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290128869","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Header\nfrom sensor_msgs.msg import Range\nimport copy\n\npi = 3.14159264\n\ntop_frame = \"/camera_top_cam_depth_optical_frame\"\nfront_frame = \"/camera_top_cam_depth_optical_frame\"\ntop_topic = \"top_camera_range\"\nfront_topic = \"front_camera_range\"\ns_range = 4\nfov = pi/4\n\ntop_pub = rospy.Publisher(top_topic, Range, queue_size = 10)\nfront_pub = rospy.Publisher(front_topic, Range, queue_size = 10)\nrospy.init_node('range_publisher')\nr = rospy.Rate(10)\n\nwhile not rospy.is_shutdown():\n h = Header()\n h.stamp = rospy.Time.now()\n h.frame_id = top_frame\n\n rg_top = Range()\n rg_top.header = h\n rg_top.field_of_view = fov\n rg_top.max_range = s_range\n rg_top.min_range = s_range\n rg_top.range = s_range\n rg_top.radiation_type = Range.INFRARED\n\n rg_front = copy.deepcopy(rg_top)\n rg_front.header.frame_id = front_frame\n\n top_pub.publish(rg_top)\n front_pub.publish(rg_front)\n\n r.sleep()\n","sub_path":"cam_scripts/src/range_publisher.py","file_name":"range_publisher.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"260523930","text":"#!/usr/bin/env python\n\n# =========================================================\n\"\"\"\n Python module to read and write SPEX res and spo files.\n See this page for the format specification: \n \n http://var.sron.nl/SPEX-doc/manualv3.04/manualse108.html#x122-2840008.2\n \n This module contains the data class:\n \n DATA: Contains the collection of spectra and\n responses organized in SPEX regions \n \n Dependencies:\n - numpy: Array operations\n - spo: The spo class from this pyspex data module\n - res: The res class from this pyspex data module\n\"\"\"\n# =========================================================\n\n# Import stuff for compatibility between python 2 and 3\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom builtins import str\n\nfrom future import standard_library\n\nimport numpy as np\n\nfrom .region import Region\nfrom .spo import Spo\nfrom .res import Res\n\nstandard_library.install_aliases()\n\n\n# =========================================================\n# Data class\n# =========================================================\n\nclass Dataset:\n \"\"\"The dataset class is the most general class containing a \n dataset with multiple regions. Using this class, users\n can read, write and manipulate spectral datasets.\"\"\"\n\n def __init__(self):\n self.regions = [] #: List of regions\n\n # -----------------------------------------------------\n # Read one region from a spo and res file.\n # -----------------------------------------------------\n\n def read_region(self, iregion, spofile, resfile, label=\"\"):\n \"\"\"Read one region with number iregion from the two SPEX files and add it to the dataset.\"\"\"\n\n # Read the spo and res files in a temporary object\n tspo = Spo()\n tspo.read_file(spofile)\n\n tres = Res()\n tres.read_file(resfile)\n\n # Create new region\n reg = Region()\n\n # Return desired region and save into local region object\n reg.spo = tspo.return_region(iregion)\n reg.res = tres.return_region(iregion)\n\n # Adapt region number to local set\n reg.res.region = reg.res.region + len(self.regions)\n\n # Run consistency checks\n reg.check()\n\n # Add label to the region\n self.label = label\n\n # Add region to list of regions\n self.regions.append(reg)\n\n # -----------------------------------------------------\n # Read all the regions from a spo and res file.\n # -----------------------------------------------------\n\n def read_all_regions(self, spofile, resfile):\n \"\"\"Read all the regions from a spo and res file and add them to the dataset.\"\"\"\n\n # Read the spo and res files in a temporary object\n tspo = Spo()\n tspo.read_file(spofile)\n\n tres = Res()\n tres.read_file(resfile)\n\n # Check if the number of regions in both files are the same\n if tspo.nregion != tres.nregion:\n print(\"Error: the spo and res files do not have the same number of regions!\")\n return\n\n for i in np.arange(tspo.nregion):\n # Initialize a new region\n reg = Region()\n\n reg.spo = tspo.return_region(i + 1)\n reg.res = tres.return_region(i + 1)\n\n reg.res.region = reg.res.region + len(self.regions)\n\n # Run consistency checks\n reg.check()\n\n # Add region to list of regions\n self.regions.append(reg)\n\n # -----------------------------------------------------\n # Append a region object to the dataset\n # -----------------------------------------------------\n def append_region(self,region):\n \"\"\"Append a region object to the dataset.\"\"\"\n\n nregions=len(self.regions)\n region.res.region = region.res.region + nregions\n self.regions.append(region)\n\n # -----------------------------------------------------\n # Write one region to a spo and res file.\n # -----------------------------------------------------\n\n def write_region(self, spofile, resfile, iregion, ext_rate=False, overwrite=False, history=None):\n \"\"\"Write one region to a spo and res file.\"\"\"\n\n if len(self.regions) >= iregion > 0:\n self.regions[iregion - 1].spo.write_file(spofile, ext_rate=ext_rate, overwrite=overwrite, history=history)\n self.regions[iregion - 1].res.write_file(resfile, overwrite=overwrite, history=history)\n else:\n print(\"Error: region number not found!\")\n return 1\n\n return 0\n\n # -----------------------------------------------------\n # Write all the regions to a spo and res file.\n # -----------------------------------------------------\n\n def write_all_regions(self, spofile, resfile, ext_rate=False, overwrite=False, history=None):\n \"\"\"Write all regions in the data object to spo and res. \"\"\"\n tspo = Spo()\n tres = Res()\n\n i = 1\n for ireg in self.regions:\n tspo.add_spo_region(ireg.spo)\n tres.add_res_region(ireg.res, i)\n i = i + 1\n\n stat=tspo.write_file(spofile, ext_rate=ext_rate, overwrite=overwrite, history=history)\n if stat != 0:\n message.error(\"Writing SPO file failed.\")\n return 1\n\n stat=tres.write_file(resfile, overwrite=overwrite, history=history)\n if stat != 0:\n message.error(\"Writing RES file failed.\")\n return 1\n\n return 0\n\n # -----------------------------------------------------\n # Show a summary of the dataset, similar to data show in SPEX\n # -----------------------------------------------------\n\n def show(self):\n \"\"\"Show a summary for the entire dataset\"\"\"\n for ireg in np.arange(len(self.regions)):\n print(\"===========================================================\")\n print(\" Part {0}\".format(ireg))\n self.regions[ireg].show()\n print(\"\")","sub_path":"pyspex/io/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"440409914","text":"import tensorflow as tf\nfrom tensorflow.keras import Model\nfrom pre_process import pre_process\nfrom models.sample_model.layers import residual\nfrom models.sample_model import resnet \nimport datetime\nimport argparse\nimport os\n\n\ntf.keras.backend.clear_session()\n\n\nap = argparse.ArgumentParser()\nap.add_argument(\"--save_file\", default=os.path.join(os.path.dirname(__file__), 'model_weights.h5'), help=\"File to save model weights to\")\nap.add_argument(\"--conv_filters_1\", default=16, help=\"Number of filters in hte base conv layers\")\nap.add_argument(\"--conv_kernel_1\", default=3, help=\"Number of kernels in base conv layers\")\nap.add_argument(\"--conv_stride_1\", default=1, help=\"Stride size of the base conv layer\")\nap.add_argument(\"--res_filters\", default=32, help=\"Number of filters in base conv layers\")\nap.add_argument(\"--res_kernel\", default=3, help=\"Kernel size in base residual block\")\nap.add_argument(\"--res_stride\", default=1, help=\"Stride size of the base residual block\")\nap.add_argument(\"--batch_size\", default=32, help=\"Training data batch size\")\nap.add_argument(\"--buffer_size\", default=1, help='Number of batch buffers to pre load')\nap.add_argument(\"--EPOCHS\", default=1000, help='Epochs to train the model on')\nap.add_argument(\"--image_size\", default=64, help=\"Image dimension\")\nap.add_argument(\"--res_model\", default=50, help=\"Model arch for resnet layers\")\nap.add_argument(\"--output_dim\", default=5, help=\"Number of outputs for class.\")\nap.add_argument(\"--log_dir\", default=os.path.join(os.path.dirname(__file__),'logs/gradient_tape'), help=\"Directory to store tensorboard\")\nargs = ap.parse_args()\n\n\n\np = pre_process.PreProcess(args.batch_size, args.buffer_size, args.image_size)\ndataset = p.build_dataset()\n\n\n\nrnet = resnet.ResNet(args.conv_filters_1, args.conv_kernel_1, args.conv_stride_1,\n args.res_kernel, args.res_stride, args.output_dim, args.res_model)\n\nloss_object = tf.keras.losses.CategoricalCrossentropy()\noptimizer = tf.keras.optimizers.Adam(learning_rate=.1)\n\ntrain_loss = tf.keras.metrics.Mean(name='train_loss')\ntrain_accuracy = tf.keras.metrics.CategoricalAccuracy(name='train_accuracy')\n\ntest_loss = tf.keras.metrics.Mean(name='test_loss')\ntest_accuracy = tf.keras.metrics.CategoricalAccuracy(name='test_accuracy')\n\n\ncurrent_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\ntrain_log_dir = os.path.join(args.log_dir , current_time , 'train')\ntest_log_dir = os.path.join(args.log_dir , current_time , 'test')\ntrain_summary_writer = tf.summary.create_file_writer(train_log_dir)\ntest_summary_writer = tf.summary.create_file_writer(test_log_dir)\n\n\n\n@tf.function\ndef train_step(images, labels):\n with tf.GradientTape() as tape:\n predictions = rnet(images)\n loss = loss_object(labels, predictions)\n gradients = tape.gradient(loss, rnet.trainable_variables)\n optimizer.apply_gradients(zip(gradients, rnet.trainable_variables))\n\n train_loss(loss)\n train_accuracy(labels, predictions)\n\n\n@tf.function\ndef test_step(images, labels):\n predictions = rnet(images)\n t_loss = loss_object(labels, predictions)\n\n test_loss(t_loss)\n test_accuracy(labels, predictions)\n\n\n\nfor epoch in range(args.EPOCHS):\n\n for inputs,labels in dataset:\n train_step(inputs,labels)\n with train_summary_writer.as_default():\n tf.summary.scalar('loss', train_loss.result(), step=epoch)\n tf.summary.scalar('accuracy', train_accuracy.result(), step=epoch)\n\n\n for test_inputs,test_labels in dataset:\n test_step(test_inputs,test_labels)\n with test_summary_writer.as_default():\n tf.summary.scalar('loss', test_loss.result(), step=epoch)\n tf.summary.scalar('accuracy', test_accuracy.result(), step=epoch)\n\n\n template = 'Epoch: {}, Loss: {}, Acc: {}, Test Loss: {}, Test Acc: {}'\n\n print(template.format(\n epoch+1,train_loss.result(),train_accuracy.result()*100,test_loss.result(),\n test_accuracy.result()*100)\n )\n\n\n # Reset metrics every epoch\n train_loss.reset_states()\n test_loss.reset_states()\n train_accuracy.reset_states()\n test_accuracy.reset_states()\n\n\nrnet.save_weights(args.save_file)\n","sub_path":"models/sample_model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"336465688","text":"# -*- coding: utf-8 -*-\n\n# This work was created by participants in the DataONE project, and is\n# jointly copyrighted by participating institutions in DataONE. For\n# more information on DataONE, see our web site at http://dataone.org.\n#\n# Copyright 2009-2016 DataONE\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 copy\nimport datetime\nimport logging\nimport os\nimport urllib.parse\n\nimport requests\nimport requests.adapters\nimport requests_toolbelt\nimport requests_toolbelt.utils.dump\n\nimport d1_common.const\nimport d1_common.date_time\nimport d1_common.url\nimport d1_common.util\n\nimport d1_client.util\n\nDEFAULT_NUMBER_OF_RETRIES = 1\nDEFAULT_USE_STREAM = False\nDEFAULT_VERIFY_TLS = True\nDEFAULT_SUPPRESS_VERIFY_WARNINGS = False\n\nUBUNTU_CA_BUNDLE_PATH = '/etc/ssl/certs/ca-certificates.crt'\n\n\nclass Session(object):\n def __init__(\n self, base_url, cert_pem_path=None, cert_key_path=None, **kwargs_dict\n ):\n \"\"\"The Session improves performance by keeping connection related state and\n allowing it to be reused in multiple API calls to a DataONE Coordinating\n Node or Member Node. This includes:\n\n - A connection pool\n - HTTP persistent connections (HTTP/1.1 and keep-alive)\n\n Based on Python Requests:\n - http://docs.python-requests.org/en/master/\n - http://docs.python-requests.org/en/master/user/advanced/#session-objects\n\n :param base_url: DataONE Node REST service BaseURL.\n :type host: string\n\n :param cert_pem_path: Path to a PEM formatted certificate file.\n :type cert_pem_path: string\n\n :param cert_key_path: Path to a PEM formatted file that contains the private\n key for the certificate file. Only required if the certificate file does\n not itself contain the private key.\n :type cert_key_path: string\n\n :param timeout_sec: Time in seconds that requests will wait for a response.\n None, 0, 0.0 disables timeouts. Default is DEFAULT_HTTP_TIMEOUT, currently 60\n seconds.\n :type timeout_sec: float, int, None\n\n :param retries: Set number of times to try a request before failing. If not\n set, retries are still performed, using the default number of retries. To\n disable retries, set to 1.\n :type retries: int\n\n :param headers: headers that will be included with all connections.\n :type headers: dictionary\n\n :param query: URL query parameters that will be included with all\n connections.\n :type query: dictionary\n\n :param use_stream: Use streaming response. When enabled, responses must be\n completely read to free up the connection for reuse. (default:False)\n :type use_stream: bool\n\n :param verify_tls: Verify the server side TLS/SSL certificate.\n (default: True). Can also hold a path that points to a trusted CA bundle\n :type verify_tls: bool or path\n\n :param suppress_verify_warnings: Suppress the warnings issued when\n {verify_tls} is set to False.\n :type suppress_verify_warnings: bool\n\n :param user_agent: Override the default User-Agent string used by d1client.\n :type user_agent: str\n\n :param charset: Override the default Charset used by d1client.\n (default: utf-8)\n :type charset: str\n\n :returns: None\n \"\"\"\n self._base_url = base_url\n self._scheme, self._host, self._port, self._path = urllib.parse.urlparse(\n base_url\n )[:4]\n self._api_major = 1\n self._api_minor = 0\n # Adapter\n self._max_retries = kwargs_dict.pop('retries', DEFAULT_NUMBER_OF_RETRIES)\n # Option to suppress SSL/TLS verification warnings\n suppress_verify_warnings = kwargs_dict.pop(\n 'suppress_verify_warnings', DEFAULT_SUPPRESS_VERIFY_WARNINGS\n )\n if suppress_verify_warnings:\n requests.packages.urllib3.disable_warnings()\n # Default parameters for requests\n self._default_request_arg_dict = {\n 'params':\n self._datetime_to_iso8601(kwargs_dict.pop('query', {})),\n 'timeout':\n kwargs_dict.pop('timeout_sec', d1_common.const.DEFAULT_HTTP_TIMEOUT),\n 'stream':\n kwargs_dict.pop('use_stream', DEFAULT_USE_STREAM),\n 'verify':\n kwargs_dict.pop('verify_tls', DEFAULT_VERIFY_TLS),\n 'headers': {\n 'User-Agent':\n kwargs_dict.pop('user_agent', d1_common.const.USER_AGENT),\n 'Charset':\n kwargs_dict.pop('charset', d1_common.const.DEFAULT_CHARSET),\n },\n }\n # Use the OS trust store on Ubuntu and derivatives\n if self._default_request_arg_dict['verify'] is True:\n if os.path.isfile(UBUNTU_CA_BUNDLE_PATH):\n self._default_request_arg_dict['verify'] = UBUNTU_CA_BUNDLE_PATH\n # Default headers\n self._default_request_arg_dict['headers'].update(\n kwargs_dict.pop('headers', {})\n )\n self._default_request_arg_dict.update(kwargs_dict)\n # Requests wants cert path as string if single file and tuple if cert/key\n # pair.\n if cert_pem_path is not None:\n self._default_request_arg_dict['cert'] = (\n cert_pem_path,\n cert_key_path if cert_key_path is not None else cert_pem_path\n )\n self._session = self._create_requests_session()\n\n @property\n def base_url(self):\n return self._base_url\n\n def GET(self, rest_path_list, **kwargs):\n \"\"\"Send a GET request.\n See requests.sessions.request for optional parameters.\n :returns: Response object\n \"\"\"\n return self._request('GET', rest_path_list, **kwargs)\n\n def HEAD(self, rest_path_list, **kwargs):\n \"\"\"Send a HEAD request.\n See requests.sessions.request for optional parameters.\n :returns: Response object\n \"\"\"\n kwargs.setdefault('allow_redirects', False)\n return self._request('HEAD', rest_path_list, **kwargs)\n\n def POST(self, rest_path_list, **kwargs):\n \"\"\"Send a POST request with optional streaming multipart encoding.\n See requests.sessions.request for optional parameters. To post regular data,\n pass a string, iterator or generator as the {data} argument. To post a\n multipart stream, pass a dictionary of multipart elements as the\n {fields} argument. E.g.:\n\n fields = {\n 'field0': 'value',\n 'field1': 'value',\n 'field2': ('filename.xml', open('file.xml', 'rb'), 'application/xml')\n }\n\n :returns: Response object\n \"\"\"\n fields = kwargs.pop('fields', None)\n if fields is not None:\n return self._send_mmp_stream('POST', rest_path_list, fields, **kwargs)\n else:\n return self._request('POST', rest_path_list, **kwargs)\n\n def PUT(self, rest_path_list, **kwargs):\n \"\"\"Send a PUT request with optional streaming multipart encoding.\n See requests.sessions.request for optional parameters. See post() for\n parameters.\n :returns: Response object\n \"\"\"\n fields = kwargs.pop('fields', None)\n if fields is not None:\n return self._send_mmp_stream('PUT', rest_path_list, fields, **kwargs)\n else:\n return self._request('PUT', rest_path_list, **kwargs)\n\n def DELETE(self, rest_path_list, **kwargs):\n \"\"\"Send a DELETE request.\n See requests.sessions.request for optional parameters.\n :returns: Response object\n \"\"\"\n return self._request('DELETE', rest_path_list, **kwargs)\n\n def OPTIONS(self, rest_path_list, **kwargs):\n \"\"\"Send a OPTIONS request.\n See requests.sessions.request for optional parameters.\n :returns: Response object\n \"\"\"\n return self._request('OPTIONS', rest_path_list, **kwargs)\n\n def get_curl_command_line(self, method, url, **kwargs):\n \"\"\"Get request as cURL command line for debugging.\n \"\"\"\n if kwargs.get('query'):\n url = '{}?{}'.format(url, d1_common.url.urlencode(kwargs['query']))\n curl_list = ['curl']\n if method.lower() == 'head':\n curl_list.append('--head')\n else:\n curl_list.append('-X {}'.format(method))\n for k, v in sorted(list(kwargs['headers'].items())):\n curl_list.append('-H \"{}: {}\"'.format(k, v))\n curl_list.append('{}'.format(url))\n return ' '.join(curl_list)\n\n def dump_request_and_response(self, response):\n \"\"\"Return a string containing a nicely formatted representation of the\n request and response objects for logging and debugging\n - Note: Does not work if the request or response body is a MultipartEncoder\n object.\n \"\"\"\n if response.reason is None:\n response.reason = ''\n return d1_client.util.normalize_request_response_dump(\n requests_toolbelt.utils.dump.dump_response(response)\n )\n\n #\n # Private\n #\n\n def _create_requests_session(self):\n session = requests.Session()\n adapter = requests.adapters.HTTPAdapter(max_retries=self._max_retries)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n def _send_mmp_stream(self, method, rest_path_list, fields, **kwargs):\n url = self._prep_url(rest_path_list)\n kwargs = self._prep_request_kwargs(kwargs)\n mmp_stream = requests_toolbelt.MultipartEncoder(fields=fields)\n kwargs['data'] = mmp_stream\n kwargs['headers'].update({\n 'Content-Type': mmp_stream.content_type,\n 'Content-Length': str(mmp_stream.len),\n })\n return self._session.request(method, url, **kwargs)\n\n def _request(self, method, rest_path_list, **kwargs):\n url = self._prep_url(rest_path_list)\n kwargs = self._prep_request_kwargs(kwargs)\n logging.debug(\n 'Request equivalent: {}'.format(\n self.get_curl_command_line(method, url, **kwargs)\n )\n )\n return self._session.request(method, url, **kwargs)\n\n def _prep_url(self, rest_path_list):\n if isinstance(rest_path_list, str):\n rest_path_list = [rest_path_list]\n return d1_common.url.joinPathElements(\n self._base_url, self._get_api_version_path_element(),\n *self._encode_path_elements(rest_path_list)\n )\n\n def _prep_request_kwargs(self, kwargs_in_dict):\n # TODO: Check if per-call args get the same processing as client create args\n kwargs_dict = {\n 'timeout':\n self._timeout_to_float(kwargs_in_dict.pop('timeout_sec', 0.0)),\n 'stream':\n kwargs_in_dict.pop('use_stream', None),\n 'verify':\n kwargs_in_dict.pop('verify_tls', None),\n 'params':\n self._format_query_values(kwargs_in_dict.pop('query', {})),\n }\n kwargs_dict.update(kwargs_in_dict)\n kwargs_dict = self._remove_none_value_items(kwargs_dict)\n result_dict = copy.deepcopy(self._default_request_arg_dict)\n if result_dict['timeout'] in (0, 0.0):\n result_dict['timeout'] = None\n d1_common.util.nested_update(result_dict, kwargs_dict)\n logging.debug(\n 'Request kwargs:\\n{}'.format(\n d1_common.util.serialize_to_normalized_compact_json(result_dict)\n )\n )\n return result_dict\n\n def _timeout_to_float(self, timeout):\n \"\"\"Convert timeout to float. Return None if timeout is None, 0 or 0.0.\n timeout=None disables timeouts in Requests.\n \"\"\"\n if timeout is not None:\n try:\n timeout_float = float(timeout)\n except ValueError:\n raise ValueError(\n 'timeout_sec must be a valid number or None. timeout=\"{}\"'.\n format(timeout)\n )\n if timeout_float:\n return timeout_float\n\n def _format_query_values(self, query_dict):\n return self._bool_to_string(\n self._datetime_to_iso8601(self._remove_none_value_items(query_dict))\n )\n\n def _remove_none_value_items(self, query_dict):\n return {k: v for k, v in list(query_dict.items()) if v is not None}\n\n def _datetime_to_iso8601(self, query_dict):\n \"\"\"Encode any datetime query parameters to ISO8601.\"\"\"\n return {\n k: v if not isinstance(v, datetime.datetime) else v.isoformat()\n for k, v in list(query_dict.items())\n }\n\n def _bool_to_string(self, query_dict):\n return {\n k: 'true' if v is True else 'false' if v is False else v\n for k, v in list(query_dict.items())\n }\n\n def _encode_path_elements(self, path_element_list):\n return [\n d1_common.url.encodePathElement(v)\n if isinstance(v,\n (int, str)) else d1_common.url.encodePathElement(v.value())\n for v in path_element_list\n ]\n\n def _get_api_version_path_element(self):\n return 'v{}'.format(self._api_major)\n\n def _get_api_version_xml_type(self):\n if (self._api_major, self._api_minor) == (1, 0):\n return 'v1'\n else:\n return 'v{}.{}'.format(self._api_major, self._api_minor)\n\n def _get_expected_schema_type_attribute(self):\n return '{}{}'.format(\n d1_common.const.DATAONE_SCHEMA_ATTRIBUTE_BASE,\n self._get_api_version_xml_type()\n )\n","sub_path":"lib_client/src/d1_client/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":12956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487368031","text":"from __future__ import print_function, division\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn; seaborn.set()\n\nfrom gatspy.datasets import fetch_rrlyrae\n\nimport os, sys\nsys.path.insert(0, 'LSSTsims')\nfrom compute_results import gather_results\n\n\ndef olusei_period_criterion(Pobs, Ptrue, Tdays, dphimax = 0.037):\n factor = dphimax / Tdays\n return abs(Pobs - Ptrue) <= (Ptrue ** 2) * factor\n\n\ntemplate_indices = np.arange(2 * 23).reshape(2, 23).T\npointing_indices = np.arange(1, 24)[:, None]\nndays = np.array([180, 365, 2*365, 5*365])[:, None, None]\ngmags = np.array([20, 21, 22, 23, 24.5])[:, None, None, None]\n\nresults_multi = 'LSSTsims/resultsLSST.npy'\nresults_ssm = 'LSSTsims/resultsLSST_ssm_{0}.npy'\n\n# Get measured periods\nPobs_multi = gather_results(results_multi,\n pointing_indices=pointing_indices,\n ndays=ndays,\n gmags=gmags,\n template_indices=template_indices)\nPobs_multi[np.isnan(Pobs_multi)] = 0\n\nPobs_ssm = np.array([gather_results(results_ssm.format(band),\n pointing_indices=pointing_indices,\n ndays=ndays,\n gmags=gmags,\n template_indices=template_indices)\n for band in 'ugriz'])\nPobs_ssm = Pobs_ssm[:, :, :, :, :, 0].transpose(1, 2, 3, 4, 0)\nPobs_ssm[np.isnan(Pobs_ssm)] = 0\n\n# Get true periods\nrrlyrae = fetch_rrlyrae()\nPtrue = np.reshape([rrlyrae.get_metadata(rrlyrae.ids[i])['P']\n for i in template_indices.ravel()],\n template_indices.shape)\n\n# Check for matches\ndphimax = 0.37\nmatches_multi = olusei_period_criterion(Pobs_multi,\n Ptrue.reshape(Ptrue.shape + (1,)),\n ndays.reshape(ndays.shape + (1,)),\n dphimax=dphimax)\nresults_multi = np.any(matches_multi, -1).mean(-1).mean(-1)\n\nmatches_ssm = olusei_period_criterion(Pobs_ssm,\n Ptrue.reshape(Ptrue.shape + (1,)),\n ndays.reshape(ndays.shape + (1,)),\n dphimax=dphimax)\nresults_ssm = np.any(matches_ssm, -1).mean(-1).mean(-1)\n\nfig, ax = plt.subplots()\nfor t, frac_multi, frac_ssm in reversed(list(zip(ndays.ravel(),\n results_multi.T,\n results_ssm.T))):\n line = ax.plot(gmags.ravel(), frac_multi,\n label='{0:.1f} years'.format(t / 365))\n line = ax.plot(gmags.ravel(), frac_ssm,\n color=line[0].get_color(), linestyle='dashed')\n ax.fill_between(gmags.ravel(), frac_ssm, frac_multi,\n edgecolor='none',\n facecolor=line[0].get_color(), alpha=0.2)\n\nax.add_artist(ax.legend(loc='lower left'))\nref_lines = ax.plot([0], [0], '-k') + ax.plot([0], [0], '--k')\nax.legend(ref_lines, ['multiband', 'supersmoother'], loc='lower center')\n\nax.set(xlabel='g-band magnitude',\n ylabel='Fraction of Periods among Top-5',\n title='Multiband Improvement over SuperSmoother for LSST',\n xlim=(20, 24.5), ylim=(0, 1.05))\n\nfig.savefig('fig09.pdf')\nplt.show()\n","sub_path":"figures/fig09_LSST_sims.py","file_name":"fig09_LSST_sims.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"10706190","text":"import unittest\nfrom double_down import double_down\n\n\nclass TestDoubleDownDecorator(unittest.TestCase):\n\n def setUp(self):\n self.arr = list(range(2))\n\n def test_decorator(self):\n @double_down\n def append(arr, num):\n arr.append(num)\n return arr\n\n result = append(self.arr, -1)\n expected = list(range(2)) + [-1, -1]\n\n self.assertEqual(result, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"539761848","text":"import time\nfrom random import randint\nfrom random import choice\nimport copy\n\n# define game objects\n\nclass GameSettings():\n\t\"\"\"Define game settings\"\"\"\n\n\tdef __init__(self):\n\t\tself.grid_size = 5\n\t\tself.starting_gold = 10\n\t\tself.difficulty = 1\n\n\tdef user_settings_change(self):\n\n\t\tmsg = 'Choose the size of the dungeon grid: '\n\n\t\tsize_choice = int(input(msg))\n\n\t\tself.grid_size = size_choice\n\nclass GameGrid():\n\t\"\"\"Creates a grid object for the game of variable size\"\"\"\n\tdef __init__(self, settings, player):\n\t\t\n\t\tself.settings = settings\n\t\tself.player = player\n\n\t\tself.row = self.settings.grid_size\n\t\tself.col = self.settings.grid_size\n\n\t\t# question: should floor_level be stored in settings?\n\t\tself.floor_level = 1 # objects constructed as levels advance will increase this number\n\t\t\t\t\t\t\t # perhaps that means I should use a __class__ attribute here? \n\n\t\tself.grid_matrix = self.make_grid()\t\t\t# grid for graphics, containing strings '*'\n\t\tself.all_room_grid = self.generate_rooms() # grid for room data, containing room dictionaries\n\n\t\tself.create_start() # same as below, adds start on construction\n\t\tself.create_exit()\t# doesn't need to return anything, just adds the exit on construction\n\t\tself.create_mystic() # one mystic in every dungeon level\n\t\t\n\t\tself.current_room_type = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Type'] \n\t\t\n\t\t# this is a bool and is used to track if current inhabited room was previously visited or not\n\t\t# and yes, you could perform this check by checking the all_room_grid and looking at 'Visited' bool directly.\n\t\tself.room_status = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Visited']\n\n\tdef make_grid(self):\n\t\t# list comprehension to create matrix of the game grid graphics\n\n\t\tgrid_matrix = [[' * ' for x in range(self.col)] for y in range(self.row)]\n\n\t\treturn grid_matrix\n\n\tdef update_player_location(self):\n\t\t\"\"\"updates the grid_matrix to show the X for the player coordinates (and change prev room back to a *)\"\"\"\n\n\t\tself.grid_matrix[self.player.previous_coords[0]][self.player.previous_coords[1]] = ' * '\n\t\tself.grid_matrix[self.player.player_location[0]][self.player.player_location[1]] = ' X '\n\n\n\tdef update_current_roomtype(self):\n\t\t\"\"\"udpate the current_room_type attribute to reflect current player location\"\"\"\n\n\t\tself.current_room_type = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Type']\n\t\tself.room_status = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Visited']\n\n\t\t# remember, all_room_grid is a list containing multiple lists, and each of THOSE lists contains a bunch of\n\t\t# dictionaries (the room dictionaries, with keys for Type and Visited, etc).\n\t\t# the above code indexes the all_room_grid with format [][][]\n\t\t# first [] - index list inside the main list, e.g. which list do we want inside the main list?\n\t\t# second [] - index that list, e.g. which dictionary do we want inside the list we've chosen?\n\t\t# third [] - index the dictionary by key, giving us the value stored for that key.\n\n\tdef generate_rooms(self):\n\t\t\"\"\"create a room that corresponds to each coordinate in the grid matrix object\"\"\"\n\t\tall_room_grid = []\t# will become a matrix (a list of lists) containing room dictionaries\n\t\t\n\t\tfor r in self.grid_matrix:\t\t# r is a list\n\n\t\t\trow = []\n\n\t\t\tfor c in r:\t\t\t\t\t# c is a string ('*'), num of loops will = num of * in list r\n\t\t\t\troom_type = self.get_room_type()\n\t\t\t\troom = {'Type':room_type, 'Visited':False, 'Post_Note': None} \n\t\t\t\trow.append(room)\n\n\t\t\tall_room_grid.append(row)\t\t# done once for each list (r) in the grid_matrix\n\t\t\t\n\t\treturn all_room_grid\n\n\tdef get_room_type(self):\n\t\t\"\"\"called by generate_rooms function to make one random room\"\"\"\n\t\troom_type = ''\n\t\tnum = randint(1,8)\n\n\t\tif num >= 1 and num <= 4:\n\t\t\troom_type = 'Empty'\n\t\telif num >= 5 and num <= 7:\n\t\t\troom_type = 'Monster'\n\t\telif num == 8:\n\t\t\troom_type = 'Treasure'\n\t\t\n\t\treturn room_type\n\n\tdef create_start(self):\n\n\t\tself.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Type'] = 'Start'\t\n\n\tdef create_exit(self):\n\t\t\"\"\"creates an exit in the room grid and makes sure it doesn't overlap with player start position\"\"\"\n\t\tactive = True\n\n\t\twhile active:\n\t\t\t# should I just change the min random number, rather than the complex conditionals in the if below ??\n\t\t\trandom_x = randint(0, self.row - 1)\n\t\t\trandom_y = randint(0, self.col - 1 )\n\n\t\t\tcoords = [random_x, random_y]\n\t\t\t# makes sure exit 1. does not overlap player 2. is not within 2 rows of the player (this logic needs some work...)\n\t\t\tif coords != self.player.player_location and abs(coords[0] - self.player.player_location[0]) \\\n\t\t\t>= 2 and abs(coords[1] - self.player.player_location[1]) >= 1:\n\t\t\t\tself.all_room_grid[random_x][random_y]['Type'] = 'Exit'\n\t\t\t\tactive = False\n\t\t\telse:\n\t\t\t\tpass\n\n\tdef create_mystic(self):\n\n\t\tactive = True\n\n\t\twhile active:\n\n\t\t\trandom_x = randint(0, self.row - 1)\n\t\t\trandom_y = randint(0, self.col - 1)\n\t\t\t\n\t\t\tcoords = [random_x, random_y]\n\n\t\t\tif coords != self.player.player_location and self.all_room_grid[random_x][random_y]['Type'] != 'Exit':\n\t\t\t\tself.all_room_grid[random_x][random_y]['Type'] = 'Mystic'\n\t\t\t\tactive = False\n\t\t\telse:\n\t\t\t\tpass\n\n\tdef print_grid(self):\n\t\t\"\"\"print the visual game grid\"\"\"\n\t\t\n\t\tprint('\\nLV.{}'.format(self.floor_level))\n\n\t\tfor r in self.grid_matrix:\n\t\t\tfor c in r:\n\t\t\t\tprint(c, end='')\n\t\t\tprint()\t\t\t\t\t\t# use print('\\n' to space out grid further)\n\n\t\tprint()\n\n\t\t#print('\\n{} is located at X'.format(self.player.info['Name']))\n\n\tdef dev_grid_showtypes(self):\n\t\t\"\"\"for dev testing, not gameplay: show current properties of all rooms\"\"\"\n\t\t\n\t\tclear_screen()\n\n\t\tr = 0\n\n\t\t#grid_matrix_copy = self.grid_matrix[:]\t # doesn't work, does a shallow copy\n\n\t\tgrid_matrix_copy = copy.deepcopy(self.grid_matrix)\n\n\t\t# modify chars in the deepcopy based on corresponding roomtype in original all_room_grid\n\t\t# incrementing variables r, c used to index (and thereby modify) contents of deepcopy grid\n\t\tfor row in self.all_room_grid:\n\t\t\tc = 0\n\t\t\tfor col in row:\n\t\t\t\tif col['Type'] == 'Empty':\t\t\t\t \n\t\t\t\t\tgrid_matrix_copy[r][c] = ' E '\t\t\n\t\t\t\telif col['Type'] == 'Monster':\t\t\t\n\t\t\t\t\tgrid_matrix_copy[r][c] = ' M '\n\t\t\t\telif col['Type'] == 'Treasure':\n\t\t\t\t\tgrid_matrix_copy[r][c] = ' T '\n\t\t\t\telif col['Type'] == 'Exit':\n\t\t\t\t\tgrid_matrix_copy[r][c] = ' @ '\n\t\t\t\telif col['Type'] == 'Start':\n\t\t\t\t\tgrid_matrix_copy[r][c] = ' S '\n\t\t\t\telif col['Type'] == 'Mystic':\n\t\t\t\t\tgrid_matrix_copy[r][c] = ' & '\n\n\t\t\t\tc += 1\n\t\t\tr += 1\n\n\t\t# print the dev grid\n\t\tfor row in grid_matrix_copy:\n\t\t\tfor val in row:\n\t\t\t\tprint(val, end = '')\n\t\t\tprint()\n\n\t\tpress_enter()\n\n\tdef build_next_dungeon_floor(self):\n\t\t\"\"\"updates dungeon grid to next floor when player exits previous floor\"\"\"\n\n\t\t# increment various things to make next dungeon more difficult.\n\t\t# update settings file accordingly so monster difficulty scales, etc.\n\nclass Dice():\n\t\"\"\"Create a variable sided die that can be rolled\"\"\"\n\tdef __init__(self):\n\t\tself.last_roll = None\n\t\tself.dice_text = ''\n\n\tdef roll(self, sides=6):\n\t\troll = randint(1, sides)\n\t\tself.last_roll = roll\n\t\treturn roll\n\n\tdef print_roll(self, mods=None):\t# mods is not actually being used at all\n\t\ttext = 'ROLLING...'\n\t\tfor c in text:\n\t\t\tprint(c, end='', flush=True)\n\t\t\ttime.sleep(0.06)\t\n\t\tprint(' {}'.format(self.last_roll)) # use lambda here to put 'if mods' inside line?\n\t\tif mods:\n\t\t\tprint('+{}'.format(mods))\n\nclass Weapon():\n\t\"\"\"Generates a weapon object with type and damage\"\"\"\n\tdef __init__(self, name, damage):\n\t\tself.name = name\n\t\tself.damage = damage\n\t\tself.icon = self.get_dam_icon()\n\n\tdef modify_weapon(self, add_to_damage):\n\t\tself.name += '++'\n\t\tself.damage += add_to_damage\n\n\tdef print_stats(self):\n\t\tprint('*** WEAPON INFO ***')\n\t\t#print()\n\t\tprint('TYPE{:.>15}'.format(self.name))\n\t\tprint('DAMAGE{:.>13}'.format(self.damage))\n\n\tdef get_dam_icon(self):\n\t\treturn '(1d' + str(self.damage) + ')'\n\nclass Armor():\n\t\"\"\"only instantiated as an attribute of player class\"\"\"\n\tdef __init__(self, name, armor_class):\n\t\tself.name = name\n\t\tself.armor_class = armor_class\n\n\tdef modify_armor(self, add_to_ac):\n\t\tself.name += '++'\n\t\tself.armor_class += add_to_ac\n\n\tdef print_stats(self):\n\t\tprint('*** ARMOR INFO ***')\n\t\tprint('TYPE{:.>14}'.format(self.name))\n\t\tprint('AC{:.>16}'.format(self.ac))\n\nclass Player():\n\t\"\"\"Generates the user character\"\"\"\n\n\tdef __init__(self, settings):\n\t\tself.settings = settings\n\n\t\tself.created = False\n\t\tself.dead = False\n\n\t\tself.info = {'Name':'None', 'Race':''}\n\n\t\t# starting values for player game attributes\n\t\tself.name = self.info['Name']\n\t\tself.level = 1\n\t\tself.hp = 10\t\t# current in game hp amount\n\t\tself.max_hp = 10\t# current max hp for player level\n\t\tself.gold = 10\n\t\tself.exp = 10\t# set on creation of player object\n\t\tself.next_level_at = self.get_level_up_val() # determined on creation of player object\n\n\t\t# checks will need to be done in game loop to see if player's current exp is > than level_up, and if so,\n\t\t# we need to call a level up function AND ALSO call a function to increase 'level_up' attribute to next\n\t\t# setting (so next level-up occurs at higher exp amount, etc).\n\n\t\tself.dice = Dice()\n\n\t\t# player items\n\t\tself.potions = []\n\t\tself.items = ['Torch',]\n\t\tself.weapon = Weapon('Dagger', 4)\n\t\tself.armor = Armor('Leather', 10)\n\n\t\t# player location on grid. continually updated during gameplay.\n\t\tself.player_location = [(self.settings.grid_size - 1), (int(self.settings.grid_size / 2) - 1)]\n\t\tself.previous_coords = [0,0]\n\n\tdef get_level_up_val(self):\n\t\tif self.level == 1:\n\t\t\treturn 100\n\t\tif self.level == 2:\n\t\t\treturn 220\n\t\tif self.level == 3:\n\t\t\treturn 350\n\t\tif self.level > 3:\n\t\t\treturn (2 * self.exp)\t# think through / clarify this math here. can you use it throughout?\n\n\tdef build_player(self):\n\t\tclear_screen()\n\n\t\ta = input('What is the name of your character? ')\n\t\tb = input('What is the Race of your character? ')\n\n\t\tself.info['Name'] = a.title()\n\t\tself.info['Race'] = b.title()\n\n\t\tclear_screen()\n\n\t\tprint('You have successfully created {} the {}.'.format(a.title(), b.title()))\n\t\tprint('You will begin with {} Hit Points and {} Gold Pieces.'.format(self.hp, self.gold))\n\t\tprint('\\nYou are now ready to start the game!')\n\n\t\tpress_enter()\n\n\tdef print_player_info(self):\n\t\t\"\"\"display all player stats on the screen\"\"\"\n\t\tclear_screen()\n\n\t\tprint(\"# PLAYER INFO #\\n\")\n\t\tprint(\"Name{:.>17} \".format(self.info['Name']))\n\t\tprint(\"Race{:.>17} \".format(self.info['Race']))\n\t\tprint(\"Level{:.>16} \".format(self.level))\n\t\tprint(\"Hit Points{:.>11} \".format(self.hp))\n\t\tprint(\"Gold Pieces{:.>10} \".format(self.gold))\n\t\tprint(\"Experience{:.>11} \".format(self.exp))\n\t\tprint(\"Next Level{:.>11} \".format(self.next_level_at))\n\n\t\tpress_enter()\n\n\tdef show_inventory(self):\n\t\t\"\"\"Prints player inventory screen\"\"\"\n\t\tclear_screen()\n\n\t\t# you have this redundant usage of player items. You could just access weapon\n\t\t# and armor info directly from the objects themselves, but instead you're doing 'inventory'.\n\t\tprint(\"# INVENTORY #\\n\")\n\t\tprint(\"Weapon{:.>17} \".format(self.weapon.name + self.weapon.icon))\n\t\tprint(\"Armor{:.>18} \".format(self.armor.name))\n\t\tprint(\"Items{:.>18} \".format(self.items[0])) # how to show all list items here ?\n\t\tprint()\n\t\tprint(\"# POTIONS #\\n\")\n\t\t\n\t\tcount = 1\n\t\tfor potion in self.potions:\n\t\t\tprint('#{} {}'.format(count, potion))\n\t\t\tcount += 1\n\n\t\tpress_enter()\n\n\tdef reset_player(self):\n\t\t\"\"\"reset the player, triggered on exit of active game\"\"\"\n\t\t# this will probably need modification once saving and loading are introduced!\n\n\t\tself.player_location = [(self.settings.grid_size - 1), (int(self.settings.grid_size / 2) - 1)]\n\n\t\tself.level = 1\n\t\tself.hp = 10\n\t\tself.max_hp = 10\n\t\tself.gold = 10\n\t\tself.exp = 0\n\t\tself.next_level_at = self.get_level_up_val()\n\n\t\tself.potions = []\n\t\tself.weapon = Weapon('Dagger', 4)\n\t\tself.armor = Armor('Leather', 10)\n\n\t\tself.dead = False\n\nclass Monster():\n\t\"\"\"Generate a monster object for battle sequences, diff parameter determines difficulty\"\"\"\n\n\tdef __init__(self, difficulty):\n\t\tself.difficulty = difficulty # add some randomization of difficulty here\n\t\tself.diff_string = self.get_diff_string()\n\t\t\n\t\tself.dice = Dice()\t# constructs a die object by calling Dice class\n\n\t\tself.advantage = False\t# determines who gets first attack, player or monster\n\n\t\tself.damage_roll = self.get_damage_roll()\n\t\tself.armor_class = self.get_armor_class()\n\n\t\tself.name = self.get_monster_name()\t# gets random name on construction\n\t\tself.hp = self.get_hit_points()\t\t# gets HP depending on difficulty\n\t\t\n\tdef get_armor_class(self):\n\t\tif self.difficulty == 1:\n\t\t\treturn 7\n\t\tif self.difficulty == 2:\n\t\t\treturn 11\n\t\tif self.difficulty == 3:\n\t\t\treturn 14\n\t\tif self.difficulty == 4:\n\t\t\treturn 16\n\n\tdef get_diff_string(self):\n\t\t\"\"\"gets appropriate string based on difficult level int\"\"\"\n\t\tif self.difficulty == 1:\n\t\t\treturn 'EASY'\n\t\tif self.difficulty == 2:\n\t\t\treturn 'MEDIUM'\n\t\tif self.difficulty == 3:\n\t\t\treturn 'HARD'\n\t\tif self.difficulty > 3:\n\t\t\treturn 'ELITE'\n\n\tdef get_monster_name(self):\n\t\t\"\"\"import name file, grab a name at random, return it -- all based on difficulty level\"\"\"\n\n\t\tif self.difficulty == 1:\n\t\t\tfilename = 'text_files/easy_monsters.txt'\n\n\t\t\twith open(filename, encoding='utf-8') as file_object:\n\t\t\t\tmonster_names = file_object.read().split()\n\n\t\t\tindex = randint(0, len(monster_names) - 1)\n\t\t\treturn monster_names[index]\n\n\t\telif self.difficulty == 2:\n\t\t\tfilename = 'text_files/medium_monsters.txt'\n\n\t\t\twith open(filename, encoding='utf-8') as file_object:\n\t\t\t\tmonster_names = file_object.read().split()\n\n\t\t\tindex = randint(0, len(monster_names) - 1)\n\t\t\treturn monster_names[index]\n\n\t\telif self.difficulty == 3:\n\t\t\tfilename = 'text_files/hard_monsters.txt'\n\n\t\t\twith open(filename, encoding='utf-8') as file_object:\n\t\t\t\tmonster_names = file_object.read().split()\n\n\t\t\tindex = randint(0, len(monster_names) - 1)\n\t\t\treturn monster_names[index]\n\n\t\telif self.difficulty > 3:\n\t\t\tfilename = 'text_files/elite_monsters.txt'\n\n\t\t\twith open(filename, encoding='utf-8') as file_object:\n\t\t\t\tmonster_names = file_object.read().split()\n\n\t\t\tindex = randint(0, len(monster_names) - 1)\n\t\t\treturn monster_names[index]\n\n\tdef get_hit_points(self):\n\t\tif self.difficulty == 1:\n\t\t\treturn self.dice.roll(4)\n\t\telif self.difficulty == 2:\n\t\t\treturn ((self.dice.roll(6)) + 2)\n\t\telif self.difficulty == 3:\n\t\t\treturn ((self.dice.roll(10)) + 4)\n\t\telif self.difficulty > 3:\n\t\t\treturn ((self.dice.roll(20)) + 10)\n\n\tdef print_stats(self):\n\t\tprint('# MONSTER STATS #') #23 chars\n\t\tprint('NAME:{:.>18}'.format(self.monster_name.upper()))\n\t\tprint('DIFF LEVEL:{:.>12}'.format(self.diff_string))\n\t\tprint('HP:{:.>20}'.format(self.hp))\n\t\tprint('AC:{:.>20}'.format(self.ac))\n\t\tprint()\n\n\tdef get_damage_roll(self):\n\t\t\"\"\"determine damage roll of monster via difficulty level\"\"\"\n\t\tif self.difficulty == 1:\n\t\t\treturn 4\n\t\tif self.difficulty == 2:\n\t\t\treturn 6\n\t\tif self.difficulty == 3:\n\t\t\treturn 8\n\t\tif self.difficulty > 3:\n\t\t\treturn 10\n\nclass GameLog():\n\t\"\"\"an object that contains the game log and displays its contents as necessary\"\"\"\n\tdef __init__(self, player, grid):\n\t\tself.player = player\n\t\tself.grid = grid\n\t\tself.room_book = self.make_room_book()\n\t\tself.room_book_visited = self.make_room_book_visited()\n\t\tself.current_room = 'None' # used only to print room type in game header\n\t\tself.current_message = 'None'\n\t\n\tdef update_log(self):\n\t\t\"\"\"update the game_log to get current room from updated grid\"\"\"\n\t\tself.current_room = self.grid.current_room_type #a bit redundant, you could access grid object to print header info.\n\t\tself.current_message = self.get_current_message()\n\n\tdef get_current_message(self):\n\t\t\"\"\"looks at grid object to determine and return appropriate log entry\"\"\"\n\n\t\t# this is where you use the room_status attribute bool, you COULD simply check the all_room_grid bool \n\t\t# 'Visited' here instead, it's the same info. You just thought having this extra var was cleaner.\n\n\t\tif self.grid.room_status == False and self.grid.current_room_type != 'Exit':\n\n\t\t\tif self.grid.current_room_type == 'Start':\n\t\t\t\tself.current_message = self.room_book['Start']\n\t\t\telif self.grid.current_room_type == 'Empty':\n\t\t\t\tself.current_message = self.room_book['Empty']\n\t\t\telif self.grid.current_room_type == 'Monster':\n\t\t\t\tself.current_message = self.room_book['Monster']\n\t\t\telif self.grid.current_room_type == 'Treasure':\n\t\t\t\tself.current_message = self.room_book['Treasure']\n\t\t\telif self.grid.current_room_type == 'Mystic':\n\t\t\t\tself.current_message = self.room_book['Mystic']\n\n\t\t# do you really need to separate the exit text like this?\n\n\t\telif self.grid.current_room_type == 'Exit':\t\t# doesn't matter if Visited is True or False, Exit always presents the same.\n\t\t\t\tself.current_message = self.room_book['Exit']\n\n\t\t# room_status = True, room has already been visited: use the visited dictionary of texts.\n\t\telse:\n\t\t\tif self.grid.current_room_type == 'Start':\n\t\t\t\tself.current_message = self.room_book_visited['Start']\n\t\t\telif self.grid.current_room_type == 'Empty':\n\t\t\t\tself.current_message = self.room_book_visited['Empty']\n\t\t\telif self.grid.current_room_type == 'Monster':\n\t\t\t\tself.current_message = self.room_book_visited['Monster']\n\t\t\telif self.grid.current_room_type == 'Treasure':\n\t\t\t\tself.current_message = self.room_book_visited['Treasure']\n\t\t\telif self.grid.current_room_type == 'Mystic':\n\t\t\t\tself.current_message = self.room_book_visited['Mystic']\n\n\t\treturn self.current_message\t\n\n\tdef print_log(self):\n\t\t\"\"\"prints the header, the current dungeon grid, and the current log text entry\"\"\"\n\t\t\n\t\t# print header stats\n\t\tprint('{} the {} \\t HP: {} GOLD: {} EXP: {}\\t ROOM: {}'.format(self.player.info['Name'].upper(), self.player.info['Race'], \\\n\t\t\tself.player.hp, self.player.gold, self.player.exp, self.current_room))\n\n\t\t# print game map\n\t\tself.grid.print_grid()\n\n\t\t# game log\n\t\tprint(self.current_message)\n\n\tdef make_room_book(self):\n\t\t\"\"\"assign a dictionary of room text to room_book attribute\"\"\"\n\n\t\tfilename = 'text_files/room_book.txt'\n\t\twith open(filename, encoding='utf-8') as file_object:\n\t\t\troom_text = file_object.read().split('X')\n\n\t\troom_dict = {\n\t\t'Start':room_text[0],\n\t\t'Empty':room_text[1],\n\t\t'Monster':room_text[2],\n\t\t'Treasure':room_text[3],\n\t\t'Mystic':room_text[4],\n\t\t'Exit':room_text[5],\n\t\t}\n\n\t\treturn room_dict\n\n\tdef make_room_book_visited(self):\n\t\t\"\"\"make the dictionary object of room text for already visited rooms\"\"\"\n\n\t\tfilename = 'text_files/room_book_visited.txt'\n\t\twith open(filename, encoding='utf-8') as file_object:\n\t\t\troom_text_b = file_object.read().split('X')\n\n\t\troom_dict_b = {\n\t\t'Start':room_text_b[0],\n\t\t'Empty':room_text_b[1],\n\t\t'Monster':room_text_b[2],\n\t\t'Treasure':room_text_b[3],\n\t\t'Mystic':room_text_b[4],\n\t\t'Exit':room_text_b[5],\n\t\t}\n\n\t\treturn room_dict_b\n\nclass MainMenu():\n\t\"\"\"Display menu and receive input for user choice\"\"\"\n\n\tdef __init__(self):\n\t\tself.nothing = None\n\n\tdef print_menu(self):\n\n\t\tclear_screen()\n\n\t\tprint('# DEEPER DUNGEONS #\\n')\n\t\tprint('1. Start New Game')\n\t\tprint('2. Load Game')\n\t\tprint('3. Change Game Settings')\n\t\tprint('4. Exit Game')\n\n\tdef main_choice(self):\n\t\t\n\t\tpossible_choices = ['1','2','3','4']\n\t\tactive = True\n\n\t\twhile active:\n\t\t\tmsg = '\\nEnter your choice: '\n\t\t\tchoice = input(msg)\n\t\t\tif choice in possible_choices:\n\t\t\t\tactive = False\n\t\t\t\treturn int(choice) # is active = False redundant since the return will exit the loop and function?\n\t\t\telse:\n\t\t\t\tprint('That\\'s not one of the menu options!')\n\n# define game UI functions.\n\ndef you_are_dead(player, text=''):\n\tif text:\n\t\tprint(text)\n\n\tprint('YOU', end='', flush=True)\n\ttime.sleep(0.5)\n\tprint('\\tARE', end='', flush=True)\n\ttime.sleep(0.5)\n\tprint('\\tDEAD.', end='', flush=True)\n\n\tprint('So passes {} the {} into the endless night.'.format(player.info['Name'], player.info['Race']))\n\n\tpress_enter()\n\ndef step_printer(word, speed=0.06):\n\t\"\"\"call whenever you want to print a word in steps\"\"\"\n\t#not modifying the word, so no need to index it\n\tfor c in word:\n\t\tprint(c, end='', flush=True)\n\t\ttime.sleep(speed)\n\n\t# old index version\n\t#for c in range(len(word)):\n\t#\tprint(word[c], end='', flush=True)\n\t#\ttime.sleep(speed)\n\ndef slow_print_two(word_one, word_two):\n\t\"\"\"call to print one word, pause, then the second word\"\"\"\n\tprint(word_one, end='', flush=True)\n\ttime.sleep(0.08)\n\tprint(word_two)\n\ndef slow_print_elipsis(word_one, word_two, elip=6):\n\t\"\"\"prints word one, then step prints elipsis, then prints word two\"\"\"\n\telipsis = ('.' * elip)\n\t\n\tprint(word_one, end='', flush=True)\n\t\n\tfor c in elipsis:\n\t\tprint(c, end='', flush=True)\n\t\ttime.sleep(0.06)\n\t\n\tprint(word_two, flush=True)\n\ndef command_menu(player):\n\t\"\"\"prints the command menu for the player\"\"\"\n\tclear_screen()\n\n\tprint('#{:^33}#'.format(player.info['Name'].upper() + '\\'s COMMANDS'))\n\tprint()\n\tprint('MOVE: North DO: Rest GAME: Save')\n\tprint(' South Item Quit')\n\tprint(' East Bio')\n\tprint(' West')\n\tprint()\n\tprint()\n\tprint('Type the first letter of a command') \n\tprint('at the game prompt (>).')\n\n\tpress_enter()\n\ndef main_menu(player):\n\t\"\"\"displays main program menu, takes user input choice and returns it\"\"\"\n\n\tclear_screen()\n\n\tprint('# DEEPER DUNGEONS #\\n')\n\tprint('1. Build character')\n\tprint('2. Start New Game')\n\tprint('3. Load Game')\n\tprint('4. Change Game Settings')\n\tprint('5. Exit Game')\n\n\tprint('\\nCurrently Loaded Character: {}'.format(player.info['Name']))\n\n\tpossible_choices = ['1','2','3','4','5']\n\t\n\tmsg = '\\nEnter your choice: '\n\tchoice = input(msg)\n\tif choice in possible_choices:\n\t\treturn int(choice)\n\telse:\n\t\tprint('That\\'s not one of the menu options!')\n\t\tpress_enter()\n\t\treturn None \t\t\t# no loop is necessary in this function because run_game's call to this func gets None,\n\t\t\t\t\t\t\t\t# therefore has no other action to perform, so it (run_game body loop) loops, calling \n\t\t\t\t\t\t\t\t# this function again. \n\ndef get_player_input():\n\tmsg = '\\n> '\n\tplayer_input = input(msg)\n\treturn player_input\n\ndef get_input_valid(text=None, key='standard'):\n\t\"\"\"a version of input function that also performs input validation\"\"\"\n\t# always put key=... in a call to this function\n\n\tif text:\n\t\tprint(text)\n\n\tcommand = ''\t# initialize command as empty string\n\t\t\t\t\t# not necessary, but clean...\n\n\tpossible_choices = get_possible_choices(key)\n\t\n\tvalid = False\n\n\twhile not valid:\n\n\t\tcommand = input('\\n> ')\n\n\t\tif command not in possible_choices:\n\t\t\tprint('You did not enter a valid command, try again.')\n\t\telse:\n\t\t\tvalid = True\n\n\treturn command\n\ndef get_possible_choices(key):\n\n\t#possible_choices = []\n\n\tif key == 'standard':\n\t\tpossible_choices = ['n','s','e','w','i','b','c','d','q']\n\telif key == 'battle':\n\t\tpossible_choices = ['attack','standard','headshot','s','h','c','p','i','b']\n\t\tpossible_choices += ['finesse','fin','flurry','flu']\n\n\t\t# you need to add the menu options for battle mode: commands, potions, items, etc.\n\n\n\t\t# think of it like this: this place is the 'master set' of valid commands.\n\t\t# inside the actual game functions, you will parse the inputs to perform the\n\t\t# corresponding actions, *always knowing that a valid command has already been \n\t\t# entered*.\n\n\t# add more as needed here\n\n\treturn possible_choices\n\ndef press_enter(text=None):\n\tif text:\n\t\tprint(text)\n\tmsg = '\\n...'\n\tinput(msg)\n\ndef clear_screen():\n\t\"\"\"simple command to clear the game screen\"\"\"\n\tprint(\"\\033[H\\033[J\")\n\n# define main 'game in play' functions\n\ndef action_menu(game_log):\n\t\"\"\"print the game_log, the map, the command menu, take user input, and Return user choice\"\"\"\n\n\tclear_screen()\n\tgame_log.print_log()\t# this is THE print command of the game header -and- game map !! \n\t\t\t\t\t\t\t# if you want to create loops that keep header active, you'll either need to figure out\n\t\t\t\t\t\t\t# how and where to move this, or call it more than once.\n\t\n\tpossible_choices = ['c', 'n', 's', 'e', 'w', 'r', 'i', 'b', 'q', 'd']\n\t\n\tcommand = get_player_input().lower()\n\n\tif command in possible_choices:\n\t\treturn command\n\telse:\n\t\tprint('\\nYou have entered an invalid command, try again.')\n\t\tpress_enter()\n\t\treturn None\n\n\t# note: the input validation performed here doesn't need to be in a while loop, because the\n\t# function that calls this function, game_action, has a while loop that essentially handles that.\n\t# if player gets the else statement above for invalid input, we fall back to game_action, which\n\t# has nothing left to do (command == None), so it loops, and this function is called again.\n\ndef game_action(settings, player, grid, game_log, dice):\n\n\tgrid.update_player_location() # needs to happen here initially so the X gets printed to board\n\tgame_log.update_log() # same, needs to happen so its attributes are not in initial state 'None'\n\n\tactive = True\n\t\n\twhile active:\n\t\t# main game event loop for *game in state of play* (as opposed to game at main menu, not in play)\n\n\t\tcommand = action_menu(game_log)\n\t\tmovement_choices = ['n','s', 'e', 'w']\n\n\t\tif command in movement_choices:\n\t\t\tif movement_engine(settings, player, grid, command):\t# True response = player moved on board\n\t\t\t\tgrid.update_player_location()\n\t\t\t\tgrid.update_current_roomtype()\n\t\t\t\tgame_log.update_log()\n\n\t\t\t\t# check if movement into new room triggers an event, and if so, trigger it.\n\t\t\t\tdetermine_next_event(settings, player, grid, game_log, command)\n\n\t\telif command == 'i':\n\t\t\t\"\"\"Show inventory screen\"\"\"\n\t\t\tplayer.show_inventory()\n\n\t\telif command == 'b':\n\t\t\t\"\"\"Show player info screen\"\"\"\n\t\t\tplayer.print_player_info()\n\n\t\telif command == 'd':\n\t\t\t\"\"\"show room types for each grid coordinate (dev only)\"\"\"\n\t\t\tgrid.dev_grid_showtypes()\n\n\t\telif command == 'c':\n\t\t\t\"\"\"show player the available game commands they can use\"\"\"\n\t\t\tcommand_menu(player)\n\n\t\telif command == 'q':\n\t\t\tprint('Returning to Main Menu...')\n\t\t\ttime.sleep(0.5)\n\t\t\tplayer.reset_player()\t#reset player so new game starts fresh, attributes back to initials\n\t\t\t#reset_grid()\t# I think this is not needed; grid is constructed when menu action 2 is chosen, so will be new.\n\t\t\t#reset_log()\t# same as grid\n\t\t\tactive = False\n\n\t\telse:\n\t\t\tpass\n\n\t\tif check_player_status(settings, player): \t# if True, player is dead, end action event loop.\n\t\t\tactive = False\n\t\t\tplayer.reset_player() # needs to be reset for new game start\n\t\t\tprint('Returning to Main Menu...', flush=True)\n\t\t\ttime.sleep(0.8)\n\t\t\n\t\telse:\n\t\t\tpass\n\n\t\t# need to perform checks here to see if player exited floor of dungeon on this turn.\n\t\t# if so, we need to udpate settings (difficulty, etc) and update grid to create the next level of the dungeon\n\t\t# Q: do we actually create a new dungeon object? or modify the existing one? which makes more sense?\t\n\n\t\t# if active:\t\t# in case anything else needs to happen here, but probably there shouldn't be.\n\ndef check_player_status(settings, player): # seems we don't actually need settings ? \n\t\"\"\"check in every pass of game action event loop to see if player status has changed in a way that triggers event\"\"\"\n\n\t# check if player is alive\n\tif player.hp <= 0:\n\t\tplayer.dead = True\n\t\tprint('\\nOh damn! Looks like {} has been defeated!'.format(player.info['Name']))\n\t\ttime.sleep(0.6)\n\t\tprint('\\nGAME',end='',flush=True)\n\t\ttime.sleep(0.8)\n\t\tprint(' OVER.')\n\t\tpress_enter()\n\t\t\n\t\treturn True\n\n\t# check if player has levelled up... surely this needs to be its own function, and probably a method of\n\t# the player class...\n\n\tif not player.dead:\n\t\tif player.exp >= player.next_level_at:\n\t\t\tplayer.level += 1\n\t\t\tplayer.next_level_at = player.get_level_up_val()\n\n\t\t\tclear_screen()\n\t\t\ttext = '**** {} LEVELS UP! ****'.format(player.info['Name'].upper())\n\t\t\tstep_printer(text, 0.04)\n\t\t\ttime.sleep(0.8)\n\t\t\tprint()\n\t\t\tprint('\\n{} is now Level {}. Awesome!'.format(player.info['Name'], player.level), flush=True)\n\t\t\tplayer.max_hp += 4 \n\t\t\ttime.sleep(0.8)\n\t\t\tprint('\\nHP has been increased to {}'.format(player.hp))\n\t\t\t\n\t\t\tpress_enter()\n\n\treturn False\n\ndef run_game(settings, player):\t\n\t\"\"\"prints Main Menu and takes user input\"\"\"\n\n\tactive = True\n\n\twhile active: #main event loop of program running (but game not in play)\n\n\t\tuser_action = main_menu(player)\n\n\t\tif user_action == 5:\n\t\t\tprint('\\nThanks for playing Deeper Dungeons!')\n\t\t\tprint()\n\t\t\tactive = False\n\n\t\telif user_action == 1:\n\n\t\t\tplayer.build_player()\n\t\t\tplayer.created = True\n\n\t\telif user_action == 2:\n\n\t\t\tif player.created:\n\t\t\t\t# we create the game grid object here, so that it's a brand new grid whenever option 2 (start game) is chosen\n\t\t\t\tgrid = GameGrid(settings, player)\n\t\t\t\tgame_log = GameLog(player, grid)\n\t\t\t\t# player entered 2, so we call game_action, which is the main 'game in play' function:\n\t\t\t\tgame_action(settings, player, grid, game_log, dice) \n\t\t\t\t# note all the locations the arguments in game_action() call are being drawn from... they're all over the place!\n\t\t\t\t# that's because of Python's weird scope rules.\n\t\t\t\t# you'd think, logically / organizationally, that this function (run_game) could only pass objects that had\n\t\t\t\t# already been passed to it. and yet....but read through it all again: dice is the only outlier!\n\t\t\telse:\n\t\t\t\tprint('\\nYou need to create a character first!')\n\t\t\t\tpress_enter()\n\n\t\telif user_action == 3 or user_action == 4:\n\t\t\tprint('\\nSorry, that part of the game is still being developed.')\n\t\t\tpress_enter()\n\ndef movement_engine(settings, player, grid, selection):\n\n\tplayer.previous_coords = player.player_location.copy()\n\n\tif selection == 'n' and player.player_location[0] > 0:\n\t\tplayer.player_location[0] -= 1\n\telif selection == 's' and player.player_location[0] < settings.grid_size - 1:\n\t\tplayer.player_location[0] += 1\n\telif selection == 'e' and player.player_location[1] < settings.grid_size - 1:\n\t\tplayer.player_location[1] += 1\n\telif selection == 'w' and player.player_location[1] > 0:\n\t\tplayer.player_location[1] -= 1\n\n\t# remember, the whole reason for the boolean return from this function is to separate between a\n\t# successful move (return true, grid update) and a border collision (return false, no grid update)\n\telse:\n\t\tprint('\\nYou\\'ve hit the boundary of the dungeon!')\n\t\tpress_enter()\n\t\treturn False # false returned, so grid will not be updated; function exited here.\n\n\tgrid.all_room_grid[player.previous_coords[0]][player.previous_coords[1]]['Visited'] = True\n\n\treturn True\n\ndef determine_next_event(settings, player, grid, game_log, command):\n\t\"\"\"determine event that should occur on entering Room, and trigger that event\"\"\"\n\tdirection = ''\n\n\tif command.lower() == 'n':\n\t\tdirection = 'North'\n\telif command.lower() == 's':\n\t\tdirection = 'South'\n\telif command.lower() == 'w':\n\t\tdirection = 'West'\n\telif command.lower() == 'e':\n\t\tdirection = 'East'\n\n\t# we could look directly at the room dictionary stored in the all_room_grid, but it's less code to simply\n\t# look at the 'current_room_type' attribute of the grid, which is based on that same info anyway.\n\n\tmove_text = ('Moving {}'.format(direction.title()))\n\n\tslow_print_elipsis(move_text, '', 4)\n\n\tif grid.current_room_type == 'Empty' and grid.room_status != True: # bypass print for already visited rooms.\n\t\tslow_print_elipsis('This room', 'is EMPTY.')\n\t\ttime.sleep(0.8)\n\telif grid.current_room_type == 'Treasure' and grid.room_status != True:\n\t\tslow_print_elipsis('This room', 'has a TREASURE chest!')\n\t\ttime.sleep(0.8)\n\t\ttreasure_event(settings, player)\n\telif grid.current_room_type == 'Exit' and grid.room_status != True:\n\t\tslow_print_elipsis('This room', 'has a staircase going DOWN!')\n\t\ttime.sleep(0.8)\n\t\texit_event()\n\telif grid.current_room_type == 'Mystic' and grid.room_status != True:\n\t\tslow_print_elipsis('This room', 'has a MYSTIC!')\n\t\ttime.sleep(0.8)\n\t\tmystic_event()\n\telif grid.current_room_type == 'Monster' and grid.room_status != True:\n\t\tslow_print_elipsis('This room', 'has a MONSTER!')\n\t\ttime.sleep(0.8)\n\t\tbattle_event(settings, player, grid, game_log)\n\telse:\n\t\tslow_print_elipsis('This room', 'seems familiar.')\n\t\ttime.sleep(0.8)\t# this else will only occur if the room being entered has already been visited.\n\n\n# define room event functions -- triggered on entering unvisited room.\n\ndef treasure_event(settings, player):\n\n\tif settings.difficulty == 1:\n\t\ttreasure_roll = randint(1, 5)\n\n\tif settings.difficulty > 1 and settings.difficulty < 3:\n\t\ttreasure_roll = (randint(1, 8) + 2)\n\n\tif settings.difficulty > 3:\n\t\ttreasure_roll = (randint(1, 10) + 3)\n\n\tstep_printer('OPENING CHEST...')\n\tprint('You found {} Gold Pieces inside!'.format(treasure_roll))\n\n\tplayer.gold += treasure_roll\n\n\ttime.sleep(0.6)\n\tprint('{} GP +{}'.format(player.info['Name'], treasure_roll))\n\tpress_enter()\n\ndef mystic_event():\n\tclear_screen()\n\tprint('A an apparition is forming in the center of this room...')\n\ttime.sleep(0.8)\n\tprint('It takes on a ghostly human shape, and speaks to you!')\n\ttime.sleep(0.8)\n\tprint('WOULD YOU LIKE TO BUY A MAGIC ELIXIR...?')\n\n\tresponse = get_player_input()\n\n\tpress_enter()\n\ndef exit_event():\n\tprint('An exit event is now triggered!')\n\tpress_enter()\n\ndef battle_event(settings, player, grid, game_log):\n\t# create a monster\n\tmonster = Monster(settings.difficulty)\n\tencounter_monster(player, monster, grid, game_log)\n\n# define all Battle functions\n\ndef encounter_monster(player, monster, grid, game_log):\n\t\"\"\"monster is engaged and decision to fight or run is chosen by player\"\"\"\n\tclear_screen()\n\n\t# determine how difficult it is for player to run away successfully\n\trun_difficulty = int(randint(2,10) + (3 * monster.difficulty))\n\n\trun_failed = False\n\n\tactive = True\n\t\n\t# step print encounter text\t\n\tslow_print_elipsis('You have encountered a', monster.name.upper())\n\n\tprint('Run Difficulty: {}'.format(run_difficulty))\n\n\twhile active:\n\n\t\tcommand = get_player_input()\n\n\t\tpossible_choices = ['fight', 'run', 'f', 'r']\n\n\t\tif command not in possible_choices:\n\t\t\tprint('You did not enter a valid command, try again.')\n\t\telse:\n\t\t\t# this if has no else case\n\t\t\tif command.lower().startswith('r'):\n\t\t\t\tif run_attempt(player, run_difficulty):\n\t\t\t\t\t# run was successful, exit encounter loop and do not start battle.\n\t\t\t\t\tactive = False\n\t\t\t\t\tprint('You successfully run away from the {}!'.format(monster.name))\n\t\t\t\t\ttime.sleep(0.8)\n\t\t\t\t\tprint('You will now return to the previous room.')\n\t\t\t\t\tpress_enter()\n\n\t\t\t\t\t# make current room (one being run out of) grid icon change back to a *\n\t\t\t\t\tgrid.grid_matrix[player.player_location[0]][player.player_location[1]] = ' * '\n\t\t\t\t\t# move player coords equal that of previously visited room\n\t\t\t\t\tplayer.player_location = player.previous_coords.copy()\n\n\t\t\t\t\t# update everything since room has reverted\n\t\t\t\t\tgrid.update_player_location()\n\t\t\t\t\tgrid.update_current_roomtype()\n\t\t\t\t\tgame_log.update_log()\n\n\n\t\t\t\t\t# NOTE: Player never 'moved' (entered move command) to leave this room, we just\n\t\t\t\t\t# force them back in next lines. movement_engine() function is where previous room\n\t\t\t\t\t# gets set to Visited = True, but that will NOT have happened in this situation,\n\t\t\t\t\t# because they never 'moved' out of it. So, it should remain Visited = False, which\n\t\t\t\t\t# is actually what we want anyway.\n\n\t\t\t\telse:\n\t\t\t\t\t# will be used to have monster attack first\n\t\t\t\t\trun_failed = True\n\t\t\t\t\tprint('You failed to run away from the {}!'.format(monster.name))\n\t\t\t\t\tprint('Now you must fight!')\n\t\t\t\t\tpress_enter()\n\n\t\t\tif command.lower().startswith('f') or active:\n\t\t\t\t# end the encounter loop and start the battle\n\t\t\t\tactive = False\n\t\t\t\tbattle_main(player, monster, run_failed)\n\t\t\t\t\t\t\ndef run_attempt(player, run_difficulty):\n\t\"\"\"rolls player dice, prints out roll, returns True if roll beats run_dc, False otherwise\"\"\"\n\troll = player.dice.roll(20)\n\tplayer.dice.print_roll()\n\treturn (roll >= run_difficulty)\t\t# returns a bool\n\ndef battle_main(player, monster, run_failed):\n\n\tturn = 0\n\tround_num = 1\n\tfight_mods = {'enemy_armor': 0, 'player_roll': 0, 'player_damage': 0}\n\n\tatype = {'attack': None}\n\tcrits = {'crit': False}\n\tplayer_turn = True\n\t\n\tif run_failed:\n\t\tplayer_turn = False\n\n\tactive = True\n\n\twhile active:\n\n\t\tbattle_header(player, monster, round_num)\n\n\t\t# player attack \n\t\tif player_turn:\n\n\t\t\tif player_attack(player, monster, fight_mods, round_num, crits, atype):\n\t\t\t\tif not crits['crit']:\n\t\t\t\t\tplayer_damage(player, monster, fight_mods, atype)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\n\t\t\tplayer_turn = False\n\n\t\t# monster attack\n\t\telse: \n\n\t\t\tif monster.hp > 0:\n\t\t\t\tif monster_attack(player, monster, round_num):\n\t\t\t\t\tmonster_damage(player, monster)\n\n\t\t\tplayer_turn = True\n\n\t\t# status check on both player and monster\n\t\tif check_battle_status(player, monster, crits):\n\t\t\tactive = False\t# player or monster is dead, so end the battle loop.\n\n\t\t# run updates if the battle is still going\n\t\tif active:\n\t\t\tpress_enter()\t\t# first of two calls to press_enter, for pause between ongoing loops\n\t\t\tturn += 1\n\t\t\tif turn % 2 == 0:\n\t\t\t\tround_num += 1\n\t\t\tcrits['crit'] = False \t# reset crit. kinda inefficient.\n\n\t\t\t# reset the fight mods and atype so each round of battle starts with empty mods.\n\t\t\tfight_mods['enemy_armor'] = 0\n\t\t\tfight_mods['player_roll'] = 0\n\t\t\tfight_mods['player_damage'] = 0\n\t\t\tatype['attack'] = None\n\n\t\telif not active:\t\t\t\t\t# shouldn't this be the same result as just 'else'? but it didn't work...\n\t\t\tprint('The battle is over!')\n\t\t\tpress_enter()\t# second of two calls to press_enter, for pause before ending battle sequence.\n\t\t\t# clear_screen()\n\ndef print_battle_commands():\n\t\"\"\"print a screen showing all possible commands in battle\"\"\"\n\tclear_screen()\n\n\tprint('***** ATTACK TYPES *****') # 31 characters used\n\tprint()\n\tprint('STANDARD (S):')\n\tprint('A normal attack. No mods to attack or damage rolls.')\n\tprint()\n\tprint('HEADSHOT (H):')\n\tprint('Aim for the head! Enemy AC gets +4 but if you hit,')\n\tprint('you deal double damage.')\n\tprint()\n\tprint('FLURRY (FLU):')\n\tprint('Run in mad and flailing! Easier to hit enemy (Roll +3),') \n\tprint('but you usually deal less damage: damage roll gets a')\n\tprint('random 0 to 3 penalty.')\n\tprint()\n\tprint('FINESSE (FIN):')\n\tprint('A deliberate attack, going for a weak point. Slightly')\n\tprint('harder to hit (Enemy AC +2) but success means +2 to ')\n\tprint('your damage roll.')\n\tprint('\\n')\n\tprint('Type the name (or shortcut) of attack to enter command.')\n\tprint()\n\tpress_enter()\n\ndef battle_header(player, monster, round_num):\n\tclear_screen()\n\tprint('ROUND: {}'.format(round_num))\n\tprint('{: <12} \\t HP: {: <3} AC: {: <3} \\t WEP: {}{}'.format(player.info['Name'].upper(), player.hp, player.armor.armor_class, player.weapon.name, player.weapon.icon))\n\tprint('{: <12} \\t HP: {: <3} AC: {: <3}'.format(monster.name.upper(), monster.hp, monster.armor_class))\n\tprint()\n\ndef check_battle_status(player, monster, crits):\n\t\"\"\"checks state of player and monster to determine if battle is over, or should continue\"\"\"\n\t\n\t#check player\n\tif player.hp <= 0:\n\t\tprint('\\nYou have been defeated by the {}!'.format(monster.name))\n\t\tplayer.dead = True\n\t\ttime.sleep(0.8)\n\t\treturn True\n\n\telif monster.hp <= 0:\n\t\tif not crits['crit']:\n\t\t\tprint('\\nYou have destroyed the {}!'.format(monster.name))\n\t\telse:\n\t\t\tprint()\t# this may not be necessary, need to playtest on critical hit success for line spacing.\n\n\t\ttime.sleep(0.8)\n\t\tgain_exp(player, monster)\n\t\ttime.sleep(0.8)\n\t\treturn True\n\t\n\telse:\n\t\t# neither player nor monster has been defeated, fight will continue.\n\t\treturn False\n\ndef player_attack(player, monster, fight_mods, round_num, crits, atype):\n\t\"\"\"runs all player attack functions and returns a bool to call in battle_main function\"\"\"\n\n\tcommand = attack_menu_input(player, monster, fight_mods, round_num)\n\n\t# if applicable, fight_mods will be updated by this call\n\tcompute_attack_mods(player, monster, fight_mods, command, atype)\n\n\t# compute_potion_mods(player)\n\n\t# here is the actual attack die roll...\n\troll = player.dice.roll(20)\n\tplayer.dice.print_roll()\n\t\n\t# check if roll is a critical hit\n\tif roll == 20:\n\t\tprint('CRITICAL HIT!')\n\t\tprint('The {} has been destroyed by your perfectly placed strike!'.format(monster.name))\n\t\tmonster.hp = 0\n\t\tcrits['crit'] = True # used as flag to skip damage roll after critical hit\n\t\treturn True\n\n\t# check if there are fight mods to Player Roll to display on screen\n\t# note: headshot doesn't appear here because it mods Enemy AC, not the player roll!\n\n\tif atype['attack'] == 'flurry' and not crits['crit']: # don't show mods on a critical hit\n\t\ttotal = roll + fight_mods['player_roll']\n\t\ttime.sleep(0.6)\n\t\tprint('+{} ({})'.format(fight_mods['player_roll'], 'flurry bonus')) \n\t\ttime.sleep(0.6)\n\t\tprint('= {}'.format(total))\n\n\telif (atype['attack'] == 'finesse' or atype['attack'] == 'standard') and not crits['crit']:\n\t\tpass # no mods to Player Roll on a standard or finesse attack.\n\n\t# check if hit was successul or not\n\tif roll + fight_mods['player_roll'] >= monster.armor_class + fight_mods['enemy_armor']:\n\t\tprint('You successfully hit the {} with your {}!'.format(monster.name, player.weapon.name))\n\t\treturn True\n\n\telse:\n\t\tprint('Your attack missed the {}, dang!'.format(monster.name))\n\t\treturn False\n\ndef attack_menu_input(player, monster, fight_mods, round_num):\n\t\"\"\"gets player input for player attack in a battle\"\"\"\n\n\tcommand = ''\t# again, just for C style initialization; not necessary\n\n\tactive = True\n\n\twhile active:\n\n\t\tbattle_header(player, monster, round_num)\t# called because menu calls will clear screen\n\n\t\tprint('Choose your attack...')\n\n\t\tcommand = get_input_valid(key='battle')\n\n\t\t# accessing menu keeps loop running; any other input exits loop and proceeds to attack\n\n\t\tif command == 'c':\n\t\t\tprint_battle_commands()\n\t\telif command == 'p':\n\t\t\tprint('This is how you will use a potion, eventually.')\n\t\t\tpress_enter()\n\t\telif command == 'i':\n\t\t\tprint('This would show player inventory.')\n\t\t\tpress_enter()\n\t\telif command == 'b':\n\t\t\tprint('And this would show player bio....')\n\t\t\tpress_enter()\n\t\telse:\n\t\t\tactive = False\t# non-menu command entered, exit loop so battle can proceed.\n\n\treturn command\n\ndef compute_attack_mods(player, monster, fight_mods, command, atype):\n\n\tattack_words = ['standard','s','attack'] # all result in standard attack\n\n\t# headshot\n\tif command.lower() == 'headshot' or command.lower() == 'h':\n\t\tatype['attack'] = 'headshot'\n\t\tfight_mods['enemy_armor'] = 4\n\t\tfight_mods['player_damage'] = 5\n\n\t\tprint('Headshot attempt!')\n\t\ttime.sleep(0.6)\n\t\tprint('The {}\\'s AC is increased to {} on this attack!'.format(monster.name, monster.armor_class + fight_mods['enemy_armor']))\n\t\ttime.sleep(0.6)\n\t\n\telif command.lower() == 'finesse' or command.lower() == 'fin':\n\t\tatype['attack'] = 'finesse'\n\t\tfight_mods['enemy_armor'] = 2\n\t\tfight_mods['player_damage'] = 2\n\n\t\tprint('Finesse attack!')\n\t\ttime.sleep(0.6)\n\t\tprint('The {}\\'s AC is increased to {} on this attack.'.format(monster.name, monster.armor_class + fight_mods['enemy_armor']))\n\t\ttime.sleep(0.6)\n\n\telif command.lower() == 'flurry' or command.lower() == 'flu':\n\t\tatype['attack'] = 'flurry'\n\t\tdamage_penalty = randint(0, 3)\n\n\t\tfight_mods['player_roll'] = 3\n\t\tfight_mods['player_damage'] = (-damage_penalty)\n\n\t\tprint('Flurry attack!')\n\t\ttime.sleep(0.6)\n\t\tprint('Attack roll will get +{} but damage will get -{}'.format(fight_mods['player_roll'], damage_penalty))\n\t\ttime.sleep(0.6)\n\n\t# normal attack; could use 'else' but I might add more possible choices later.\n\telif command.lower() in attack_words:\n\t\tatype['attack'] = 'standard'\n\t\t#print('Standard attack')\n\t\t#time.sleep(0.6)\n\ndef player_damage(player, monster, fight_mods, atype):\n\n\t# non-headshot attack damage roll\n\tif atype['attack'] != 'headshot':\n\t\tdamage = player.dice.roll(player.weapon.damage) + fight_mods['player_damage']\n\n\t\t# prevent negative damage from flurry + a low roll\n\t\tif damage <= 0:\n\t\t\tdamage = 1\n\n\t# headshot damage roll (different because it's the only one with multiplication)\n\telse:\n\t\tdamage = player.dice.roll(player.weapon.damage) * 2\n\t\n\t# print damage roll\n\tplayer.dice.print_roll()\n\n\tif atype['attack'] == 'headshot':\n\t\ttime.sleep(0.6)\n\t\tprint('x2 (headshot bonus)')\n\t\ttime.sleep(0.6)\n\t\tprint('= {}'.format(damage))\n\n\telif atype['attack'] == 'flurry' and fight_mods['player_damage'] != 0:\n\t\ttime.sleep(0.6)\n\t\tprint('{} (flurry penalty)'.format(fight_mods['player_damage']))\n\t\ttime.sleep(0.6)\n\t\tprint('= {}'.format(damage))\n\n\telif atype['attack'] == 'finesse':\n\t\ttime.sleep(0.6)\n\t\tprint('+{} (finesse bonus)'.format(fight_mods['player_damage']))\n\t\ttime.sleep(0.6)\n\t\tprint('= {}'.format(damage))\n\telse:\n\t\tpass # standard attack prints no modifiers\n\n\tprint('You dealt {} points of damage to the {}'.format(damage, monster.name.upper()))\n\n\tmonster.hp -= damage\n\n\t# this is here simply so the header doesn't show a negative number for monster hp\n\t# after monster is defeated.\n\tif monster.hp < 0:\n\t\tmonster.hp = 0\n\t\t\ndef monster_attack(player, monster, round_num):\n\n\t# put here to be consistent with player attack\n\tbattle_header(player, monster, round_num)\n\n\tprint('The {} is attacking you!'.format(monster.name))\n\n\t# time.sleep() here ?\n\n\troll = monster.dice.roll(20)\n\tmonster.dice.print_roll()\n\n\tif roll == 20:\n\t\tprint('CRITICAL HIT, OUCH!')\n\t\tprint('Automatic 5 points of damage, plus normal damage roll.')\n\t\tplayer.hp -= 5\n\t\treturn True\n\n\tif roll > player.armor.armor_class:\n\t\tprint('The {}\\'s attack hits you!'.format(monster.name))\n\t\treturn True\n\telse:\n\t\tprint('The {}\\'s attack misses you, phew!'.format(monster.name))\n\t\treturn False\n\ndef monster_damage(player, monster):\n\n\tdamage = monster.dice.roll(monster.damage_roll)\n\n\tmonster.dice.print_roll()\n\n\tprint('You take {} points of damage!'.format(damage))\n\n\tplayer.hp -= damage\n\ndef gain_exp(player, monster):\n\t\"\"\"award experience to player for beating a monster\"\"\"\n\n\texp = ((monster.difficulty * 10) + randint(0,10))\n\tplayer.exp += exp\n\n\t#any gain of exp always prints a message about the gain...might need to decouple the two.\n\tprint('You gained {} experience points.'.format(exp))\n\ttime.sleep(0.08)\n\n# instantiate game objects\n\n# how do I make these not be global variables? should I have a 'build start objects' function\n# that is called before run_game? \n\nsettings = GameSettings()\nplayer = Player(settings)\ndice = Dice()\n\n# call the main run_game function loop\nrun_game(settings, player)\n\n\n\n","sub_path":"old_files (archive)/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":45765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"551616483","text":"\"\"\"Workspace rule for downloading package dependencies.\"\"\"\n\nload(\"//:http_archive.bzl\", \"http_archive\")\n\nVERSION = \"0.27.3\"\n\nURL = \"https://exiv2.org/builds/exiv2-{version}-Source.tar.gz\"\n\nSHA256 = \"a79f5613812aa21755d578a297874fb59a85101e793edc64ec2c6bd994e3e778\"\n\ndef download_exiv2():\n http_archive(\n name = \"lib_exiv2\",\n version = VERSION,\n urls = [URL],\n sha256 = SHA256,\n strip_prefix = \"exiv2-{version}-Source\",\n )\n","sub_path":"lib/exiv2/package.bzl","file_name":"package.bzl","file_ext":"bzl","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"251599363","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter.ttk import *\nimport Crypto\nfrom Crypto.Util import Counter\nfrom Crypto import Random\nfrom Crypto.Util.number import *\nimport libnum\n\nroot = Tk()\nauth_user = [\"Ravi\", \"Bob\", \"Ram\", \"Ayush\", \"John\", \"Kelly\"]\nuwu = {\"Ravi\":390314650276167803, \"Bob\":483710515075373321, \"Ram\":860209867719162361, \"Ayush\":581633013168578947, \"John\":640621416611553599, \"Kelly\":488455929614637841}\ncandidate = [\"Bob Ross\", \"Van Gogh\"]\ncandidate_res = {\"Bob Ross\":0, \"Van Gogh\":0}\nmsg = StringVar()\nmsg2 = StringVar()\nbits = 30\n\n'''f = open(\"voterauth.txt\",\"r\")\n\nfor i in f:\n auth_user.append(i)\n\nf.close()'''\n\n# Function to generate key which will be stored in a separate txt file\ndef keygenerate():\n p = Crypto.Util.number.getPrime(bits,randfunc = Crypto.Random.get_random_bytes)\n q = Crypto.Util.number.getPrime(bits,randfunc= Crypto.Random.get_random_bytes)\n\n phi = (p-1)*(q-1)\n n = p*q\n\n e = 65537\n d = (libnum.invmod(e,phi))\n return ((e,n),(d,n))\n\ndef encrypt(privkkey,plaintext):\n key,n = privkkey\n cipher = [pow(ord(char),key,n) for char in plaintext]\n return cipher\n\ndef decrypt(pubkkey,ciphertext):\n key,n = pubkkey\n plain = [chr((char ** key) % n) for char in ciphertext]\n return ''.join(plain)\n\ndef public_enc(privkkey,data):\n key,n = privkkey\n S = [pow(i,key,n) for i in data]\n return S\n\ndef public_dec(pubkkey,data):\n key,n = pubkkey\n D = [pow(i,key,n) for i in data]\n return D\n\nCTFpub,CTFpriv = keygenerate()\nuser_priv = (0,0)\nuser_pub = (0,0)\n\ndef check(oof,name):\n for i in oof:\n if i == name:\n return True\n return False\n\ndef getkey():\n msg2 = ip1.get(\"1.0\",'end-1c')\n msg = ip3.get(\"1.0\",'end-1c')\n msg = int(msg)\n pub = (65537,uwu[msg2])\n priv = (msg,uwu[msg2])\n return (pub,priv)\n\n\ndef BR():\n global user_priv\n global user_pub\n msg = ip1.get(\"1.0\",'end-1c')\n if check(auth_user,msg):\n if check(existing_user,msg) == False:\n user_pub,user_priv = getkey()\n pt = \"Bob Ross\"\n user_sign = encrypt(user_priv,pt)\n ct_enc = public_enc(CTFpub,user_sign)\n ct_dec = public_dec(CTFpriv,ct_enc)\n user_dec = decrypt(user_pub,ct_dec)\n if user_dec == pt:\n candidate_res[\"Bob Ross\"]+=1\n existing_user.append(msg)\n\ndef VG():\n global user_priv\n global user_pub\n msg = ip1.get(\"1.0\",'end-1c')\n if check(auth_user,msg):\n if check(existing_user,msg) == False:\n user_pub, user_priv = getkey()\n pt = \"Van Gogh\"\n user_sign = encrypt(user_priv,pt)\n ct_enc = public_enc(CTFpub,user_sign)\n ct_dec = public_dec(CTFpriv,ct_enc)\n user_dec = decrypt(user_pub,ct_dec)\n if user_dec == pt:\n candidate_res[\"Van Gogh\"]+=1\n existing_user.append(msg)\n\n\n\ndef get_result():\n ip2.delete(\"1.0\",'end-1c')\n for i in candidate:\n upd = i + \" \" + str(candidate_res[i])\n ip2.insert(END,upd + '\\n')\n\n\nroot.geometry(\"1000x600\")\nroot.title('Vote')\n\nframe1 = Frame(root)\nframe2 = Frame(root)\n\nframe1.grid(row=0,column=0,sticky=W)\nframe2.grid(row=0,column=1,sticky=E)\n\nroot.rowconfigure(0, weight=1)\nroot.columnconfigure(0, weight=1)\nroot.columnconfigure(1, weight=1)\n\nip1 = Text(frame1,height=5,width=60,wrap=WORD)\nip1.grid(sticky=N)\n\nip3 = Text(frame1, height = 5, width=60, wrap = WORD)\nip3.grid(sticky=N)\n\nbr = tk.Button(frame1, text = \"Bob Ross\",bg=\"purple\",fg=\"white\", command = BR)\nbr.grid(sticky = S)\nvg = tk.Button(frame1,text = \"Van Gogh\",bg=\"green\",fg=\"white\",command = VG)\nvg.grid(sticky = S)\n\nip2 = Text(frame2, height = 4, width = 60, wrap = WORD)\nip2.grid(sticky=N)\nresult = tk.Button(frame2, text = \"RANKING\",bg=\"orange\",fg=\"white\",command = get_result)\nresult.grid(sticky = S)\nroot.mainloop()\n","sub_path":"vote.py","file_name":"vote.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299947895","text":"import re\n\ndef main():\n # read sophias result\n\n with open(\"sophia.txt\", \"r\") as f:\n res_in_lines = f.read().splitlines()\n\n current_1 = None\n current_2 = None\n current_3 = None\n res_lines = []\n\n for line in res_in_lines:\n line = line.strip()\n\n if \"summa\" in line.lower():\n pass\n elif \"=\" in line:\n current_3 = line.split(\"=\")[0].strip()\n x = float(line.split(\"=\")[1].replace(\"+\", \"\").replace(\" \", \"\").replace(\",\", \".\").replace(\"−\", \"-\"))\n res_lines.append([current_1, current_2, current_3, x])\n elif re.match(\"\\w+\\d+\", line):\n current_2 = line\n elif line:\n current_1 = line\n else:\n pass\n\n # read budget\n\n with open(\"budget.csv\", \"r\") as f:\n budget_in_lines = f.read().splitlines()\n\n current_1 = None\n current_2 = None\n current_3 = None\n budget_lines = []\n\n for line in budget_in_lines:\n line = line.strip()\n\n if not line:\n continue\n\n a, b = line.split(\",\")\n\n if not a:\n continue\n\n if \"summa\" in a.lower():\n continue\n\n if \"mål\" in a.lower():\n continue\n\n if not b:\n if re.match(\"\\w+\\d+\", a):\n current_2 = a\n else:\n current_1 = a\n else:\n current_3 = a\n x = float(b)\n budget_lines.append([current_1, current_2, current_3, x])\n\n # generate report lines\n\n report_lines = []\n\n check = False\n\n for budget_line, res_line in zip(budget_lines, res_lines):\n if budget_line[:2] != res_line[:2]:\n print(\"mismatch error\")\n print(budget_line)\n print(res_line)\n exit()\n\n if check:\n a = budget_line[2]\n b = res_line[2]\n if a != b:\n print(\"{:>30} {:>30}\".format(a, b))\n\n report_lines.append(budget_line + [res_line[3]])\n\n if len(budget_lines) != len(res_lines):\n print(\"len mismatch error\")\n exit()\n\n # generate report\n\n doc = []\n doc += pre\n\n tcum_b = tcum_r = tcum_d = 0.0\n\n cum_b = cum_r = cum_d = 0.0\n last_c1 = last_c2 = None\n\n for i, line in enumerate(report_lines):\n c1, c2, c3, b, r = line\n d = r - b\n\n if not last_c1 or c1 != last_c1:\n if last_c1:\n doc += sumlines(cum_b, cum_r, cum_d)\n doc += endtab\n\n doc += begintab\n doc += newc1(c1)\n cum_b = 0\n cum_r = 0\n cum_d = 0\n\n if not last_c2 or c2 != last_c2:\n doc += [\" \\\\textbf{%s} \\\\\\\\\"%c2]\n\n doc += [\" %s & %s & %s & %s \\\\\\\\\"%(c3, mfmt(b), mfmt(r), mfmt(d))]\n\n cum_b += b\n cum_r += r\n cum_d += d\n\n tcum_b += b\n tcum_r += r\n tcum_d += d\n\n last_c1 = c1\n last_c2 = c2\n\n doc += sumlines(cum_b, cum_r, cum_d)\n doc += endtab\n\n doc += begintab\n doc += newc1(\"Total summa\")\n doc += sumline(tcum_b, tcum_r, tcum_d)\n doc += endtab\n\n doc += post\n\n with open(\"out.tex\", \"w\") as f:\n f.write(\"\\n\".join(doc))\n\n print(\"done\")\n\npre = [\n \"\\\\documentclass[../_main/handlingar.tex]{subfiles}\",\n \"\",\n \"\\\\begin{document}\",\n \"\",\n \"\\\\subsection{Budgetuppföljning för 2017}\",\n]\n\npost = [\n \"\",\n \"\\\\newpage\",\n \"\",\n \"\\end{document}\",\n \"\"\n]\n\nbegintab = [\"\", \"\\\\begin{tabularx}{12cm}{X r r r}\"]\nendtab = [\"\\\\end{tabularx}\"]\n\ndef mfmt(x):\n return \"\\\\SI{%.0f}{kr}\"%x\n\ndef newc1(s):\n return [\n \" \\\\textbf{\\\\large %s} & \\\\textbf{Budget} & \\\\textbf{Resultat} & \\\\textbf{Differans} \\\\\\\\\"%s,\n \" \\\\hline\"\n ]\n\ndef sumlines(b, r, d):\n return [\" \\\\hline\"] + sumline(b, r, d)\n\ndef sumline(b, r, d):\n return [\" \\\\textbf{Summa} & \\\\textbf{%s} & \\\\textbf{%s} & \\\\textbf{%s} \\\\\\\\\"%(mfmt(b), mfmt(r), mfmt(d))]\n\nmain()\n","sub_path":"scripts/budgetuppf-2017/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107483200","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/spm1d/rft1d/examples/val_max_7_cca_0d.py\n# Compiled at: 2019-08-22 04:37:04\n# Size of source mod 2**32: 1937 bytes\nfrom math import sqrt, log\nimport numpy as np\nfrom scipy import stats\nfrom matplotlib import pyplot\n\ndef here_cca(y, x):\n N = y.shape[0]\n X, Y = np.matrix(x.T).T, np.matrix(y)\n Z = np.matrix(np.ones(N)).T\n Rz = np.eye(N) - Z * np.linalg.inv(Z.T * Z) * Z.T\n XStar = Rz * X\n YStar = Rz * Y\n p, r = (1.0, 1.0)\n m = N - p - r\n H = YStar.T * XStar * np.linalg.inv(XStar.T * XStar) * XStar.T * YStar / p\n W = YStar.T * (np.eye(nResponses) - XStar * np.linalg.inv(XStar.T * XStar) * XStar.T) * YStar / m\n F = np.linalg.inv(W) * H\n ff = np.linalg.eigvals(F)\n fmax = float(np.real(ff.max()))\n r2max = fmax * p / (m + fmax * p)\n rmax = sqrt(r2max)\n p, m = float(N), float(y.shape[1])\n x2 = -(p - 1 - 0.5 * (m + 2)) * log(1 - rmax ** 2)\n return x2\n\n\nnp.random.seed(0)\nnResponses = 20\nnComponents = 3\nnIterations = 1000\nW0 = np.eye(nComponents)\ndf = nComponents\nx = np.linspace(0, 1, nResponses)\nX2 = []\nfor i in range(nIterations):\n y = np.random.multivariate_normal(np.zeros(nComponents), W0, nResponses)\n chi2 = here_cca(y, x)\n X2.append(chi2)\n\nX2 = np.asarray(X2)\nheights = np.linspace(3, 12, 21)\nsf = np.array([(X2 > h).mean() for h in heights])\nsfE = stats.chi2.sf(heights, df)\npyplot.close('all')\nax = pyplot.axes()\nax.plot(heights, sf, 'o', label='Simulated')\nax.plot(heights, sfE, '-', label='Theoretical')\nax.set_xlabel('$u$', size=20)\nax.set_ylabel('$P (\\\\chi^2 > u)$', size=20)\nax.legend()\nax.set_title('CCA validation (0D)', size=20)\npyplot.show()","sub_path":"pycfiles/spm1d-0.4.2-py3.6/val_max_7_cca_0d.cpython-36.py","file_name":"val_max_7_cca_0d.cpython-36.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36373185","text":"import numpy as np\nimport scipy.sparse as sp\nimport scipy.linalg as la\n\n# Plotting imports:\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as mtri\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Our code:\nfrom .fem_2d_solver import Poisson2DSolver \nfrom ..tools import quadrature1D, quadrature2D, \\\n BCtype, matprint\nfrom .tasks import display_analytical_solution\n\n\ndef basic_tests():\n # Filler arguments:\n a = Poisson2DSolver(200, 0.0, 0.0, 0.0, 0.0)\n\n # Test transforms:\n element_i = 12\n eta_test = [0.62, 0.135]\n test_xy = a.reference_to_global_transformation(eta=eta_test, element=element_i)\n eta_result = a.global_to_reference_transformation(p=test_xy, element=element_i)\n # After applying the transform and its inverse for the same element, \n # \"eta_test\" should be the same as \"eta_result\"\n assert(np.allclose(eta_test, eta_result))\n\n # node_to_hit = a.nodes[a.triang[element_i][1]]\n # a.display_mesh(nodes=4)\n # a.display_mesh()\n\n # Test surface plot:\n # u_h = np.zeros(a.num_nodes)\n # u_h[10] = 1.0\n # u_h[11] = -1.0\n u_h = np.arange(a.num_nodes)/(a.num_nodes)\n a.display_solution(u_h)\n\n\ndef test_A_i_j():\n num_nodes = 10\n a = Poisson2DSolver(num_nodes, 0.0, 0.0, 0.0, 0.0)\n print(\"nodes:\\n\", a.nodes)\n # a.display_mesh(nodes=len(a.nodes)-1)\n \n # test_elem = 0\n # J = a.generate_jacobian(test_elem)\n # J_inv = np.linalg.inv(J)\n # elem_area = np.linalg.det(J)*0.5\n \n # i, j = 1, 2\n # A_i_j = a.A_i_j(i, j, J_inv, elem_area)\n # print(f\"A_{i}_{j} = {A_i_j:.6f}\")\n\n a.generate_A_h()\n print(\"\\nA_h:\")\n A_h = a.A_h.toarray()\n matprint(A_h)\n col_sums = np.sum(A_h, axis=-1)\n print(\"col_sums:\\n\", col_sums)\n # x_test = np.linalg.solve(A_h, np.random.randn(num_nodes))\n # A_h_eigvals = la.eigvals(A_h) # One zero-eigenvalue. Singular.\n a.display_mesh()\n\n\ndef test_F_h():\n\n def f(p):\n \"\"\"\n Source function f(r, theta) = −8π*cos(2πr²)+ 16π²r²sin(2πr²)\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n term_1 = -8.0*np.pi*np.cos(2*np.pi*r_squared)\n term_2 = 16*np.pi**2*r_squared*np.sin(2*np.pi*r_squared)\n return term_1 + term_2\n\n def u(p):\n \"\"\"\n Analytical solution to the Poisson-problem, with homogeneous dirichlet BCs\n and the source term f(p).\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n return np.sin(2*np.pi*r_squared)\n\n N = 2000\n solver = Poisson2DSolver(N, f, 0.0, 0.0, 0.0)\n solver.generate_F_h()\n print(solver.F_h)\n solver.display_mesh()\n\n\ndef integrate_source_func_over_triangle(f, k, i_loc, FEM_solver):\n # Testing integration of the source function over a triangle. \n # In the Global Coordinates.\n glob_loc_coord = FEM_solver.global_to_reference_transformation\n\n def integrand(p):\n return f(p)*FEM_solver.basis_functions[i_loc](glob_loc_coord(p, k))\n\n p1, p2, p3 = FEM_solver.nodes[FEM_solver.triang[k]]\n\n I = quadrature2D(integrand, p1, p2, p3)\n return I\n\n\ndef big_polynomial_solution(N=1000):\n\n def f(p):\n return 4.0\n \n def u(p):\n return 1.0 - (p[0]**2 + p[1]**2)\n\n def class_BC(p):\n \"\"\"\n Classify all edge nodes as Dirichlet\n \"\"\"\n return 1\n \n # Jukser, setter presise Dirichlet-betingelser i hver kant-node:\n FEM_poly = Poisson2DSolver(N=N, f=f, g_D=u, g_N=None, class_BC=class_BC)\n\n FEM_poly.solve_direct_dirichlet()\n\n display_analytical_solution(N=N, u=u)\n\n FEM_poly.display_solution()\n\n\ndef small_polynomial_solution(N=4):\n print(\"\\nTESTING POLYNOMIAL EASY SOLUTION, N=4 nodes!\")\n # N = 4\n \n def f(p):\n return 4.0\n \n def u(p):\n return 1.0 - (p[0]**2 + p[1]**2)\n\n def class_BC(p):\n \"\"\"\n Classify all edge nodes as Dirichlet\n \"\"\"\n return 1\n \n FEM_poly = Poisson2DSolver(N=N, f=f, g_D=u, g_N=None, class_BC=class_BC)\n FEM_poly.display_mesh(nodes=None, elements=FEM_poly.edge_triangle_indexes)\n\n # Løser verdien i ett punkt:\n FEM_poly.solve_direct_dirichlet()\n FEM_poly.display_solution()\n\n # Prøvde å endre lokal-indekseringen av noder i et element:\n # FEM_poly.triang[1] = np.array([0, 3, 2], dtype='int32')\n # Gav rare utslag, som at A[2, 2] = 9.99e-16\n \n FEM_poly.generate_A_h()\n print(\"A_h:\")\n matprint(FEM_poly.A_h.toarray())\n\n # Insert very specific source vec:\n # FEM_poly.F_h = np.array([FEM_poly.A_h[0, 0], 0.0, 0.0, 0.0]).reshape(4, 1)\n # FEM_poly.apply_direct_dirichlet()\n # FEM_poly.u_h = np.array([u(p) for p in FEM_poly.nodes])\n # FEM_poly.u_h[0] = sp.linalg.spsolve(FEM_poly.A_h, FEM_poly.F_h)\n # FEM_poly.display_solution()\n\n FEM_poly.generate_F_h()\n print(f\"\\nF_h:\")\n print(FEM_poly.F_h)\n\n def F_1():\n \"\"\"\n Find the second element of the source vector in the 4-node \n super simple case.\n \"\"\"\n print(\"Finding the second element of the source vector, F_h[1]:\")\n I_0_2 = integrate_source_func_over_triangle(f=f, k=0, i_loc=1, FEM_solver=FEM_poly)\n I_2_3 = integrate_source_func_over_triangle(f=f, k=2, i_loc=2, FEM_solver=FEM_poly)\n F_h_1 = I_0_2 + I_2_3\n \n print(f\"F_h[1] integrated in global coordinates: {F_h_1:.6e}\")\n return F_h_1\n \n def F_0():\n \"\"\"\n Find the first element of the source vector in the 4-node \n super simple case.\n \"\"\"\n print(\"Find the first element of the source vector, F_h[0]:\")\n I_0_0 = integrate_source_func_over_triangle(f=f, k=0, i_loc=0, FEM_solver=FEM_poly)\n I_1_1 = integrate_source_func_over_triangle(f=f, k=1, i_loc=1, FEM_solver=FEM_poly)\n I_2_0 = integrate_source_func_over_triangle(f=f, k=2, i_loc=0, FEM_solver=FEM_poly)\n F_h_0 = I_0_0 + I_1_1 + I_2_0\n\n print(f\"F_h[0] integrated in global coordinates: {F_h_0:.6e}\")\n return F_h_0\n\n F_1()\n F_0()\n\n def A_1_1():\n print(\"\\nFind A_1_1 by 'hand'.\")\n\n J_0 = FEM_poly.generate_jacobian(element=0)\n J_0_inv = la.inv(J_0)\n I_0 = 0.5*la.det(J_0)*la.norm(J_0_inv[:, 0])**2\n\n J_2 = FEM_poly.generate_jacobian(element=2)\n J_2_inv = la.inv(J_2)\n I_2 = 0.5*la.det(J_2)*la.norm(J_2_inv[:, 1])**2\n\n print(f\"A_1_1: {(I_0 + I_2):.6e}\")\n return I_0 + I_2\n\n def A_3_3():\n print(\"\\nFind A_3_3 by 'hand'.\")\n\n J_1 = FEM_poly.generate_jacobian(element=1)\n J_1_inv = la.inv(J_1)\n inv_col_sum = J_1_inv[:, 0] + J_1_inv[:, 1]\n I_1 = 0.5*la.det(J_1)*la.norm(inv_col_sum)**2\n\n J_2 = FEM_poly.generate_jacobian(element=2)\n J_2_inv = la.inv(J_2)\n I_2 = 0.5*la.det(J_2)*la.norm(J_2_inv[:, 0])**2\n\n print(f\"A_3_3: {(I_1 + I_2):.6e}\")\n return I_1 + I_2\n\n A_1_1()\n A_3_3()\n\n print(\"\\nFull matrix A_h:\")\n matprint(FEM_poly.A_h.toarray())\n\n\ndef test_CG_FEM_solution(N=1000, TOL=1e-5):\n\n def f(p):\n \"\"\"\n Source function f(r, theta) = −8π*cos(2πr²)+ 16π²r²sin(2πr²)\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n term_1 = -8.0*np.pi*np.cos(2*np.pi*r_squared)\n term_2 = 16*np.pi**2*r_squared*np.sin(2*np.pi*r_squared)\n return term_1 + term_2\n \n def g_D(p):\n return 0.0\n \n def class_BC(p):\n \"\"\"\n Classify all edge nodes as Dirichlet\n \"\"\"\n return BCtype.Dir\n\n FEM_solver = Poisson2DSolver(N=N, f=f, g_D=g_D, g_N=None, class_BC=class_BC, eps=1.0e-14)\n from time import time\n start = time()\n FEM_solver.solve_direct_dirichlet_CG(TOL=TOL) # Might expand 'solve()' method to perform the above function calls.\n end = time()\n min_uh = min(FEM_solver.u_h)\n max_uh = max(FEM_solver.u_h)\n\n print(\"Showing Direct Dirichlet CG solution:\")\n\n print(f\"Minimum value: {min_uh:.5e}\\nMax value: {max_uh:.5e}\")\n\n print(f\"CG solver: {(end-start):.2f} s\")\n\n # FEM_solver.display_mesh()\n FEM_solver.display_solution()\n\n\ndef test_simpler_solution(N=1000):\n\n def u_simple(p):\n \"\"\"\n Analytical solution to the Poisson-problem, with homogeneous dirichlet BCs\n and the source term f(p).\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n return np.sin(np.pi*r_squared)\n\n def f_simple(p):\n \"\"\"\n Source function f(r, theta) = −8π*cos(2πr²)+ 16π²r²sin(2πr²)\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n term_1 = -4.0*np.pi*np.cos(np.pi*r_squared)\n term_2 = 4*np.pi**2*r_squared*np.sin(np.pi*r_squared)\n return term_1 + term_2\n \n def g_D(p):\n return 0.0\n \n def class_BC(p):\n \"\"\"\n Classify all edge nodes as Dirichlet\n \"\"\"\n return 1\n \n FEM_solver = Poisson2DSolver(N=N, f=f_simple, g_D=g_D, g_N=None, class_BC=class_BC)\n FEM_solver.solve_direct_dirichlet() # Might expand 'solve()' method to perform the above function calls.\n min_uh = min(FEM_solver.u_h)\n max_uh = max(FEM_solver.u_h)\n\n print(\"Showing Simple Direct Dirichlet solution:\")\n\n print(f\"Minimum value: {min_uh:.5e}\\nMax value: {max_uh:.5e}\")\n\n # FEM_solver.display_mesh()\n FEM_solver.display_solution()\n\n print(\"Showing analytical solution:\")\n display_analytical_solution(N=N, u=u_simple)\n\n\ndef test_error():\n\n def u_ex(p):\n return np.sin(2*np.pi * (p[0]**2 + p[1]**2))\n\n def f(p):\n \"\"\"\n Source function f(r, theta) = −8π*cos(2πr²)+ 16π²r²sin(2πr²)\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n term_1 = -8.0*np.pi*np.cos(2*np.pi*r_squared)\n term_2 = 16*np.pi**2*r_squared*np.sin(2*np.pi*r_squared)\n return term_1 + term_2\n \n def g_D(p):\n return 0.0\n \n def class_BC(p):\n \"\"\"\n Classify all edge nodes as Dirichlet\n \"\"\"\n return BCtype.Dir\n\n Es = []\n Ns = [20, 40, 80, 160, 320, 640, 1280]\n for N in Ns:\n\n FEM_solver = Poisson2DSolver(N=N, f=f, g_D=g_D, g_N=None, class_BC=class_BC, eps=1.0e-14)\n FEM_solver.solve_direct_dirichlet()\n\n e = FEM_solver.error_est(u_ex)\n\n Es.append(e)\n\n Es = np.array(Es, dtype=float)\n Ns = np.array(Ns, dtype=float)\n plt.loglog(Ns, Es, 'k-', label=r\"$||u - u_h||_{L_2(\\Omega)}$\")\n plt.xlabel(\"Degrees of freedom\")\n #plt.ylabel(r\"$||u - u_h||_{L_2(\\Omega)}$\")\n plt.legend()\n\n def beta(x, y):\n '''\n Estimator for the coefficient of beta in linear regression model\n y = alpha + beta * x\n '''\n beta = np.sum( (x - np.mean(x)) * (y - np.mean(y))) / np.sum( (x - np.mean(x))**2 )\n return beta\n\n beta = beta(np.log(Ns), np.log(Es))\n print(f'beta = {beta}')\n\n plt.show()\n\n\ndef test_error_neumann():\n\n def u_ex(p):\n return np.sin(2*np.pi * (p[0]**2 + p[1]**2))\n\n def f(p):\n \"\"\"\n Source function f(r, theta) = −8π*cos(2πr²)+ 16π²r²sin(2πr²)\n p: np.array([x, y])\n \"\"\"\n r_squared = p[0]**2 + p[1]**2\n term_1 = -8.0*np.pi*np.cos(2*np.pi*r_squared)\n term_2 = 16*np.pi**2*r_squared*np.sin(2*np.pi*r_squared)\n return term_1 + term_2\n \n def g_D(p):\n return 0.0\n\n def g_N(p):\n r = np.sqrt(p[0]**2 + p[1]**2)\n return 4*np.pi*r*np.cos(2*np.pi*r**2)\n \n def class_BC(p):\n if p[1] <= 0.0:\n return BCtype.Dir\n else:\n return BCtype.Neu\n\n Es = []\n Ns = [20, 40, 80, 160, 320, 640, 1280]\n for N in Ns:\n\n FEM_solver = Poisson2DSolver(N=N, f=f, g_D=g_D, g_N=g_N, class_BC=class_BC, eps=1.0e-14)\n FEM_solver.solve()\n\n e = FEM_solver.error_est(u_ex)\n\n Es.append(e)\n\n norm_u = np.pi / 2\n\n Es = np.array(Es, dtype=float)\n Es_rel = Es / norm_u\n Ns = np.array(Ns, dtype=float)\n plt.loglog(Ns, Es_rel, 'k-', label=r\"$||u - u_h||_{L_2(\\Omega)}$\")\n plt.xlabel(\"Degrees of freedom\")\n plt.title(\"Relative error, Neumann\")\n plt.legend()\n\n def beta(x, y):\n '''\n Estimator for the coefficient of beta in linear regression model\n y = alpha + beta * x\n '''\n n = x.shape[0]\n beta = np.sum( (x - np.mean(x)) * (y - np.mean(y))) / np.sum( (x - np.mean(x))**2 )\n return beta\n\n beta = beta(np.log(Ns), np.log(Es_rel))\n print(f'beta = {beta}')\n\n plt.show()\n\n\ndef test_main():\n basic_tests()\n test_A_i_j()\n test_F_h()\n test_error()\n test_error_neumann()\n return\n\nif __name__ == \"__main__\":\n test_main()","sub_path":"root/project_1/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":12690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"32254372","text":"#!/usr/bin/python3\nfrom torrent_downloader import torrent_downloader\nfrom pprint import pprint\nfrom Query import Query\nimport downloader_settings\nimport os\nimport sys\nimport inspect\nimport signal\nimport util_functions\nimport torrent\nimport re\n\n\nproviders_file = 'providers.txt'\nsearching_for_file = 'searching_for.txt'\nsettings_file = 'settings.yaml'\npath=''\nurl = 'http://www.nyaa.se/?page=rss'\nurl2 = 'http://www.nyaa.se/?page=rss&cats=1_11'\nproviders = set()\nsearching_for = set()\n\ndef assign_settings(properties):\n\tproperties = properties['properties']\n\tglobal path \n\tpath = properties['filepath']\n\ttorrent.min_seeders = int(properties['seeders'])\n\ttorrent.min_leechers = int(properties['leechers'])\n\ttorrent.max_size = int(properties['maxFileSizeMB'])\ndef number_of_arguements(function):\n\tnum_args = len(inspect.getargspec(function).args)\n\treturn num_args\n\n#Get a list of providers and torrent titles from text files\ndef get_info():\n\tproviders = downloader_settings.read_list(providers_file)\n\tsearching_for = downloader_settings.read_list(searching_for_file)\n\tproperties = downloader_settings.read_yaml(settings_file)\n\tpprint (properties)\n\treturn providers, searching_for,properties\ndef write_info():\n\tdownloader_settings.write_list(providers_file,torrent_providers) \n\tdownloader_settings.write_list(searching_for_file,searching_for)\n\n#Write providers and titles to text files\ndef write_info():\n\tdownloader_settings.write_list(providers_file,torrent_providers)\n\tdownloader_settings.write_list(searching_for_file,searching_for)\n#Following functions are called upon console command\ndef display_titles():\n\tprint(sorted(searching_for))\ndef display_providers():\n\tprint(sorted(torrent_providers))\ndef add_titles(titles):\n\tfor title in titles:\n\t\t\tsearching_for.add(title)\ndef add_providers(providers):\n\tfor provider in providers:\n\t\t\ttorrent_providers.add(provider)\ndef del_titles(titles):\n\tfor title in titles:\n\t\tsearching_for.remove(title)\ndef del_providers(providers):\n\tfor provider in providers:\n\t\ttorrent_providers.remove(provider)\ndef clear_all():\n\ttorrent_providers.clear()\n\tsearching_for.clear()\ndef clear_titles():\n\tsearching_for.clear()\ndef clear_providers():\n\ttorrent_providers.clear()\ndef cleanup_folder():\n\tutil_functions.remove_files(extension='.mp4')\n\tutil_functions.remove_files(extension=\".torrent\")\ndef copy_to_media():\n\tutil_functions.move_files(path)\ndef set_path(p):\n\tpath = p[0]\n\tdownloader_settings.write_yaml(settings_file,p)\ndef print_path():\n\tif not path:\n\t\tprint(\"No path has been specified\")\n\telse:\n\t\tprint(path)\ndef save():\n\twrite_info()\ndef exit_program():\n\tsys.exit()\ndef run_once():\n\tt=torrent_downloader(url,searching_for,torrent_providers)\n\twrite_info()\n\tt.run(run_once=True)\ndef get(args):\n\tt=torrent_downloader(url2,args,torrent_providers)\n\tt.run(run_once=True)\ndef run_downloader():\n\tt = torrent_downloader(url,searching_for,torrent_providers)\n\twrite_info()\n\tt.run(run_once=False)\ndef search(args):\n\tt = torrent_downloader(url, args, torrent_providers, query_type = Query.SPECIFIC)\n\tt.run(run_once=True)\ndef print_commands():\n\tutil_functions.help();\n\n\n#Dictionary implemented switch statement\t\ndef switch(command,args):\n\targs[:]=[arg.strip() for arg in args]\n\tswitch_statement = {\n\n\t'search':search,\n\t'get':get,\n\t'fetch':get,\n\t'run once':run_once,\n\t'run':run_downloader,\n\t'add title':add_titles,\n\t'remove title':del_titles,\n\t'add provider':add_providers,\n\t'remove provider':del_providers,\n\t'clear all':clear_all,\n\t'clear providers':clear_providers,\n\t'clear titles':clear_titles,\n\t'cleanup':cleanup_folder,\n\t'copy':copy_to_media,\n\t'cp':copy_to_media,\n\t'path':print_path,\n\t'set path':set_path,\n\t'print path':print_path,\n\t'providers':display_providers,\n\t'provs':display_providers,\n\t'titles':display_titles,\n\t'shows':display_titles,\n\t'help':print_commands,\n\t'man':print_commands,\n\t'manual':print_commands,\n\t'commands':print_commands,\n\t'comm':print_commands,\n\t'save':save,\n\t'exit':exit_program,\n\t'quit':exit_program\n\t}\n\tif command in switch_statement.keys():\n\t\tnumber_args = number_of_arguements(switch_statement[command])\n\t\tif number_args ==0:\n\t\t\treturn switch_statement[command]()\n\t\telse:\n\t\t\treturn switch_statement[command](args)\n\telse:\n\t\tprint(\"Command not recognized\")\n\n\n#Main part of program\ntorrent_providers, searching_for,properties = get_info()\nassign_settings(properties)\nif not path:\n\tprint(\"path not yet specified\")\nmain_command = ''\n\n#main loop\nwhile main_command!='run':\n\tuser_string = input(\">>> \")\n\targuements = re.split(',|-',user_string)\n\tmain_command = arguements[0]\n\tdel arguements[0]\n\tswitch(main_command,arguements)\nrun_downloader()\n","sub_path":"torr.py","file_name":"torr.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624188768","text":"import cv2\nimport numpy as np\nimport glob\nfrom sklearn import svm\nfrom sklearn.externals import joblib\nimport itertools\nimport imutils\nfrom imutils.object_detection import non_max_suppression\nimport os\n\nhog = cv2.HOGDescriptor('/home/alireza/Documents/cv-lab14/hog.xml')\ntrain_data = []\ntrain_labels = []\nX = []\n\n# reading positive samples\nfnamesPos = glob.glob('/home/alireza/Documents/cv-lab14/pos/*.png')\n\nfor fname in fnamesPos:\n I1 = cv2.imread(fname)\n I1 = I1[3:-3, 3:-3, :]\n feature = hog.compute(I1)\n train_data.append(feature)\n train_labels.append(1)\n\n# reading negative samples\nfnamesNeg = glob.glob('/home/alireza/Documents/cv-lab14/neg/*.png')\n\nfor fname in fnamesNeg:\n I1 = cv2.imread(fname)\n # creating some random negative samples from images which don't contain any pedestrians.\n samples1 = np.random.randint(0, I1.shape[1] - 64, 10)\n samples2 = np.random.randint(0, I1.shape[0] - 128, 10)\n samples = zip(samples1, samples2)\n for sample in samples:\n I2 = I1[sample[1]:sample[1] + 128, sample[0]:sample[0] + 64, :]\n feature = hog.compute(I2)\n train_data.append(feature)\n train_labels.append(0)\n\nX = np.asarray(train_data, dtype=np.float64)\nX = np.reshape(X, (X.shape[0], X.shape[1]))\ntrain_labels = np.asarray(train_labels)\n\n# training the SVM classifier\nfile_name = 'saved_svm.sav'\n\nclassifier = svm.SVC(kernel='poly', C=1.7, tol=1e-6, coef0=1.5, gamma='auto', max_iter=-1)\n\n# if not os.path.isfile(file_name):\n# print('training the SVM')\n# classifier.fit(X, train_labels)\n# joblib.dump(classifier, file_name)\n# else:\n# classifier = joblib.load(file_name)\n# print('saved classifier loaded')\n\nos.path.isfile( file_name )\nprint( 'training the SVM' )\nclassifier.fit( X, train_labels )\njoblib.dump( classifier, file_name )\n# else:\n# classifier = joblib.load( file_name )\n# print( 'saved classifier loaded' )\n\n# putting the final support vector params in correct order for feeding to our HoGDescriptor\nsupportVectors = []\nsupportVectors.append(np.dot(classifier.dual_coef_, classifier.support_vectors_)[0])\nsupportVectors.append([classifier.intercept_])\nsupportVectors = list(itertools.chain(*supportVectors))\nhog.setSVMDetector(np.array(supportVectors, dtype=np.float64))\n\n# testing\nscale = 1.05#1.05\npadding = (6,6)#(4, 4)\nwinStride = (4,4)#(8, 8)\n\nfnamesTest = glob.glob('/home/alireza/Documents/cv-lab14/Test/*.png')\nfor fname in fnamesTest:\n I = cv2.imread(fname)\n I = imutils.resize(I, width=min(400, I.shape[1]))\n (rects, weights) = hog.detectMultiScale(I, winStride=winStride, padding=padding, scale=scale,\n useMeanshiftGrouping=True)\n rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])\n rects = non_max_suppression(rects, probs=None, overlapThresh=0.6)\n for (xA, yA, xB, yB) in rects:\n cv2.rectangle(I, (xA, yA), (xB, yB), (0, 255, 0), 2)\n cv2.imshow(\"detected pedestrians\", I)\n cv2.waitKey(0)\n","sub_path":"Computer vision course-ws/cv-lab14-ws/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"507369022","text":"# -*- coding:utf-8 -*-\nimport time\nfrom threading import Thread\nfrom control.check_watcher import CheckWatcher\nfrom control.email_watcher import EmailWatcher\nfrom control.fetch_watcher import FetchWatcher\nfrom control.ip_watcher import IPWatcher\nfrom control.task_watcher.compute import TaskCompute\nfrom control.task_watcher.loader_queue import TaskQueueLoader\nfrom control.task_watcher.watcher import TaskWatcher\nfrom utils.config import get_config_value\n\n\nclass Watcher(Thread):\n interval = get_config_value('control', 'interval', 'int') or 1\n\n def __init__(self):\n Thread.__init__(self, name='watcher-thread')\n self.daemon = True\n self.fetch_watcher = FetchWatcher()\n self.ip_watcher = IPWatcher()\n self.task_watcher = TaskWatcher()\n self.loader_queue = TaskQueueLoader()\n self.check_watcher = CheckWatcher()\n self.email_watcher = EmailWatcher()\n self.compute = TaskCompute()\n\n def run(self):\n while True:\n try:\n time.sleep(self.interval)\n self.fetch_watcher.run()\n self.loader_queue.run()\n self.task_watcher.run()\n self.ip_watcher.run()\n self.compute.control()\n self.check_watcher.run()\n self.email_watcher.run()\n except Exception as e:\n raise e\n","sub_path":"control/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"488519098","text":"\"\"\"\n @author : Rajeshkumar Reddy \n\n REST API endpoint to invoke the actual shell library\n\"\"\"\nimport socket\nimport json\n\nfrom flask import Flask, request\nfrom flask import jsonify\n\nfrom rhandle import RestHandle\n\napp = Flask(__name__)\n\n\n@app.route('/api/', methods=['GET'])\ndef get(operation):\n \"\"\"\n GET request\n :param operation: operation name\n :return: response\n \"\"\"\n if not operation:\n return {\n \"RESULT\": \"FAILED\",\n \"ERROR\": \"Must present operation value\"\n }\n handle = RestHandle()\n return handle.executescript(operation)\n\n\n@app.route('/api', methods=['POST'])\ndef post():\n \"\"\"\n POST request\n :return: response\n \"\"\"\n req_data = json.loads(request.data)\n if not req_data['operation']:\n return jsonify({\n \"RESULT\": \"FAILED\",\n \"ERRPR\": \"Must present operation value\"\n })\n handle = RestHandle()\n return jsonify(handle.executescript(req_data['OPERATION'], data=req_data['INPUTPARAMS']))\n\nif __name__ == '__main__':\n # entry point\n app.run(host=socket.gethostname(), port='5002')\n","sub_path":"rest_sh/hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"526826821","text":"###############################################################################\n#\n# Andrea Estrada | andrea9973@gmail.com\n# Girls Who Code Summer 2018 Application \n# Handles player-to-player interactions\n# Server outline (starter code): https://kdchin.gitbooks.io/sockets-module-manual/content/\n# \n###############################################################################\nimport socket\nimport threading\nfrom queue import Queue\nimport fileinput\nimport main\nimport sys\n\n#designate which computer will host game\nHOST = \"\" #insert IP Address for cross-computer game play\n\n#port for gameplay: change until gameplay is smooth\nPORT = 0 #RESTRICT S.T.: 10000 < PORT < 80000\n\ndef runServer():\n import userPort\n HOST = userPort.host\n PORT = int(userPort.port)\n\n #number of players who can join game\n BACKLOG = 2 #2 player game\n\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket\n server.bind((HOST,PORT)) #connect socket to specified values\n server.listen(BACKLOG)\n\n #note messages sent before player is added will not be sent later\n\n def handleClient(client, serverChannel, cID, clientele):\n client.setblocking(1)\n msg = \"\"\n while True:\n try:\n msg += client.recv(10).decode(\"UTF-8\") #bytestring --> text string\n command = msg.split(\"\\n\") #signals end of message\n while (len(command) > 1): #string formatting of message\n readyMsg = command[0]\n msg = \"\\n\".join(command[1:])\n serverChannel.put(str(cID) + \" \" + readyMsg) #put action on server thread\n command = msg.split(\"\\n\")\n except: return #error occured\n\n #Message restrictions: first instruction must be 1 word\n #Details *must* be included after instruction\n #End every message with a newline\n #NO SPACES BETWEEN COMMANDS\n def serverThread(clientele, serverChannel):\n while True:\n msg = serverChannel.get(True, None)\n msgList = msg.split(\" \")\n senderID = msgList[0]\n instruction = msgList[1]\n details = \" \".join(msgList[2:])\n if (details != \"\"):\n for cID in clientele:\n if cID != senderID:\n sendMsg = instruction + \" \" + senderID + \" \" + details + \"\\n\"\n clientele[cID].send(sendMsg.encode())\n serverChannel.task_done()\n\n clientele = dict() #server thread\n playerNum = 0 #waiting for players to join\n\n serverChannel = Queue(100)\n threading.Thread(target = serverThread, args = (clientele, serverChannel)).start()\n\n names = [\"Player1\", \"Player2\"]\n\n while True:\n try:\n client, address = server.accept()\n # myID is the key to the client in the clientele dictionary\n myID = names[playerNum]\n for cID in clientele:\n clientele[cID].send((\"PlayerJoined %s\\n\" % myID).encode())\n client.send((\"PlayerJoined %s\\n\" % cID).encode())\n clientele[myID] = client\n client.send((\"MyIDis %s \\n\" % myID).encode())\n #print(\"Connection recieved from %s\" % myID)\n threading.Thread(target = handleClient, args = \n (client ,serverChannel, myID, clientele)).start()\n playerNum += 1\n except: pass\n #print(\"Max players previously reached. Could not join.\")\n\nif __name__ == '__main__': runServer()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"638656936","text":"def solve(k,n):\n dp=[]\n for i in range(k+1):\n dps=[]\n for j in range(n+1):\n dps.append(0)\n dp.append(dps)\n for i in range(1,k+1):\n for step in range(1,n+1):\n dp[i][step] = dp[i-1][step-1] + (dp[i][step-1]+1)\n if dp[k][step]>= n:\n return step\n return 0\n\nk=int(input())\nn=int(input())\nprint(solve(k,n))","sub_path":"Code/CodeRecords/2277/60636/247915.py","file_name":"247915.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"121209594","text":"# python3.6\n# Created: 09-11-2018\n\n# Write function compute 3x+1\ndef f(x):\n return 3*x +1\n\nlambda x: 3*x +1\ng = lambda x:3*x+1\nprint(g(2))\n\nfull_name = lambda fn, ln: fn.strip().title() + \" \" + ln.strip().title()\nprint(full_name(\" leonhard\", \"EULER\"))\n\nscifi_authors = [\"Issac Asimov\", \"Orson Scott Card\", \"Douglas Adams\"]\nhelp(scifi_authors.sort)\n# Last name sort\nscifi_authors.sort(key=lambda name: name.split(\" \")[-1].lower()) # ???\nprint(scifi_authors)\n\ndef build_quadratic_function(a, b, c):\n \"\"\"Returns the function f(x) = ax^2 + bx + c\"\"\"\n return lambda x: a*x**2 + b*x + c\n\nf = build_quadratic_function(2, 3, -5)\nprint(f(0))\n","sub_path":"socratica-youtube/lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210085486","text":"import json\nimport os\nimport string\nfrom random import randint, choice\n\nimport yaml\nfrom openapi_core import create_spec\nfrom openapi_core.validation.request.datatypes import (OpenAPIRequest, RequestParameters)\nfrom openapi_core.validation.request.validators import RequestValidator\nfrom openapi_core.validation.response.datatypes import OpenAPIResponse\nfrom openapi_core.validation.response.validators import ResponseValidator\nfrom werkzeug.datastructures import ImmutableMultiDict\n\nENDPOINT_ACTIVATE = '/v1/activate'\nENDPOINT_CONFIG = '/v1/config'\nENDPOINT_NOTIFICATIONS = '/v1/notifications/event-stream'\nENDPOINT_OVERRIDE = '/v1/override'\nENDPOINT_TRACK = '/v1/track'\nENDPOINT_BATCH = '/v1/batch'\nENDPOINT_DECIDE = '/v1/decide'\nENDPOINT_DATAFILE = '/v1/datafile'\n\nYAML_FILE_PATH = os.getenv('OPENAPI_YAML_PATH', 'api/openapi-spec/openapi.yaml')\n\nspec_dict = None\nwith open(YAML_FILE_PATH, 'r') as stream:\n try:\n spec_dict = yaml.safe_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\nspec = create_spec(spec_dict)\n\n\ndef get_random_string():\n \"\"\"\n :return: randomized string\n \"\"\"\n return \"\".join(choice(string.ascii_letters) for _ in range(randint(10, 15)))\n\n\ndef get_pretty_json(dictionary, spaces=4):\n \"\"\"\n Makes JSON output prettuer and readable.\n :return: stringified JSON\n \"\"\"\n return json.dumps(dictionary, indent=spaces)\n\n\ndef sort_response(response_dict, *args):\n \"\"\"\n Used in tests to sort responses by two or more keys.\n For example if response includes experimentKey and FeatureKey, the function\n will sort by primary and secondary key, depending which one you put first.\n The first param will be primary sorted, second secondary.\n Can handle arbitrary number of arguments.\n :param response_dict: response\n :param args: usually experimentKey and featureKey\n :return: sorted response\n \"\"\"\n return sorted(response_dict, key=lambda k: tuple(map(k.__getitem__, args)))\n\n\n# Helper funcitons for overrides\ndef activate_experiment(sess):\n \"\"\"\n Helper function to activate experiment.\n :param sess: API request session_object\n :return: response\n \"\"\"\n payload = '{\"userId\": \"matjaz\", \"userAttributes\": {\"attr_1\": \"hola\"}}'\n params = {\"experimentKey\": \"ab_test1\"}\n\n resp = create_and_validate_request_and_response(ENDPOINT_ACTIVATE, 'post', sess, payload=payload, params=params)\n\n return resp\n\n\ndef override_variation(sess, override_with):\n \"\"\"\n Helper funciton to override a variation.\n :param sess: API request session object.\n :param override_with: provide new variation name as string to override with\n :return: response\n \"\"\"\n payload = {\"userId\": \"matjaz\", \"userAttributes\": {\"attr_1\": \"hola\"},\n \"experimentKey\": \"ab_test1\", \"variationKey\": f\"{override_with}\"}\n\n resp = create_and_validate_request_and_response(\n ENDPOINT_OVERRIDE, 'post', sess, payload=json.dumps(payload)\n )\n\n return resp\n\n\ndef create_and_validate_request(endpoint, method, payload='', params=[], headers=[]):\n \"\"\"\n Helper function to create OpenAPIRequest and validate it\n :param endpoint: API endpoint\n :param method: API request method\n :param payload: API request payload\n :param params: API request payload\n :param headers: API request headers\n :return:\n - request: OpenAPIRequest\n - request_result: result of request validation\n \"\"\"\n parameters = RequestParameters(\n query=ImmutableMultiDict(params),\n path=endpoint,\n header=headers\n )\n\n request = OpenAPIRequest(\n full_url_pattern=endpoint,\n method=method,\n parameters=parameters,\n body=payload,\n mimetype='application/json',\n )\n\n validator = RequestValidator(spec)\n request_result = validator.validate(request)\n\n return request, request_result\n\n\ndef create_and_validate_response(request, response):\n \"\"\"\n Helper function to create OpenAPIResponse and validate it\n :param request: OpenAPIRequest\n :param response: API response\n :return:\n - result: result of response validation\n \"\"\"\n response = OpenAPIResponse(\n data=response.content,\n status_code=response.status_code,\n mimetype='application/json'\n )\n\n validator = ResponseValidator(spec)\n result = validator.validate(request, response)\n return result\n\n\ndef create_and_validate_request_and_response(endpoint, method, session, bypass_validation_request=False,\n bypass_validation_response=False, payload='', params=[]):\n \"\"\"\n Helper function to create OpenAPIRequest, OpenAPIResponse and validate both\n :param endpoint: API endpoint\n :param session: API valid session object\n :param bypass_validation_request: Flag to bypass request validation of invalid requests\n :param bypass_validation_response: Flag to bypass request validation of invalid responses\n :param method: API request method\n :param payload: API request payload\n :param params: API request payload\n :return:\n - response: API response object\n \"\"\"\n request, request_result = create_and_validate_request(\n endpoint, method, payload, params, dict(session.headers)\n )\n\n if not bypass_validation_request:\n request_result.raise_for_errors()\n\n base_url = os.getenv('host')\n\n if method == 'post':\n response = session.post(base_url + endpoint, params=params, data=payload)\n elif method == 'get':\n response = session.get(base_url + endpoint, params=params, data=payload)\n response_result = create_and_validate_response(request, response)\n\n if not bypass_validation_response:\n response_result.raise_for_errors()\n\n return response\n","sub_path":"tests/acceptance/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608116536","text":"from flask import current_app\nfrom jackdaw.dbmodel.netshare import NetShare\nimport string\n\ndef get_by_id(shareid):\n\tdb = current_app.db\n\tres = db.session.query(NetShare).get(shareid)\n\treturn res\n\ndef get_by_machinesid(domaind, machinesid):\n\tdb = current_app.db\n\tshares = []\n\tfor res in db.session.query(NetShare).filter_by(machine_sid = machinesid).filter(NetShare.ad_id == domainid):\n\t\tshares.append(res.to_dict())\n\t\n\treturn shares\n\ndef list_interesting(domainid):\n\tdefault_shares = ['print$','IPC$','ADMIN$', 'SYSVOL', 'NETLOGON']\n\tfor x in string.ascii_uppercase:\n\t\tdefault_shares.append('%s$' % x)\n\tdb = current_app.db\n\tshares = []\n\tq = db.session.query(NetShare)\\\n\t\t.filter_by(ad_id = domainid)\\\n\t\t.filter(NetShare.netname.notin_(default_shares))\n\tfor share in q.all():\n\t\tshares.append(share.to_dict())\n\t\n\treturn shares","sub_path":"jackdaw/nest/api/share.py","file_name":"share.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"295590143","text":"from collections import defaultdict\nimport operator\nimport numpy as np\nimport random\neps = np.finfo(float).eps\ndef getCentralUsers(G,userList,ratio):\n central_users = {}\n groups = defaultdict(list)\n for u in userList:\n groups[userList[u]].append(u)\n for group in groups:\n degs = G.in_degree(groups[group])\n degs = sorted(degs.iteritems(), key = operator.itemgetter(1), reverse = True)\n central_users.update({c:group for c,d in degs[0:int(len(degs)*ratio)]})\n return central_users\n\n\ndef randomWalkPolarity(G, userList, iterC, walkStep):\n\n central_users = getCentralUsers(G,userList,0.01)\n\n nodeIndices = {} #screen_name -> adjacency matrix row index\n nodes = {} #adj.matrix row index-> screen_name\n index = 0\n for node in userList:\n nodeIndices[node] = index\n nodes[index] = node\n index += 1\n\n #iterC = 1000\n inner = 0.0\n cross = 0.0\n ll = 0.0\n lr = 0.0\n rl = 0.0\n rr = 0.0\n #print('Traversal Starts...')\n while iterC > 0:\n # 1- Choose random node\n start_node_ind = random.randint(0, len(nodeIndices)-1)\n start_label = userList[nodes[start_node_ind]]\n visited = {}\n node = nodes[start_node_ind]\n walkStepIt = walkStep\n while walkStepIt > 0:\n neighbors = G.neighbors(node)\n if len(neighbors) == 0:\n walkStepIt = 0 # walk failed\n break\n i = random.randint(0,len(neighbors)-1)\n node = neighbors[i]\n if node in central_users:\n #print('\\tHit the center...')\n break\n walkStepIt -= 1\n if walkStepIt > 0:\n if start_label == 'left' and userList[node] == 'left':\n ll += 1\n inner += 1\n elif start_label == 'left' and userList[node] == 'right':\n lr += 1\n cross += 1\n elif start_label == 'right' and userList[node] == 'left':\n rl += 1\n cross += 1\n elif start_label == 'right' and userList[node] == 'right':\n rr += 1\n inner += 1\n\n iterC -= 1\n e1 = ll*1.0/(ll+rl+eps)\n e2 = lr*1.0/(lr+rr+eps)\n e3 = rl*1.0/(ll+rl+eps)\n e4 = rr*1.0/(lr+rr+eps)\n\n involvement = 0\n rwc = e1*e4 - e2*e3\n polarization = float(inner)/float(cross+inner+eps)\n \n return (rwc,polarization)\n","sub_path":"code/synthetic_network_generation/RWC.py","file_name":"RWC.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242262485","text":"from libs.base_classes.page_base import PageBase\nfrom selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException\nfrom pages.locators.search_results_locators import SearchResultsLocators\n\n\nclass SearchResultsPage(PageBase):\n\n def __init__(self, driver):\n\n super().__init__(driver=driver)\n\n self.set_explicit_wait(\n timeout=30,\n poll_frequency=1,\n ignored_exceptions={\n NoSuchElementException,\n ElementNotVisibleException,\n }\n )\n\n def enter_search_string(self, string):\n self.enter_text_via_send_keys(locator=SearchResultsLocators.SEARCH_INPUT, string=string)\n\n def click_on_search_button(self):\n self.click_on(locator=SearchResultsLocators.SEARCH_BTN)\n\n def get_results_list(self):\n results_list = self.find_elements(locator=SearchResultsLocators.SEARCH_RESULTS_LIST)\n results_elements = []\n for result in results_list:\n results_elements.append({\n \"title\": result.find_element_by_css_selector(\"span\").text,\n \"element\": result\n })\n return results_elements\n\n def click_on_result_by_position(self, position):\n result = self.get_results_list()[position - 1]['element']\n destination_url = result.get_attribute(\"href\")\n self.click_on_element(element=result)\n self.wait_for_url_to_change_to(expected_url=destination_url)\n\n","sub_path":"pages/search_results_page.py","file_name":"search_results_page.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"444992067","text":"#!/usr/bin/python3\n\nimport dawdle\nimport os.path\nimport random\nimport sys\nimport tempfile\nimport time\nimport unittest\n\nclass TestPlayerDBSqlite3(unittest.TestCase):\n def test_db(self):\n dawdle.conf['rpbase'] = 600\n with tempfile.TemporaryDirectory() as tmpdir:\n db = dawdle.PlayerDB(dawdle.Sqlite3PlayerStore(os.path.join(tmpdir, 'dawdle_test.db')))\n self.assertFalse(db.exists())\n db.create()\n p = db.new_player('foo', 'bar', 'baz')\n p.online = True\n db.write()\n self.assertTrue(db.exists())\n db.load()\n self.assertEqual(db['foo'].name, 'foo')\n self.assertEqual(db['foo'].online, True)\n db.close()\n\n def test_passwords(self):\n with tempfile.TemporaryDirectory() as tmpdir:\n db = dawdle.PlayerDB(dawdle.Sqlite3PlayerStore(os.path.join(tmpdir, 'dawdle_test.db')))\n self.assertFalse(db.exists())\n db.create()\n p = db.new_player('foo', 'bar', 'baz')\n self.assertTrue(db.check_login('foo', 'baz'))\n self.assertFalse(db.check_login('foo', 'azb'))\n p.set_password('azb')\n self.assertTrue(db.check_login('foo', 'azb'))\n db.close()\n\n\nclass TestPlayerDBIdleRPG(unittest.TestCase):\n def test_db(self):\n with tempfile.TemporaryDirectory() as tmpdir:\n db = dawdle.PlayerDB(dawdle.IdleRPGPlayerStore(os.path.join(tmpdir, 'dawdle_test.db')))\n db.create()\n op = db.new_player('foo', 'bar', 'baz')\n op.amulet = 55\n op.helm = 42\n op.helmname = \"Jeff's Cluehammer of Doom\"\n db.write()\n db.load()\n p = db['foo']\n self.maxDiff = None\n self.assertEqual(vars(op), vars(p))\n db.close()\n\n\nclass TestIRCMessage(unittest.TestCase):\n def test_basic(self):\n line = \"@time=2021-07-31T13:55:00,bar=baz :nick!example@example.com PART #example :later!\"\n msg = dawdle.IRCClient.parse_message(None, line)\n self.assertEqual(msg.tags, {\"time\": \"2021-07-31T13:55:00\", \"bar\": \"baz\"})\n self.assertEqual(msg.src, \"nick\")\n self.assertEqual(msg.user, \"example\")\n self.assertEqual(msg.host, \"example.com\")\n self.assertEqual(msg.cmd, \"PART\")\n self.assertEqual(msg.args, [\"#example\", \"later!\"])\n self.assertEqual(msg.trailing, \"later!\")\n self.assertEqual(msg.line, line)\n self.assertEqual(msg.time, 1627754100)\n\n def test_notags(self):\n line = \":nick!example@example.com PART #example :later!\"\n msg = dawdle.IRCClient.parse_message(None,line)\n self.assertEqual(msg.tags, {})\n self.assertEqual(msg.src, \"nick\")\n\n def test_badtags(self):\n line = \"@asdf :nick!example@example.com PART #example :later!\"\n msg = dawdle.IRCClient.parse_message(None,line)\n self.assertEqual(msg.tags, {'asdf': None})\n self.assertEqual(msg.src, \"nick\")\n\n line = \"@ :nick!example@example.com PART #example :later!\"\n msg = dawdle.IRCClient.parse_message(None,line)\n self.assertEqual(msg.tags, {})\n self.assertEqual(msg.src, \"nick\")\n\n def test_bad_encoding(self):\n line = \"\\255\\035\"\n msg = dawdle.IRCClient.parse_message(None, line)\n\n\nclass TestIRCClient(unittest.TestCase):\n\n def test_handle_cap(self):\n dawdle.conf['botnick'] = 'foo'\n irc = dawdle.IRCClient(None)\n irc.handle_cap(dawdle.IRCClient.Message(tags={}, src='tungsten.libera.chat', user=None, host=None, cmd='CAP', args=['*', 'ACK', 'multi-prefix'], trailing='multi-prefix', line=':tungsten.libera.chat CAP * ACK :multi-prefix', time=1629501206))\n self.assertIn(\"multi-prefix\", irc._caps)\n\n\nclass FakeIRCClient(object):\n def __init__(self):\n self._nick = 'dawdlerpg'\n self._users = {}\n self.server = \"irc.example.com\"\n self.chanmsgs = []\n self.notices = {}\n\n def chanmsg(self, text):\n self.chanmsgs.append(text)\n\n def notice(self, nick, text):\n self.notices.setdefault(nick, []).append(text)\n\n\nclass FakePlayerStore(dawdle.PlayerStore):\n\n def __init__(self):\n self._mem = {}\n\n def create(self):\n pass\n\n def readall(self):\n pass\n\n def writeall(self, p):\n pass\n\n def close(self):\n pass\n\n def new(self, p):\n self._mem[p.name] = p\n\n def rename(self, old, new):\n self._mem[new] = self._mem[old]\n self._mem.pop(old)\n\n def delete(self, pname):\n self._mem.pop(pname)\n\n\nclass TestPvPBattle(unittest.TestCase):\n\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['modsfile'] = '/tmp/modsfile.txt'\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n\n def test_player_battle_win(self):\n a = self.bot._players.new_player('a', 'b', 'c')\n a.amulet = 20\n b = self.bot._players.new_player('b', 'c', 'd')\n b.amulet = 40\n self.bot._overrides = {\n 'pvp_player_roll': 20,\n 'pvp_opp_roll': 10,\n 'pvp_critical': False,\n 'pvp_swap_item': False,\n 'pvp_find_item': False\n }\n self.bot.pvp_battle(a, b, \"fought\", \"and has won\", \"and has lost\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"a [20/20] has fought b [10/40] and has won! 0 days, 00:00:42 is removed from a's clock.\",\n \"a reaches next level in 0 days, 00:09:18.\"\n ])\n self.assertEqual(a.nextlvl, 558)\n\n\n def test_player_battle_bot(self):\n dawdle.conf['botnick'] = 'dawdlerpg'\n a = self.bot._players.new_player('a', 'b', 'c')\n a.amulet = 20\n self.bot._overrides = {\n 'pvp_player_roll': 20,\n 'pvp_opp_roll': 10,\n 'pvp_critical': False,\n 'pvp_swap_item': False,\n 'pvp_find_item': False\n }\n self.bot.pvp_battle(a, None, \"fought\", \"and has won\", \"and has lost\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"a [20/20] has fought dawdlerpg [10/21] and has won! 0 days, 00:02:00 is removed from a's clock.\",\n \"a reaches next level in 0 days, 00:08:00.\"\n ])\n self.assertEqual(a.nextlvl, 480)\n\n\n def test_player_battle_lose(self):\n a = self.bot._players.new_player('a', 'b', 'c')\n a.amulet = 20\n b = self.bot._players.new_player('b', 'c', 'd')\n b.amulet = 40\n self.bot._overrides = {\n 'pvp_player_roll': 10,\n 'pvp_opp_roll': 20,\n 'pvp_critical': False,\n 'pvp_swap_item': False,\n 'pvp_find_item': False\n }\n self.bot.pvp_battle(a, b, \"fought\", \"and has won\", \"and has lost\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"a [10/20] has fought b [20/40] and has lost! 0 days, 00:00:42 is added to a's clock.\",\n \"a reaches next level in 0 days, 00:10:42.\"\n ])\n self.assertEqual(a.nextlvl, 642)\n\n\n def test_player_battle_critical(self):\n a = self.bot._players.new_player('a', 'b', 'c')\n a.amulet = 20\n b = self.bot._players.new_player('b', 'c', 'd')\n b.amulet = 40\n self.bot._overrides = {\n 'pvp_player_roll': 20,\n 'pvp_opp_roll': 10,\n 'pvp_critical': True,\n 'pvp_cs_penalty_pct': 10,\n 'pvp_swap_item': False,\n 'pvp_find_item': False\n }\n self.bot.pvp_battle(a, b, \"fought\", \"and has won\", \"and has lost\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"a [20/20] has fought b [10/40] and has won! 0 days, 00:00:42 is removed from a's clock.\",\n \"a reaches next level in 0 days, 00:09:18.\",\n \"a has dealt b a Critical Strike! 0 days, 00:01:30 is added to b's clock.\",\n \"b reaches next level in 0 days, 00:11:30.\"\n ])\n self.assertEqual(a.nextlvl, 558)\n self.assertEqual(b.nextlvl, 690)\n\n\n def test_player_battle_swapitem(self):\n a = self.bot._players.new_player('a', 'b', 'c')\n a.level = 20\n a.amulet = 20\n b = self.bot._players.new_player('b', 'c', 'd')\n b.amulet = 40\n self.bot._overrides = {\n 'pvp_player_roll': 20,\n 'pvp_opp_roll': 10,\n 'pvp_critical': False,\n 'pvp_swap_item': True,\n 'pvp_swap_itemtype': 'amulet',\n 'pvp_find_item': False\n }\n self.bot.pvp_battle(a, b, \"fought\", \"and has won\", \"and has lost\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"a [20/20] has fought b [10/40] and has won! 0 days, 00:00:42 is removed from a's clock.\",\n \"a reaches next level in 0 days, 00:09:18.\",\n \"In the fierce battle, b dropped their level 40 amulet! a picks it up, tossing their old level 20 amulet to b.\"\n ])\n self.assertEqual(a.nextlvl, 558)\n self.assertEqual(a.amulet, 40)\n self.assertEqual(b.amulet, 20)\n\n\n def test_player_battle_finditem(self):\n a = self.bot._players.new_player('a', 'b', 'c')\n a.nick = 'a'\n a.amulet = 20\n b = self.bot._players.new_player('b', 'c', 'd')\n b.amulet = 40\n self.bot._overrides = {\n 'pvp_player_roll': 20,\n 'pvp_opp_roll': 10,\n 'pvp_critical': False,\n 'pvp_swap_item': False,\n 'pvp_find_item': True,\n 'specitem_find': False,\n 'find_item_itemtype': 'charm',\n 'find_item_level': 5\n }\n self.bot.pvp_battle(a, b, \"fought\", \"and has won\", \"and has lost\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"a [20/20] has fought b [10/40] and has won! 0 days, 00:00:42 is removed from a's clock.\",\n \"a reaches next level in 0 days, 00:09:18.\",\n \"While recovering from battle, a notices a glint in the mud. Upon investigation, they find an old lost item!\"\n ])\n self.assertListEqual(self.irc.notices['a'], [\n \"You found a level 5 charm! Your current charm is only level 0, so it seems Luck is with you!\"\n ])\n\n self.assertEqual(a.nextlvl, 558)\n\n\nclass TestTeamBattle(unittest.TestCase):\n\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['modsfile'] = '/tmp/modsfile.txt'\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n\n def test_setup_insufficient_players(self):\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcde\"]\n self.bot.team_battle(op)\n self.assertEqual(self.irc.chanmsgs, [])\n\n\n def test_win(self):\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcdef\"]\n op[0].amulet, op[0].nextlvl = 20, 1200\n op[1].amulet, op[1].nextlvl = 20, 3600\n op[2].amulet, op[2].nextlvl = 20, 3600\n op[3].amulet, op[3].nextlvl = 40, 3600\n op[4].amulet, op[4].nextlvl = 40, 3600\n op[5].amulet, op[5].nextlvl = 40, 3600\n self.bot._overrides = {\n 'team_battle_members': op,\n 'team_a_roll': 60,\n 'team_b_roll': 30\n }\n self.bot.team_battle(op)\n self.assertEqual(self.irc.chanmsgs[0], \"a, b, and c [60/60] have team battled d, e, and f [30/120] and won! 0 days, 00:04:00 is removed from their clocks.\")\n\n def test_loss(self):\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcdef\"]\n op[0].amulet, op[0].nextlvl = 20, 1200\n op[1].amulet, op[1].nextlvl = 20, 3600\n op[2].amulet, op[2].nextlvl = 20, 3600\n op[3].amulet, op[3].nextlvl = 40, 3600\n op[4].amulet, op[4].nextlvl = 40, 3600\n op[5].amulet, op[5].nextlvl = 40, 3600\n self.bot._overrides = {\n 'team_battle_members': op,\n 'team_a_roll': 30,\n 'team_b_roll': 60\n }\n self.bot.team_battle(op)\n self.assertEqual(self.irc.chanmsgs[0], \"a, b, and c [30/60] have team battled d, e, and f [60/120] and lost! 0 days, 00:04:00 is added to their clocks.\")\n\n\nclass TestEvilness(unittest.TestCase):\n\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['modsfile'] = '/tmp/modsfile.txt'\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n\n def test_theft(self):\n op = [self.bot._players.new_player('a', 'b', 'c'), self.bot._players.new_player('b', 'c', 'd')]\n op[0].alignment = 'e'\n op[1].alignment = 'g'\n op[1].amulet = 20\n self.bot._overrides = {\n 'evilness_theft': True,\n 'evilness_item': 'amulet'\n }\n self.bot.evilness(op)\n self.assertEqual(self.irc.chanmsgs[0], \"a stole b's level 20 amulet while they were sleeping! a leaves their old level 0 amulet behind, which b then takes.\")\n\n\n def test_penalty(self):\n op = [self.bot._players.new_player('a', 'b', 'c')]\n op[0].alignment = 'e'\n self.bot._overrides = {\n 'evilness_theft': False,\n 'evilness_penalty_pct': 5\n }\n self.bot.evilness(op)\n self.assertEqual(self.irc.chanmsgs[0], \"a is forsaken by their evil god. 0 days, 00:00:30 is added to their clock.\")\n\n\nclass TestGoodness(unittest.TestCase):\n\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['modsfile'] = '/tmp/modsfile.txt'\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n\n def test_goodness(self):\n op = [self.bot._players.new_player('a', 'b', 'c'), self.bot._players.new_player('b', 'c', 'd')]\n op[0].alignment = 'g'\n op[1].alignment = 'g'\n self.bot._overrides = {\n 'goodness_players': op,\n 'goodness_gain_pct': 10,\n }\n self.bot.goodness(op)\n self.assertListEqual(self.irc.chanmsgs, [\n \"a and b have not let the iniquities of evil people poison them. Together have they prayed to their god, and light now shines down upon them. 10% of their time is removed from their clocks.\",\n \"a reaches next level in 0 days, 00:09:00.\",\n \"b reaches next level in 0 days, 00:09:00.\"\n ])\n self.assertEqual(op[0].nextlvl, 540)\n self.assertEqual(op[1].nextlvl, 540)\n\n\nclass TestHandOfGod(unittest.TestCase):\n\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n\n def test_forward(self):\n op = [self.bot._players.new_player('a', 'b', 'c')]\n self.bot._overrides = {\n 'hog_effect': True,\n 'hog_amount': 10\n }\n self.bot.hand_of_god(op)\n self.assertEqual(self.irc.chanmsgs[0], \"Verily I say unto thee, the Heavens have burst forth, and the blessed hand of God carried a 0 days, 00:01:30 toward level 1.\")\n self.assertEqual(self.irc.chanmsgs[1], \"a reaches next level in 0 days, 00:08:30.\")\n\n\n def test_back(self):\n op = [self.bot._players.new_player('a', 'b', 'c')]\n self.bot._overrides = {\n 'hog_effect': False,\n 'hog_amount': 10\n }\n self.bot.hand_of_god(op)\n self.assertEqual(self.irc.chanmsgs[0], \"Thereupon He stretched out His little finger among them and consumed a with fire, slowing the heathen 0 days, 00:01:30 from level 1.\")\n self.assertEqual(self.irc.chanmsgs[1], \"a reaches next level in 0 days, 00:11:30.\")\n\n\nclass TestQuest(unittest.TestCase):\n\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['datadir'] = os.path.join(os.path.dirname(__file__), \"data\")\n dawdle.conf['eventsfile'] = \"events.txt\"\n dawdle.conf['writequestfile'] = True\n dawdle.conf['questfilename'] = \"/tmp/testquestfile.txt\"\n dawdle.conf['quest_interval_min'] = 6*3600\n dawdle.conf['quest_min_level'] = 24\n dawdle.conf['penquest'] = 15\n dawdle.conf['penlogout'] = 20\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n self.bot._state = \"ready\"\n self.bot.refresh_events()\n\n\n def test_questing_mode_1(self):\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcd\"]\n now = time.time()\n for p in op:\n p.online = True\n p.level = 25\n p.lastlogin = now - 36001\n self.bot._overrides = {\n \"quest_members\": op,\n \"quest_selection\": \"1 locate the centuries-lost tomes of the grim prophet Haplashak Mhadhu\",\n \"quest_time\": 12\n }\n self.bot.quest_start(now)\n self.bot.private_message('foo', 'quest')\n # time passes\n self.bot._quest.qtime = now-1\n self.bot.quest_check(now)\n\n self.assertListEqual(self.irc.chanmsgs, [\n \"a, b, c, and d have been chosen by the gods to locate the centuries-lost tomes of the grim prophet Haplashak Mhadhu. Quest to end in 0 days, 12:00:00.\",\n \"a, b, c, and d have blessed the realm by completing their quest! 25% of their burden is eliminated.\"\n ])\n self.assertListEqual(self.irc.notices['foo'], [\n \"a, b, c, and d are on a quest to locate the centuries-lost tomes of the grim prophet Haplashak Mhadhu. Quest to complete in 0 days, 11:59:59.\"\n ])\n self.assertEqual(op[0].nextlvl, 450)\n self.assertEqual(op[1].nextlvl, 450)\n self.assertEqual(op[2].nextlvl, 450)\n self.assertEqual(op[3].nextlvl, 450)\n\n\n def test_questing_mode_2(self):\n dawdle.conf['mapurl'] = \"https://example.com/\"\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcd\"]\n now = time.time()\n for p in op:\n p.online = True\n p.level = 25\n p.lastlogin = now - 36001\n self.bot._overrides = {\n \"quest_members\": op,\n \"quest_selection\": \"2 400 475 480 380 explore and chart the dark lands of T'rnalvph\",\n }\n self.bot._players._online = op\n self.bot.quest_start(now)\n self.bot.private_message('foo', 'quest')\n for p in op:\n p.posx, p.posy = 400, 475\n self.bot.quest_check(1)\n for p in op:\n p.posx, p.posy = 480, 380\n self.bot.quest_check(2)\n\n self.assertEqual(self.irc.chanmsgs, [\n \"a, b, c, and d have been chosen by the gods to explore and chart the dark lands of T'rnalvph. Participants must first reach (400,475), then (480,380). See https://example.com/ to monitor their journey's progress.\",\n \"a, b, c, and d have reached a landmark on their journey! 1 landmark remains.\",\n \"a, b, c, and d have completed their journey! 25% of their burden is eliminated.\"\n ])\n self.assertListEqual(self.irc.notices['foo'], [\n \"a, b, c, and d are on a quest to explore and chart the dark lands of T'rnalvph. Participants must first reach (400, 475), then (480, 380). See https://example.com/ to monitor their journey's progress.\"\n ])\n self.assertEqual(op[0].nextlvl, 450)\n self.assertEqual(op[1].nextlvl, 450)\n self.assertEqual(op[2].nextlvl, 450)\n self.assertEqual(op[3].nextlvl, 450)\n\n\n def test_questing_failure(self):\n dawdle.conf['rppenstep'] = 1.14\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcd\"]\n now = time.time()\n for p in op:\n p.online = True\n p.nick = p.name\n p.level = 25\n p.lastlogin = now - 36001\n self.bot._overrides = {\n \"quest_members\": op,\n \"quest_selection\": \"1 locate the centuries-lost tomes of the grim prophet Haplashak Mhadhu\",\n \"quest_time\": 12\n }\n self.bot.quest_start(now)\n self.bot.penalize(op[0], 'logout')\n\n self.assertListEqual(self.irc.chanmsgs, [\n \"a, b, c, and d have been chosen by the gods to locate the centuries-lost tomes of the grim prophet Haplashak Mhadhu. Quest to end in 0 days, 12:00:00.\",\n \"a's insolence has brought the wrath of the gods down upon them. Your great wickedness burdens you like lead, drawing you downwards with great force towards hell. Thereby have you plunged 15 steps closer to that gaping maw.\"\n ])\n self.assertListEqual(self.irc.notices['a'],\n [\"Penalty of 0 days, 00:08:40 added to your timer for LOGOUT command.\"])\n self.assertEqual(op[0].nextlvl, 1516)\n self.assertEqual(op[1].nextlvl, 996)\n self.assertEqual(op[2].nextlvl, 996)\n self.assertEqual(op[3].nextlvl, 996)\n\nclass TestAdminCommands(unittest.TestCase):\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n def test_delold(self):\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcd\"]\n level = 25\n expired = time.time() - 9 * 86400\n for p in op[:2]:\n p.lastlogin = expired\n op[3].online = True\n op[3].isadmin = True\n self.bot.cmd_delold(op[3], op[3].nick, \"7\")\n self.assertListEqual(self.irc.chanmsgs, [\n \"2 accounts not accessed in the last 7 days removed by d.\"\n ])\n self.assertNotIn(op[0].name, self.bot._players)\n self.assertNotIn(op[1].name, self.bot._players)\n self.assertIn(op[2].name, self.bot._players)\n self.assertIn(op[3].name, self.bot._players)\n\n\nclass TestPlayerCommands(unittest.TestCase):\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['color'] = False\n dawdle.conf['allowuserinfo'] = True\n dawdle.conf['helpurl'] = \"http://example.com/\"\n dawdle.conf['botchan'] = \"#dawdlerpg\"\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n def test_unrestricted_commands_without_player(self):\n for cmd in dawdle.DawdleBot.ALLOWALL:\n # We don't care what it does, as long as it doesn't crash.\n getattr(self.bot, f\"cmd_{cmd}\")(None, \"foo\", \"\")\n\n def test_cmd_info(self):\n self.bot.cmd_info(None, \"foo\", \"\")\n self.assertIn(\"DawdleRPG v\", self.irc.notices[\"foo\"][0])\n player = self.bot._players.new_player(\"bar\", 'a', 'b')\n self.bot.cmd_info(player, \"bar\", \"\")\n self.assertIn(\"DawdleRPG v\", self.irc.notices[\"bar\"][0])\n\n\nclass TestGameTick(unittest.TestCase):\n\n def setUp(self):\n dawdle.conf['rpbase'] = 600\n dawdle.conf['rpstep'] = 1.14\n dawdle.conf['detectsplits'] = True\n dawdle.conf['splitwait'] = 300\n dawdle.conf['datadir'] = os.path.join(os.path.dirname(__file__), \"data\")\n dawdle.conf['eventsfile'] = \"events.txt\"\n dawdle.conf['writequestfile'] = True\n dawdle.conf['questfilename'] = \"/tmp/testquestfile.txt\"\n dawdle.conf['quest_min_level'] = 24\n dawdle.conf['self_clock'] = 1\n dawdle.conf['mapx'] = 500\n dawdle.conf['mapy'] = 500\n dawdle.conf['color'] = False\n self.bot = dawdle.DawdleBot(dawdle.PlayerDB(FakePlayerStore()))\n self.irc = FakeIRCClient()\n self.bot.connected(self.irc)\n\n def test_gametick(self):\n op = [self.bot._players.new_player(pname, 'a', 'b') for pname in \"abcd\"]\n level = 25\n for p in op:\n p.online = True\n p.level = level\n level += 3\n self.bot.gametick(0, 0)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"dawdle_test.py","file_name":"dawdle_test.py","file_ext":"py","file_size_in_byte":24367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"632223659","text":"import outputs\n\n\ndef start_program() -> None:\n \"\"\"\n The main entry point for the program.\n Runs the program.\n \"\"\"\n numLocations = get_input_integer()\n locations = get_input_strings(numLocations)\n numOutputs = get_input_integer()\n outputStrings = get_input_strings(numOutputs)\n\n outputObjects = []\n for outputType in outputStrings:\n outputObjects.append(get_output_class(outputType))\n\n print('')\n for output in outputObjects:\n # Catch any errors that would be thrown from things like mapquest being down or not having internet\n try:\n output.print_output(locations)\n except:\n print('MAPQUEST ERROR')\n\n print('')\n\n print(\"Directions Courtesy of MapQuest; Map Data Copyright OpenStreetMap Contributors\")\n\n\ndef get_output_class(type: str) -> object:\n \"\"\"\n Creates an instance of the output class given the type string\n :param type: The type of output that is needed\n :return: An instance of an output class\n \"\"\"\n if type.upper() == 'STEPS':\n return outputs.Steps()\n elif type.upper() == 'TOTALDISTANCE':\n return outputs.TotalDistance()\n elif type.upper() == 'TOTALTIME':\n return outputs.TotalTime()\n elif type.upper() == 'LATLONG':\n return outputs.LatLong()\n else:\n return outputs.Elevation()\n\n\ndef get_input_strings(number: int) -> [str]:\n \"\"\"\n Gets a the given number of strings from the standard input and returns them as a list\n :param number: The number of strings to get from the input\n :return: A list of strings retrieved from the standard input\n \"\"\"\n returnList = []\n for i in range(number):\n line = input().strip()\n returnList.append(line)\n return returnList\n\n\ndef get_input_integer() -> int:\n \"\"\"\n Gets an integer from the standard input\n :return: The integer retrieved from the standard input\n \"\"\"\n value = input().strip()\n return int(value)\n\n\nif __name__ == '__main__':\n start_program()\n","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556908273","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom typing import List, Dict, Any\nimport networkx as nx\nfrom coincurve import PublicKey\nfrom coincurve.utils import sha256\nfrom eth_utils import is_checksum_address, is_same_address, to_checksum_address\nfrom networkx import DiGraph\nfrom raiden_libs.utils import compute_merkle_tree, get_merkle_root, public_key_to_address\nfrom web3.contract import Contract\nfrom pathfinder.config import DIVERSITY_PEN_DEFAULT\nfrom pathfinder.model.balance_proof import BalanceProof\nfrom pathfinder.model.channel_view import ChannelView\nfrom pathfinder.model.lock import Lock\nfrom pathfinder.utils.types import Address, ChannelId\n\n\nlog = logging.getLogger(__name__)\n\n\nclass TokenNetwork:\n \"\"\" Manages a token network for pathfinding.\n\n Problems:\n - Do we set a default fee? Otherwise we estimate all opened channels with a zero fee.\n The other options to just take channels into account once a fee has been set.\n - Are fees absolute or relative to the transferred value (or base + relative)?\n TODO: test all these methods once we have sample data, DO NOT let these crucial functions\n remain uncovered! \"\"\"\n\n def __init__(\n self,\n token_network_contract: Contract\n ):\n \"\"\" Initializes a new TokenNetwork. \"\"\"\n\n self.token_network_contract = token_network_contract\n self.address = to_checksum_address(self.token_network_contract.address)\n self.token_address = self.token_network_contract.functions.token().call()\n self.channel_id_to_addresses = dict()\n self.G = DiGraph()\n self.max_fee = 0.0\n\n # Contract event listener functions\n\n def handle_channel_opened_event(\n self,\n channel_id: ChannelId,\n participant1: Address,\n participant2: Address,\n ):\n \"\"\" Register the channel in the graph, add participents to graph if necessary.\n\n Corresponds to the ChannelOpened event. Called by the contract event listener. \"\"\"\n\n assert is_checksum_address(participant1)\n assert is_checksum_address(participant2)\n\n self.channel_id_to_addresses[channel_id] = (participant1, participant2)\n\n view1 = ChannelView(channel_id, participant1, participant2, deposit=0)\n view2 = ChannelView(channel_id, participant2, participant1, deposit=0)\n\n self.G.add_edge(participant1, participant2, view=view1)\n self.G.add_edge(participant2, participant1, view=view2)\n\n def handle_channel_new_deposit_event(\n self,\n channel_id: ChannelId,\n receiver: Address,\n total_deposit: int\n ):\n \"\"\" Register a new balance for the beneficiary.\n\n Corresponds to the ChannelNewDeposit event. Called by the contract event listener. \"\"\"\n\n assert is_checksum_address(receiver)\n\n try:\n participant1, participant2 = self.channel_id_to_addresses[channel_id]\n\n if receiver == participant1:\n self.G[participant1][participant2]['view'].update_capacity(deposit=total_deposit)\n elif receiver == participant2:\n self.G[participant2][participant1]['view'].update_capacity(deposit=total_deposit)\n else:\n log.error(\n \"Receiver in ChannelNewDeposit does not fit the internal channel\"\n )\n except KeyError as ke:\n log.error(\n \"Received ChannelNewDeposit event for unknown channel '{}'\".format(\n channel_id\n )\n )\n\n def handle_channel_closed_event(self, channel_id: ChannelId):\n \"\"\" Close a channel. This doesn't mean that the channel is settled yet, but it cannot\n transfer any more.\n\n Corresponds to the ChannelClosed event. Called by the contract event listener. \"\"\"\n\n try:\n # we need to unregister the channel_id here\n participant1, participant2 = self.channel_id_to_addresses.pop(channel_id)\n\n self.G.remove_edge(participant1, participant2)\n self.G.remove_edge(participant2, participant1)\n except KeyError as ke:\n log.error(\n \"Received ChannelClosed event for unknown channel '{}'\".format(\n channel_id\n )\n )\n\n # pathfinding endpoints\n\n def update_balance(\n self,\n balance_proof: BalanceProof,\n locks: List[Lock]\n ):\n \"\"\" Update the channel balance with the new balance proof.\n This needs to check that the balance proof is valid.\n\n Called by the public interface. \"\"\"\n\n participant1, participant2 = self.channel_id_to_addresses(balance_proof.channel_id)\n if is_same_address(participant1, balance_proof.sender):\n receiver = participant2\n elif is_same_address(participant2, balance_proof.sender):\n receiver = participant1\n else:\n raise ValueError('Balance proof signature does not match any of the participants.')\n\n view1: ChannelView = self.G[balance_proof.sender][receiver]['view']\n view2: ChannelView = self.G[receiver][balance_proof.sender]['view']\n\n if view1.transferred_amount >= balance_proof.transferred_amount:\n # FIXME: use nonce instead for this check?\n raise ValueError('Balance proof is outdated.')\n\n reconstructed_merkle_tree = compute_merkle_tree(lock.compute_hash() for lock in locks)\n reconstructed_merkle_root = get_merkle_root(reconstructed_merkle_tree)\n\n if not reconstructed_merkle_root == balance_proof.locksroot:\n raise ValueError('Supplied locks do not match the provided locksroot')\n\n view1.update_capacity(\n transferred_amount=balance_proof.transferred_amount,\n locked_amount=sum(lock.amount_locked for lock in locks)\n )\n view2.update_capacity(\n received_amount=balance_proof.transferred_amount\n )\n\n def update_fee(\n self,\n channel_id: ChannelId,\n new_fee: bytes,\n signature: bytes\n ):\n \"\"\" Update the channel with a new fee. New_fee bytes are of the form '0.0012'.encode()\"\"\"\n # Fixme: I need a nonce for replay protection\n msg = new_fee\n signer = public_key_to_address(\n PublicKey.from_signature_and_message(\n signature,\n msg,\n hasher=sha256\n )\n )\n\n participant1, participant2 = self.channel_id_to_addresses[channel_id]\n if is_same_address(participant1, signer):\n sender = participant1\n receiver = participant2\n elif is_same_address(participant2, signer):\n sender = participant2\n receiver = participant1\n else:\n raise ValueError('Signature does not match any of the participants.')\n\n new_fee = float(new_fee)\n channel_view = self.G[sender][receiver]['view']\n\n if new_fee >= self.max_fee:\n # Equal case is included to avoid a recalculation of the max fee.\n self.max_fee = new_fee\n channel_view.fee = new_fee\n elif channel_view.fee == self.max_fee:\n # O(n) operation but rarely called, amortized likely constant.\n channel_view.fee = new_fee\n self.max_fee = max(\n edge_data['view'].fee\n for _, _, edge_data in self.G.edges(data=True)\n )\n\n channel_view.fee = new_fee\n\n def get_paths(\n self,\n source: Address,\n target: Address,\n value: int,\n k: int,\n **kwargs\n ):\n visited: Dict[ChannelId, float] = {}\n paths = []\n hop_bias = kwargs.get('bias', 0)\n assert 0 <= hop_bias <= 1\n\n def weight(\n u: Address,\n v: Address,\n attr: Dict[str, Any]\n ):\n view: ChannelView = attr['view']\n if view.capacity < value:\n return None\n else:\n return hop_bias*self.max_fee + (1-hop_bias)*view.fee + visited.get(\n view.channel_id,\n 0\n )\n\n for i in range(k):\n path = nx.dijkstra_path(self.G, source, target, weight=weight)\n for node1, node2 in zip(path[:-1], path[1:]):\n channel_id = self.G[node1][node2]['view'].channel_id\n visited[channel_id] = visited.get(channel_id, 0) + DIVERSITY_PEN_DEFAULT\n paths.append(path)\n return paths\n\n # functions for persistence\n\n def save_snapshot(self, filename):\n \"\"\" Serializes the token network so it doesn't need to sync from scratch when\n the snapshot is loaded.\n\n We probably need to save the lasts synced block here. \"\"\"\n pass\n\n @staticmethod\n def load_snapshot(filename):\n \"\"\" Deserializes the token network so it doesn't need to sync from scratch \"\"\"\n pass\n","sub_path":"pathfinder/token_network.py","file_name":"token_network.py","file_ext":"py","file_size_in_byte":8992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567316869","text":"# 2606번\ncomp, conn = int(input()), int(input())\nclist = [[] for _ in range(comp+1)] # 연결 상태\ndef dfs(graph, v):\n visited = []\n need_visit = []\n need_visit.append(v) # 시작점 넣기\n while need_visit:\n node = need_visit.pop()\n if node not in visited:\n visited.append(node)\n need_visit.extend(graph[node])\n return visited\nfor _ in range(conn):\n s, e = map(int,input().split()) # s 연결 시작, e 연결된 부분\n clist[s].append(e)\n clist[e].append(s)\nprint(len(dfs(clist,1))-1)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Baekjoon/BFS DFS/바이러스.py","file_name":"바이러스.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"511005089","text":"\nfrom ..httpclient import FileRepositorySession\nfrom ..storage import StorageManager\nfrom ..logger import Logger\nfrom ..persistance import LogRepository, ProcessedElementLog\nfrom .generictypeprocessor import GenericEntryProcessor\nfrom .filetypeprocessor import FileTypeProcessor\nfrom typing import List\n\n\nclass EventProcessor(GenericEntryProcessor):\n \"\"\"\n Aggregator for GenericEntryProcessor interface (calls multiple implementation of this interface)\n \"\"\"\n\n children: List[GenericEntryProcessor]\n instance_name: str\n\n def __init__(self, client: FileRepositorySession, storage: StorageManager, log_repository: LogRepository, instance_name: str):\n self.children = [FileTypeProcessor(client, storage, log_repository)]\n self.instance_name = instance_name\n\n super().__init__(client, storage, log_repository)\n\n def process(self, entry: ProcessedElementLog):\n \"\"\"\n Process incoming events. Pass to proper event processors that claims can handle such data type\n Persist results to database\n \"\"\"\n\n for processor in self.children:\n if processor.can_process(entry):\n Logger.debug('Processing element type \"' + entry.element_type + '\" using ' + str(processor))\n\n if self.repository.was_already_processed(entry.element_type, entry.element_id):\n Logger.info('Element id=' + str(entry.element_id) + ', type=' + str(entry.element_type) +\n ' was already processed')\n return\n\n # mark as in-progress\n entry.mark_as_in_progress(self.instance_name)\n self.repository.persist(entry)\n\n # process\n processor.process(entry)\n\n # mark as done\n entry.mark_as_processed()\n self.repository.persist(entry)\n return\n\n raise Exception('Cannot process entry, no available handler found that can process the data: ' + str(entry))\n\n def can_process(self, entry: ProcessedElementLog) -> bool:\n for processor in self.children:\n if processor.can_process(entry):\n return True\n\n return False\n","sub_path":"kropot-cli/src/kropotcli/processor/eventprocessor.py","file_name":"eventprocessor.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567956220","text":"def checkifdbl(name,length):\n n=int(length/2)\n s1=name[:n]\n s2=name[n:]\n if s1==s2:\n return True\n else:\n return False\n\n\nfor _ in range(int(input())):\n name=input()\n length=len(name)\n if(length==1):\n print(\"NO\");\n continue;\n if(length%2==0):\n if(checkifdbl(name,length)):\n print(\"YES\")\n else:\n print(\"NO\")\n else:\n for k in range(length):\n newname = name[:k] + name[k+1:]\n if (checkifdbl(newname,length-1)):\n print(\"YES\")\n break\n elif k==length-1:\n print(\"NO\")\n break\n","sub_path":"CodeChef/CHEFSPL.py","file_name":"CHEFSPL.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"141928864","text":"#!/usr/bin/python3\n\n\"\"\"\nUnit test for procedure reading from socket.\n\"\"\"\n\nimport socket\nimport argparse\nimport sys\n\ndef get_socket_by_args(arguments):\n \"\"\"\n Gets client socket according to commandline arguments.\n \"\"\"\n if arguments.family == 'inet':\n sock_family = socket.AF_INET\n address = ('localhost', arguments.port)\n elif arguments.family == 'unix':\n sock_family = sock.AF_LOCAL\n address = (arguments.unix_address,)\n else:\n raise\n client = socket.socket(sock_family, socket.SOCK_STREAM)\n client.connect(address)\n\n return client\n\ndef run_interactive_mode(client_socket):\n while True:\n data = input('In: >>> ')\n client_socket.send(data.encode('ascii'))\n print('Msg: >>> sent {} bytes'.format(len(data)))\n read_data = client_socket.recv(512)\n print('Out: >>> {}'.format(read_data.decode('ascii')))\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Unit test for reading data procedure')\n parser.add_argument('-f', '--family', type=str, help='Socket family (unix|inet)')\n parser.add_argument('-p', '--port', help='Port (in the case of inet socket family)',\n type=int)\n parser.add_argument('-u', '--unix-address', help='Filesystem path of unix socket (for unix socket family)')\n parser.add_argument('-i', '--interactive', help='Run test in interactive mode',\n action = 'store_true')\n \n \n args = parser.parse_args()\n \n client = get_socket_by_args(args)\n\n if args.interactive:\n run_interactive_mode(client)\n \n \n","sub_path":"test/test_read_data.py","file_name":"test_read_data.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"307314293","text":"import matplotlib.pylab as plt\r\nimport numpy as np\r\n\r\nx = np.arange(-8, 8, 0.1)\r\nw = 5.0\r\nb1 = -8.0\r\nb2 = 0.0\r\nb3 = 8.0\r\nl1 = 'b = -8.0'\r\nl2 = 'b = 0.0'\r\nl3 = 'b = 8.0'\r\nfor b, l in [(b1, l1), (b2, l2), (b3, l3)]:\r\n f = 1 / (1 + np.exp(-(x*w+b)))\r\n plt.plot(x, f, label=l)\r\nplt.xlabel('x')\r\nplt.ylabel('h_wb(x)')\r\nplt.legend(loc=2)\r\nplt.show()\r\n\r\n#the w1 has been increased to simulate a more defined “turn on” function.\r\n# by varying the bias “weight” b, you can change when the\r\n# node activates.Therefore, by adding a bias term,\r\n# you can make the node simulate if function, i.e.\r\n# if (x > z) then 1 else 0.\r\n# Without a bias term, you are unable to vary the z\r\n# in that if statement,\r\n# it will be always stuck around 0.\r\n# This is obviously very useful if you are\r\n# trying to simulate conditional relationships.","sub_path":"adventures in ML/neuron_with_bias.py","file_name":"neuron_with_bias.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361890180","text":"# Q.1 check if user input is leap year or not\n# A.1 ->\n\nprint('enter the year to check')\nyear = int(input())\nif year % 4 == 0:\n print('year mentioned IS leap year')\nelse:\n print('year input IS NOT a leap year')\n\n# Q.2 check if square or rectangle\n# A.2 ->\n\nprint('\\n\\n')\nprint('enter the 2 sides of the desired parallelogram')\nside1 = int(input())\nside2 = int(input())\nif side1 == side2:\n print('the parallelogram with desired sides is a SQUARE')\nelse:\n print('the parallelogram with desired sides is a RECTANGLE')\n\n# Q.3 oldest and youngest\n# A.3 ->\n\nprint('\\n\\n')\nprint('enter the required ages of the 3 people')\nage1 = int(input())\nage2 = int(input())\nage3 = int(input())\nif age1 >= age2 and age1 >= age3:\n old = age1\nelif age2 >= age1 and age2 >= age3:\n old = age2\nelse:\n old = age3\nif age1 <= age2 and age1 <= age3:\n young = age1\nelif age2 <= age1 and age2 <= age3:\n young = age2\nelse:\n young = age3\nprint('person with age %d is oldest', old)\nprint('person with age %d is youngest', young)\n\n# Q.4 WORK AREA\n# A.4 ->\n\nprint('\\n\\n')\nprint(\"enter the applicant's age, sex(m/f), and marital status(y/n)\")\nage1 = int(input())\nsex = input()\nm_s = input()\nif sex == 'f' or sex == 'F':\n print('as a FEMALE, applicant is only has access to URBAN AREA WORK')\nelif sex == 'm' or sex == 'M':\n if 20 < age1 < 40:\n print('as a MALE with age %d, applicant has access to WORK ANYWHERE' % age1)\n elif 40 < age1 < 60:\n print('as a MALE with age %d, applicant has access to WORK ANYWHERE' % age1)\nelse:\n print('INVALID INPUT')\n\n# Q.5 COST\n# A.5 ->\n\nprint('\\n\\n')\nprint('enter the number of units you want to purchase, each unit costs 100, you get discount for units worth 1000')\nunits = int(input())\ndiscount = int(units / 10) * 100\ncost = (units * 1000) - discount\nprint('your final cost is %d with %d discount that was implemented' % (cost, discount))\n\n# ''''''' LOOPS '''''''\n\n# Q.1 INPUT 10 INT AND PRINT\n# A.1 ->\n\nprint('\\n\\n')\nn = []\nprint('enter 10 numbers to be displayed on screen')\nfor i in range(0, 10):\n a = int(input())\n n.append(a)\nfor i in range(0, 10):\n print('no: ', n[i])\n\n# Q.2 INFINITE LOOP\n# A.2 ->\n\nprint('\\n\\n')\ni = 1\n#while i > 0:\n# print('infinite')\nprint(\"remove the above given two '#' for an infinite loop\")\n\n# Q.3 LIST2 CONTAINS SQUARE OF ELE OF LIST1\n# A.3 ->\n\nprint('\\n\\n')\nprint('enter the list elements and type -1 for ending input of list 1')\nl1 = []\nl2 = []\ni = int(input())\nwhile i != -1:\n l1.append(i)\n i = int(input())\nfor i in range(0, len(l1)):\n a = int(l1[i] * l1[i])\n l2.append(a)\nprint(l1)\nprint(l2)\n\n# Q.4 list with int,float,str and store then separately\n# A.4 ->\n\nprint('\\n\\n')\nprint('enter the list elements')\nl1 = []\nlint = []\nlflt = []\nlstr = []\ni = 'a'\nwhile str(i) != 'end':\n i = input()\n l1.append(i)\n print(\"to end entering in list enter 'end' otherwise enter next element\")\n i = input()\nfor i in range(0, len(l1)):\n if l1[i].isalpha():\n lstr.append(l1[i])\n elif l1[i].isdecimal():\n lflt.append(l1[i])\n elif l1[i].isnumeric():\n lint.append(l1[i])\nprint('original list: ', l1)\nprint('int list: ', lint)\nprint('float list: ', lflt)\nprint('string list: ', lstr)\n\n# Q.5 using range (1,101) for prime numbers\n# A.5 ->\n\nprint('\\n\\n')\nl1 = []\nfor i in range(1, 101):\n flag = True\n for j in range(2, int(i/2)+1):\n if i % j == 0:\n flag = False\n continue\n if flag:\n l1.append(i)\nprint(l1)\n\n# Q.6 PRINT PATTERN\n# A.6 ->\n\nprint('\\n\\n')\nfor i in range(1, 6):\n print('*' * i)\n\n# Q.7 USER LIST, DELETING ELE USING FOR\n# A.7 ->\n\nprint('\\n\\n')\nprint('enter the list elements and type \"end\" for ending input of list 1')\nl1 = []\ni = input()\nwhile i != 'end':\n l1.append(i)\n i = input()\ntest = input('enter the element you want to search and delete\\n')\ncount = len(l1)\nfor i in range(0, count):\n if l1[i] == test:\n del l1[i]\n count -= 1\nprint(l1)\n","sub_path":"Assignment5/assignment5.py","file_name":"assignment5.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385323866","text":"import numpy as np \nimport math\nfrom keras.datasets import mnist\n\n#convert the input data into batchs\ndef init_batch(inputs, batch_size):\n num_full_batch = len(inputs[0]) // batch_size\n batchs = []\n for i in range(num_full_batch):\n batchs.append(inputs[:,i * batch_size : (i+1) * batch_size])\n if len(inputs[0]) % batch_size:\n batchs.append(inputs[:, num_full_batch * batch_size :])\n return np.asarray(batchs)\n# print(init_batch(x_train_flatten, BATCH_SIZE))\n\n#Initialize parameters\ndef init_parameters(layers):\n ''' Initilize the parameters of each layer\n In this case, we only have input layer(28*28) and output layer(1) \n '''\n parameters = []\n for layer in range(1, len(layers)):\n # print(len(layers))\n # print(layers[layer])\n parameters.append(np.zeros((layers[layer], layers[layer - 1])))\n # print(parameters[0].shape)\n return parameters\n\n# parameters = init_parameters(layers)\n# print(len(parameters))\n\n#forward propagation using only logistic regression function\ndef sigmoid(X, w):\n z = np.dot(w, X)\n # print(z[0][:2])\n res = 1 / (1 + np.exp(-z))\n # print(res[0][:5])\n # samples = [i for i in res[0] if i == 0]\n # print(samples)\n return res \n\n# print(sigmoid(x_train_flatten[:, 1], parameters[0]))\n\ndef mean_square_cost(X, A, Y):\n m = Y.shape[1] \n cost = (1 / m) * np.sum(np.square(A - Y))\n dw = (1 / m) * np.dot(X, (2 * (A - Y) * A * (1 - A)).T)\n return cost, dw\n \ndef corss_entropy_cost(X, A, Y):\n m = Y.shape[1]\n # print(m)\n cost = (-1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A)))\n dw = (1 / m) * np.dot(X, (A - Y).T)\n return cost, dw\n\ndef predict(classifiers, X):\n outputs = []\n for parameter in classifiers:\n outputs.append(sigmoid(X, parameter[0]))\n return np.argmax(outputs, axis=0)\n\ndef one_hot(Y): # (1, 60000) to (10, 60000)\n res = []\n for num in Y[0]:\n entry = np.zeros(10)\n entry[num] = 1\n res.append(entry)\n res = np.asarray(res)\n return res.T\n\ndef softmax(Z): # (10, num_of_examples)\n exps = np.exp(Z)\n return exps / np.sum(exps, axis=0) #compute softmax based on rows\n\ndef multiclass_cross_entropy(Z, Y):\n Y = Y.T \n Z = Z.T\n m = Y.shape[0]\n p = softmax(Z)\n log_likelihood = -np.log(p[range(m), Y])\n loss = np.sum(log_likelihood) / m\n return loss\n\n \n# Y = np.asarray([[1,2,3]])\n# res = one_hot(Y)\n# print(res)\n# x = np.random.randn(3, 5)\n# print(softmax(x))\n\n \n \n\n\n\n\n\n\n\n\n\n \n\n\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"647305629","text":"from nltk.stem.lancaster import LancasterStemmer\nimport re, os, pickle, nltk, WordNet\nfrom nltk.corpus import wordnet as w\nfrom nltk.stem.lancaster import LancasterStemmer\nfrom collections import defaultdict\nimport dicts, math\nfrom nltk.book import text2\n\ntext = \" \".join(text2.tokens)\n\n# parameters\nadj_factor = 0.6\t\t\t# how strongly adjectives are weighted\nadv_factor = 0.4\t\t\t# how strongly adverbs are weighted\nver_factor = 0.7\t\t\t# how strongly verbs are weighted\nhyp_factor = 0.0\t\t\t# how strongly hyponyms are added to their hypernyms\ncorpus_length = 2500000\t\t# actual length: I don't know\nsyn_factor = 0.1\t\t\t# how strongly synynoms are added to their synonyms\n\nwnp = WordNet.WordNetParser()\n \ndef getwords(text):\n text = text.lower()\n for abbr in dicts.abbrs.keys():\n text = text.replace(\" \"+abbr.lower(),\" \"+dicts.abbrs[abbr].lower())\n words = re.findall('[a-z]{2,}(?:(?:\\-|\\')[a-z]+)*', text)\n return words\n \ndef getrelfreqtext(all_words):\n words = {}\n sum_words = len(all_words)\n for word in all_words:\n if word in words:\n words[word] = words[word] + (1.0/sum_words)\n else:\n words[word] = 1.0/sum_words\n return words\n \ndef comparetextcorpus(relwordfreqtext,wordtags):\n file = open('ukcorpusrel.txt','r')\n corpus = pickle.load(file)\n file.close()\n pos = ['JJ','JJR','JJS','NN','NNS','RB','RBR','RBS','VB','VBD','VBG','VBN','VBP','VBZ']\n freqs = {}\n for word in relwordfreqtext:\n if word in wordtags and wordtags[word] in pos:\n if word in corpus:\n freqs[word] = relwordfreqtext[word] / corpus[word]\n else:\n freqs[word] = relwordfreqtext[word] / (1.0/corpus_length)\n return freqs \n \ndef getstems(dict):\n l = LancasterStemmer()\n stems = {}\n for word in dict:\n if word in dicts.irregforms:\n stems[word] = l.stem(dicts.irregforms[word])\n else:\n stems[word] = l.stem(word)\n return stems \n \ndef morphology(dict,stems):\n stemvalues = {}\n \n for word in dict:\n if stems[word] in stemvalues:\n stemvalues[stems[word]] = stemvalues[stems[word]] + dict[word]\n else:\n stemvalues[stems[word]] = dict[word] \n for word in dict:\n dict[word] = stemvalues[stems[word]]\n return dict\n\ndef NNStoNN(word):\n noun = word\n if word.endswith('ies'):\n noun = re.sub(r'ies$',r'y',word)\n elif word.endswith('ves'):\n noun = re.sub(r'ves$',r'fe',word) \n elif word.endswith('es'):\n noun = re.sub(r'es$',r'',word)\n elif word.endswith('s'):\n noun = re.sub(r's$',r'',word) \n return noun\n \ndef JJRtoNN(word):\n positive = word\n if word in dicts.irregforms:\n positive = dicts.irregforms[word]\n elif word.endswith('ier'):\n positive = re.sub(r'ier$',r'y',word)\n elif word.endswith('er'):\n if len(word)>4 and word[len(word)-4]==word[len(word)-3]:\n positive = word[:len(word)-3]\n else:\n positive = word[:len(word)-2]\n return positive\n \ndef JJStoNN(word):\n positive = word\n if word in dicts.irregforms:\n positive = dicts.irregforms[word]\n elif word.endswith('iest'):\n positive = re.sub(r'iest$',r'y',word)\n elif word.endswith('est'):\n if len(word)>5 and word[len(word)-5]==word[len(word)-4]:\n positive = word[:len(word)-4]\n else:\n positive = word[:len(word)-3]\n return positive\n\ndef RBtoNN(word):\n adjective = word\n if word.endswith('ily'):\n adjective = re.sub(r'ily',r'y',word)\n elif word.endswith('ly'):\n adjective = adjective[:len(word)-2]\n return adjective \n \ndef RBRtoNN(word):\n adverb = word\n if word in dicts.irregforms:\n adverb = dicts.irregforms[word]\n elif word.endswith('ier'):\n adverb = re.sub(r'ier$',r'y',word)\n elif word.endswith('er'):\n if len(word)>4 and word[len(word)-4]==word[len(word)-3]:\n adverb = word[:len(word)-3]\n else:\n adverb = word[:len(word)-2]\n return RBtoNN(adverb) \n \ndef RBStoNN(word):\n adverb = word\n if word in dicts.irregforms:\n adverb = dicts.irregforms[word]\n elif word.endswith('iest'):\n adverb = re.sub(r'iest$',r'y',word)\n elif word.endswith('est'):\n if len(word)>5 and word[len(word)-5]==word[len(word)-4]:\n adverb = word[:len(word)-4]\n else:\n adverb = word[:len(word)-3]\n return RBtoNN(adverb) \n \ndef VBDtoNN(word): # past\n verb = word\n if word in dicts.irregforms:\n verb = dicts.irregforms[word]\n elif word.endswith('ed'):\n if len(word)>4 and word[len(word)-4]==word[len(word)-3]:\n verb = word[:len(word)-3]\n else:\n verb = word[:len(word)-2]\n return verb\n \ndef VBGtoNN(word): # gerund\n verb = word\n if word.endswith('ing'):\n if len(word)>5 and word[len(word)-5]==word[len(word)-4]:\n verb = word[:len(word)-4]\n else:\n verb = word[:len(word)-3]\n if verb.endswith('v'):\n verb = verb + 'e' \n return verb \n \ndef VBNtoNN(word): # past participle\n verb = word\n if word in dicts.irregforms:\n verb = dicts.irregforms[word]\n elif word.endswith('ed'):\n return VBDtoNN(verb)\n return verb\n \ndef VBZtoNN(word): # 3rd pers sing pres\n verb = word\n if word in dicts.irregforms:\n verb = dicts.irregforms[word]\n elif word.endswith('ies'):\n verb = re.sub(r'ies$',r'y',word)\n elif word.endswith('s'):\n verb = word[:len(word)-1] \n return verb\n\ndef getsinglenouns(dict,tags):\n nouns = {}\n verbs = {}\n adjadv = {}\n for word in dict:\n if word not in tags:\n continue\n elif tags[word]=='NN':\n nouns[word] = word\n elif tags[word]=='NNS':\n nouns[word] = NNStoNN(word)\n elif tags[word]=='JJ':\n adjadv[word] = word\n elif tags[word]=='JJR':\n adjadv[word] = JJRtoNN(word)\n elif tags[word]=='JJS':\n adjadv[word] = JJStoNN(word) \n elif tags[word]=='RB':\n adjadv[word] = RBtoNN(word) \n elif tags[word]=='RBR':\n adjadv[word] = RBRtoNN(word) \n elif tags[word]=='RBS':\n adjadv[word] = RBStoNN(word) \n elif tags[word]=='VB' or tags[word]=='VBP':\n verbs[word] = word \n elif tags[word]=='VBD':\n verbs[word] = VBDtoNN(word) \n elif tags[word]=='VBG':\n verbs[word] = VBGtoNN(word) \n elif tags[word]=='VBN':\n verbs[word] = VBNtoNN(word) \n elif tags[word]=='VBZ':\n verbs[word] = VBZtoNN(word) \n return (nouns,adjadv,verbs)\n \ndef normalize(dict):\n maximum = max(dict.values())\n minimum = min(dict.values())\n for entry in dict:\n dict[entry] = math.log(((dict[entry]-minimum)*(9/(maximum-minimum)))+1)\n return dict \n\ndef synonymshypernyms(morphequal):\n nouns_syns = {}\n for key in morphequal:\n nouns_syns[key] = []\n syns = wnp.do_synonyms(key)\n for syn in syns:\n if syn in morphequal:\n nouns_syns[key].append(morphequal[syn])\n \n for key in morphequal:\n for i in range(0,len(nouns_syns[key])):\n morphequal[key] = morphequal[key] + (nouns_syns[key][i]*syn_factor)\n return morphequal\n \ndef getposbias(words,tags): \n for word in words:\n if word in tags:\n if tags[word].startswith('JJ'):\n words[word] = adj_factor*words[word]\n elif tags[word].startswith('RB'):\n words[word] = adv_factor*words[word]\n elif tags[word].startswith('VB'):\n words[word] = ver_factor*words[word]\n return words \n\ndef getwordpriority(text):\n words = getwords(text)\n relwordfreqtext = getrelfreqtext(words)\n wordtags = tagger(relwordfreqtext) \n relwordfreqcompared = comparetextcorpus(relwordfreqtext,wordtags)\n stems = getstems(relwordfreqcompared) \n morphequal = morphology(relwordfreqcompared,stems) \n posbias = getposbias(morphequal,wordtags) \n synohyps = synonymshypernyms(posbias) \n return normalize(synohyps)\n\ndef tagger(dict):\n\tfile = open('taggerdump.txt','w')\n\tfor key in dict:\n\t file.write(key+'\\n')\n\tfile.close()\n\tos.system('cmd/tree-tagger-english taggerdump.txt > taggerdump2.txt')\n\tfile = open('taggerdump2.txt','r')\n\tdict = {}\n\tfor line in file.readlines():\n\t\tl = re.search(r'^([a-zA-Z]{2,})\\s+([A-Z]+)\\s',line)\n\t\tif l:\n\t\t\tdict[l.group(1)] = l.group(2)\n\treturn dict\n\t\n#if __name__ == '__main__':\n # wordpriority = getwordpriority(text) \n # \n # items = [(v, k) for k, v in wordpriority.items()]\n #items.sort()\n #items.reverse()\n #items = [(k, v) for v, k in items]\n #count = 0\n #for k,v in items:\n # print \"%s: %1.20f\" % (k,v)\n","sub_path":"code/getwordpriority.py","file_name":"getwordpriority.py","file_ext":"py","file_size_in_byte":9193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"58667216","text":"# -*- coding:utf-8 -*-\n\nclass Reverse:\n\n def reverseSentence(self, A, n):\n # 句子整体逆序\n tmp_s=self.reverse(A,0,n-1)\n # 单词逆序\n l=0\n r=-1\n for i in range(n-1):\n if tmp_s[i] != ' ':\n r=i-1\n self.reverse(tmp_s,l,r)\n l=i+1\n elif i==n-1:\n r=i\n self.reverse(tmp_s,l,r)\n return tmp_s\n\n def reverse(self, s, start, end):\n for i in range(start, end):\n tmp = s[start]\n s[start] = s[end]\n s[end] = tmp\n start += 1\n end -= 1\n return s\n","sub_path":"String/Reverse.py","file_name":"Reverse.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"363672837","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nface_cascade = cv2.CascadeClassifier('/home/ansuman/DIP/lensflare/haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('/home/ansuman/DIP/lensflare/haarcascade_eye.xml')\n\nlf = cv2.imread(\"/home/ansuman/Downloads/lensf1.jpg\")\nuser = cv2.imread(\"/home/ansuman/Downloads/Dicaprio.jpg\")\ngray_user = cv2.cvtColor(user, cv2.COLOR_BGR2GRAY)\n\nfaces = face_cascade.detectMultiScale(gray_user, 1.3, 5)\nfor (x,y,w,h) in faces:\n roi_gray = gray_user[y:y+h,x:x+w]\n eyes = eye_cascade.detectMultiScale(roi_gray)\n for (ex,ey,ew,eh) in eyes:\n ew=ew+400\n eh=eh+400\n ey=ey-202\n ex=ex-206\n #cv2.rectangle(roi_gray,(ex,ey),(ex+ew,ey+eh),(0,0,255),3)\n \n # resizing & paste the lf image on user\n roi_eye = user[y+ey:y+ey+eh,x+ex:x+ex+ew]\n resized_lensflare = cv2.resize(lf,(eh,ew)) \n \n # making fg,bg and alpha\n fg = resized_lensflare.copy()\n alpha = fg.copy()\n bg = roi_eye.copy()\n \n # converting uint8 to float\n fg = fg.astype(float)\n bg = bg.astype(float)\n \n # Normalizing the alpha mask to keep intensity between 0 and 1\n alpha = alpha.astype(float)/255\n \n fg = cv2.multiply(alpha,fg)\n bg = cv2.multiply(1.0 - alpha,bg)\n final = cv2.add(fg,bg)\n \n user[y+ey:y+ey+eh,x+ex:x+ex+ew] = final\n\ncv2.imshow(\"image\",user)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"lensflare.py","file_name":"lensflare.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370491315","text":"\r\n#from NDList_iterator import *\r\n\r\nclass NDList:\r\n\r\n # # # # # # # # # # # # #\r\n # Static Functions #\r\n # # # # # # # # # # # # #\r\n\r\n # Function Overview:\r\n # -> createNDList([2, 2, 2])\r\n # -> flattnList(targetList)\r\n # -> getListDimensions(targetList)\r\n # -> getItem(targetList, indecies)\r\n # -> setItem(targetList, indecies, value)\r\n # -> addRowToDimension(targetList, indexOfDimension)\r\n # -> removeRowFromDimension(targetList, indexOfDimension)\r\n # -> insertDimensionToList(targetList, indexOfDimension, rowsToCreate)\r\n # -> removeDimensionFromList(targetList, indexOfDimension)\r\n # -> applyFunction(targetList, functionToApply)\r\n\r\n\r\n\r\n # Creates A Multidimensional List Based On The Paramters\r\n # @Params: -dimensions = a list describing the dimensions\r\n # [2, 2, 2] would create a 3D List\r\n # made up of lists witch each 2 sublists\r\n # -depth is used for recusion so initially 0\r\n # @Return: -A Multidimensional List\r\n @staticmethod\r\n def createNDList(dimensions):\r\n # Early Error Catching:\r\n if len(dimensions) == 0:\r\n return []\r\n\r\n # Do The Recursion\r\n return NDList._createNDList(dimensions, 0)\r\n\r\n\r\n # USED INTERNALLY\r\n # Creates A Multidimensional List Based On The Paramters\r\n # @Params: -dimensions = a list describing the dimensions\r\n # [2, 2, 2] would create a 3D List\r\n # made up of lists witch each 2 sublists\r\n # -depth is used for recusion so initially 0\r\n # @Return: -A Multidimensional List\r\n @staticmethod\r\n def _createNDList(dimensions, depth):\r\n\r\n # defines what to do on the data level\r\n if len(dimensions)-1 == depth:\r\n return [0 for x in range(dimensions[-1])]\r\n\r\n # creates the parent list that holds inner lists\r\n subLists = []\r\n for i in range(dimensions[depth]):\r\n subLists.append(NDList._createNDList(dimensions, depth+1))\r\n return subLists\r\n\r\n\r\n # Reduces N Dimensions To 1\r\n # @Params: -targetList = the list to boil down\r\n # @Return: -the fattend list\r\n @staticmethod\r\n def flattnList(targetList):\r\n # Early Error Catching:\r\n if len(targetList) == 0:\r\n return []\r\n\r\n # Do The Recursion\r\n return NDList._flattnList(targetList)\r\n\r\n # USED INTERNALLY\r\n # Reduces N Dimensions To 1\r\n # @Params: -targetList = the list to boil down\r\n # @Return: -the fattend list\r\n @staticmethod\r\n def _flattnList(targetList):\r\n # Is The Content Of The List Data Return The Itself\r\n if not isinstance(targetList[0], list):\r\n return targetList\r\n\r\n # Otherwise Create A Parent List And Join Flattend Sublists Together\r\n lists = []\r\n for l in targetList:\r\n lists += NDList._flattnList(l)\r\n return lists\r\n\r\n\r\n\r\n # Returns The Content At That Position\r\n # @Params: -targetList = the list to use\r\n # -indecies = e.g. [2, 2, 2] means look for the item in the\r\n # second list of the second list\r\n # @Return: -an item\r\n @staticmethod\r\n def getItem(targetList, indecies):\r\n # Early Error Catching:\r\n if len(targetList) == 0:\r\n raise Exception(\"Can't return an item from an empy list\")\r\n\r\n # Do The Recusion\r\n return NDList._getItem(targetList, indecies, 0)\r\n\r\n\r\n # USED INTERNALLY\r\n # Returns The Content At That Position\r\n # @Params: -targetList = the list to use\r\n # -indecies = e.g. [2, 2, 2] means look for the item in the\r\n # second list of the second list\r\n # -depth is used for recusion and initially 0\r\n # @Return: -an item\r\n @staticmethod\r\n def _getItem(targetList, indecies, depth):\r\n # If It Is The Last Dimension Return The Content At That Position\r\n if len(indecies)-1 == depth:\r\n # Error Catching:\r\n if isinstance(targetList[0], list):\r\n raise Exception(\"The specified indecies don't point to a value but a list\")\r\n\r\n # Return The Item\r\n return targetList[indecies[depth]]\r\n\r\n # Error Catching:\r\n if not isinstance(targetList[0], list):\r\n raise Exception(\"The specified indecies overstep the dimensions of the list\")\r\n\r\n # Otherwise Go Deeper And Ask The Inner List To Get It's Content\r\n return NDList._getItem(targetList[indecies[depth]], indecies, depth +1)\r\n\r\n\r\n\r\n # Set The Content At That Position To A Specific Value\r\n # @Params: -targetList = the list to search\r\n # -indecies = e.g. [2, 2, 2] means use the item in the\r\n # second list of the second list\r\n # -value = the value to set the list index to\r\n # @Return: -void\r\n @staticmethod\r\n def setItem(targetList, indecies, value):\r\n # Early Error Catching:\r\n if len(targetList) == 0:\r\n raise Exception(\"Can't set an item in a empty list\")\r\n\r\n # Do The Recursion\r\n NDList._setItem(targetList, indecies, value, 0)\r\n\r\n\r\n # USED INTERNALLY\r\n # Set The Content At That Position To A Specific Value\r\n # @Params: -targetList = the list to search\r\n # -indecies = e.g. [2, 2, 2] means use the item in the\r\n # second list of the second list\r\n # -value = the value to set the list index to\r\n # -depth is used for recusion and initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def _setItem(targetList, indecies, value, depth):\r\n # If It Is The Last Dimension Set The Value At That Position In The List\r\n if len(indecies)-1 == depth:\r\n # Error Catching:\r\n if isinstance(targetList[0], list):\r\n raise Exception(\"The specified indecies don't point to a value but a list\")\r\n # Set The Value\r\n targetList[indecies[depth]] = value\r\n return\r\n\r\n # Error Catching:\r\n if not isinstance(targetList[0], list):\r\n raise Exception(\"The specified indecies overstep the dimensions of the list\")\r\n\r\n # Otherwise Go Deeper And Ask The Inner List To Get It's Content\r\n NDList._setItem(targetList[indecies[depth]], indecies, value, depth+1)\r\n\r\n\r\n # Gives The Dimensions Of A List Of Unspecified Dimensions\r\n # @Params: -targetList = the list to use\r\n # @Return: -a list containing the dimensions\r\n # [2, 2] -> means 2 Dimensions with each 2 rows\r\n @staticmethod\r\n def getListDimensions(targetList):\r\n # Earyl Error Catching;\r\n if len(targetList) == 0:\r\n return []\r\n # Do The Actual Recursion\r\n return NDList._getListDimensions(targetList)\r\n\r\n # USED INTERNALLY\r\n # Gives The Dimensions Of A List Of Unspecified Dimensions\r\n # @Params: -targetList = the list to use\r\n # @Return: -a list containing the dimensions\r\n # [2, 2] -> means 2 Dimensions with each 2 rows\r\n @staticmethod\r\n def _getListDimensions(targetList):\r\n # Is The Content Of This A List Then Go Deeper\r\n if isinstance(targetList[0], list):\r\n return [len(targetList)] + NDList._getListDimensions(targetList[0])\r\n\r\n # If It Is The End Return The Length Of The Current Target List\r\n return [len(targetList)]\r\n\r\n\r\n # Adds Another Row To The Specified Dimension\r\n # @Params: -targetList = the list to modify\r\n # -targetDimensionIndex = the dimensions to add more to\r\n # @Return: -void\r\n @staticmethod\r\n def addRowToDimension(targetList, targetDimensionIndex):\r\n # Early Error Catching:\r\n if len(targetList) == 0:\r\n raise Exception(\"Can't add a row to an empy list\")\r\n if targetDimensionIndex < 0:\r\n raise Exception(\"Can't add a row to target dimension: \" + str(targetDimensionIndex))\r\n\r\n dimensionsOfList = NDList.getListDimensions(targetList)\r\n if len(dimensionsOfList)-1 <= targetDimensionIndex:\r\n raise Exception(\"Can't add a row on the data level -> (len(getListDimensions(targetList)) = \"\r\n + str(len(dimensionsOfList)) + \") is equal to (targetDimensionIndex = \"\r\n + str(targetDimensionIndex) + \")\")\r\n\r\n # Do The Actual Recursion\r\n NDList._addRowToDimension(targetList, targetDimensionIndex, dimensionsOfList, 0)\r\n\r\n # USED INTERNALLY\r\n # Adds Another Row To The Specified Dimension\r\n # @Params: -targetList = the list to modify\r\n # -targetDimensionIndex = the dimensions to add more to\r\n # -dimensions = the list of all dimensionss of that n d list\r\n # -depth for recursion initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def _addRowToDimension(targetList, targetDimensionIndex, dimensions, depth):\r\n\r\n # Create Sublists With The Same Structure As The Others And Add It As Row\r\n # To The Target Dimension\r\n if depth == targetDimensionIndex:\r\n # Create SubLists With Same Structure And Add Them\r\n subLists = NDList.createNDList(dimensions[depth+1:])\r\n targetList.append(subLists)\r\n return\r\n\r\n # go deeper in all sub lists until the desired dimention is reached\r\n for innerList in targetList:\r\n NDList._addRowToDimension(innerList, targetDimensionIndex, dimensions, depth+1)\r\n\r\n\r\n\r\n # Removes A Row From The Specified Dimension\r\n # @Params: -targetList = the list to modify\r\n # -targetDimensionIndex = the dimention where a row should be removed\r\n # @Return: -void\r\n @staticmethod\r\n def removeRowFromDimension(targetList, targetDimensionIndex):\r\n # Early Error Catching:\r\n if len(targetList) == 0:\r\n raise Exception(\"Can't remove row if list is empty\")\r\n if targetDimensionIndex < 0:\r\n raise Exception(\"Can't remove row in target dimension: \" + str(targetDimensionIndex))\r\n\r\n # Do The Actual Recursion\r\n NDList._removeRowFromDimension(targetList, targetDimensionIndex, 0)\r\n\r\n\r\n # USED INTERNALLY\r\n # Removes A Row From The Specified Dimension\r\n # @Params: -targetList = the list to modify\r\n # -targetDimensionIndex = the dimention where a row should be removed\r\n # -depth is used for recursion initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def _removeRowFromDimension(targetList, targetDimensionIndex, depth):\r\n # In The Parent Of The Desired Dimension Loop Through All Children\r\n # To Remove Their Last Child\r\n\r\n if depth == targetDimensionIndex:\r\n # Error Catching:\r\n if not isinstance(targetList, list):\r\n raise Exception(\"Choose a dimension that has sublists to remove\")\r\n # Remove The Last Element From The List\r\n targetList.pop()\r\n return\r\n\r\n # Go Deeper on all subLists\r\n for innerList in targetList:\r\n NDList._removeRowFromDimension(innerList, targetDimensionIndex, depth+1)\r\n\r\n\r\n # Inserts A New Dimension To The Specified Depth\r\n # @Params: -targetList = the list to modify\r\n # -targetDimensionIndex = the dimension where to create a new one at\r\n # -rowsOfNewDimension = amount of rows to be added to the inserted dimension\r\n # -depth is used for recursion initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def insertDimensionToList(targetList, targetDimensionIndex, rowsOfNewDimension):\r\n # Early Error Catching:\r\n if targetDimensionIndex < 0:\r\n raise Exception(\"Can't insert to \" + str(targetDimensionIndex) + \" dimension\")\r\n if rowsOfNewDimension < 1:\r\n raise Exception(\"Can't create \" + str(rowsOfNewDimension) + \" many rows\")\r\n # Do The Actual Recursion\r\n NDList._insertDimensionToList(targetList, targetDimensionIndex, rowsOfNewDimension, 0)\r\n\r\n # USED INTERNALLY\r\n # Inserts A New Dimension To The Specified Depth\r\n # @Params: -targetList = the list to modify\r\n # -targetDimensionIndex = the dimension where to create a new one at\r\n # -rowsOfNewDimension = amount of rows to be added to the inserted dimension\r\n # -depth is used for recursion initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def _insertDimensionToList(targetList, targetDimensionIndex, rowsOfNewDimension, depth):\r\n # If Dove Deep Enough, Make A Copy Of The Sublists, Clear Current Lists,\r\n # Add Rows To That Dimension, Add Saved Sublists To The Rows\r\n\r\n if depth == targetDimensionIndex:\r\n # Error Catching\r\n if not isinstance(targetList, list):\r\n raise Exception(\"Can't insert a new dimension on the data level\")\r\n\r\n # Encapsulate In New List\r\n save = list(targetList)\r\n targetList.clear()\r\n for l in range(rowsOfNewDimension):\r\n targetList.append(list(save))\r\n return\r\n\r\n # Dive Deeper On All Sublists\r\n for innerList in targetList:\r\n NDList._insertDimensionToList(innerList, targetDimensionIndex, rowsOfNewDimension, depth+1)\r\n\r\n\r\n # Removes A Dimension From At A Specified Depth\r\n # @Params: -targetList = list to modify\r\n # -targetDimensionIndex = the dimension to be removed\r\n # @Return: -void\r\n @staticmethod\r\n def removeDimensionFromList(targetList, targetDimensionIndex):\r\n # Early Error Catching\r\n if targetDimensionIndex == 0:\r\n raise Exception(\"Can't Remove The First Dimension\")\r\n # Do The Recursion\r\n NDList._removeDimensionFromList(targetList, targetDimensionIndex, 0)\r\n\r\n # USED INTERNALLY\r\n # Removes A Dimension From At A Specified Depth Except 0\r\n # @Params: -targetList = list to modify\r\n # -targetDimensionIndex = the dimension to be removed\r\n # -depth for recursion initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def _removeDimensionFromList(targetList, targetDimensionIndex, depth):\r\n # Is It The Parent Of The Desired Dimension\r\n if depth == targetDimensionIndex-1:\r\n # Early Error Catching\r\n if not isinstance(targetList[0][0], list):\r\n raise Exception(\"Can't remove a row on the data level\")\r\n\r\n # Save Sublists Of Target Dimensions\r\n targetDimensionSave = [list(subList) for innerList in targetList for subList in innerList ]\r\n # Remove All From Parent\r\n targetList.clear()\r\n # Add All Saved Sublists To The Parent\r\n for saved in targetDimensionSave:\r\n targetList.append(saved)\r\n return\r\n\r\n # Go Deeper\r\n for l in targetList:\r\n NDList._removeDimensionFromList(l, targetDimensionIndex, depth+1)\r\n\r\n\r\n # Applies A Function On The Data\r\n # @Params: -targetList = the list to go over\r\n # -function = the function to apply\r\n # @Return: -void\r\n @staticmethod\r\n def applyFunction(targetList, function):\r\n # Early Error Catching:\r\n if len(targetList) == 0:\r\n raise Exception(\"Can't applyFunction a function to an empty list\")\r\n\r\n return NDList._applyFunction(targetList, function, 0)\r\n\r\n # USED INTERNALLY\r\n # Applies A Function On The Data\r\n # @Params: -targetList = the list to go over\r\n # -function = the function to apply\r\n # -depth = used for recursion initially 0\r\n # @Return: -void\r\n @staticmethod\r\n def _applyFunction(targetList, function, depth):\r\n # if it is the list containing data apply the function on it\r\n if not isinstance(targetList[0], list):\r\n for data in targetList:\r\n function(data)\r\n return\r\n\r\n # Otherwise Go Deeper In All Sublists\r\n for l in targetList:\r\n NDList._applyFunction(l, function, depth+1)\r\n\r\n\r\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\n\r\n # # # # # # # # # # # # #\r\n # Class Definition #\r\n # # # # # # # # # # # # #\r\n\r\n\r\n def __init__(self, data = None, dimensions = None):\r\n if not data == None:\r\n self.data = data\r\n self.dimensions = NDList.getListDimensions(data)\r\n elif not dimensions == None:\r\n self.data = NDList.createNDList(dimensions)\r\n self.dimensions = dimensions\r\n\r\n\r\n def __iter__(self):\r\n return NDList.Iterator(self.data)\r\n\r\n def __str__(self):\r\n return self._toString(self.data)\r\n\r\n\r\n # Overrides get function to return an item in the specified location\r\n # @Usage: nameOfList[ indecies ] -> nameOfList[ [1, 1, 0] ]\r\n # @Params: -indecies = list of integers pointing to the data\r\n # @Return: -data at that location\r\n def __getitem__(self, indecies):\r\n return NDList.getItem(self.data, indecies)\r\n\r\n # Overrides set function to set a item in the specified location\r\n # @Usage: nameOfList[ indecies ] = value-> nameOfList[ [1, 1, 0] ] = 10\r\n # @Params: -indecies = list of integers pointing to the data\r\n # -value = the value to set that position to\r\n # @Return: void\r\n def __setitem__(self, indecies, value):\r\n NDList.setItem(self.data, indecies, value)\r\n\r\n # Returns a list that contains\r\n # the amount of rows for each dimension\r\n def getDimensions(self):\r\n return NDList.getListDimensions(self.data)\r\n\r\n # Adds A Row To The Specified Dimension\r\n def addRow(self, targetDimensionIndex):\r\n NDList.addRowToDimension(self.data, targetDimensionIndex)\r\n\r\n # Removes A Row From The Specified Dimension\r\n def removeRow(self, targetDimensionIndex):\r\n NDList.removeRowFromDimension(self.data, targetDimensionIndex)\r\n\r\n # Inserts A New Dimension With The Specified Amount Of Rows\r\n # In To The Specified Dimension While Keeping The Previous\r\n # Substructure\r\n def insertDimension(self, targetDimensionIndex, amountOfRows):\r\n NDList.insertDimensionToList(self.data, targetDimensionIndex, amountOfRows)\r\n\r\n # Removes The Specified Dimension While Keeping The Substructure\r\n def removeDimension(self, targetDimensionIndex):\r\n NDList.removeDimensionFromList(self.data, targetDimensionIndex)\r\n\r\n # Applies A Function To Values In The List\r\n def apply(self, function):\r\n NDList.applyFunction(self.data, function)\r\n\r\n # Reduces N Dimensions To 1\r\n def flattn(self):\r\n return NDList.flattnList(self.data)\r\n\r\n # Usedd Internally for recursion\r\n def _toString(self, innerList, depth = 0):\r\n buff = '[ \\n'\r\n\r\n # Is The Content Not A List\r\n if not isinstance(innerList[0], list):\r\n return innerList.__str__()\r\n\r\n for l in innerList:\r\n buff += '\\t'*(depth+1) + self._toString(l, depth = depth+1) + '\\n'\r\n\r\n buff += '\\t'*depth + '] \\n'\r\n return buff\r\n\r\n\r\n\r\n\r\n # # # # # # # # # # # # #\r\n # Iterator For ND Lists #\r\n # # # # # # # # # # # # #\r\n\r\n\r\n class Iterator:\r\n\r\n def __init__(self, data):\r\n # Take The List Object And Get It's Dimensions\r\n self.data = data\r\n self.dimensions = NDList.getListDimensions(data)\r\n\r\n # Reset The Loop Index\r\n self.loopIndex = [0 for x in range(len(self.dimensions))]\r\n # Max To Iterate to\r\n self.maxLoopIndex = [x-1 for x in self.dimensions]\r\n # Put List Pointer To The First Value\r\n self._jumpTo(self.data, list(self.loopIndex))\r\n # The Flag If The Iteration Is Finished\r\n self.isFinished = False\r\n # Return The Iterator Object\r\n\r\n def __iter__(self):\r\n '''\r\n Called by the for loop to create an iterator\r\n (something that implemented next())\r\n '''\r\n return self\r\n\r\n def __next__(self):\r\n ''' Called by the for loop to get he data '''\r\n\r\n # When The Max Loop Index Is Overstepped Raise The Stop Iteration\r\n if self.isFinished:\r\n raise StopIteration()\r\n\r\n # Set The Flag If The Last Item Is Reached\r\n if self.loopIndex == self.maxLoopIndex:\r\n self.isFinished = True\r\n\r\n # Get The Value For The Index\r\n returnValue = self.innerList\r\n returnLoopIndex = self.loopIndex\r\n\r\n # Only If It Is Not Finished Get The Next Index\r\n if not self.isFinished:\r\n # Increase The Loop Index And Manage The Correct Size\r\n self._getNext()\r\n # Set The InnerList Pointer To The New LoopIndex\r\n self._jumpTo(self.data, list(self.loopIndex))\r\n\r\n # Return The Values To Be Received In The Loop\r\n return returnLoopIndex, returnValue\r\n\r\n\r\n def _resetListIndex(self, targetList):\r\n ''' Jumps To The First value Element In The List '''\r\n if not isinstance(targetList[0], list):\r\n self.innerList = targetList\r\n return\r\n self._resetListIndex(targetList[0])\r\n\r\n def _getNext(self):\r\n ''' Manages The Loop Index '''\r\n # Count Up The Highest Dimension\r\n self.loopIndex[-1] += 1\r\n\r\n # Check From Highest To Lowest If The Index Is As Big As The Dimension\r\n # That Means That There Are No More Rows In That Dimension\r\n # Therefore Count Up The Lower Dimension And Zero Out All Following\r\n # The For Loop Starts At The End And Corrects The LoopIndex Iteration By Iteration\r\n for loopPos, maxLoopPos in zip(range(len(self.loopIndex)-1, -1, -1), range(len(self.maxLoopIndex)-1, -1, -1)):\r\n # Only Do The Correction If It Is Not Allready The Lowest Dimension\r\n if self.loopIndex[loopPos] > self.maxLoopIndex[maxLoopPos]:\r\n if not loopPos == 0:\r\n # Count Up On The Lower Dimension\r\n self.loopIndex[loopPos-1] += 1\r\n # Null Out The Higher Dimensions\r\n for i in range(loopPos, len(self.loopIndex)):\r\n self.loopIndex[i] = 0\r\n\r\n\r\n def _jumpTo(self, subList, indecies):\r\n if not len(indecies) == 0:\r\n self._jumpTo(subList[indecies.pop(0)], indecies)\r\n else:\r\n self.innerList = subList\r\n","sub_path":"NDList.py","file_name":"NDList.py","file_ext":"py","file_size_in_byte":22798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"276599483","text":"import numpy as np\r\n\r\n# --- PyCUDA initialization\r\nimport pycuda.gpuarray as gpuarray\r\nimport pycuda.driver as cuda\r\nimport pycuda.autoinit\r\nfrom pycuda.compiler import SourceModule\r\n\r\n###################\r\n# iDivUp FUNCTION #\r\n###################\r\ndef iDivUp(a, b):\r\n return a // b + 1\r\n\r\n########\r\n# MAIN #\r\n########\r\n\r\nstart = cuda.Event()\r\nend = cuda.Event()\r\n\r\nN = 100000\r\n\r\nBLOCKSIZE = 256\r\n\r\n# --- Create random vectorson the CPU\r\nh_a = np.random.randn(1, N)\r\nh_b = np.random.randn(1, N)\r\n\r\n# --- Set CPU arrays as single precision\r\nh_a = h_a.astype(np.float32)\r\nh_b = h_b.astype(np.float32)\r\nh_c = np.empty_like(h_a)\r\n\r\nmod = SourceModule(\"\"\"\r\n__global__ void deviceElementwise(float * __restrict__ d_c, const float * __restrict__ d_a, \r\n const float * __restrict__ d_b,\r\n const int N)\r\n{\r\n const int tid = threadIdx.x + blockIdx.x * blockDim.x;\r\n if (tid >= N) return;\r\n d_c[tid] = sqrt(fabs(d_a[tid])) + exp(d_b[tid]);\r\n}\r\n\"\"\")\r\n\r\nd_a = gpuarray.to_gpu(h_a)\r\nd_b = gpuarray.to_gpu(h_b)\r\nd_c = gpuarray.zeros_like(d_a)\r\n\r\n# --- Define a reference to the __global__ function and call it\r\ndeviceElementwise = mod.get_function(\"deviceElementwise\")\r\nblockDim = (BLOCKSIZE, 1, 1)\r\ngridDim = (iDivUp(N, BLOCKSIZE), 1, 1)\r\nstart.record()\r\ndeviceElementwise(d_c, d_a, d_b, np.int32(N), block = blockDim, grid = gridDim)\r\nend.record() \r\nend.synchronize()\r\nsecs = start.time_till(end) * 1e-3\r\nprint(\"Processing time = %fs\" % (secs))\r\n\r\nh_c = d_c.get()\r\n\r\nif np.all(abs(h_c - (np.sqrt(np.abs(h_a)) + np.exp(h_b))) < 1e-5):\r\n print(\"Test passed!\")\r\nelse :\r\n print(\"Error!\")\r\n\r\n# --- Flush context printf buffer\r\ncuda.Context.synchronize()","sub_path":"elementwiseFunctions/elementwiseFunctions_v2.py","file_name":"elementwiseFunctions_v2.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"131586626","text":"\"\"\"This module describes the ObjectRecognitionServer.\"\"\"\n\nimport traceback\nimport os\n\nimport numpy as np\nimport rospy\nimport trimesh\nfrom cosypose.datasets.datasets_cfg import make_urdf_dataset\nfrom geometry_msgs.msg import Point\nfrom object_recognition_msgs.msg import ObjectInformation\nfrom object_recognition_msgs.srv import (GetObjectInformation,\n GetObjectInformationResponse)\nfrom shape_msgs.msg import Mesh, MeshTriangle\n\nfrom .object_database import ObjectDatabase\n\n__all__ = ('ObjectInformationService')\n\n\nclass ObjectInformationService:\n \"\"\"The ObjectInformationServer class.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor for a ObjectInformationServer.\n \"\"\"\n self._datasets = {}\n self._meshes = {}\n\n self._service = rospy.Service(\n '/get_object_information', GetObjectInformation, self.execute)\n\n def execute(self, req):\n \"\"\"Action server callback.\n\n Callback gets called in a separate thread whenever\n a new goal is received.\n\n Args:\n req (GetObjectInformationRequest): service request\n\n Returns:\n GetObjectInformationResponse: object information \n \"\"\"\n try:\n db, key = req.type.db, req.type.key\n rospy.logdebug('Get information for %s/%s', db, key)\n\n if db == 'file':\n mesh = self.make_mesh(key, (1.0, 1.0, 1.0))\n name = os.path.basename(key)\n else:\n if db not in self._datasets:\n self._datasets[db] = ObjectDatabase(db)\n dataset = self._datasets[db]\n\n if (db, key) not in self._meshes:\n self._meshes[(db, key)] = self.make_mesh(\n dataset.get_mesh_path(key),\n dataset.get_mesh_scale(key))\n mesh = self._meshes[(db, key)]\n name = dataset.get_name(key)\n\n response = GetObjectInformationResponse()\n response.information.name = name\n response.information.ground_truth_mesh = mesh\n return response\n except Exception as ex:\n rospy.logerr('Get information failed: %s', ex)\n rospy.logdebug(traceback.format_exc())\n raise ex\n\n @staticmethod\n def make_mesh(path, scale):\n \"\"\"Load a mesh from disk and convert to a message.\n\n Arguments:\n path {str} -- path to the mesh file on disk\n scale {list} -- mesh scale x,y,z\n\n Returns:\n Mesh -- mesh message\n \"\"\"\n rospy.logdebug('Make mesh: %s, scale: %.3f,%.3f,%.3f', path, *scale)\n\n mesh = trimesh.load(path, force='mesh')\n return Mesh(\n vertices=[Point(*vertex) for vertex in mesh.vertices * scale],\n triangles=[MeshTriangle(vertex_indices=indices) for indices in mesh.faces])\n","sub_path":"src/ros_cosypose/object_information_service.py","file_name":"object_information_service.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"301502343","text":"# coding=utf-8\n# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport unittest\n\nfrom pex.pex_bootstrapper import get_pex_info\n\nfrom pants.util.contextutil import temporary_dir\nfrom pants_test.backend.python.interpreter_selection_utils import (PY_3, PY_27,\n python_interpreter_path,\n skip_unless_python3_present,\n skip_unless_python27_and_python3_present,\n skip_unless_python27_present)\nfrom pants_test.pants_run_integration_test import PantsRunIntegrationTest, ensure_daemon\nfrom pants_test.testutils.pexrc_util import setup_pexrc_with_pex_python_path\n\n\nclass PythonRunIntegrationTest(PantsRunIntegrationTest):\n testproject = 'testprojects/src/python/interpreter_selection'\n\n @classmethod\n def hermetic(cls):\n return True\n\n @skip_unless_python3_present\n @ensure_daemon\n def test_run_3(self):\n self._run_version(PY_3)\n\n @skip_unless_python27_present\n @ensure_daemon\n def test_run_27(self):\n self._run_version(PY_27)\n\n def _run_version(self, version):\n echo = self._run_echo_version(version)\n v = echo.split('.') # E.g., 2.7.13.\n self.assertTrue(len(v) > 2, 'Not a valid version string: {}'.format(v))\n expected_components = version.split('.')\n self.assertEqual(expected_components, v[:len(expected_components)])\n\n def _run_echo_version(self, version):\n binary_name = 'echo_interpreter_version_{}'.format(version)\n binary_target = '{}:{}'.format(self.testproject, binary_name)\n # Build a pex.\n # Avoid some known-to-choke-on interpreters.\n if version == PY_3:\n constraint = '[\"CPython>=3.4,<3.7\"]'\n else:\n constraint = '[\"CPython>=2.7,<3\"]'\n command = ['run',\n binary_target,\n '--python-setup-interpreter-constraints={}'.format(constraint),\n '--quiet']\n pants_run = self.run_pants(command=command)\n return pants_run.stdout_data.splitlines()[0].strip()\n\n @skip_unless_python27_and_python3_present\n def test_run_27_and_then_3(self):\n with temporary_dir() as interpreters_cache:\n pants_ini_config = {'python-setup': {'interpreter_cache_dir': interpreters_cache}}\n pants_run_27 = self.run_pants(\n command=['run', '{}:echo_interpreter_version_2.7'.format(self.testproject)],\n config=pants_ini_config\n )\n self.assert_success(pants_run_27)\n pants_run_3 = self.run_pants(\n command=['run', '{}:echo_interpreter_version_3'.format(self.testproject),\n '--python-setup-interpreter-constraints=CPython>=2.7,<3',\n '--python-setup-interpreter-constraints=CPython>=3.4,<3.7'],\n config=pants_ini_config\n )\n self.assert_success(pants_run_3)\n\n @skip_unless_python3_present\n def test_run_3_by_option(self):\n with temporary_dir() as interpreters_cache:\n pants_ini_config = {'python-setup': {'interpreter_constraints': [\"CPython>=2.7,<3.7\"],\n 'interpreter_cache_dir': interpreters_cache}}\n pants_run_3 = self.run_pants(\n command=['run', '{}:echo_interpreter_version_3'.format(self.testproject),\n '--python-setup-interpreter-constraints=[\"CPython>=3\"]'],\n config=pants_ini_config\n )\n self.assert_success(pants_run_3)\n\n @skip_unless_python27_present\n def test_run_2_by_option(self):\n with temporary_dir() as interpreters_cache:\n pants_ini_config = {'python-setup': {'interpreter_constraints': [\"CPython>=2.7,<3.7\"],\n 'interpreter_cache_dir': interpreters_cache}}\n pants_run_2 = self.run_pants(\n command=['run', '{}:echo_interpreter_version_2.7'.format(self.testproject),\n '--python-setup-interpreter-constraints=[\"CPython<3\"]'],\n config=pants_ini_config\n )\n self.assert_success(pants_run_2)\n\n def test_die(self):\n command = ['run',\n '{}:die'.format(self.testproject),\n '--python-setup-interpreter-constraints=[\"CPython>=2.7,<3\", \">=3.4,<3.7\"]',\n '--quiet']\n pants_run = self.run_pants(command=command)\n assert pants_run.returncode == 57\n\n def test_get_env_var(self):\n var_key = 'SOME_MAGICAL_VAR'\n var_val = 'a value'\n command = ['-q',\n 'run',\n 'testprojects/src/python/print_env',\n '--',\n var_key]\n pants_run = self.run_pants(command=command, extra_env={var_key: var_val})\n self.assert_success(pants_run)\n self.assertEqual(var_val, pants_run.stdout_data.strip())\n\n @unittest.skip(\n \"Upgrade PEX: https://github.com/pantsbuild/pants/pull/7186. \\\n NB: Ensure https://github.com/pantsbuild/pex/pull/678 is merged into the PEX release.\")\n @skip_unless_python27_and_python3_present\n def test_pants_run_interpreter_selection_with_pexrc(self):\n py27_path, py3_path = python_interpreter_path(PY_27), python_interpreter_path(PY_3)\n with setup_pexrc_with_pex_python_path([py27_path, py3_path]):\n with temporary_dir() as interpreters_cache:\n pants_ini_config = {'python-setup': {'interpreter_cache_dir': interpreters_cache}}\n pants_run_27 = self.run_pants(\n command=['run', '{}:main_py2'.format(os.path.join(self.testproject,\n 'python_3_selection_testing'))],\n config=pants_ini_config\n )\n self.assert_success(pants_run_27)\n self.assertIn(py27_path, pants_run_27.stdout_data)\n pants_run_3 = self.run_pants(\n command=['run', '{}:main_py3'.format(os.path.join(self.testproject,\n 'python_3_selection_testing'))],\n config=pants_ini_config\n )\n self.assert_success(pants_run_3)\n self.assertIn(py3_path, pants_run_3.stdout_data)\n\n @unittest.skip(\n \"Upgrade PEX: https://github.com/pantsbuild/pants/pull/7186. \\\n NB: Ensure https://github.com/pantsbuild/pex/pull/678 is merged into the PEX release.\")\n @skip_unless_python27_and_python3_present\n def test_pants_binary_interpreter_selection_with_pexrc(self):\n py27_path, py3_path = python_interpreter_path(PY_27), python_interpreter_path(PY_3)\n with setup_pexrc_with_pex_python_path([py27_path, py3_path]):\n with temporary_dir() as interpreters_cache:\n pants_ini_config = {'python-setup': {'interpreter_cache_dir': interpreters_cache}}\n pants_run_27 = self.run_pants(\n command=['binary', '{}:main_py2'.format(os.path.join(self.testproject,\n 'python_3_selection_testing'))],\n config=pants_ini_config\n )\n self.assert_success(pants_run_27)\n pants_run_3 = self.run_pants(\n command=['binary', '{}:main_py3'.format(os.path.join(self.testproject,\n 'python_3_selection_testing'))],\n config=pants_ini_config\n )\n self.assert_success(pants_run_3)\n\n # Ensure proper interpreter constraints were passed to built pexes.\n py2_pex = os.path.join(os.getcwd(), 'dist', 'main_py2.pex')\n py3_pex = os.path.join(os.getcwd(), 'dist', 'main_py3.pex')\n py2_info = get_pex_info(py2_pex)\n py3_info = get_pex_info(py3_pex)\n self.assertIn('CPython>2.7.6,<3', py2_info.interpreter_constraints)\n self.assertIn('CPython>3', py3_info.interpreter_constraints)\n\n # Cleanup created pexes.\n os.remove(py2_pex)\n os.remove(py3_pex)\n\n @unittest.skip(\n \"Upgrade PEX: https://github.com/pantsbuild/pants/pull/7186. \\\n NB: Ensure https://github.com/pantsbuild/pex/pull/678 is merged into the PEX release.\")\n @skip_unless_python3_present\n def test_target_constraints_with_no_sources(self):\n with temporary_dir() as interpreters_cache:\n pants_ini_config = {\n 'python-setup': {\n 'interpreter_cache_dir': interpreters_cache,\n 'interpreter_constraints': ['CPython>3'],\n }\n }\n # Run task.\n pants_run = self.run_pants(\n command=['run', '{}:test_bin'.format(os.path.join(self.testproject,\n 'test_target_with_no_sources'))],\n config=pants_ini_config\n )\n self.assert_success(pants_run)\n self.assertIn('python3', pants_run.stdout_data)\n\n # Binary task.\n pants_run = self.run_pants(\n command=['binary', '{}:test_bin'.format(os.path.join(self.testproject,\n 'test_target_with_no_sources'))],\n config=pants_ini_config\n )\n self.assert_success(pants_run)\n\n # Ensure proper interpreter constraints were passed to built pexes.\n py2_pex = os.path.join(os.getcwd(), 'dist', 'test_bin.pex')\n py2_info = get_pex_info(py2_pex)\n self.assertIn('CPython>3', py2_info.interpreter_constraints)\n # Cleanup.\n os.remove(py2_pex)\n","sub_path":"tests/python/pants_test/backend/python/tasks/test_python_run_integration.py","file_name":"test_python_run_integration.py","file_ext":"py","file_size_in_byte":9221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107557080","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Blood transfusion service center\n\n# V1: Recency - months since last donation
    \n# V2: Frequency - total number of donation
    \n# V3: Monetary - total blood donated in c.c.
    \n# V4: Time - months since first donation), and a binary variable representing whether he/she donated blood
    \n# in March 2007 (1 stand for donating blood; 0 stands for not donating blood).\n\n# The target attribute is a binary variable representing whether
    \n# he/she donated blood in March 2007 (2 stands for donating blood; 1 stands for not donating blood).\n\n# In[130]:\n\n\n# https://www.openml.org/d/1464\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom keras.utils import np_utils\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nimport pickle\n\n\n# In[131]:\n\n\ndf = pd.read_csv(\"blood-transfusion-service-center.csv\")\ndf.head()\n\n\n# In[132]:\n\n\ndf = df.dropna(how='all')\n\n\n# In[133]:\n\n\ndf[\"Class\"].value_counts()\n\n\n# In[134]:\n\n\nfrom sklearn.utils import resample\n\ndf_majority = df[df.Class==2]\ndf_minority = df[df.Class==1]\n\n# Upsample minority class\ndf_minority_upsampled = resample(df_minority, \n replace=True, # sample with replacement\n n_samples=178, # to match majority class\n random_state=42) # reproducible results\n\n# Combine majority class with upsampled minority class\ndf = pd.concat([df_majority, df_minority_upsampled])\n\n# Display new class counts\ndf.Class.value_counts()\n\n\n# In[135]:\n\n\ndf[\"Class\"].value_counts()\n\n\n# In[136]:\n\n\nX = df.drop(['Class'], axis=1).values\n#X = StandardScaler().fit_transform(X)\nY = df['Class']\n\n\n# In[137]:\n\n\nX_Train, X_Test, Y_Train, Y_Test = train_test_split(X, Y, test_size = 0.30, random_state = 101)\n\n\n# In[138]:\n\n\ntrainedforest = RandomForestClassifier(n_estimators=700).fit(X_Train,Y_Train)\npredictionforest = trainedforest.predict(X_Test)\ntrainedforest.score(X_Train, Y_Train)\n\n\n# In[139]:\n\n\ntrainedforest = RandomForestClassifier(n_estimators=700).fit(X,Y)\n\n\n# In[140]:\n\n\n# Saving model to disk\npickle.dump(trainedforest, open('model.pkl','wb'))\n\n\n# In[141]:\n\n\n# Loading model to compare the results\nmodel = pickle.load(open('model.pkl','rb'))\n\n\n# In[148]:\n\n\n# print(model.predict([[2, 430, 10350, 86]]))\n\n\n# In[157]:\n\n\n# p = model.predict(X_Test)\n# #print(X_Test)\n# print(list(p).count(1))\n# print(list(p).count(2))","sub_path":"ML-Deployement/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"161032011","text":"#!/usr/bin/env python3\n\nimport csv\nimport os\n\nfrom mail import send_certificate\n\nwith open(\"../Participants.csv\") as participants_file:\n participants = csv.reader(participants_file, delimiter=\",\")\n for row in participants:\n attendance = open(\"../CodexAttendance.csv\")\n attended = csv.reader(attendance, delimiter=\"|\")\n for person in attended:\n names = [name.strip() for name in person[0].split(\",\")]\n if row[0] not in names:\n continue\n for name, email in zip(names, person[1].split(\",\")):\n if name == row[0]:\n print(f\"{row[0]} with id {row[3]} has email {email.strip()}.\")\n if os.path.exists(\n f\"../certs/{int(row[3].replace('CX1219', ''))}.jpg\"\n ):\n print(f\"{row[3]} cert found\")\n send_certificate(\n name,\n email.strip(),\n f\"../certs/{int(row[3].replace('CX1219', ''))}.jpg\",\n )\n else:\n print(\"Cert for {name} doesn't exist?\")\n attendance.close()\n","sub_path":"csv_parse.py","file_name":"csv_parse.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390155105","text":"from parser import *\nfrom scanner import tokens\nfrom parse.expressions.expressions_math import *\nfrom parse.expressions.expressions_base import *\nfrom parse.expressions.expressions_trig import *\nfrom treeGraph import *\n\nstart = 'init'\n\nprecedence = (\n\n # Arthmetic\n ('left', 'MAS', 'MENOS'),\n ('left', 'POR', 'DIAGONAL'),\n ('left', 'EXPONENCIANCION'),\n ('right', 'UMENOS'),\n ('right', 'UMAS'),\n # Relational\n ('left', 'MENOR', 'MAYOR', 'IGUAL', 'MENORQ', 'MAYORQ'),\n # logic\n # ('left', 'OR'),\n # ('left', 'AND'),\n # ('right', 'NOT'),\n\n)\n\n\ndef p_init(t):\n ''' init : statements'''\n t[0] = t[1]\n\n\ndef p_statements(t):\n ''' statements : statements statement '''\n t[1].append(t[2])\n t[0] = t[1]\n\n\ndef p_statements2(t):\n ''' statements : statement '''\n t[0] = [t[1]]\n\n\ndef p_statement(t):\n '''statement : relExpression PUNTOCOMA\n '''\n t[0] = t[1]\n\n\n########## Definition of opttional productions, who could reduce to 'empty' (epsilon) ################\n# def p_not_opt(t):\n# '''not_opt : NOT\n# | empty'''\n########## Definition of Relational expressions ############## \ndef p_relExpression(t):\n '''relExpression : expression MENOR expression \n | expression MAYOR expression\n | expression IGUAL expression\n | expression MENORQ expression\n | expression MAYORQ expression\n | expression DIFERENTE expression\n | expression NOT LIKE TEXTO\n | expression LIKE TEXTO'''\n token = t.slice[2]\n if token.type == \"MENOR\":\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = RelationalExpression(t[1], t[3], OpRelational.LESS, 0, 0, graph_ref)\n elif token.type == \"MAYOR\":\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = RelationalExpression(t[1], t[3], OpRelational.GREATER, 0, 0, graph_ref)\n elif token.type == \"IGUAL\":\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = RelationalExpression(t[1], t[3], OpRelational.EQUALS, 0, 0, graph_ref)\n elif token.type == \"MENORQ\":\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = RelationalExpression(t[1], t[3], OpRelational.LESS_EQUALS, 0, 0, graph_ref)\n elif token.type == \"MAYORQ\":\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = RelationalExpression(t[1], t[3], OpRelational.GREATER_EQUALS, 0, 0, graph_ref)\n elif token.type == \"DIFERENTE\":\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = RelationalExpression(t[1], t[3], OpRelational.NOT_EQUALS, 0, 0, graph_ref)\n elif token.type == \"NOT\":\n graph_ref = graph_node(str(str(t[2] + \" \" + t[3]), [t[1].graph_ref]))\n t[0] = RelationalExpression(t[1], t[4], OpRelational.NOT_LIKE, 0, 0, graph_ref)\n elif token.type == \"LIKE\":\n graph_ref = graph_node(str(str(t[2] + \" \" + t[3]), [t[1].graph_ref]))\n t[0] = RelationalExpression(t[1], t[3], OpRelational.LIKE, 0, 0, graph_ref)\n else:\n print(\"Missing code from: \", t.slice)\n\n\ndef p_relExpReducExp(t):\n '''relExpression : expression'''\n t[0] = t[1]\n\n\n########## Defintions of produtions for expression :== ##############\ndef p_expression(t):\n ''' expression : expression MAS expression\n | expression MENOS expression\n | expression POR expression\n | expression DIAGONAL expression\n | expression PORCENTAJE expression\n | expression EXPONENCIANCION expression \n '''\n if t[2] == '+':\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = BinaryExpression(t[1], t[3], OpArithmetic.PLUS, 0, 0, graph_ref)\n elif t[2] == '-':\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = BinaryExpression(t[1], t[3], OpArithmetic.MINUS, 0, 0, graph_ref)\n elif t[2] == '*':\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = BinaryExpression(t[1], t[3], OpArithmetic.TIMES, 0, 0, graph_ref)\n elif t[2] == '/':\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = BinaryExpression(t[1], t[3], OpArithmetic.DIVIDE, 0, 0, graph_ref)\n elif t[2] == '%':\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = BinaryExpression(t[1], t[3], OpArithmetic.MODULE, 0, 0, graph_ref)\n elif t[2] == '^':\n graph_ref = graph_node(str(t[2]), [t[1].graph_ref, t[3].graph_ref])\n t[0] = BinaryExpression(t[1], t[3], OpArithmetic.POWER, 0, 0, graph_ref)\n else:\n print(\"You forgot wirte code for the operator: \", t[2])\n\n\ndef p_trigonometric(t):\n ''' expression : ACOS PARA expression PARC\n | ACOSD PARA expression PARC\n | ASIN PARA expression PARC\n | ASIND PARA expression PARC\n | ATAN PARA expression PARC\n | ATAND PARA expression PARC\n | ATAN2 PARA expression COMA expression PARC\n | ATAN2D PARA expression COMA expression PARC\n | COS PARA expression PARC\n | COSD PARA expression PARC\n | COT PARA expression PARC\n | COTD PARA expression PARC\n | SIN PARA expression PARC\n | SIND PARA expression PARC\n | TAN PARA expression PARC\n | TAND PARA expression PARC\n | SINH PARA expression PARC\n | COSH PARA expression PARC\n | TANH PARA expression PARC\n | ASINH PARA expression PARC\n | ACOSH PARA expression PARC\n | ATANH PARA expression PARC'''\n\n if t.slice[1].type == 'ACOS':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Acos(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ACOSD':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Acosd(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ASIN':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Asin(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ASIND':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Asind(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ATAN':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Atan(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ATAND':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Atand(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ATAN2':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Atan2(t[3], t[5], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ATAN2D':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Atan2d(t[3], t[5], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'COS':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Cos(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'COSD':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Cosd(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'COT':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Cot(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'COTD':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Cotd(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'SIN':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Sin(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'SIND':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Sind(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'TAN':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Tan(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'TAND':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Tand(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'SINH':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Sinh(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'COSH':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Cosh(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'TANH':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Tanh(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ASINH':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Asinh(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ACOSH':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Acosh(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n elif t.slice[1].type == 'ATANH':\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Atanh(t[3], t.slice[1].lineno, t.slice[1].lexpos, graph_ref)\n\n\ndef p_aritmetic(t):\n '''expression : ABS PARA expression PARC \n | CBRT PARA expression PARC\n | CEIL PARA expression PARC\n | CEILING PARA expression PARC\n | DEGREES PARA expression PARC\n | DIV PARA expression COMA expression PARC\n | EXP PARA expression PARC\n | FACTORIAL PARA expression PARC \n | FLOOR PARA expression PARC\n | GCD PARA expression COMA expression PARC\n | LCM PARA expression COMA expression PARC\n | LN PARA expression PARC \n | LOG PARA expression PARC\n | LOG10 PARA expression PARC\n | MIN_SCALE PARA expression PARC\n | MOD PARA expression COMA expression PARC\n | PI PARA PARC\n | POWER PARA expression COMA expression PARC\n | RADIANS PARA expression PARC \n | ROUND PARA expression PARC\n | SCALE PARA expression PARC\n | SIGN PARA expression PARC\n | SQRT PARA expression PARC\n | TRIM_SCALE PARA expression PARC\n | WIDTH_BUCKET PARA expression COMA expression PARC\n | RANDOM PARA PARC\n | SETSEED PARA expression PARC\n '''\n token = t.slice[1]\n if token.type == \"ABS\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Abs(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"CBRT\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Cbrt(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"CEIL\" or token.type == \"CEILING\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Ceil(t[3], token.lineno, token.lexpos)\n elif token.type == \"DEGREES\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Degrees(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"DIV\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Div(t[3], t[5], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"EXP\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Exp(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"FACTORIAL\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Factorial(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"FLOOR\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Floor(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"GCD\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Gcd(t[3], t[5], token.lineno, token.lexpos, graph_ref)\n ###\n elif token.type == \"LCM\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Lcm(t[3], t[5], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"LN\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Ln(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"LOG\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Log(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"LOG10\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Log10(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"MIN_SCALE\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = MinScale(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"MOD\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Mod(t[3], t[5], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"PI\":\n graph_ref = graph_node(str(t[1]))\n t[0] = PI(token.lineno, token.lexpos, graph_ref)\n elif token.type == \"POWER\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = Power(t[3], t[5], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"RADIANS\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Radians(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"ROUND\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Round(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"SCALE\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Scale(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"SIGN\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Sign(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"SQRT\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Sqrt(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"TRIM_SCALE\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = TrimScale(t[3], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"WIDTH_BUCKET\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref, t[5].graph_ref])\n t[0] = WithBucket(t[3], t[5], token.lineno, token.lexpos, graph_ref)\n elif token.type == \"RANDOM\":\n graph_ref = graph_node(str(t[1]))\n t[0] = Random(token.lineno, token.lexpos, graph_ref)\n elif token.type == \"SETSEED\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = SetSeed(t[3], token.lineno, token.lexpos, graph_ref)\n\n\n# | NOT expression\n# '''\n# | PARA logicExpression PARC'''\ndef p_exp_unary(t):\n '''expression : MENOS expression %prec UMENOS\n | MAS expression %prec UMAS '''\n if t[1] == '+':\n graph_ref = graph_node(str(t[1]), [t[2].graph_ref])\n t[0] = BinaryExpression(Numeric(1, 0, 0, 0), t[2], OpArithmetic.TIMES, 0, 0, graph_ref)\n elif t[1] == '-':\n graph_ref = graph_node(str(t[1]), [t[2].graph_ref])\n t[0] = BinaryExpression(NumericNegative(1, 0, 0, 0), t[2], OpArithmetic.TIMES, 0, 0, graph_ref)\n else:\n print(\"Missed code from unary expression\")\n\n\ndef p_exp_num(t):\n '''expression : numero\n | col_name'''\n t[0] = t[1]\n\n\ndef p_exp_val(t):\n '''expression : TEXTO\n | BOOLEAN_VALUE \n | NOW PARA PARC'''\n token = t.slice[1]\n if token.type == \"TEXTO\":\n graph_ref = graph_node(str(t[1]))\n t[0] = Text(token.value, token.lineno, token.lexpos, graph_ref)\n if token.type == \"BOOLEAN_VALUE\":\n graph_ref = graph_node(str(t[1]))\n t[0] = BoolAST(token.value, token.lineno, token.lexpos, graph_ref)\n if token.type == \"NOW\":\n graph_ref = graph_node(str(t[1]))\n t[0] = Now(token.lineno, token.lexpos, graph_ref)\n\n\ndef p_exp_afunc1(t):\n '''expression : TRUC PARA expression PARC'''\n\n token = t.slice[1]\n if token.type == \"TRUC\":\n graph_ref = graph_node(str(t[1]), [t[3].graph_ref])\n t[0] = Trunc(t[3], 0, 0, graph_ref)\n\n # else:\n # print(\"Missing code from: \",t[1])\n\n\n# def p_empty(t):\n# '''empty :'''\n# pass\n\ndef p_error(p):\n if not p:\n print(\"End of file!\")\n return\n # Read ahead looking for a closing ';'\n while True:\n tok = parse.token() # Get the next token\n if not tok or tok.type == 'PUNTOCOMA':\n print(\"-->Syntax Error: Ilega token \\\"\" + str(p.type) + \"\\\" Line: \" + str(p.lineno) + \"Column: \" + str(\n p.lexpos))\n break\n parse.restart()\n\n\ndef p_numero(t):\n ''' numero : ENTERO\n | FLOAT'''\n token = t.slice[1]\n graph_ref = graph_node(str(t[1]))\n t[0] = Numeric(token.value, token.lineno, token.lexpos, graph_ref)\n\n\ndef p_col_name(t):\n ''' col_name : ID PUNTO ID\n | ID '''\n token = t.slice[1]\n if len(t) == 2:\n graph_ref = graph_node(str(t[1]))\n t[0] = ColumnName(None, t[1], token.lineno, token.lexpos, graph_ref)\n else:\n graph_ref = graph_node(str(t[1] + t[2] + t[3]))\n t[0] = ColumnName(t[1], t[3], token.lineno, token.lexpos, graph_ref)\n\n\nimport ply.yacc as yacc\n\nparse = yacc.yacc()\n\n\ndef toParse(input):\n # return parse.parse(input,lexer)\n parse.parse(input)\n dot.view()\n return parse.parse(input)\n","sub_path":"parser/team03/grammarReview.py","file_name":"grammarReview.py","file_ext":"py","file_size_in_byte":18512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318279008","text":"# -*- coding: utf-8 -*-\nfrom django.core.management import BaseCommand\nfrom grab import Grab\nfrom piano.get_piano_lesson import headers, GetPianoInfo\n\n\nclass Command(BaseCommand):\n help = 'Load extra sql to the db'\n\n def handle(self, *args, **options):\n SEARCH_NAME = 'piano lessons'\n URL = 'https://helpouts.google.com/'\n g = Grab()\n g.go(URL)\n g.set_input('q', SEARCH_NAME)\n g.submit()\n\n spider = GetPianoInfo()\n spider.initial_urls = [g.response.url]\n spider.base_url = URL\n spider.setup_grab(headers=headers)\n spider.run()\n","sub_path":"parser/apps/piano/management/commands/get_piano_lesson.py","file_name":"get_piano_lesson.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"20154970","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\nfrom sklearn.metrics import confusion_matrix\n\nfont_path = '/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf'\nfont_prop = FontProperties(fname=font_path)\nmatplotlib.rcParams['font.family'] = font_prop.get_name()\n\n# 参考\n# http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\n\n# フォント周りの設定はここも参考\n# http://qiita.com/conta_/items/4b031a44acceb137ec73\n\ndef make_confusion_matrix(y_true, y_pred, labels, image_name='confusion_matrix.png'):\n cm = confusion_matrix(y_true, y_pred)\n\n cmap = plt.cm.Blues\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title('confusion matrix')\n plt.colorbar()\n tick_marks = np.arange(len(labels))\n plt.xticks(tick_marks, labels, rotation=0)\n plt.yticks(tick_marks, labels)\n\n plt.tight_layout()\n plt.ylabel('正解')\n plt.xlabel('判定')\n plt.savefig(image_name)\n print('confusion matrix %s' % image_name)\n# plt.show()\n\n return cm\n\n\n\nif __name__ == '__main__':\n y_true = [2, 0, 2, 2, 0, 1]\n y_pred = [0, 0, 2, 2, 0, 2]\n labels = ['cat', 'dog', 'bird']\n ret = make_confusion_matrix(y_true, y_pred, labels)\n print(ret)\n","sub_path":"release/softmax/analyze_tools.py","file_name":"analyze_tools.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585166972","text":"from app import app\nimport re\nimport datetime\nimport string\nfrom jinja2 import escape\n\n\n@app.template_filter('timesince')\ndef timesince(value):\n now = datetime.datetime.utcnow()\n delta = now - value\n if delta.days > 365:\n num = delta.days//365\n return '%s年前'% num\n if delta.days > 30:\n num = delta.days//30\n return '%s个月前'% num\n if delta.days > 0:\n num = delta.days\n return '%s天前'% num\n if delta.seconds > 3600:\n num = delta.seconds//3600\n return '%s小时前'% num\n if delta.seconds > 60:\n num = delta.seconds//60\n return '%s分钟前'% num\n return '刚刚'\n\n@app.template_filter('time')\ndef datatimetime(v):\n time = v.strftime('%Y-%m-%d %H:%M:%S')\n return time\n\n@app.template_filter('year')\ndef datatime(v):\n time = v.strftime('%Y年%m月%d日')\n return time\n\n@app.template_filter('timefeed')\ndef datatimefeed(v):\n time = v.strftime('%Y-%m-%dT%H:%M:%SZ')\n return time\n\n@app.template_filter('small')\ndef small(v):\n\timg = app.config[\"QINIU_URL\"]+v+'-small'\n\treturn img\n\n@app.template_filter('normal')\ndef normal(v):\n\timg = app.config[\"QINIU_URL\"]+v\n\treturn img\n\n","sub_path":"bearwave/tpl_filter.py","file_name":"tpl_filter.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"460077563","text":"\"\"\"\nGather information about an entity/record type\n\"\"\"\n\n__author__ = \"Graham Klyne (GK@ACM.ORG)\"\n__copyright__ = \"Copyright 2014, G. Klyne\"\n__license__ = \"MIT (http://opensource.org/licenses/MIT)\"\n\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom annalist import message\nfrom annalist import util\n\nfrom annalist.identifiers import ANNAL, RDF, RDFS\n\nfrom annalist.models.annalistuser import AnnalistUser\nfrom annalist.models.recordtype import RecordType\nfrom annalist.models.recordlist import RecordList\nfrom annalist.models.recordview import RecordView\nfrom annalist.models.recordgroup import RecordGroup\nfrom annalist.models.recordfield import RecordField\nfrom annalist.models.recordenum import RecordEnumFactory\nfrom annalist.models.recordtypedata import RecordTypeData\nfrom annalist.models.entitydata import EntityData\n\nENTITY_MESSAGES = (\n { 'parent_heading': message.RECORD_TYPE_ID\n , 'parent_missing': message.RECORD_TYPE_NOT_EXISTS\n , 'entity_heading': message.ENTITY_DATA_ID\n , 'entity_invalid_id': message.ENTITY_DATA_ID_INVALID\n , 'entity_exists': message.ENTITY_DATA_EXISTS\n , 'entity_not_exists': message.ENTITY_DATA_NOT_EXISTS\n , 'entity_removed': message.ENTITY_DATA_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nUSER_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.ANNALIST_USER_ID\n , 'entity_invalid_id': message.ANNALIST_USER_ID_INVALID\n , 'entity_exists': message.ANNALIST_USER_EXISTS\n , 'entity_not_exists': message.ANNALIST_USER_NOT_EXISTS\n , 'entity_removed': message.ANNALIST_USER_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nTYPE_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.RECORD_TYPE_ID\n , 'entity_invalid_id': message.RECORD_TYPE_ID_INVALID\n , 'entity_exists': message.RECORD_TYPE_EXISTS\n , 'entity_not_exists': message.RECORD_TYPE_NOT_EXISTS\n , 'entity_removed': message.RECORD_TYPE_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nLIST_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.RECORD_LIST_ID\n , 'entity_invalid_id': message.RECORD_LIST_ID_INVALID\n , 'entity_exists': message.RECORD_LIST_EXISTS\n , 'entity_not_exists': message.RECORD_LIST_NOT_EXISTS\n , 'entity_removed': message.RECORD_LIST_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nVIEW_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.RECORD_VIEW_ID\n , 'entity_invalid_id': message.RECORD_VIEW_ID_INVALID\n , 'entity_exists': message.RECORD_VIEW_EXISTS\n , 'entity_not_exists': message.RECORD_VIEW_NOT_EXISTS\n , 'entity_removed': message.RECORD_VIEW_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nGROUP_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.RECORD_GROUP_ID\n , 'entity_invalid_id': message.RECORD_GROUP_ID_INVALID\n , 'entity_exists': message.RECORD_GROUP_EXISTS\n , 'entity_not_exists': message.RECORD_GROUP_NOT_EXISTS\n , 'entity_removed': message.RECORD_GROUP_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nFIELD_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.RECORD_FIELD_ID\n , 'entity_invalid_id': message.RECORD_FIELD_ID_INVALID\n , 'entity_exists': message.RECORD_FIELD_EXISTS\n , 'entity_not_exists': message.RECORD_FIELD_NOT_EXISTS\n , 'entity_removed': message.RECORD_FIELD_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nENUM_MESSAGES = (\n { 'parent_heading': message.COLLECTION_ID\n , 'parent_missing': message.COLLECTION_NOT_EXISTS\n , 'entity_heading': message.RECORD_ENUM_ID\n , 'entity_invalid_id': message.RECORD_ENUM_ID_INVALID\n , 'entity_exists': message.RECORD_ENUM_EXISTS\n , 'entity_not_exists': message.RECORD_ENUM_NOT_EXISTS\n , 'entity_removed': message.RECORD_ENUM_REMOVED\n , 'entity_type_heading': message.ENTITY_TYPE_ID\n , 'entity_type_invalid': message.ENTITY_TYPE_ID_INVALID\n })\n\nADMIN_PERMISSIONS = (\n { \"view\": \"ADMIN\" # View user record\n , \"list\": \"ADMIN\" # ..\n , \"search\": \"ADMIN\" # ..\n , \"new\": \"ADMIN\" # Create user record\n , \"copy\": \"ADMIN\" # ..\n , \"edit\": \"ADMIN\" # Update user record\n , \"delete\": \"ADMIN\" # Delete user record\n , \"config\": \"CONFIG\" # Change collection configuration\n , \"admin\": \"ADMIN\" # Change users or permissions\n })\n\nCONFIG_PERMISSIONS = (\n { \"view\": \"VIEW\" # View config record\n , \"list\": \"VIEW\" # ..\n , \"search\": \"VIEW\" # ..\n , \"new\": \"CONFIG\" # Create config record\n , \"copy\": \"CONFIG\" # ..\n , \"edit\": \"CONFIG\" # Update config record\n , \"delete\": \"CONFIG\" # Delete config record\n , \"config\": \"CONFIG\" # Change collection configuration\n , \"admin\": \"ADMIN\" # Change users or permissions\n })\n\nENTITY_PERMISSIONS = (\n { \"view\": \"VIEW\" # View data record\n , \"list\": \"VIEW\" # ..\n , \"search\": \"VIEW\" # ..\n , \"new\": \"CREATE\" # Create data record\n , \"copy\": \"CREATE\" # ..\n , \"edit\": \"UPDATE\" # Update data record\n , \"delete\": \"DELETE\" # Delete data record\n , \"config\": \"CONFIG\" # Change collection configuration\n , \"admin\": \"ADMIN\" # Change users or permissions\n })\n\nTYPE_CLASS_MAP = (\n { '_user': AnnalistUser\n , '_type': RecordType\n , '_list': RecordList\n , '_view': RecordView\n , '_group': RecordGroup\n , '_field': RecordField\n , 'Enum_list_type': RecordEnumFactory('Enum_list_type', 'Enum_list_type')\n , 'Enum_render_type': RecordEnumFactory('Enum_render_type', 'Enum_render_type')\n , 'Enum_bib_type': RecordEnumFactory('Enum_bib_type', 'Enum_bib_type')\n })\n\nTYPE_MESSAGE_MAP = (\n { '_user': USER_MESSAGES\n , '_type': TYPE_MESSAGES\n , '_list': LIST_MESSAGES\n , '_view': VIEW_MESSAGES\n , '_group': GROUP_MESSAGES\n , '_field': FIELD_MESSAGES\n , 'Enum_list_type': ENUM_MESSAGES\n , 'Enum_render_type': ENUM_MESSAGES\n , 'Enum_bib_type': ENUM_MESSAGES\n })\n\nTYPE_PERMISSIONS_MAP = (\n { '_user': ADMIN_PERMISSIONS\n , '_type': CONFIG_PERMISSIONS\n , '_list': CONFIG_PERMISSIONS\n , '_view': CONFIG_PERMISSIONS\n , '_group': CONFIG_PERMISSIONS\n , '_field': CONFIG_PERMISSIONS\n , 'Enum_list_type': CONFIG_PERMISSIONS\n , 'Enum_render_type': CONFIG_PERMISSIONS\n , 'Enum_bib_type': CONFIG_PERMISSIONS\n })\n\ndef get_built_in_type_ids():\n \"\"\"\n Returns an interator over the built-in types\n \"\"\"\n return TYPE_CLASS_MAP.iterkeys()\n\nclass EntityTypeInfo(object):\n \"\"\"\n Check a supplied type identifier, and access values for:\n Entity class\n Entity parent\n Entity alternative parent for site-wide values\n Type-dependent messages\n \"\"\"\n\n def __init__(self, site, coll, type_id, create_typedata=False):\n \"\"\"\n Set up type attribute values.\n\n site current site object\n coll collection object in which type is used\n type_id entity type id, which is a collection-defined value,\n or one of a number of special site-wide built-in types.\n create_typedata if true, requests that a RecordTypeData entity be created\n and saved on disk for user-defined types if it does not \n already exist. (Creating a RecordTypeData entity ensures\n that the corresponding data storage location is available \n for saving entity data.)\n\n Attributes of type information object are:\n\n recordtype type object describing the identified type\n entityparent Parent enbtity for entities of this type, or None if \n the type is not defined for the collection\n entityaltparent Alternative (site-wide) parent entity for built-in types, \n or None\n entityclass Python class object for entity\n entitymessages a table of message strings for diagnostics relating to \n operations on this type.\n\n and other values as initialized here.\n \"\"\"\n self.entitysite = site\n self.entitycoll = coll\n self.recordtype = None\n self.entityparent = None\n self.coll_id = coll.get_id()\n self.type_id = type_id\n self.permissions_map = None\n if type_id in TYPE_CLASS_MAP:\n self.recordtype = RecordType.load(coll, type_id, site)\n self.entityparent = coll\n self.entityaltparent = site\n self.entityclass = TYPE_CLASS_MAP[type_id]\n self.entitymessages = TYPE_MESSAGE_MAP[type_id]\n self.permissions_map = TYPE_PERMISSIONS_MAP[type_id]\n else:\n if RecordType.exists(coll, type_id, site):\n self.recordtype = RecordType.load(coll, type_id, site)\n if create_typedata and not RecordTypeData.exists(coll, type_id):\n self.entityparent = RecordTypeData.create(coll, type_id, {})\n else:\n self.entityparent = RecordTypeData(coll, type_id)\n self.entityaltparent = None\n self.entityclass = EntityData\n self.entitymessages = ENTITY_MESSAGES\n self.permissions_map = ENTITY_PERMISSIONS\n if not self.recordtype:\n # .recordtype is used by views.displayinfo to locate the default\n # view and/or list id for examining records of a particular type.\n #\n # Also used in entityedit for getting @type URI/CURIE values.\n #\n # Used in render_utils to get link to type record\n log.warning(\"EntityTypeInfo.__init__: RecordType %s not found\"%type_id)\n return\n\n def parent_exists(self):\n \"\"\"\n Test for existence of parent entity for the current type.\n \"\"\"\n return self.entityparent._exists()\n\n def entity_exists(self, entity_id, use_altparent=False):\n \"\"\"\n Test for existence of identified entity of the current type.\n \"\"\"\n altparent = self.entityaltparent if use_altparent else None\n return self.entityclass.exists(self.entityparent, entity_id, altparent=altparent)\n\n def create_entity(self, entity_id, entity_values):\n \"\"\"\n Creates and returns an entity for the current type, with the supplied values.\n \"\"\"\n log.debug(\n \"create_entity id %s, parent %s, values %r\"%\n (entity_id, self.entityparent, entity_values)\n )\n # Set type URI for entity; previous types are not carried forwards\n # If type does not define a URI, use type URL\n typeuri = None\n if self.recordtype:\n if ANNAL.CURIE.uri in self.recordtype:\n typeuri = self.recordtype[ANNAL.CURIE.uri]\n if not typeuri:\n typeuri = self.recordtype[ANNAL.CURIE.url]\n entity_values['@type'] = typeuri # NOTE: previous type not carried forward\n # Don't save entity URI if same as URL\n if entity_values.get(ANNAL.CURIE.uri) == entity_values.get(ANNAL.CURIE.url):\n entity_values.pop(ANNAL.CURIE.uri, None)\n return self.entityclass.create(self.entityparent, entity_id, entity_values)\n\n def remove_entity(self, entity_id):\n \"\"\"\n Remove identified entity for the current type.\n \"\"\"\n log.debug(\n \"remove_entity id %s, parent %s\"%\n (entity_id, self.entityparent)\n )\n return self.entityclass.remove(self.entityparent, entity_id)\n\n def get_entity(self, entity_id, action=\"view\"):\n \"\"\"\n Loads and returns an entity for the current type, or \n returns None if the entity does not exist.\n\n If `action` is \"new\" then a new entity is initialized (but not saved).\n \"\"\"\n log.debug(\n \"get_entity id %s, parent %s, altparent %s, action %s\"%\n (entity_id, self.entityparent, self.entityaltparent, action)\n )\n entity = None\n if util.valid_id(entity_id):\n if action == \"new\":\n entity = self.entityclass(self.entityparent, entity_id)\n entity_initial_values = self.get_initial_entity_values(entity_id)\n entity.set_values(entity_initial_values)\n elif self.entityclass.exists(\n self.entityparent, entity_id, altparent=self.entityaltparent\n ):\n entity = self.entityclass.load(self.entityparent, entity_id, altparent=self.entityaltparent)\n return entity\n\n def get_entity_with_aliases(self, entity_id, action=\"view\"):\n \"\"\"\n Loads and returns an entity for the current type, or \n returns None if the entity does not exist.\n\n If `action` is \"new\" then a new entity is initialized (but not saved).\n\n Field aliases defined in the associated record type are populated\n in the value returned.\n \"\"\"\n entity = self.get_entity(entity_id, action=action)\n # Fill in field aliases\n if entity and ANNAL.CURIE.field_aliases in self.recordtype:\n for alias in self.recordtype[ANNAL.CURIE.field_aliases]:\n tgt = alias[ANNAL.CURIE.alias_target]\n src = alias[ANNAL.CURIE.alias_source]\n if entity.get(tgt, None) in [None, \"\"]:\n entity[tgt] = entity.get(src, \"\")\n return entity\n\n def enum_entity_ids(self, usealtparent=False):\n \"\"\"\n Iterate over entity identifiers in collection with current type.\n\n usealtparent is True if site-wide entities are to be included.\n \"\"\"\n altparent = self.entityaltparent if usealtparent else None\n if self.entityparent:\n for eid in self.entityparent.child_entity_ids(\n self.entityclass, \n altparent=altparent):\n yield eid\n else:\n log.warning(\"EntityTypeInfo.enum_entity_ids: missing entityparent; type_id %s\"%(self.type_id))\n return\n\n def enum_entities(self, user_perms=None, usealtparent=False):\n \"\"\"\n Iterate over entities in collection with current type.\n Returns entities with alias fields instantiated.\n\n usealtparent is True if site-wide entities are to be included.\n \"\"\"\n if (not user_perms or \n self.permissions_map['list'] in user_perms[ANNAL.CURIE.user_permissions]):\n altparent = self.entityaltparent if usealtparent else None\n if self.entityparent:\n for eid in self.entityparent.child_entity_ids(\n self.entityclass, \n altparent=altparent):\n yield self.get_entity_with_aliases(eid)\n else:\n log.warning(\"EntityTypeInfo.enum_entities: missing entityparent; type_id %s\"%(self.type_id))\n return\n\n def get_initial_entity_values(self, entity_id):\n \"\"\"\n Returns an initial value dictionary for the indicated entity.\n\n Attempts to read initial values from the type parent directory.\n Failing that, returns system-wide default values.\n \"\"\"\n values = (\n { '@type': [ANNAL.CURIE.EntityData]\n , ANNAL.CURIE.type_id: self.type_id\n , RDFS.CURIE.label: \"\"\n , RDFS.CURIE.comment: \"\"\n })\n init_entity = self.get_entity(\"_initial_values\")\n if init_entity:\n values = init_entity.get_values()\n values.pop(\"@id\", None)\n values.pop(ANNAL.CURIE.id, None)\n values.pop(ANNAL.CURIE.url, None)\n values[ANNAL.CURIE.id] = entity_id\n return values\n\n def get_default_view_id(self):\n \"\"\"\n Returns the default view id for the current record type\n \"\"\"\n view_id = None\n if self.recordtype:\n view_id = self.recordtype.get(ANNAL.CURIE.type_view, None)\n else:\n log.warning(\"EntityTypeInfo.get_default_view_id: no type data for %s\"%(self.type_id))\n return view_id or \"Default_view\"\n\n# End.\n","sub_path":"src/annalist_root/annalist/models/entitytypeinfo.py","file_name":"entitytypeinfo.py","file_ext":"py","file_size_in_byte":17993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335680315","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nfrom rest_framework import routers\n\nfrom .views import (IndexView, UserViewSet, GroupViewSet, RestrictedView)\nfrom projects.views import (ProjectViewSet, UserProjectViewSet)\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'groups', GroupViewSet)\nrouter.register(r'projects', ProjectViewSet)\nrouter.register(r'userprojects', UserProjectViewSet)\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', IndexView.as_view(), name='home'),\n\n # This is the base url for the DRF API. The DRF router will handle all api calls\n url(r'^api/v1.0/', include(router.urls)),\n\n # URL for handling authorization of API calls\n url(r'^api/v1.0/api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n\n # Auth\n url(r'^api/v1.0/auth/login/', 'rest_framework_jwt.views.obtain_jwt_token'),\n\n # TEST\n url(r'^api-token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),\n url(r'^restricted/$', RestrictedView.as_view()),\n\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"clearances/clearances/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"615723587","text":"from django.contrib import messages\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render, redirect\nfrom .models import Contact, post, Catagory, BlogComment\nfrom django.http import HttpResponse\nfrom shop.models import MyProfile\nfrom blog.templatetags import extras\nfrom .serializers import postSerializer\nfrom rest_framework.renderers import JSONRenderer\n\ndef index(request):\n dataa = post.acceptpost.all().order_by('-post_id')\n datar = post.acceptpost.filter().order_by('-post_id')[0:3]\n cat = Catagory.objects.all()\n\n paginator = Paginator(dataa, 2)\n page_num = request.GET.get('page')\n page_obj = paginator.get_page(page_num)\n d = {'data': page_obj, 'data1': datar, 'catag': cat}\n return render(request, 'blog/home.html', d)\n\n\ndef post_detail(request, id):\n dataa = post.objects.get(post_id=id)\n datar = post.objects.filter().order_by('-post_id')[0:3]\n cat = Catagory.objects.all()\n com = BlogComment.objects.filter(post=dataa, parent=None)\n replies = BlogComment.objects.filter(post=dataa).exclude(parent=None)\n replyDict = {}\n for reply in replies:\n if reply.parent.sno not in replyDict.keys():\n replyDict[reply.parent.sno] = [reply]\n else:\n replyDict[reply.parent.sno].append(reply)\n d = {'i': dataa, 'data1': datar, 'catag': cat, 'comments': com, 'user': request.user, 'replyDict': replyDict}\n return render(request, 'blog/blog-details.html', d)\n\n\ndef post_Search(request):\n d = \"\"\n if request.method == \"POST\":\n datas = request.POST['query']\n data1 = post.objects.filter(title__icontains=datas)\n data2 = post.objects.filter(author__username__contains=datas)\n data3 = post.objects.filter(content__icontains=datas)\n data = data1.union(data2, data3)\n if data.count == 0:\n messages.warning(request, \"no result can be found please refine your query\")\n\n d = {'data': data}\n return render(request, 'blog/search.html', d)\n\n\ndef about(request):\n return render(request, 'about.html')\n\n\ndef contact(request):\n if request.method == \"POST\":\n name = request.POST['name']\n email = request.POST['email']\n phone = request.POST['phone']\n content = request.POST['content']\n print(\"=========================\")\n print(name)\n print(\"=========================\")\n contact = Contact(name=name, email=email, phone=phone, content=content)\n contact.save()\n return render(request, 'contractus.html')\n\n\ndef postComment(request):\n if request.method == \"POST\":\n comment = request.POST.get('comment')\n user = request.user\n userpf = MyProfile.objects.get(user=user)\n postSno = request.POST.get('postSno')\n parentSno = request.POST.get('parentSno')\n postx = post.objects.get(post_id=postSno)\n\n\n if parentSno == None:\n comment = BlogComment(comment=comment, user=userpf, post=postx)\n comment.save()\n messages.success(request, \"Your comment has been posted successfully\")\n else:\n print(parentSno)\n parent = BlogComment.objects.get(sno=parentSno)\n comment = BlogComment(comment=comment, user=userpf, post=postx, parent=parent)\n comment.save()\n messages.success(request, \"Your reply has been posted successfully\")\n\n return redirect(f\"display-post/{postx.post_id}/\")\n # return redirect('/shop')\n\n\n\n\ndef postsdetail(request):\n stu = post.objects.all()\n serializer = postSerializer(stu,many=True)\n json_data = JSONRenderer().render(serializer.data)\n print(json_data)\n return HttpResponse(json_data , content_type='application/json')","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"547083826","text":"import unittest\nfrom ddt import ddt,data,file_data,unpack\n\n@ddt\nclass A(unittest.TestCase):\n @data([1,-4,7,8],[3,7,9,10])\n def test_a(self,value):\n print(\"value=\",value)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"0527练习/06/alltestcases/test_ddt.py","file_name":"test_ddt.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"277351691","text":"'''\nCreated on 9Sep.,2016\n\n@author: thomas.e\n'''\n\nimport sys\nimport os\nimport ruffus\nimport pydevd\nimport socket\nfrom ruffus.task import Pipeline\nimport subprocess\n\nHOST = '10.1.17.131'\nSOFTWARE = \"/usr/local/bioinfsoftware\"\nHOME = os.getenv(\"HOME\")\n\ndef originate(stuff):\n pass\n\ndef trim(inf, outf):\n TRIMMOMATIC = \"java -jar \" + SOFTWARE + \"/trimmomatic/current/trimmomatic-0.30.jar\"\n ADAPTORS = \"ILLUMINACLIP:\" + SOFTWARE + \"/trimmomatic/Trimmomatic-0.30/adapters/TruSeq3-SE.fa:2:30:10\"\n \n cmd = TRIMMOMATIC + \" SE \" + inf + \" \" + outf + \" \" + ADAPTORS\n rc = os.system(cmd)\n \n if rc != 0:\n raise ChildProcessError(\"trimmomatic completed abnormally: rc=\" + rc)\n\n\ndef align(inf, outf):\n BWA=SOFTWARE + \"/bwa/current/bin/bwa\"\n REF_SEQ = HOME + \"/local/share/bcbio/genomes/Hsapiens/GRCh37/bwa/GRCh37.fa\"\n \n \"\"\"\n Index the FQ file\n \"\"\"\n rc = os.system(BWA + \" index \" + inf)\n if rc != 0:\n raise ChildProcessError(\"bwa index completed abnormally: rc=\" + str(rc))\n \n \"\"\"\n Align to a SAM file\n \"\"\"\n cmd = [BWA, 'mem', '-R', r'@RG\\tID:Seq01p\\tSM:Seq01\\tPL:ILLUMINA\\tPI:330', REF_SEQ, inf]\n outfh = open(outf, 'wb')\n p = subprocess.Popen(cmd, stdout=outfh, stderr=sys.stderr)\n rc = p.wait()\n if rc != 0:\n raise ChildProcessError(\"bwa mem completed abnormally: rc=\" + rc)\n\n \ndef convert_to_sorted_bam(inf, outf):\n SAM = SOFTWARE + \"/samtools/samtools-1.3.1/bin/samtools\"\n \n convertCmd = [SAM, \"view\", \"-b\", inf]\n sortCmd = [SAM, 'sort', '-']\n outfh = open(outf, 'wb')\n pipein, pipeout = os.pipe()\n \n try:\n convertProcess = subprocess.Popen(convertCmd, stderr=sys.stderr, stdout=pipeout)\n sortProcess = subprocess.Popen(sortCmd, stdin=pipein, stdout=outfh, stderr=sys.stderr)\n \n rc = convertProcess.wait()\n if rc != 0:\n raise ChildProcessError(\"samtool view -b \" + inf + \": rc=\" + rc)\n \n rc = sortProcess.wait()\n if rc != 0:\n raise ChildProcessError(\"samtool sort \" + inf + \": rc=\" + rc)\n \n finally:\n outfh.close()\n \ndef convert_to_indexed_bam(inf, outf):\n SAM = SOFTWARE + '/samtools/samtools-1.3.1/bin/samtools'\n \n cmd = SAM + ' index ' + inf + ' ' + outf\n rc = os.system(cmd)\n if rc != 0:\n raise ChildProcessError(cmd + ' completed abnormally: rc=' + str(rc)) \n \n \ndef call(inf, outf):\n REF_SEQ = HOME + '/local/share/bcbio/genomes/Hsapiens/GRCh37/seq/GRCh37.fa'\n MUTECT2 = 'java -jar ' + SOFTWARE + '/gatk/current/GenomeAnalysisTK.jar -T MuTect2'\n \n cmd = MUTECT2 + ' --artifact_detection_mode -R ' + REF_SEQ + ' -I:tumor ' + inf + ' -o ' + outf\n \n rc = os.system(cmd)\n if rc != 0:\n raise ChildProcessError('mutect2 completed abnormally: rc=' + str(rc))\n\n\ndef pipeLineFactory (name, initial_files):\n \n pl = Pipeline(name)\n \n pl.originate(originate, initial_files)\n \n pl.transform(task_func = trim,\n name = 'trim',\n input = originate,\n filter = ruffus.suffix(\".fastq\"),\n output = '-trimmed.fastq'\n )\n \n pl.transform(task_func = align,\n name = 'align',\n input = ruffus.output_from('trim'),\n filter = ruffus.suffix('-trimmed.fastq'),\n output = '-aligned.sam'\n )\n \n pl.transform(task_func = convert_to_sorted_bam,\n name = 'convert to sorted sam',\n input = ruffus.output_from('align'),\n filter = ruffus.suffix('-aligned.sam'),\n output = '-aligned-sorted.bam'\n )\n \n pl.transform(task_func = convert_to_indexed_bam,\n name = 'convert to indexed bam',\n input = ruffus.output_from('convert to sorted sam'),\n filter = ruffus.suffix('-aligned-sorted.bam'),\n output = '-aligned-sorted.bai'\n )\n \n pl.transform(task_func = call,\n name = 'call',\n input = ruffus.output_from('convert to sorted sam'),\n filter = ruffus.suffix('-aligned-sorted.bam'),\n output = '.vcf'\n ).follows('convert to indexed bam')\n \n return pl\n\nprint('Waiting for debug server...\\n\\n')\npydevd.settrace(HOST, stdoutToServer=True, stderrToServer=True)\nprint('Running on host: ' + socket.gethostname())\n\ninitial_files = [\"data/ev.fastq\"]\n\npl = pipeLineFactory('first pipe', initial_files)\npl.run()","sub_path":"rufus/src/rto.py","file_name":"rto.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317089268","text":"import _plotly_utils.basevalidators\n\n\nclass YAxisValidator(_plotly_utils.basevalidators.SubplotidValidator):\n def __init__(self, plotly_name=\"yaxis\", parent_name=\"ohlc\", **kwargs):\n super(YAxisValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n dflt=kwargs.pop(\"dflt\", \"y\"),\n edit_type=kwargs.pop(\"edit_type\", \"calc+clearAxisTypes\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass XsrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"xsrc\", parent_name=\"ohlc\", **kwargs):\n super(XsrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass XcalendarValidator(_plotly_utils.basevalidators.EnumeratedValidator):\n def __init__(self, plotly_name=\"xcalendar\", parent_name=\"ohlc\", **kwargs):\n super(XcalendarValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"info\"),\n values=kwargs.pop(\n \"values\",\n [\n \"gregorian\",\n \"chinese\",\n \"coptic\",\n \"discworld\",\n \"ethiopian\",\n \"hebrew\",\n \"islamic\",\n \"julian\",\n \"mayan\",\n \"nanakshahi\",\n \"nepali\",\n \"persian\",\n \"jalali\",\n \"taiwan\",\n \"thai\",\n \"ummalqura\",\n ],\n ),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass XAxisValidator(_plotly_utils.basevalidators.SubplotidValidator):\n def __init__(self, plotly_name=\"xaxis\", parent_name=\"ohlc\", **kwargs):\n super(XAxisValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n dflt=kwargs.pop(\"dflt\", \"x\"),\n edit_type=kwargs.pop(\"edit_type\", \"calc+clearAxisTypes\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass XValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"x\", parent_name=\"ohlc\", **kwargs):\n super(XValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc+clearAxisTypes\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator):\n def __init__(self, plotly_name=\"visible\", parent_name=\"ohlc\", **kwargs):\n super(VisibleValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"info\"),\n values=kwargs.pop(\"values\", [True, False, \"legendonly\"]),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass UirevisionValidator(_plotly_utils.basevalidators.AnyValidator):\n def __init__(self, plotly_name=\"uirevision\", parent_name=\"ohlc\", **kwargs):\n super(UirevisionValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass UidValidator(_plotly_utils.basevalidators.StringValidator):\n def __init__(self, plotly_name=\"uid\", parent_name=\"ohlc\", **kwargs):\n super(UidValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"plot\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass TickwidthValidator(_plotly_utils.basevalidators.NumberValidator):\n def __init__(self, plotly_name=\"tickwidth\", parent_name=\"ohlc\", **kwargs):\n super(TickwidthValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n max=kwargs.pop(\"max\", 0.5),\n min=kwargs.pop(\"min\", 0),\n role=kwargs.pop(\"role\", \"style\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass TextsrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"textsrc\", parent_name=\"ohlc\", **kwargs):\n super(TextsrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass TextValidator(_plotly_utils.basevalidators.StringValidator):\n def __init__(self, plotly_name=\"text\", parent_name=\"ohlc\", **kwargs):\n super(TextValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n array_ok=kwargs.pop(\"array_ok\", True),\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass StreamValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"stream\", parent_name=\"ohlc\", **kwargs):\n super(StreamValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Stream\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n maxpoints\n Sets the maximum number of points to keep on\n the plots from an incoming stream. If\n `maxpoints` is set to 50, only the newest 50\n points will be displayed on the plot.\n token\n The stream id number links a data trace on a\n plot with a stream. See https://chart-\n studio.plotly.com/settings for more details.\n\"\"\",\n ),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass ShowlegendValidator(_plotly_utils.basevalidators.BooleanValidator):\n def __init__(self, plotly_name=\"showlegend\", parent_name=\"ohlc\", **kwargs):\n super(ShowlegendValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"style\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass SelectedpointsValidator(_plotly_utils.basevalidators.AnyValidator):\n def __init__(self, plotly_name=\"selectedpoints\", parent_name=\"ohlc\", **kwargs):\n super(SelectedpointsValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass OpensrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"opensrc\", parent_name=\"ohlc\", **kwargs):\n super(OpensrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass OpenValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"open\", parent_name=\"ohlc\", **kwargs):\n super(OpenValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass OpacityValidator(_plotly_utils.basevalidators.NumberValidator):\n def __init__(self, plotly_name=\"opacity\", parent_name=\"ohlc\", **kwargs):\n super(OpacityValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"style\"),\n max=kwargs.pop(\"max\", 1),\n min=kwargs.pop(\"min\", 0),\n role=kwargs.pop(\"role\", \"style\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass NameValidator(_plotly_utils.basevalidators.StringValidator):\n def __init__(self, plotly_name=\"name\", parent_name=\"ohlc\", **kwargs):\n super(NameValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"style\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass MetasrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"metasrc\", parent_name=\"ohlc\", **kwargs):\n super(MetasrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass MetaValidator(_plotly_utils.basevalidators.AnyValidator):\n def __init__(self, plotly_name=\"meta\", parent_name=\"ohlc\", **kwargs):\n super(MetaValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n array_ok=kwargs.pop(\"array_ok\", True),\n edit_type=kwargs.pop(\"edit_type\", \"plot\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass LowsrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"lowsrc\", parent_name=\"ohlc\", **kwargs):\n super(LowsrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass LowValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"low\", parent_name=\"ohlc\", **kwargs):\n super(LowValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass LineValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"line\", parent_name=\"ohlc\", **kwargs):\n super(LineValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Line\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n dash\n Sets the dash style of lines. Set to a dash\n type string (\"solid\", \"dot\", \"dash\",\n \"longdash\", \"dashdot\", or \"longdashdot\") or a\n dash length list in px (eg \"5px,10px,2px,2px\").\n Note that this style setting can also be set\n per direction via `increasing.line.dash` and\n `decreasing.line.dash`.\n width\n [object Object] Note that this style setting\n can also be set per direction via\n `increasing.line.width` and\n `decreasing.line.width`.\n\"\"\",\n ),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass LegendgroupValidator(_plotly_utils.basevalidators.StringValidator):\n def __init__(self, plotly_name=\"legendgroup\", parent_name=\"ohlc\", **kwargs):\n super(LegendgroupValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"style\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass IncreasingValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"increasing\", parent_name=\"ohlc\", **kwargs):\n super(IncreasingValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Increasing\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n line\n :class:`plotly.graph_objects.ohlc.increasing.Li\n ne` instance or dict with compatible properties\n\"\"\",\n ),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass IdssrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"idssrc\", parent_name=\"ohlc\", **kwargs):\n super(IdssrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass IdsValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"ids\", parent_name=\"ohlc\", **kwargs):\n super(IdsValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HovertextsrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"hovertextsrc\", parent_name=\"ohlc\", **kwargs):\n super(HovertextsrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HovertextValidator(_plotly_utils.basevalidators.StringValidator):\n def __init__(self, plotly_name=\"hovertext\", parent_name=\"ohlc\", **kwargs):\n super(HovertextValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n array_ok=kwargs.pop(\"array_ok\", True),\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"hoverlabel\", parent_name=\"ohlc\", **kwargs):\n super(HoverlabelValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Hoverlabel\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n align\n Sets the horizontal alignment of the text\n content within hover label box. Has an effect\n only if the hover label text spans more two or\n more lines\n alignsrc\n Sets the source reference on Chart Studio Cloud\n for align .\n bgcolor\n Sets the background color of the hover labels\n for this trace\n bgcolorsrc\n Sets the source reference on Chart Studio Cloud\n for bgcolor .\n bordercolor\n Sets the border color of the hover labels for\n this trace.\n bordercolorsrc\n Sets the source reference on Chart Studio Cloud\n for bordercolor .\n font\n Sets the font used in hover labels.\n namelength\n Sets the default length (in number of\n characters) of the trace name in the hover\n labels for all traces. -1 shows the whole name\n regardless of length. 0-3 shows the first 0-3\n characters, and an integer >3 will show the\n whole name if it is less than that many\n characters, but if it is longer, will truncate\n to `namelength - 3` characters and add an\n ellipsis.\n namelengthsrc\n Sets the source reference on Chart Studio Cloud\n for namelength .\n split\n Show hover information (open, close, high, low)\n in separate labels.\n\"\"\",\n ),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HoverinfosrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"hoverinfosrc\", parent_name=\"ohlc\", **kwargs):\n super(HoverinfosrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HoverinfoValidator(_plotly_utils.basevalidators.FlaglistValidator):\n def __init__(self, plotly_name=\"hoverinfo\", parent_name=\"ohlc\", **kwargs):\n super(HoverinfoValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n array_ok=kwargs.pop(\"array_ok\", True),\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n extras=kwargs.pop(\"extras\", [\"all\", \"none\", \"skip\"]),\n flags=kwargs.pop(\"flags\", [\"x\", \"y\", \"z\", \"text\", \"name\"]),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HighsrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"highsrc\", parent_name=\"ohlc\", **kwargs):\n super(HighsrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass HighValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"high\", parent_name=\"ohlc\", **kwargs):\n super(HighValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass DecreasingValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"decreasing\", parent_name=\"ohlc\", **kwargs):\n super(DecreasingValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Decreasing\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n line\n :class:`plotly.graph_objects.ohlc.decreasing.Li\n ne` instance or dict with compatible properties\n\"\"\",\n ),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass CustomdatasrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"customdatasrc\", parent_name=\"ohlc\", **kwargs):\n super(CustomdatasrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"customdata\", parent_name=\"ohlc\", **kwargs):\n super(CustomdataValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass ClosesrcValidator(_plotly_utils.basevalidators.SrcValidator):\n def __init__(self, plotly_name=\"closesrc\", parent_name=\"ohlc\", **kwargs):\n super(ClosesrcValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"none\"),\n role=kwargs.pop(\"role\", \"info\"),\n **kwargs\n )\n\n\nimport _plotly_utils.basevalidators\n\n\nclass CloseValidator(_plotly_utils.basevalidators.DataArrayValidator):\n def __init__(self, plotly_name=\"close\", parent_name=\"ohlc\", **kwargs):\n super(CloseValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n role=kwargs.pop(\"role\", \"data\"),\n **kwargs\n )\n","sub_path":"contrib/python/plotly/py2/plotly/validators/ohlc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":21865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335273869","text":"\"\"\"\nPrediction.py\npredict training set and calculate accuracy\n\"\"\"\n\nfrom dr.mathEx import *\nfrom dr.utils import \\\n load_datas, \\\n load_parameters, \\\n print_pypath\n\n\ndef predict(x, y, parameters):\n \"\"\"\n prediction over a dataset\n\n :param x: input X\n :param y: output Y\n :param parameters: parameters got from training\n :return: array of prediction\n \"\"\"\n m = x.shape[1]\n n = len(parameters) // 2 # number of layers in the neural network\n\n # Forward propagation\n probas, caches = l_model_forward(x, parameters)\n\n # changing probabilities to predictions using one vs. all method\n prediction = one_vs_all_prediction(probas)\n\n # print results\n # print (\"predictions: \" + str(prediction))\n # print (\"true labels: \" + str(y))\n print(\"Accuracy: \" + str(np.sum((prediction == y) / m)))\n\n return prediction\n\n\ndef run():\n np.random.seed(1)\n\n # load data\n train_x_orig, train_y_orig, test_x_orig, test_y_orig = load_datas()\n\n # standardization\n train_x = train_x_orig / 255.\n test_x = test_x_orig / 255.\n\n # load parameters\n parameters = load_parameters()\n\n # predict on training set and test set\n pred_train = predict(train_x, train_y_orig, parameters)\n pred_test = predict(test_x, test_y_orig, parameters)\n\n\nif __name__ == '__main__':\n print_pypath()\n run()\n\n","sub_path":"dr/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"645567756","text":"import os\nimport numpy as np\nimport tensorflow as tf\n\nfrom utils import pp, to_json, show_all_variables\nfrom trainer import Trainer\nfrom membership_trainer import MembershipTrainer\n\nflags = tf.app.flags\nflags.DEFINE_integer(\"epoch\", 20, \"Epoch to train [20]\")\nflags.DEFINE_float(\n \"learning_rate\",\n 0.0002,\n \"Learning rate of for adam [0.0002]\")\nflags.DEFINE_float(\"beta1\", 0.5, \"Momentum term of adam [0.5]\")\nflags.DEFINE_integer(\"train_size\", None, \"The size of train images [None]\")\nflags.DEFINE_integer(\"batch_size\", 64, \"The size of batch images [64]\")\nflags.DEFINE_integer(\n \"output_height\",\n 64,\n \"The size of the output images to produce [64]\")\nflags.DEFINE_integer(\n \"output_width\",\n None,\n \"The size of the output images to produce. If None, same value as output_height [None]\")\nflags.DEFINE_string(\n \"name\",\n \"model\",\n \"Name of the model [model]\")\nflags.DEFINE_string(\n \"train_set\",\n None,\n \"The directory that contains the images used for training. Should locate\" +\n \"/data. If None, same value as name [None]\")\nflags.DEFINE_string(\n \"test_set\",\n None,\n \"The directory that contains the images used for testing. Should locate\" +\n \"/data. If None, same value as name [None]\")\nflags.DEFINE_string(\n \"input_fname_pattern\",\n \"*.jpg\",\n \"Glob pattern of filename of input images [*.jpg]\")\nflags.DEFINE_string(\n \"checkpoint_dir\",\n \"checkpoint\",\n \"The directory to save the checkpoints [checkpoint]\")\nflags.DEFINE_string(\n \"sample_dir\",\n \"samples\",\n \"The directory to save the image samples [samples]\")\nflags.DEFINE_boolean(\n \"crop\",\n False,\n \"Center-crop input images [False]\")\nFLAGS = flags.FLAGS\n\ndef main(_):\n pp.pprint(flags.FLAGS.__flags)\n\n if FLAGS.output_width is None:\n FLAGS.output_width = FLAGS.output_height\n if FLAGS.train_set is None:\n FLAGS.train_set = os.path.join(FLAGS.name, 'train')\n if FLAGS.test_set is None:\n FLAGS.test_set = os.path.join(FLAGS.name, 'test')\n\n #gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)\n run_config = tf.ConfigProto()\n run_config.gpu_options.allow_growth = True\n\n with tf.Session(config=run_config) as sess:\n trainer = MembershipTrainer(\n sess,\n FLAGS.name,\n FLAGS.train_set,\n FLAGS.test_set,\n batch_size=FLAGS.batch_size,\n output_width=FLAGS.output_width,\n output_height=FLAGS.output_height,\n train_size=FLAGS.train_size,\n input_fname_pattern=FLAGS.input_fname_pattern,\n checkpoint_dir=FLAGS.checkpoint_dir)\n\n show_all_variables()\n\n trainer.train(FLAGS)\n # to_json(\"./web/js/layers.js\", [dcgan.h0_w, dcgan.h0_b, dcgan.g_bn0],\n # [dcgan.h1_w, dcgan.h1_b, dcgan.g_bn1],\n # [dcgan.h2_w, dcgan.h2_b, dcgan.g_bn2],\n # [dcgan.h3_w, dcgan.h3_b, dcgan.g_bn3],\n # [dcgan.h4_w, dcgan.h4_b, None])\n\n # Below is codes for visualization\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613214351","text":"import FWCore.ParameterSet.Config as cms\n\n#####################\n# Options parsing #\n#####################\n\nfrom FWCore.ParameterSet.VarParsing import VarParsing\nimport os, sys\n\noptions = VarParsing('analysis')\noptions.register('isData',False,VarParsing.multiplicity.singleton,VarParsing.varType.bool,'Run on real data')\noptions.register('applyMETFilters',True,VarParsing.multiplicity.singleton,VarParsing.varType.bool,'Apply MET filters')\noptions.register('applyJEC',False,VarParsing.multiplicity.singleton,VarParsing.varType.bool,'Apply JEC corrections')\noptions.register('fillMCScaleWeight',True,VarParsing.multiplicity.singleton,VarParsing.varType.bool,'Fill PDF weights')\noptions.register('fillPUInfo',True,VarParsing.multiplicity.singleton,VarParsing.varType.bool,'Fill PU info')\noptions.register('nPDF', -1, VarParsing.multiplicity.singleton, VarParsing.varType.int, \"nPDF\")\noptions.register('confFile', 'conf.xml', VarParsing.multiplicity.singleton, VarParsing.varType.string, \"Flattree variables configuration\")\noptions.register('bufferSize', 32000, VarParsing.multiplicity.singleton, VarParsing.varType.int, \"Buffer size for branches of the flat tree\")\noptions.parseArguments()\n\n##########################\n# Global configuration #\n##########################\n\nprocess = cms.Process(\"FlatTree\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\nprocess.MessageLogger.cerr.threshold = 'ERROR'\nprocess.MessageLogger.suppressWarning = cms.untracked.vstring([\"JetPtMismatchAtLowPt\",\"NullTransverseMomentum\"])\n\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')\nfrom Configuration.AlCa.GlobalTag import GlobalTag\n\nif options.isData:\n process.GlobalTag.globaltag = '80X_dataRun2_2016SeptRepro_v5'\nelse: \n process.GlobalTag.globaltag = '80X_mcRun2_asymptotic_2016_TrancheIV_v6'\n\nprocess.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\n \ncorName=\"Summer16_23Sep2016V3_MC\"\ncorTag=\"JetCorrectorParametersCollection_\"+corName\nif options.isData:\n corName=\"Summer16_23Sep2016AllV3_DATA\"\n corTag=\"JetCorrectorParametersCollection_\"+corName\ndBFile=corName+\".db\"\n\nprocess.load(\"CondCore.CondDB.CondDB_cfi\")\nprocess.jec = cms.ESSource(\"PoolDBESSource\",\n DBParameters = cms.PSet(\n messageLevel = cms.untracked.int32(0)\n ),\n timetype = cms.string('runnumber'),\n toGet = cms.VPSet(\n cms.PSet(\n record = cms.string('JetCorrectionsRecord'),\n tag = cms.string(corTag+\"_AK4PF\"),\n label = cms.untracked.string('AK4PF')\n ),\n cms.PSet(\n record = cms.string('JetCorrectionsRecord'),\n tag = cms.string(corTag+\"_AK4PFchs\"),\n label = cms.untracked.string('AK4PFchs')\n ),\n cms.PSet(\n record = cms.string('JetCorrectionsRecord'),\n tag = cms.string(corTag+\"_AK8PF\"),\n label = cms.untracked.string('AK8PF')\n ),\n cms.PSet(\n record = cms.string('JetCorrectionsRecord'),\n tag = cms.string(corTag+\"_AK8PFchs\"),\n label = cms.untracked.string('AK8PFchs')\n ),\n ),\n connect = cms.string(\"sqlite_file:\"+dBFile)\n)\nprocess.es_prefer_jec = cms.ESPrefer('PoolDBESSource','jec') \n\nprocess.load('Configuration.StandardSequences.Services_cff')\nif not options.isData:\n process.RandomNumberGeneratorService = cms.Service(\"RandomNumberGeneratorService\",\n calibratedPatElectrons = cms.PSet( initialSeed = cms.untracked.uint32(81),\n engineName = cms.untracked.string('TRandom3'),\n ),\n calibratedPatPhotons = cms.PSet( initialSeed = cms.untracked.uint32(81),\n engineName = cms.untracked.string('TRandom3'),\n ),\n )\n\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\n\ncorList = cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute'])\nif options.isData:\n corList = cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'])\n\n# Re-apply JEC to AK4\nfrom PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection\n\nbTagDiscriminators = [\n 'deepFlavourJetTags:probudsg',\n 'deepFlavourJetTags:probb',\n 'deepFlavourJetTags:probc',\n 'deepFlavourJetTags:probbb',\n 'deepFlavourJetTags:probcc',\n]\n \n#updateJetCollection(\n# process,\n# jetSource = cms.InputTag('slimmedJets'),\n# labelName = 'UpdatedJEC',\n# jetCorrections = ('AK4PFchs', corList, 'None')\n#)\n\nupdateJetCollection(\n process,\n jetSource = cms.InputTag('slimmedJets'),\n labelName = 'UpdatedJEC',\n jetCorrections = ('AK4PFchs', corList, 'None'),\n btagDiscriminators = bTagDiscriminators\n)\n\njetsNameAK4=\"selectedUpdatedPatJetsUpdatedJEC\"\n#jetsNameAK4=\"slimmedJets\"\n\n########################\n# Additional modules #\n########################\n\nif not options.isData:\n process.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\n\n from PhysicsTools.JetMCAlgos.HadronAndPartonSelector_cfi import selectedHadronsAndPartons\n process.selectedHadronsAndPartons = selectedHadronsAndPartons.clone(\n particles = \"prunedGenParticles\"\n )\n\n from PhysicsTools.JetMCAlgos.AK4PFJetsMCFlavourInfos_cfi import ak4JetFlavourInfos\n process.genJetFlavourInfos = ak4JetFlavourInfos.clone(\n jets = \"slimmedGenJets\"\n )\n\n from PhysicsTools.JetMCAlgos.GenHFHadronMatcher_cff import matchGenBHadron\n process.matchGenBHadron = matchGenBHadron.clone(\n genParticles = \"prunedGenParticles\",\n jetFlavourInfos = \"genJetFlavourInfos\"\n )\n\n from PhysicsTools.JetMCAlgos.GenHFHadronMatcher_cff import matchGenCHadron\n process.matchGenCHadron = matchGenCHadron.clone(\n genParticles = \"prunedGenParticles\",\n jetFlavourInfos = \"genJetFlavourInfos\"\n )\n\n# egamma\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\nswitchOnVIDElectronIdProducer(process,DataFormat.MiniAOD)\n\n# https://twiki.cern.ch/twiki/bin/view/CMS/CutBasedElectronIdentificationRun2\n# https://twiki.cern.ch/twiki/bin/view/CMS/MultivariateElectronIdentificationRun2\n\nmy_id_modules = [\n'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Summer16_80X_V1_cff',\n'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV60_cff',\n'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_nonTrig_V1_cff'\n]\n\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)\n\nprocess.load(\"RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi\")\n\n# https://twiki.cern.ch/twiki/bin/viewauth/CMS/EGMSmearer\nprocess.load('EgammaAnalysis.ElectronTools.calibratedElectronsRun2_cfi')\n\nprocess.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')\nprocess.BadChargedCandidateFilter.muons = cms.InputTag(\"slimmedMuons\")\nprocess.BadChargedCandidateFilter.PFCandidates = cms.InputTag(\"packedPFCandidates\")\n\nprocess.load('RecoMET.METFilters.BadPFMuonFilter_cfi')\nprocess.BadPFMuonFilter.muons = cms.InputTag(\"slimmedMuons\")\nprocess.BadPFMuonFilter.PFCandidates = cms.InputTag(\"packedPFCandidates\")\n\n#####################\n# MET Significance #\n#####################\nprocess.load(\"RecoMET/METProducers.METSignificance_cfi\")\nprocess.load(\"RecoMET/METProducers.METSignificanceParams_cfi\")\nfrom RecoMET.METProducers.testInputFiles_cff import recoMETtestInputFiles\n\n###########\n# Input #\n###########\n\nprocess.source = cms.Source(\"PoolSource\",\n duplicateCheckMode = cms.untracked.string(\"noDuplicateCheck\"), # WARNING / FIXME for test only !\n fileNames = cms.untracked.vstring(\n# '/store/data/Run2016B/DoubleEG/MINIAOD/23Sep2016-v3/00000/68C5F6A4-1999-E611-B338-02163E013B09.root'\n '/store/mc/RunIISummer16MiniAODv2/TTWJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext2-v1/110000/0015BB42-9BAA-E611-8C7F-0CC47A7E0196.root'\n )\n)\n\n############\n# Output #\n############\n\nprocess.TFileService = cms.Service(\"TFileService\", fileName = cms.string(\"output.root\"))\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(False),\n allowUnscheduled = cms.untracked.bool(True)\t # needed for ak10 computation (JMEAnalysis/JetToolbox)\n)\n \n#############################\n# Flat Tree configuration #\n#############################\n\nprocess.FlatTree = cms.EDAnalyzer('FlatTreeProducer',\n\n dataFormat = cms.string(\"MINIAOD\"),\n\n bufferSize = cms.int32(options.bufferSize),\n confFile = cms.string(options.confFile),\n\n isData = cms.bool(options.isData),\n applyMETFilters = cms.bool(options.applyMETFilters),\n fillMCScaleWeight = cms.bool(options.fillMCScaleWeight),\n fillPUInfo\t = cms.bool(options.fillPUInfo),\n nPDF = cms.int32(options.nPDF),\n \n vertexInput = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n electronInput = cms.InputTag(\"slimmedElectrons\"),\n #electronPATInput = cms.InputTag(\"slimmedElectrons\"),\n electronPATInput = cms.InputTag(\"calibratedPatElectrons\"),\n\n# eleVetoCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-veto\"),\n# eleLooseCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-loose\"),\n# eleMediumCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium\"),\n# eleTightCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-tight\"),\n eleVetoCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto\"),\n eleLooseCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose\"),\n eleMediumCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium\"),\n eleTightCBIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight\"),\n eleHEEPCBIdMap = cms.InputTag(\"egmGsfElectronIDs:heepElectronID-HEEPV60\"),\n\n eleMediumMVAIdMap = cms.InputTag(\"egmGsfElectronIDs:mvaEleID-Spring15-25ns-nonTrig-V1-wp90\"),\n eleTightMVAIdMap = cms.InputTag(\"egmGsfElectronIDs:mvaEleID-Spring15-25ns-nonTrig-V1-wp80\"),\n mvaValuesMap = cms.InputTag(\"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values\"),\n mvaCategoriesMap = cms.InputTag(\"electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Categories\"),\n\n BadMuonFilter = cms.InputTag(\"BadPFMuonFilter\",\"\"),\n BadChargedCandidateFilter = cms.InputTag(\"BadChargedCandidateFilter\",\"\"),\n \n filterTriggerNames = cms.untracked.vstring(\n# \"*\"\n \"HLT_Ele35_WPLoose_Gsf_v*\",\n \"HLT_Ele27_WPTight_Gsf_v*\",\n \"HLT_Ele32_eta2p1_WPTight_Gsf_v*\",\n \"HLT_IsoMu22_v*\",\n \"HLT_IsoTkMu22_v*\",\n \"HLT_IsoMu24_v*\",\n \"HLT_IsoTkMu24_v*\"\n ),\n \n muonInput = cms.InputTag(\"slimmedMuons\"),\n tauInput = cms.InputTag(\"slimmedTaus\"),\n jetInput = cms.InputTag(jetsNameAK4),\n genJetInput = cms.InputTag(\"slimmedGenJets\"),\n jetFlavorMatchTokenInput = cms.InputTag(\"jetFlavourMatch\"),\n metInput = cms.InputTag(\"slimmedMETs\"),\n metPuppiInput = cms.InputTag(\"slimmedMETsPuppi\"),\n metNoHFInput = cms.InputTag(\"slimmedMETsNoHF\"),\n metSigInput = cms.InputTag(\"METSignificance\"),\n metCovInput = cms.InputTag(\"METSignificance\",\"METCovariance\"),\n rhoInput = cms.InputTag(\"fixedGridRhoFastjetCentralNeutral\"),\n genParticlesInput = cms.InputTag(\"prunedGenParticles\"),\n genEventInfoInput = cms.InputTag(\"generator\"),\n LHEEventProductInput = cms.InputTag(\"externalLHEProducer\"),\n bsInput = cms.InputTag(\"offlineBeamSpot\"),\n pfcandsInput = cms.InputTag(\"packedPFCandidates\"),\n hConversionsInput = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n puInfoInput\t\t = cms.InputTag(\"slimmedAddPileupInfo\"),\n# puInfoInput\t\t = cms.InputTag(\"addPileupInfo\"),\n objects = cms.InputTag(\"selectedPatTrigger\"),\n \n genTTXJets = cms.InputTag(\"slimmedGenJets\"),\n genTTXBHadJetIndex = cms.InputTag(\"matchGenBHadron\",\"genBHadJetIndex\"),\n genTTXBHadFlavour = cms.InputTag(\"matchGenBHadron\",\"genBHadFlavour\"),\n genTTXBHadFromTopWeakDecay = cms.InputTag(\"matchGenBHadron\",\"genBHadFromTopWeakDecay\"),\n genTTXBHadPlusMothers = cms.InputTag(\"matchGenBHadron\",\"genBHadPlusMothers\"),\n genTTXBHadPlusMothersIndices = cms.InputTag(\"matchGenBHadron\",\"genBHadPlusMothersIndices\"),\n genTTXBHadIndex = cms.InputTag(\"matchGenBHadron\",\"genBHadIndex\"),\n genTTXBHadLeptonHadronIndex = cms.InputTag(\"matchGenBHadron\",\"genBHadLeptonHadronIndex\"),\n genTTXBHadLeptonViaTau = cms.InputTag(\"matchGenBHadron\",\"genBHadLeptonViaTau\"),\n genTTXCHadJetIndex = cms.InputTag(\"matchGenCHadron\",\"genCHadJetIndex\"),\n genTTXCHadFlavour = cms.InputTag(\"matchGenCHadron\",\"genCHadFlavour\"),\n genTTXCHadFromTopWeakDecay = cms.InputTag(\"matchGenCHadron\",\"genCHadFromTopWeakDecay\"),\n genTTXCHadBHadronId = cms.InputTag(\"matchGenCHadron\",\"genCHadBHadronId\")\n)\n\n##########\n# Path #\n##########\n\nprocess.p = cms.Path(\n process.calibratedPatElectrons+\n process.electronMVAValueMapProducer+\n process.egmGsfElectronIDSequence+\n process.METSignificance+\n process.BadChargedCandidateFilter+\n process.BadPFMuonFilter+\n process.FlatTree\n )\n","sub_path":"FlatTreeProducer/python/ConfFile_MINIAOD_cfg.py","file_name":"ConfFile_MINIAOD_cfg.py","file_ext":"py","file_size_in_byte":15932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635908750","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/dbtexmf/dblatex/grubber/ps2pdf.py\n# Compiled at: 2017-04-03 18:58:57\n\"\"\"\nPostScript to PDF conversion using GhostScript.\n\"\"\"\nimport sys, os\nfrom msg import _, msg\nfrom maker import DependShell\nfrom plugins import TexModule\n\nclass Module(TexModule):\n\n def __init__(self, doc, dict):\n env = doc.env\n ps = env.dep_last().prods[0]\n root, ext = os.path.splitext(ps)\n if ext != '.ps':\n msg.error(_(\"I can't use ps2pdf when not producing a PS\"))\n sys.exit(2)\n pdf = root + '.pdf'\n cmd = ['ps2pdf']\n for opt in doc.paper.split():\n cmd.append('-sPAPERSIZE=' + opt)\n\n cmd.extend([ps, pdf])\n dep = DependShell(env, cmd, prods=[pdf], sources={ps: env.dep_last()})\n env.dep_append(dep)","sub_path":"pycfiles/dblatex-0.3.10-py2.7/ps2pdf.py","file_name":"ps2pdf.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351050931","text":"from collections import Counter\nfrom zipfile import ZipFile\nimport re\n'''\nI would like to note that there are inconsitencies between the provided code here and the provided code in the test files. \nThat is to say that this file in its current form will return a byte-like object error with the provided main function code, but will pass the tests from tests.py\nI believe this is due to the fact that yield returns byte-like objects, and the testing file can handle this, but the provided code cannot. \nThe fix to get this file to run correctly is to uncomment the decode line in the words() function. \nDoing this will make the file not pass the tests. \n'''\nkWORDS = re.compile(\"[a-z]{4,}\")\n#re.compile takes a regex expression and saves it for later to be compared against, I use it in the words function\n\ndef text_from_zipfile(zip_file):\n \"\"\"\n Given a zip file, yield an iterator over the text in each file in the\n zip file.\n \"\"\"\n # Modify this function\n with ZipFile(zip_file,'r') as speeches:\n text_files = speeches.namelist()\n for filename in text_files:\n with speeches.open(filename) as speech_text:\n yield(speech_text.read())\ndef words(text):\n \"\"\"\n Return all words in a string, where a word is four or more contiguous\n characters in the range a-z or A-Z. The resulting words should be\n lower case.\n \"\"\"\n #text = text.decode('utf-8','ignore')\n text=text.lower()\n matched_words = kWORDS.findall(text)\n return matched_words\n\ndef accumulate_counts(words, total=Counter()):\n \"\"\"\n Take an iterator over words, add the sum to the total, and return the\n total.\n\n @words An iterable object that contains the words in a document\n @total The total counter we should add the counts to\n \"\"\"\n assert isinstance(total, Counter)\n for i in words:\n total[i] += 1\n # Modify this function \n return total\n\nif __name__ == \"__main__\":\n # You should not need to modify this part of the code\n total = Counter()\n for tt in text_from_zipfile(\"data/state_union.zip\"):\n total = accumulate_counts(words(tt), total)\n\n for ii, cc in total.most_common(100):\n print(\"%s\\t%i\" % (ii, cc))\n","sub_path":"Assignment1/word_counts.py","file_name":"word_counts.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443068812","text":"import os, os.path as op\nimport logging\nimport shutil\nimport progressbar\n\nfrom shuffler.utils import general as general_utils\nfrom shuffler.utils import parser as parser_utils\n\n\ndef add_parsers(subparsers):\n exportYoloParser(subparsers)\n\n\ndef exportYoloParser(subparsers):\n parser = subparsers.add_parser(\n 'exportYolo',\n description='Export the database into YOLO format. '\n 'Limitations: \"segments\" is TODO.')\n parser.set_defaults(func=exportYolo)\n parser.add_argument('--yolo_dir',\n required=True,\n help='Root directory of YOLO.')\n images_policy = parser.add_mutually_exclusive_group()\n images_policy.add_argument(\n '--copy_images',\n action='store_true',\n help=\n 'If specified, will copy images to args.yolo_dir/\"images\"/args.subset. '\n 'Required, if the media is stored as video. ')\n images_policy.add_argument(\n '--symlink_images',\n action='store_true',\n help='If specified, creates a symbolic link from imagefiles '\n 'to imagefiles at args.coco_dir/\"yolo\"/args.subset/. '\n 'Valid only if all the media is stored as images.')\n parser.add_argument('--subset',\n required=True,\n help='Name of the subset, such as \"train2017')\n parser.add_argument(\n '--classes',\n required=True,\n help='Classes of interest in order. Will look at object names for them.'\n )\n parser.add_argument(\n '--as_polygons',\n action='store_true',\n help=\n 'Save in the format of https://github.com/XinzeLee/PolygonObjectDetection'\n )\n parser_utils.addExportedImageNameArguments(parser)\n\n\n# Truncates numbers to N decimals\ndef _truncate(n, decimals=0):\n multiplier = 10**decimals\n return int(n * multiplier) / multiplier\n\n\ndef _exportImage(c, imagefile, imwidth, imheight, classes):\n lines = []\n c.execute('SELECT name,x1,y1,width,height FROM objects WHERE imagefile=?',\n (imagefile, ))\n for name, x1, y1, width, height in c.fetchall():\n try:\n label_id = classes.index(name)\n except ValueError:\n continue\n\n xn = (x1 + width / 2.) / imwidth\n yn = (y1 + height / 2.) / imheight\n wn = width / imwidth\n hn = height / imheight\n\n logging.debug('x1: %f, width: %f, imwidth: %f, xn: %f, wn: %f', x1,\n width, imwidth, xn, wn)\n\n line = (f'{label_id} {_truncate(xn, 7)} {_truncate(yn, 7)} ' +\n f'{_truncate(wn, 7)} {_truncate(hn, 7)}\\n')\n logging.debug('label entry: %s', line)\n lines.append(line)\n return lines\n\n\ndef _exportImageAsPolygons(c, imagefile, imwidth, imheight, classes):\n lines = []\n c.execute('SELECT objectid,name FROM objects WHERE imagefile=?',\n (imagefile, ))\n for objectid, name in c.fetchall():\n # In case bboxes were not recorded as polygons.\n general_utils.bbox2polygon(c, objectid)\n\n try:\n label_id = classes.index(name)\n except ValueError:\n continue\n\n c.execute('SELECT x,y FROM polygons WHERE objectid=?', (objectid, ))\n polygon = c.fetchall()\n if len(polygon) != 4:\n logging.warning(\n 'Polygon for objectid has %d points instead of 4. Skip.',\n len(polygon))\n continue\n\n x1 = polygon[0][0] / imwidth\n x2 = polygon[1][0] / imwidth\n x3 = polygon[2][0] / imwidth\n x4 = polygon[3][0] / imwidth\n y1 = polygon[0][1] / imheight\n y2 = polygon[1][1] / imheight\n y3 = polygon[2][1] / imheight\n y4 = polygon[3][1] / imheight\n\n line = (f'{label_id} ' + f'{_truncate(x1, 7)} {_truncate(y1, 7)} ' +\n f'{_truncate(x2, 7)} {_truncate(y2, 7)} ' +\n f'{_truncate(x3, 7)} {_truncate(y3, 7)} ' +\n f'{_truncate(x4, 7)} {_truncate(y4, 7)}\\n')\n logging.debug('label entry: %s', line)\n lines.append(line)\n return lines\n\n\ndef exportYolo(c, args):\n\n # Images dir.\n image_dir = op.join(args.yolo_dir, 'images', args.subset)\n if op.exists(image_dir):\n shutil.rmtree(image_dir)\n if not op.exists(image_dir):\n os.makedirs(image_dir)\n\n # Labels dir.\n labels_dir = op.join(args.yolo_dir, 'labels', args.subset)\n if op.exists(labels_dir):\n shutil.rmtree(labels_dir)\n if not op.exists(labels_dir):\n os.makedirs(labels_dir)\n\n logging.info('Writing images.')\n c.execute('SELECT imagefile,width,height FROM images')\n for imagefile, imwidth, imheight in progressbar.progressbar(c.fetchall()):\n logging.debug('imagefile with: %s', imagefile)\n\n # Maybe copy or make a symlink for images.\n src_image_path = op.join(args.rootdir, imagefile)\n if not op.exists(src_image_path):\n raise FileNotFoundError(\n \"Image not found at %s (using rootdir %s).\" %\n (src_image_path, args.rootdir))\n\n image_path = general_utils.makeExportedImageName(\n image_dir, imagefile, args.dirtree_level_for_name,\n args.fix_invalid_image_names)\n if args.copy_images:\n shutil.copyfile(src_image_path, image_path)\n elif args.symlink_images:\n os.symlink(op.abspath(src_image_path),\n image_path,\n target_is_directory=False)\n\n # Objects.\n if args.as_polygons:\n lines = _exportImageAsPolygons(c, imagefile, imwidth, imheight,\n args.classes)\n else:\n lines = _exportImage(c, imagefile, imwidth, imheight, args.classes)\n\n # Write to labels file.\n if len(lines) > 0:\n labels_path = general_utils.makeExportedImageName(\n labels_dir, imagefile, args.dirtree_level_for_name,\n args.fix_invalid_image_names)\n labels_path = op.splitext(labels_path)[0] + '.txt'\n logging.debug('Writing labels to file: %s', labels_path)\n with open(labels_path, 'w') as f:\n f.writelines(lines)\n else:\n logging.debug('No labels in file, continue: %s', imagefile)\n","sub_path":"shuffler/operations/datasets/yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":6285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235171256","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 21 09:32:09 2017\n\n@author: LPZ\n\"\"\"\n\n#设置训练数据比例\ntrain_percentage = 1\n\n\n##使用boston数据集 \n#from sklearn import datasets\n#boston=datasets.load_boston()\n#train_size = (int)(boston.data.shape[0]*train_percentage)\n#X=boston.data[:train_size] \n#y=boston.target[:train_size] \n#X_test=boston.data[train_size:] \n#y_test=boston.target[train_size:]\n\n\n#使用protein数据集\nimport numpy as np\nimport pandas\ndata_input = pandas.read_csv(\"CASP.csv\", header = None)\n#transform pandas data to numpy data\ndata = data_input.as_matrix()\ntrain_size = (int)(data.shape[0]*train_percentage)\n#get the train data and target data\ndata = data[1:,:]\nnp.random.shuffle(data)\nX = data[:train_size,1:]\ny = data[:train_size,:1]\ny = y.reshape(y.size)\ny = y.astype(float)\n\n\n##使用friedman3数据集\n#from sklearn.datasets import make_friedman3\n#X,y = make_friedman3(n_samples=800,noise=0.0111,random_state=None)\n\n\n#使用Bagging和IterativeBagging算法进行预测并输出均方差\nfrom sklearn.ensemble import BaggingRegressor\nfrom sklearn.metrics import mean_squared_error\n\n#使用Bagging算法进行回归预测\nbr = BaggingRegressor(n_estimators=80,oob_score=True)\nbr.fit(X, y)\nprint(\"BaggingRegressor:train\")\n#包内回归测试\npredict_train = br.predict(X)\nprint(mean_squared_error(y,predict_train))\n#包外回归测试\npredict_train = br._lpz_predict(X,y)\nprint(mean_squared_error(y,predict_train))\n#print(bc.oob_score_)\n#print(\"BaggingRegressor:test\")\n#predict = br.predict(X_test)\n#print(mean_squared_error(y_test,predict))\ny1 = y\n\nerr = mean_squared_error(y,predict_train)\nmin_err = err\n#使用IterativeBagging算法进行回归预测\nprint(\"IterativeBagging\")\nfor i in range(1):\n #predict test data\n y1 = y1 - br._lpz_predict(X,y1)\n br.fit(X, y1)\n predict_train += br._lpz_predict(X,y1)\n err = mean_squared_error(y,predict_train)\n print(err)\n if(err>1.2*min_err):\n break\n if(err 0]) < 1:\n\t\tshutit.log(modules,level=logging.DEBUG)\n\t\tpath = ':'.join(shutit.host['shutit_module_path'])\n\t\tshutit.log('\\nIf you are new to ShutIt, see:\\n\\n\\thttp://ianmiell.github.io/shutit/\\n\\nor try running\\n\\n\\tshutit skeleton\\n\\n',level=logging.INFO)\n\t\tif path == '':\n\t\t\tshutit.fail('No ShutIt modules aside from core ones found and no ShutIt module path given.\\nDid you set --shutit_module_path/-m wrongly?\\n')\n\t\telif path == '.':\n\t\t\tshutit.fail('No modules aside from core ones found and no ShutIt module path given apart from default (.).\\n\\n- Did you set --shutit_module_path/-m?\\n- Is there a STOP* file in your . dir?')\n\t\telse:\n\t\t\tshutit.fail('No modules aside from core ones found and no ShutIt modules in path:\\n\\n' + path + '\\n\\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.')\n\n\tshutit.log('PHASE: base setup', level=logging.DEBUG)\n\n\trun_orders = {}\n\thas_core_module = False\n\tfor module in modules:\n\t\tassert isinstance(module, ShutItModule)\n\t\tif module.module_id in shutit.shutit_map:\n\t\t\tshutit.fail('Duplicated module id: ' + module.module_id + '\\n\\nYou may want to check your --shutit_module_path setting')\n\t\tif module.run_order in run_orders:\n\t\t\tshutit.fail('Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\\n\\nYou may want to check your --shutit_module_path setting')\n\t\tif module.run_order == 0:\n\t\t\thas_core_module = True\n\t\tshutit.shutit_map[module.module_id] = run_orders[module.run_order] = module\n\n\tif not has_core_module:\n\t\tshutit.fail('No module with run_order=0 specified! This is required.')\n\n\ndef conn_target(shutit):\n\t\"\"\"Connect to the target.\n\t\"\"\"\n\tconn_module = None\n\tfor mod in shutit.conn_modules:\n\t\tif mod.module_id == shutit.build['conn_module']:\n\t\t\tconn_module = mod\n\t\t\tbreak\n\tif conn_module is None:\n\t\tshutit.fail('Couldn\\'t find conn_module ' + shutit.build['conn_module'])\n\n\t# Set up the target in pexpect.\n\tconn_module.get_config(shutit)\n\tconn_module.build(shutit)\n\n\ndef finalize_target():\n\t\"\"\"Finalize the target using the core finalize method.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tshutit.pause_point('\\nFinalizing the target module (' + shutit.shutit_main_dir + '/shutit_setup.py)', print_input=False, level=3)\n\t# Can assume conn_module exists at this point\n\tfor mod in shutit.conn_modules:\n\t\tif mod.module_id == shutit.build['conn_module']:\n\t\t\tconn_module = mod\n\t\t\tbreak\n\tconn_module.finalize(shutit)\n\n\n# Once we have all the modules, then we can look at dependencies.\n# Dependency validation begins.\ndef resolve_dependencies(to_build, depender):\n\t\"\"\"Add any required dependencies.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tshutit.log('In resolve_dependencies',level=logging.DEBUG)\n\tcfg = shutit.cfg\n\tfor dependee_id in depender.depends_on:\n\t\tdependee = shutit.shutit_map.get(dependee_id)\n\t\t# Don't care if module doesn't exist, we check this later\n\t\tif (dependee and dependee not in to_build\n\t\t and cfg[dependee_id]['shutit.core.module.build_ifneeded']):\n\t\t\tto_build.append(dependee)\n\t\t\tcfg[dependee_id]['shutit.core.module.build'] = True\n\treturn True\n\n\ndef check_dependee_exists(depender, dependee, dependee_id):\n\t\"\"\"Checks whether a depended-on module is available.\n\t\"\"\"\n\t# If the module id isn't there, there's a problem.\n\tif dependee is None:\n\t\treturn 'module: \\n\\n' + dependee_id + '\\n\\nnot found in paths: ' + str(shutit_global.shutit.host['shutit_module_path']) + ' but needed for ' + depender.module_id + '\\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg \"--shutit_module_path /path/to/other/module/:.\"\\n\\nAlso check that the module is configured to be built with the correct module id in that module\\'s configs/build.cnf file.\\n\\nSee also help.'\n\n\ndef check_dependee_build(depender, dependee, dependee_id):\n\t\"\"\"Checks whether a depended on module is configured to be built.\n\t\"\"\"\n\tcfg = shutit_global.shutit.cfg\n\t# If depender is installed or will be installed, so must the dependee\n\tif not (cfg[dependee.module_id]['shutit.core.module.build'] or\n\t shutit_util.is_to_be_built_or_is_installed(dependee)):\n\t\treturn 'depender module id:\\n\\n[' + depender.module_id + ']\\n\\nis configured: \"build:yes\" or is already built but dependee module_id:\\n\\n[' + dependee_id + ']\\n\\n is not configured: \"build:yes\"'\n\n\ndef check_dependee_order(depender, dependee, dependee_id):\n\t\"\"\"Checks whether run orders are in the appropriate order.\n\t\"\"\"\n\t# If it depends on a module id, then the module id should be higher up\n\t# in the run order.\n\tif dependee.run_order > depender.run_order:\n\t\treturn 'depender module id:\\n\\n' + depender.module_id + '\\n\\n(run order: ' + str(depender.run_order) + ') ' + 'depends on dependee module_id:\\n\\n' + dependee_id + '\\n\\n(run order: ' + str(dependee.run_order) + ') ' + 'but the latter is configured to run after the former'\n\n\ndef make_dep_graph(depender):\n\t\"\"\"Returns a digraph string fragment based on the passed-in module\n\t\"\"\"\n\tdigraph = ''\n\tfor dependee_id in depender.depends_on:\n\t\tdigraph = (digraph + '\"' + depender.module_id + '\"->\"' + dependee_id + '\";\\n')\n\treturn digraph\n\n\ndef check_deps():\n\t\"\"\"Dependency checking phase is performed in this method.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tcfg = shutit.cfg\n\tshutit.log('PHASE: dependencies', level=logging.DEBUG)\n\tshutit.pause_point('\\nNow checking for dependencies between modules', print_input=False, level=3)\n\t# Get modules we're going to build\n\tto_build = [\n\t\tshutit.shutit_map[module_id] for module_id in shutit.shutit_map\n\t\tif module_id in cfg and cfg[module_id]['shutit.core.module.build']\n\t]\n\t# Add any deps we may need by extending to_build and altering cfg\n\tfor module in to_build:\n\t\tresolve_dependencies(to_build, module)\n\n\t# Dep checking\n\tdef err_checker(errs, triples):\n\t\t\"\"\"Collate error information.\n\t\t\"\"\"\n\t\tnew_triples = []\n\t\tfor err, triple in zip(errs, triples):\n\t\t\tif not err:\n\t\t\t\tnew_triples.append(triple)\n\t\t\t\tcontinue\n\t\t\tfound_errs.append(err)\n\t\treturn new_triples\n\n\tfound_errs = []\n\ttriples = []\n\tfor depender in to_build:\n\t\tfor dependee_id in depender.depends_on:\n\t\t\ttriples.append((depender, shutit.shutit_map.get(dependee_id), dependee_id))\n\n\ttriples = err_checker([ check_dependee_exists(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples)\n\ttriples = err_checker([ check_dependee_build(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples)\n\ttriples = err_checker([ check_dependee_order(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples)\n\n\tif found_errs:\n\t\treturn [(err,) for err in found_errs]\n\n\tshutit.log('Modules configured to be built (in order) are: ', level=logging.DEBUG)\n\tfor module_id in shutit_util.module_ids():\n\t\tmodule = shutit.shutit_map[module_id]\n\t\tif cfg[module_id]['shutit.core.module.build']:\n\t\t\tshutit.log(module_id + ' ' + str(module.run_order), level=logging.DEBUG)\n\tshutit.log('\\n', level=logging.DEBUG)\n\n\treturn []\n\n\ndef check_conflicts(shutit):\n\t\"\"\"Checks for any conflicts between modules configured to be built.\n\t\"\"\"\n\tcfg = shutit.cfg\n\t# Now consider conflicts\n\tshutit.log('PHASE: conflicts', level=logging.DEBUG)\n\terrs = []\n\tshutit.pause_point('\\nNow checking for conflicts between modules', print_input=False, level=3)\n\tfor module_id in shutit_util.module_ids():\n\t\tif not cfg[module_id]['shutit.core.module.build']:\n\t\t\tcontinue\n\t\tconflicter = shutit.shutit_map[module_id]\n\t\tfor conflictee in conflicter.conflicts_with:\n\t\t\t# If the module id isn't there, there's no problem.\n\t\t\tconflictee_obj = shutit.shutit_map.get(conflictee)\n\t\t\tif conflictee_obj is None:\n\t\t\t\tcontinue\n\t\t\tif ((cfg[conflicter.module_id]['shutit.core.module.build'] or\n\t\t\t shutit_util.is_to_be_built_or_is_installed(conflicter)) and\n\t\t\t (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or\n\t\t\t shutit_util.is_to_be_built_or_is_installed(conflictee_obj))):\n\t\t\t\terrs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,))\n\treturn errs\n\n\ndef check_ready(throw_error=True):\n\t\"\"\"Check that all modules are ready to be built, calling check_ready on\n\teach of those configured to be built and not already installed\n\t(see shutit_util.is_installed).\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tcfg = shutit.cfg\n\tshutit.log('PHASE: check_ready', level=logging.DEBUG)\n\terrs = []\n\tshutit.pause_point('\\nNow checking whether we are ready to build modules configured to be built', print_input=False, level=3)\n\t# Find out who we are to see whether we need to log in and out or not.\n\tfor module_id in shutit_util.module_ids():\n\t\tmodule = shutit.shutit_map[module_id]\n\t\tshutit.log('considering check_ready (is it ready to be built?): ' + module_id, level=logging.DEBUG)\n\t\tif cfg[module_id]['shutit.core.module.build'] and module.module_id not in shutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_ready and not shutit_util.is_installed(module):\n\t\t\tshutit.log('checking whether module is ready to build: ' + module_id, level=logging.DEBUG)\n\t\t\tshutit.login(prompt_prefix=module_id,command='bash --noprofile --norc',echo=False)\n\t\t\t# Move to the correct directory (eg for checking for the existence of files needed for build)\n\t\t\trevert_dir = os.getcwd()\n\t\t\tshutit_global.shutit.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(module.__module_file)\n\t\t\tshutit.chdir(shutit_global.shutit.get_current_shutit_pexpect_session_environment().module_root_dir)\n\t\t\tif not is_ready(module) and throw_error:\n\t\t\t\terrs.append((module_id + ' not ready to install.\\nRead the check_ready function in the module,\\nor log messages above to determine the issue.\\n\\n', shutit.get_shutit_pexpect_session_from_id('target_child')))\n\t\t\tshutit.logout(echo=False)\n\t\t\tshutit.chdir(revert_dir)\n\treturn errs\n\n\ndef do_remove(loglevel=logging.DEBUG):\n\t\"\"\"Remove modules by calling remove method on those configured for removal.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tcfg = shutit.cfg\n\t# Now get the run_order keys in order and go.\n\tshutit.log('PHASE: remove', level=loglevel)\n\tshutit.pause_point('\\nNow removing any modules that need removing', print_input=False, level=3)\n\t# Login at least once to get the exports.\n\tfor module_id in shutit_util.module_ids():\n\t\tmodule = shutit.shutit_map[module_id]\n\t\tshutit.log('considering whether to remove: ' + module_id, level=logging.DEBUG)\n\t\tif cfg[module_id]['shutit.core.module.remove']:\n\t\t\tshutit.log('removing: ' + module_id, level=logging.DEBUG)\n\t\t\tshutit.login(prompt_prefix=module_id,command='bash --noprofile --norc',echo=False)\n\t\t\tif not module.remove(shutit):\n\t\t\t\tshutit.log(shutit_util.print_modules(), level=logging.DEBUG)\n\t\t\t\tshutit.fail(module_id + ' failed on remove', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child)\n\t\t\telse:\n\t\t\t\tif shutit.build['delivery'] in ('docker','dockerfile'):\n\t\t\t\t\t# Create a directory and files to indicate this has been removed.\n\t\t\t\t\tshutit.send(' command mkdir -p ' + shutit.build['build_db_dir'] + '/module_record/' + module.module_id + ' && command rm -f ' + shutit.build['build_db_dir'] + '/module_record/' + module.module_id + '/built && command touch ' + shutit.build['build_db_dir'] + '/module_record/' + module.module_id + '/removed', loglevel=loglevel)\n\t\t\t\t\t# Remove from \"installed\" cache\n\t\t\t\t\tif module.module_id in shutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_installed:\n\t\t\t\t\t\tshutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_installed.remove(module.module_id)\n\t\t\t\t\t# Add to \"not installed\" cache\n\t\t\t\t\tshutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_not_installed.append(module.module_id)\n\t\t\tshutit.logout(echo=False)\n\n\n\ndef build_module(module, loglevel=logging.DEBUG):\n\t\"\"\"Build passed-in module.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tcfg = shutit.cfg\n\tshutit.log('Building ShutIt module: ' + module.module_id + ' with run order: ' + str(module.run_order), level=logging.INFO)\n\tshutit.build['report'] = (shutit.build['report'] + '\\nBuilding ShutIt module: ' + module.module_id + ' with run order: ' + str(module.run_order))\n\tif not module.build(shutit):\n\t\tshutit.fail(module.module_id + ' failed on build', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child)\n\telse:\n\t\tif shutit.build['delivery'] in ('docker','dockerfile'):\n\t\t\t# Create a directory and files to indicate this has been built.\n\t\t\tshutit.send(' command mkdir -p ' + shutit.build['build_db_dir'] + '/module_record/' + module.module_id + ' && command touch ' + shutit.build['build_db_dir'] + '/module_record/' + module.module_id + '/built && command rm -f ' + shutit.build['build_db_dir'] + '/module_record/' + module.module_id + '/removed', loglevel=loglevel)\n\t\t# Put it into \"installed\" cache\n\t\tshutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_installed.append(module.module_id)\n\t\t# Remove from \"not installed\" cache\n\t\tif module.module_id in shutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_not_installed:\n\t\t\tshutit_global.shutit.get_current_shutit_pexpect_session_environment().modules_not_installed.remove(module.module_id)\n\tshutit.pause_point('\\nPausing to allow inspect of build for: ' + module.module_id, print_input=True, level=2)\n\tshutit.build['report'] = (shutit.build['report'] + '\\nCompleted module: ' + module.module_id)\n\tif cfg[module.module_id]['shutit.core.module.tag']:\n\t\tshutit.log(shutit_util.build_report('#Module:' + module.module_id), level=logging.DEBUG)\n\tif not cfg[module.module_id]['shutit.core.module.tag'] and shutit.build['interactive'] >= 2:\n\t\tprint (\"\\n\\nDo you want to save state now we\\'re at the \" + \"end of this module? (\" + module.module_id + \") (input y/n)\")\n\t\tcfg[module.module_id]['shutit.core.module.tag'] = (shutit_util.util_raw_input(default='y') == 'y')\n\tif cfg[module.module_id]['shutit.core.module.tag'] or shutit.build['tag_modules']:\n\t\tshutit.log(module.module_id + ' configured to be tagged, doing repository work',level=logging.INFO)\n\t\t# Stop all before we tag to avoid file changing errors, and clean up pid files etc..\n\t\tstop_all(module.run_order)\n\t\tshutit.do_repository_work(str(module.module_id) + '_' + str(module.run_order), password=shutit.host['password'], docker_executable=shutit.host['docker_executable'], force=True)\n\t\t# Start all after we tag to ensure services are up as expected.\n\t\tstart_all(module.run_order)\n\tif shutit.build['interactive'] >= 2:\n\t\tprint (\"\\n\\nDo you want to stop interactive mode? (input y/n)\\n\")\n\t\tif shutit_util.util_raw_input(default='y') == 'y':\n\t\t\tshutit.build['interactive'] = 0\n\n\ndef do_build():\n\t\"\"\"Runs build phase, building any modules that we've determined\n\tneed building.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tcfg = shutit.cfg\n\tshutit.log('PHASE: build, repository work', level=logging.DEBUG)\n\tmodule_id_list = shutit_util.module_ids()\n\tif shutit.build['deps_only']:\n\t\tmodule_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list)\n\tfor module_id in module_id_list:\n\t\tmodule = shutit.shutit_map[module_id]\n\t\tshutit.log('Considering whether to build: ' + module.module_id, level=logging.INFO)\n\t\tif cfg[module.module_id]['shutit.core.module.build']:\n\t\t\tif shutit.build['delivery'] not in module.ok_delivery_methods:\n\t\t\t\tshutit.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\\nSee shutit build -h for more info, or try adding: --delivery to your shutit invocation')\n\t\t\tif shutit_util.is_installed(module):\n\t\t\t\tshutit.build['report'] = (shutit.build['report'] + '\\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order))\n\t\t\telse:\n\t\t\t\t# We move to the module directory to perform the build, returning immediately afterwards.\n\t\t\t\tif shutit.build['deps_only'] and module_id == module_id_list_build_only[-1]:\n\t\t\t\t\t# If this is the last module, and we are only building deps, stop here.\n\t\t\t\t\tshutit.build['report'] = (shutit.build['report'] + '\\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\\n\\tas this is the final module and we are building dependencies only')\n\t\t\t\telse:\n\t\t\t\t\trevert_dir = os.getcwd()\n\t\t\t\t\tshutit_global.shutit.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(module.__module_file)\n\t\t\t\t\tshutit.chdir(shutit_global.shutit.get_current_shutit_pexpect_session_environment().module_root_dir)\n\t\t\t\t\tshutit.login(prompt_prefix=module_id,command='bash --noprofile --norc',echo=False)\n\t\t\t\t\tbuild_module(module)\n\t\t\t\t\tshutit.logout(echo=False)\n\t\t\t\t\tshutit.chdir(revert_dir)\n\t\tif shutit_util.is_installed(module):\n\t\t\tshutit.log('Starting module',level=logging.DEBUG)\n\t\t\tif not module.start(shutit):\n\t\t\t\tshutit.fail(module.module_id + ' failed on start', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child)\n\n\ndef do_test():\n\t\"\"\"Runs test phase, erroring if any return false.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\tif not shutit.build['dotest']:\n\t\tshutit.log('Tests configured off, not running',level=logging.DEBUG)\n\t\treturn\n\t# Test in reverse order\n\tshutit.log('PHASE: test', level=logging.DEBUG)\n\tstop_all()\n\tstart_all()\n\tfor module_id in shutit_util.module_ids(rev=True):\n\t\t# Only test if it's installed.\n\t\tif shutit_util.is_installed(shutit.shutit_map[module_id]):\n\t\t\tshutit.log('RUNNING TEST ON: ' + module_id, level=logging.DEBUG)\n\t\t\tshutit.login(prompt_prefix=module_id,command='bash --noprofile --norc',echo=False)\n\t\t\tif not shutit.shutit_map[module_id].test(shutit):\n\t\t\t\tshutit.fail(module_id + ' failed on test', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child)\n\t\t\tshutit.logout(echo=False)\n\n\ndef do_finalize():\n\t\"\"\"Runs finalize phase; run after all builds are complete and all modules\n\thave been stopped.\n\t\"\"\"\n\tshutit = shutit_global.shutit\n\t# Stop all the modules\n\tstop_all()\n\t# Finalize in reverse order\n\tshutit.log('PHASE: finalize', level=logging.DEBUG)\n\t# Login at least once to get the exports.\n\tfor module_id in shutit_util.module_ids(rev=True):\n\t\t# Only finalize if it's thought to be installed.\n\t\tif shutit_util.is_installed(shutit.shutit_map[module_id]):\n\t\t\tshutit.login(prompt_prefix=module_id,command='bash --noprofile --norc',echo=False)\n\t\t\tif not shutit.shutit_map[module_id].finalize(shutit):\n\t\t\t\tshutit.fail(module_id + ' failed on finalize', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child)\n\t\t\tshutit.logout(echo=False)\n\n\ndef setup_shutit_path():\n\t# try the current directory, the .. directory, or the ../shutit directory, the ~/shutit\n\tshutit = shutit_global.shutit\n\tif not shutit.host['add_shutit_to_path']:\n\t\treturn\n\tres = shutit_util.util_raw_input(prompt='shutit appears not to be on your path - should try and we find it and add it to your ~/.bashrc (Y/n)?')\n\tif res in ['n','N']:\n\t\twith open(os.path.join(shutit.host['shutit_path'], 'config'), 'a') as f:\n\t\t\tf.write('\\n[host]\\nadd_shutit_to_path: no\\n')\n\t\treturn\n\tpath_to_shutit = ''\n\tfor d in ['.','..','~','~/shutit']:\n\t\tpath = os.path.abspath(d + '/shutit')\n\t\tif not os.path.isfile(path):\n\t\t\tcontinue\n\t\tpath_to_shutit = path\n\twhile path_to_shutit == '':\n\t\td = shutit_util.util_raw_input(prompt='cannot auto-find shutit - please input the path to your shutit dir\\n')\n\t\tpath = os.path.abspath(d + '/shutit')\n\t\tif not os.path.isfile(path):\n\t\t\tcontinue\n\t\tpath_to_shutit = path\n\tif path_to_shutit != '':\n\t\tbashrc = os.path.expanduser('~/.bashrc')\n\t\twith open(bashrc, \"a\") as myfile:\n\t\t\t#http://unix.stackexchange.com/questions/26676/how-to-check-if-a-shell-is-login-interactive-batch\n\t\t\tmyfile.write('\\nexport PATH=\"$PATH:' + os.path.dirname(path_to_shutit) + '\"\\n')\n\t\tshutit_util.util_raw_input(prompt='\\nPath set up - please open new terminal and re-run command\\n')\n\t\tshutit_util.handle_exit()\n\n\n\ndef main():\n\t\"\"\"Main ShutIt function.\n\n\tHandles the configured actions:\n\n\t\t- skeleton - create skeleton module\n\t\t- list_configs - output computed configuration\n\t\t- depgraph - output digraph of module dependencies\n\t\"\"\"\n\tif sys.version_info.major == 2:\n\t\tif sys.version_info.minor < 7:\n\t\t\tshutit_global.shutit.fail('Python version must be 2.7+')\n\n\tshutit = shutit_global.shutit\n\tshutit_util.parse_args()\n\n\tif not shutit.build['exam']:\n\t\tshutit.log('# ShutIt Started... ',transient=True)\n\t\tshutit.log('# Loading configs...',transient=True)\n\tshutit_util.load_configs()\n\n\tif shutit.action['skeleton']:\n\t\tshutit_skeleton.create_skeleton()\n\t\tshutit.build['completed'] = True\n\t\treturn\n\n\t# Try and ensure shutit is on the path - makes onboarding easier\n\t# Only do this if we're in a terminal\n\tif shutit_util.determine_interactive() and spawn.find_executable('shutit') is None:\n\t\tsetup_shutit_path()\n\n\tshutit_util.load_mod_from_file(os.path.join(shutit.shutit_main_dir, 'shutit_setup.py'))\n\tshutit_util.load_shutit_modules()\n\tshutit.log('ShutIt modules loaded',level=logging.INFO)\n\n\tinit_shutit_map(shutit)\n\n\tshutit_util.config_collection()\n\tshutit.log('Configuration loaded',level=logging.INFO)\n\n\tif shutit.action['list_modules']:\n\t\tshutit_util.list_modules()\n\t\tshutit_util.handle_exit()\n\tif not shutit.action['list_deps'] and not shutit.action['list_modules']:\n\t\tconn_target(shutit)\n\t\tshutit.log('Connected to target',level=logging.INFO)\n\n\tif shutit.build['interactive'] > 0 and shutit.build['choose_config']:\n\t\terrs = do_interactive_modules()\n\telse:\n\t\terrs = []\n\t\terrs.extend(check_deps())\n\n\tdo_lists(shutit)\n\n\t# Check for conflicts now.\n\terrs.extend(check_conflicts(shutit))\n\t# Cache the results of check_ready at the start.\n\terrs.extend(check_ready(throw_error=False))\n\tif errs:\n\t\tshutit.log(shutit_util.print_modules(), level=logging.ERROR)\n\t\tchild = None\n\t\tfor err in errs:\n\t\t\tshutit.log(err[0], level=logging.ERROR)\n\t\t\tif not child and len(err) > 1:\n\t\t\t\tchild = err[1]\n\t\tshutit.fail(\"Encountered some errors, quitting\", shutit_pexpect_child=child)\n\n\tdo_remove()\n\tdo_build()\n\tdo_test()\n\tdo_finalize()\n\tfinalize_target()\n\tshutit.log(shutit_util.build_report('#Module: N/A (END)'), level=logging.DEBUG)\n\tdo_exam_output(shutit)\n\tdo_final_messages(shutit)\n\n\t# Mark the build as completed\n\tshutit.build['completed'] = True\n\tshutit.log('ShutIt run finished',level=logging.INFO)\n\tshutit_util.handle_exit(exit_code=0)\n\n\ndef do_lists(shutit):\n\tif shutit.action['list_deps']:\n\t\tcfg = shutit.cfg\n\t\t# Show dependency graph\n\t\tdigraph = 'digraph depgraph {\\n'\n\t\tdigraph += '\\n'.join([ make_dep_graph(module) for module_id, module in shutit.shutit_map.items() if module_id in cfg and cfg[module_id]['shutit.core.module.build'] ])\n\t\tdigraph += '\\n}'\n\t\tf = open(shutit.build['log_config_path'] + '/digraph.txt','w')\n\t\tf.write(digraph)\n\t\tf.close()\n\t\tdigraph_all = 'digraph depgraph {\\n'\n\t\tdigraph_all += '\\n'.join([ make_dep_graph(module) for module_id, module in shutit.shutit_map.items() ])\n\t\tdigraph_all += '\\n}'\n\t\tfname = shutit.build['log_config_path'] + '/digraph_all.txt'\n\t\tf = open(fname,'w')\n\t\tf.write(digraph_all)\n\t\tf.close()\n\t\tshutit.log('\\n================================================================================\\n' + digraph_all)\n\t\tshutit.log('\\nAbove is the digraph for ALL MODULES SEEN in this ShutIt invocation. Use graphviz to render into an image, eg\\n\\n\\tcat ' + fname + ' | dot -Tpng -o depgraph.png\\n')\n\t\tshutit.log('\\n================================================================================\\n')\n\t\tfname = shutit.build['log_config_path'] + '/digraph_this.txt'\n\t\tf = open(fname,'w')\n\t\tf.write(digraph_all)\n\t\tf.close()\n\t\tshutit.log('\\n\\n' + digraph)\n\t\tshutit.log('\\n================================================================================\\n' + digraph)\n\t\tshutit.log('\\nAbove is the digraph for all modules configured to be built IN THIS ShutIt invocation. Use graphviz to render into an image, eg\\n\\ncat ' + fname + ' | dot -Tpng -o depgraph.png\\n')\n\t\tshutit.log('\\n================================================================================\\n')\n\t\t# Exit now\n\t\tshutit_util.handle_exit()\n\t# Dependency validation done, now collect configs of those marked for build.\n\tshutit_util.config_collection_for_built()\n\n\n\tif shutit.action['list_configs'] or shutit.build['loglevel'] <= logging.DEBUG:\n\t\t# Set build completed\n\t\tshutit.build['completed'] = True\n\t\tshutit.log('================================================================================')\n\t\tshutit.log('Config details placed in: ' + shutit.build['log_config_path'])\n\t\tshutit.log('================================================================================')\n\t\tshutit.log('To render the digraph of this build into an image run eg:\\n\\ndot -Tgv -o ' + shutit.build['log_config_path'] + '/digraph.gv ' + shutit.build['log_config_path'] + '/digraph.txt && dot -Tpdf -o digraph.pdf ' + shutit.build['log_config_path'] + '/digraph.gv\\n\\n')\n\t\tshutit.log('================================================================================')\n\t\tshutit.log('To render the digraph of all visible modules into an image, run eg:\\n\\ndot -Tgv -o ' + shutit.build['log_config_path'] + '/digraph_all.gv ' + shutit.build['log_config_path'] + '/digraph_all.txt && dot -Tpdf -o digraph_all.pdf ' + shutit.build['log_config_path'] + '/digraph_all.gv\\n\\n')\n\t\tshutit.log('================================================================================')\n\t\tshutit.log('\\nConfiguration details have been written to the folder: ' + shutit.build['log_config_path'] + '\\n')\n\t\tshutit.log('================================================================================')\n\tif shutit.action['list_configs']:\n\t\treturn\n\n\ndef do_final_messages(shutit):\n\t# Show final report messages (ie messages to show after standard report).\n\tif shutit.build['report_final_messages'] != '':\n\t\tshutit.log(shutit_util.colourise(31,'\\r\\n\\r\\n' + shutit.build['report_final_messages'] + '\\r\\n\\r\\n'), level=logging.INFO, transient=True)\n\n\ndef do_exam_output(shutit):\n\tif shutit.build['exam_object']:\n\t\ttest = shutit.build['exam_object']\n\t\ttest.calculate_score()\n\t\ttest_output = str(test)\n\t\tshutit.log(test_output,level=logging.CRITICAL)\n\t\tf = open('/tmp/shutit_exam_output', 'w')\n\t\tf.write(test_output)\n\t\tf.close()\n\n\ndef do_phone_home(msg=None,question='Error seen - would you like to inform the maintainers?'):\n\t\"\"\"Report message home.\n\tmsg - message to send home\n\tquestion - question to ask - assumes Y/y for send message, else no\n\t\"\"\"\n\tif msg is None:\n\t\tmsg = {}\n\tif shutit_global.shutit.build['interactive'] == 0:\n\t\treturn\n\tmsg.update({'shutitrunstatus':'fail','pwd':os.getcwd(),'user':os.environ.get('LOGNAME', '')})\n\tif question != '' and shutit_util.util_raw_input(prompt=question + ' (Y/n)\\n') not in ('y','Y',''):\n\t\treturn\n\ttry:\n\t\turllib.urlopen(\"http://shutit.tk?\" + urllib.urlencode(msg))\n\texcept Exception as e:\n\t\tshutit_global.shutit.log('failed to send message: ' + str(e.message),level=logging.ERROR)\n\n\ndef do_interactive_modules():\n\tshutit = shutit_global.shutit\n\tcfg = shutit.cfg\n\terrs = []\n\twhile True:\n\t\tshutit_util.list_modules(long_output=False,sort_order='run_order')\n\t\t# Which module do you want to toggle?\n\t\tmodule_id = shutit_util.util_raw_input(prompt='Which module id do you want to toggle?\\n(just hit return to continue with build)\\n(you can enter a substring if it is uniquely matching)\\n')\n\t\tif module_id:\n\t\t\ttry:\n\t\t\t\t_=cfg[module_id]\n\t\t\texcept NameError:\n\t\t\t\tmatched_to = []\n\t\t\t\tfor m in cfg.keys():\n\t\t\t\t\tif re.match('.*'+module_id+'.*',m):\n\t\t\t\t\t\tmatched_to.append(m)\n\t\t\t\tif len(matched_to) > 1:\n\t\t\t\t\tprint('Please input a uniquely matchable module id. Matches were: ' + str(matched_to))\n\t\t\t\t\tcontinue\n\t\t\t\telif len(matched_to) == 0:\n\t\t\t\t\tprint('Please input a valid module id')\n\t\t\t\telse:\n\t\t\t\t\tmodule_id = matched_to[0]\n\t\t\tcfg[module_id]['shutit.core.module.build'] = not cfg[module_id]['shutit.core.module.build']\n\t\t\tif not shutit_util.config_collection_for_built(throw_error=False):\n\t\t\t\tcfg[module_id]['shutit.core.module.build'] = not cfg[module_id]['shutit.core.module.build']\n\t\t\t\tshutit_util.util_raw_input(prompt='Hit return to continue.\\n')\n\t\t\t\tcontinue\n\t\t\t# If true, set up config for that module\n\t\t\tif cfg[module_id]['shutit.core.module.build']:\n\t\t\t\t# TODO: does this catch all the ones switched on? Once done, get configs for all those.\n\t\t\t\tnewcfg_list = []\n\t\t\t\twhile True:\n\t\t\t\t\tprint(shutit_util.print_config(cfg,module_id=module_id))\n\t\t\t\t\tname = shutit_util.util_raw_input(prompt='Above is the config for that module. Hit return to continue, or a config item you want to update.\\n')\n\t\t\t\t\tif name:\n\t\t\t\t\t\tdoing_list = False\n\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\tif doing_list:\n\t\t\t\t\t\t\t\tval_type = shutit_util.util_raw_input(prompt='Input the type for the next list item: b(oolean), s(tring).\\n')\n\t\t\t\t\t\t\t\tif val_type not in ('b','s',''):\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tval_type = shutit_util.util_raw_input(prompt='Input the type for that config item: b(oolean), s(tring), l(ist).\\n')\n\t\t\t\t\t\t\t\tif val_type not in ('b','s','l',''):\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\tif val_type == 's':\n\t\t\t\t\t\t\t\tval = shutit_util.util_raw_input(prompt='Input the value new for that config item.\\n')\n\t\t\t\t\t\t\t\tif doing_list:\n\t\t\t\t\t\t\t\t\tnewcfg_list.append(val)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telif val_type == 'b':\n\t\t\t\t\t\t\t\tval = shutit_util.util_raw_input(prompt='Input the value new for the boolean (t/f).\\n')\n\t\t\t\t\t\t\t\tif doing_list:\n\t\t\t\t\t\t\t\t\tif val == 't':\n\t\t\t\t\t\t\t\t\t\tnewcfg_list.append(True)\n\t\t\t\t\t\t\t\t\telif val == 'f':\n\t\t\t\t\t\t\t\t\t\tnewcfg_list.append(False)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tprint('Input t or f please')\n\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telif val_type == 'l':\n\t\t\t\t\t\t\t\tdoing_list = True\n\t\t\t\t\t\t\t\tnewcfg_list = []\n\t\t\t\t\t\t\telif val_type == '':\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t# TODO: handle blank/None\n\t\t\t\t\t\tif doing_list:\n\t\t\t\t\t\t\tcfg[module_id][name] = newcfg_list\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcfg[module_id][name] = val\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tpass\n\t\t\t\t# TODO: if removing, get any that depend on it, and remove those too\n\t\telse:\n\t\t\tbreak\n\treturn errs\n\n\ndef setup_signals():\n\tsignal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler)\n\tsignal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)\n\nshutit_version='0.9.343'\n\nif __name__ == '__main__':\n\tsetup_signals()\n\tmain()\n","sub_path":"shutit_main.py","file_name":"shutit_main.py","file_ext":"py","file_size_in_byte":34338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"237340417","text":"import types\nfrom urllib import request\nimport requests\nimport urllib.parse\nimport json\nimport os\nimport threading\n\nhost = \"https://museum.morview.com/\"\nurl = \"https://api.morview.com/v2.1/exhibits?museum_id=4\"\n\ninfourl = \"https://api.morview.com/v2.1/exhibitInfo?exhibit_id=\"\ncommenturl = \"https://api.morview.com/v2.1/exhibitComments?exhibit_id=\"\n\nlovalsavepath = \"/Users/chenwenjuan/Desktop/down_load/local_api/\"\n\n\n\n#利用urllib2获取网络数据\ndef registerUrl():\n\n req = requests.get(url)\n\n content = req.json()\n\n if content :\n dataary = content[\"data\"][\"res\"]\n for i, val in enumerate(dataary):\n\n reallist = val[\"exhibits\"]\n # list = list(dataary)\n for i, val in enumerate(reallist):\n\n exhibitid = val[\"exhibit_id\"]\n req = requests.get(infourl + exhibitid)\n\n content = req.json()\n if content:\n responsedata = content[\"data\"]\n savedata = str(content).replace('\\'', '\\\"')\n # 保存展品详情的文字接口\n saveJsonFile(\"%sexhibit/\" % (lovalsavepath), savedata, exhibitid)\n\n audio = responsedata[\"audio\"] # 保存展品详情的语音文件\n\n images = responsedata[\"images\"]\n\n vedio = responsedata[\"video\"]\n\n threading.Thread(target=saveAudio, args=(audio,)).start()\n # saveAudio(audio) #保存语音\n\n # saveImages(images) #保存图片(大图和小图)\n threading.Thread(target=saveImages, args=(images,)).start()\n\n # saveVedio(vedio) #保存视频\n threading.Thread(target=saveVedio, args=(vedio,)).start()\n\n # saveComment(exhibitid) #保存评论\n threading.Thread(target=saveComment,args=(exhibitid,)).start()\n\n\n##### 保存文件\ndef saveComment(exhibitid):\n pageindex = 1;\n totalcomment = []\n hasnext = True\n while hasnext:\n reqcomment = requests.get(commenturl + exhibitid + \"&page_index=\" + str(pageindex)) # 下载评论\n\n if reqcomment:\n commentdata = reqcomment.json()\n if commentdata: # 保存评论数据\n comment = commentdata[\"data\"][\"comments\"]\n if comment:\n\n totalcomment.extend(comment)\n else:\n\n commentdata[\"data\"][\"comments\"] = totalcomment\n\n savedata = str(commentdata).replace('\\'', '\\\"')\n\n saveJsonFile(\"%scomment/\" % (lovalsavepath), savedata, exhibitid)\n hasnext = False\n else:\n saveJsonFile(\"%scomment/\" % (lovalsavepath), \"\", exhibitid)\n hasnext = False\n\n pageindex += 1\n\ndef saveVedio(vedio):\n if vedio:\n vediourl = vedio[\"videourl\"]\n vedioimg = vedio[\"img\"]\n if vediourl != \"\":\n downimgurl = '%s%s' % (host, vedioimg)\n downvediourl = '%s%s' % (host, vediourl)\n savevedio = \"%s%s\" % (lovalsavepath, vediourl)\n saveimg = \"%s%s\" % (lovalsavepath, vedioimg)\n createFilePath(savevedio)\n createFilePath(saveimg)\n urllib.request.urlretrieve(downvediourl, savevedio) # 下载视频\n urllib.request.urlretrieve(downimgurl, saveimg) # 下载图片\n\n\ndef saveAudio(audio):\n if audio:\n for i, val in enumerate(audio):\n if val[\"filename\"]:\n filename = val[\"filename\"];\n newurl = '%s%s' % (host, val[\"filename\"])\n savepath = \"%s%s\" % (lovalsavepath, filename)\n createFilePath(savepath)\n urllib.request.urlretrieve(newurl, savepath) # 下载语音\n\ndef saveImages(images):\n if images:\n for i, val in enumerate(images):\n imgary = val.split(\".\")\n\n bigpicurl = imgary[0][0:len(imgary[0]) - 2] + \".\" + imgary[1]\n\n bignewurl = '%s%s' % (host, bigpicurl)\n\n newurl = '%s%s' % (host, val)\n savepath = \"%s%s\" % (lovalsavepath, val)\n createFilePath(savepath)\n urllib.request.urlretrieve(newurl, savepath) # 下载图片\n\n savebigpath = \"%s%s\" % (lovalsavepath, bigpicurl)\n createFilePath(savebigpath)\n\n urllib.request.urlretrieve(bignewurl, savebigpath) # 下载大图片\n\ndef createFilePath(pathname):\n dirname = os.path.dirname(pathname)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n\n\ndef saveJsonFile(loalpath,fileData,filename):\n path = \"%s%s.json\" % (loalpath,filename)\n dirname = os.path.dirname(path)\n\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n else:\n file = open(path,\"w\")\n file.write(fileData)\n file.close()\n\nregisterUrl()\n","sub_path":"ios_kundan_local_morepot/readapi.py","file_name":"readapi.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"67836137","text":"import warnings\r\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\r\nimport pandas as pd\r\npd.set_option('display.max_columns', None)\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nimport xgboost as xgb\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_score, KFold\r\nimport numpy as np\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn import metrics\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nfrom sklearn import preprocessing\r\nfrom collections import defaultdict\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\n#read the raw data in excel\r\nrawdata = pd.read_excel(\"Global_Superstore2.xlsx\",parse_dates= [\"Order Date\", \"Ship Date\"]) #51290*24 dim\r\ndata = rawdata.drop(columns=[\"Row ID\",\"Order ID\",\"Customer ID\",\"Customer Name\",\"City\",\"State\",\"Country\",\"Postal Code\",\"Profit\"],axis=1) #removing the other columns not interested for my use case\r\ndata.dropna(inplace=True) #if 0 drops rows with 0 and 1 drops rows with missing values\r\n#creating features\r\nod = data[\"Order Date\"]\r\nsd = data[\"Ship Date\"]\r\ndata[\"Days_to_Ship_Product\"] = abs(sd - od) #first feature #creating the no.of.days to ship the product as it would also be an important factor for product demand\r\n#2nd feature = Extracting the month of the order date - important for predicting demand monthwise\r\ndata['Order month'] = pd.DatetimeIndex(data['Order Date']).month\r\n#3rd feature #we have sales column which is the total sales for all quantites.\r\ndata[\"Price\"] = ((data[\"Sales\"] / data[\"Quantity\"]) * (data[\"Discount\"]+1)) #this will give the price of the product for one quantity along with discount.\r\n#print(dataclean)\r\ndata[\"Ship Mode\"] = data[\"Ship Mode\"].astype('category')\r\ndata[\"Ship Mode cat\"] = data[\"Ship Mode\"].cat.codes\r\ndata[\"Segment\"] = data[\"Segment\"].astype('category')\r\ndata[\"Segment cat\"] = data[\"Segment\"].cat.codes\r\ndata[\"Market\"] = data[\"Market\"].astype('category')\r\ndata[\"Market cat\"] = data[\"Market\"].cat.codes\r\ndata[\"Region\"] = data[\"Region\"].astype('category')\r\ndata[\"Region cat\"] = data[\"Region\"].cat.codes\r\ndata[\"Order Priority\"] = data[\"Order Priority\"].astype('category')\r\ndata[\"Order Priority cat\"] = data[\"Order Priority\"].cat.codes\r\ndata[\"Category\"] = data[\"Category\"].astype('category')\r\ndata[\"Category cat\"] = data[\"Category\"].cat.codes\r\ndata[\"Sub-Category\"] = data[\"Sub-Category\"].astype('category')\r\ndata[\"Sub-Category cat\"] = data[\"Sub-Category\"].cat.codes\r\ndata[\"Days_to_Ship_Product\"] = data[\"Days_to_Ship_Product\"].astype('str')\r\ndata[\"Product shipping Days\"] = [str(i).split(\" \")[0] if \" \" in i else \"not days\" for i in\r\n data[\"Days_to_Ship_Product\"]]\r\n#print(data) # now the data is cleaned with new features created.\r\n#final df preprocessed and cleaned # removing sales column as it is correlated to price\r\nfinaldf = data.drop(columns=[\"Sales\", \"Ship Mode\",\"Segment\",\"Market\",\"Region\",\"Order Priority\", \"Product ID\",\"Product Name\",\"Category\",\"Sub-Category\",\"Days_to_Ship_Product\"])\r\n#print(finaldf)\r\nfinaldf.isna().sum() # to check which column has null values.\r\n\r\n#Using Pearson Correlation - to check features correlation\r\nplt.figure(figsize=(12,10))\r\ncor = data.corr()\r\nsns.heatmap(cor, annot=True, cmap=plt.cm.Reds)\r\nplt.show()\r\n#Correlation with output variable\r\ncor_target = abs(cor[\"Quantity\"])\r\nrelevant_features = cor_target[cor_target>0.5] # this is just a cross check to see if there are highly correlated variables and to remove them and have only 1 of the two\r\n#print(relevant_features)\r\n#fitting linear reg model for features selected\r\n#X = pd.DataFrame(np.c_[finaldf['Discount'], finaldf['Shipping Cost'],finaldf['Price'], finaldf['Ship Mode cat'],finaldf['Segment cat'],finaldf['Market cat'],finaldf['Order month'],finaldf['Region cat'], finaldf['Order Priority cat'], finaldf['Category cat'],finaldf['Sub-Category cat'],finaldf['Product shipping Days']],\r\n #columns=['Discount','Shipping Cost','Price','Ship Mode cat','Segment cat','Market cat','Order month','Region cat', 'Order Priority cat','Category cat','Sub-Category cat','Product shipping Days'])\r\n#target = np.array(data[\"Quantity\"])\r\n#print(target)\r\n\r\n#modeling #XGboost\r\ncleandf = finaldf.iloc[:,3:15]\r\n#cleandf.to_excel(r'C:\\Users\\gltla\\OneDrive - Bayer\\Personal Data\\Thesis\\mlflow\\cleandfxgb.xlsx')\r\ncleandf['Product shipping Days'] = cleandf['Product shipping Days'].astype(str).astype(int)\r\nprint(cleandf)\r\ny= finaldf.iloc[:,2]\r\nprint(y)\r\nxtrain, xtest, ytrain, ytest = train_test_split(cleandf, y, test_size=0.20) #quantity is my y variable target\r\nprint(xtrain.shape, ytrain.shape)\r\nprint(xtest.shape, ytest.shape)\r\nxgbr = xgb.XGBRegressor(booster='gbtree', colsample_bylevel=1, colsample_bytree=1, learning_rate=0.1,\r\n objective=\"reg:linear\",max_depth = 5, alpha = 10, n_estimators = 300,random_state=42)\r\nxgbr.fit(xtrain, ytrain)\r\nscore = xgbr.score(xtrain, ytrain)\r\nprint(\"Training score: \", score)\r\n# - cross validataion\r\nscores = cross_val_score(xgbr, xtrain, ytrain, cv=5)\r\nprint(\"Mean cross-validation score: %.2f\" % scores.mean())\r\nkfold = KFold(n_splits=10, shuffle=True)\r\nkf_cv_scores = cross_val_score(xgbr, xtrain, ytrain, cv=kfold)\r\nprint(\"K-fold CV average score: %.2f\" % kf_cv_scores.mean())\r\nypred = xgbr.predict(xtest) #prediction on testdata --------- ypred is quantity - its coming in decimal because model is not so accurate\r\nprint(\"Checking for types to plot\")\r\nprint(type(xtest)) #df\r\nprint(type(ypred)) #array\r\nprint(type(ytest)) #series, dtype - int64\r\nprint(xtest)\r\nprint(ypred) #plot this against ytest---actual values #10258 records\r\nprint(ytest)\r\nplt.figure()\r\nplt.scatter(ytest,ypred)\r\nplt.xlabel(\"Actual\")\r\nplt.ylabel(\"Predictions\")\r\nplt.title(\"Actual vs Predictions\")\r\nplt.show()\r\n\r\nxtestbkp = xtest.copy(deep=True)\r\nxtestbkp['ytest'] = ytest\r\nxtestbkp['ypred'] = ypred\r\nprint(xtestbkp)\r\n\r\n#xtestbkp.to_excel(\"Test_Df_with_predicions.xlsx\")\r\n#reverting back to the labels\r\n\r\n#encoded_labels = [2, 0, 1]\r\n#decoded_labels = le.inverse_transform(encoded_labels)\r\n#print(\"Encoded labels =\", encoded_labels)\r\n#print(\"Decoded labels =\", list(decoded_labels))\r\n\r\nxtestdf = xtestbkp.drop(columns = ['Discount','Order month','Shipping Cost','Price','Ship Mode cat','Segment cat','Market cat','Order Priority cat','Sub-Category cat','Product shipping Days'],axis = 1)\r\n#xtestdf.plot(x=\"Order month\", y=[\"ytest\", \"ypred\"],figsize=(12,10),legend=True)\r\n#plt.show()\r\n#predplotsre = xtestdf.groupby(by=['Region cat']).count()\r\n#predplotsre.plot(x=\"Order month\", y=[\"ytest\", \"ypred\"],figsize=(12,10),legend=True)\r\n#plt.ylabel('Quantity')\r\n#plt.show()\r\nxtestdf1 = xtestbkp.drop(columns = ['Discount','Order month','Shipping Cost','Price','Ship Mode cat','Segment cat','Market cat','Order Priority cat','Sub-Category cat','Product shipping Days','Region cat'],axis = 1)\r\npredplotscat = xtestdf.groupby(by=['Region cat','Category cat']).count().unstack()\r\npredplotscat.columns = predplotscat.columns.droplevel()\r\npredplotscat.reset_index().plot.bar()\r\nplt.ylabel('Quantity')\r\nplt.show()\r\n#for pr, group in xtestdf1.groupby(\"Category cat\"):\r\n #group.plot(x=\"Order month\",y=[\"ytest\",\"ypred\"],legend=True, figsize=(14, 10))\r\n #group[\"ypred\"].plot(x=\"Order month\", legend=True, figsize=(14, 10), label = pr)\r\n#plt.legend(loc=(1.05, 0.0))\r\n#plt.tight_layout()\r\n#plt.xlabel('Order month')\r\n#plt.ylabel('Quantity')\r\n#plt.show()\r\n(xtestdf.groupby(['Category cat','Region cat'])['ypred','ytest'].count().unstack('Category cat').plot.bar())\r\nplt.show()\r\n#xtestdf1.groupby(['Category cat'])['Category cat'].count().plot.bar()\r\n#plt.show()\r\n#overall best performing category\r\n\r\n\r\n#checking for metrics\r\nmse = mean_squared_error(ytest, ypred)\r\nprint(\"MSE: %.2f\" % mse)\r\nprint(\"RMSE: %.2f\" % (mse ** (1 / 2.0)))\r\nr2xg = metrics.r2_score(ytest,ypred)\r\nprint(\"R-Squared in XGBtree:\",r2xg)\r\n#building 3 fold cv model in xgboost - so change these hyper parms and checking for rmse and r2\r\ndata_dmatrix = xgb.DMatrix(data=cleandf,label=y)\r\nparams = {\"objective\":\"reg:squarederror\",'colsample_bytree': 0.3,'learning_rate': 0.1,\r\n 'max_depth': 5, 'alpha': 10}\r\ncv_results = xgb.cv(dtrain=data_dmatrix, params=params, nfold=3,\r\n num_boost_round=50,early_stopping_rounds=10,metrics=\"rmse\", as_pandas=True, seed=123)\r\nprint(cv_results.head())\r\nprint((cv_results[\"test-rmse-mean\"]).tail(1))\r\nxg_reg = xgb.train(params=params, dtrain=data_dmatrix, num_boost_round=10)\r\n#feature importance plot\r\nxgb.plot_importance(xg_reg)\r\nplt.rcParams['figure.figsize'] = [5, 5]\r\nplt.show()\r\n#actual vs predicted plot\r\nx_ax = xtest['Order month'].values\r\nplt.plot(x_ax, ytest, color=\"blue\", label=\"original\")\r\nplt.plot(x_ax, ypred, color=\"red\", label=\"predicted\")\r\nplt.legend()\r\nplt.title(\"Product demand actual vs predicted plot\")\r\nplt.show()\r\n\r\n#Randomforest model\r\n# Instantiate model with 500 decision trees\r\nrf = RandomForestRegressor(n_estimators = 500, random_state = 42)\r\n# Train the model on training data\r\nrf.fit(xtrain, ytrain)\r\npredictions = rf.predict(xtest) # Use the forest's predict method on the test data\r\nmserf = mean_squared_error(ytest,predictions)\r\nrmserf = np.sqrt(mserf)\r\nr2 = metrics.r2_score(ytest,predictions)\r\nprint('Mean Absolute Error of RF :', metrics.mean_absolute_error(ytest, predictions))\r\nprint('MSE OF Random forest model:', mserf)\r\nprint('RMSE OF Random forest model:', rmserf)\r\nprint('R-Squared of RF model:',r2)\r\n#feature importance plot #Extract the two most important features\r\ntarget = np.array(data[\"Quantity\"])\r\n# Saving feature names for later use\r\nfeature_list = list(cleandf.columns) #cleandf = features has all data other than target\r\nprint(feature_list)\r\n# Convert to numpy array\r\nfeatures = np.array(cleandf)\r\n#variable importance\r\nimportances = list(rf.feature_importances_)\r\n# List of tuples with variable and importance\r\nfeature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]\r\n# Sort the feature importances by most important first\r\nfeature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)\r\n# Print out the feature and importances\r\n[print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances]\r\nplt.style.use('fivethirtyeight') #set the style and plot importance\r\n# list of x locations for plotting\r\nx_values = list(range(len(importances)))\r\n# Make a bar chart\r\nplt.bar(x_values, importances, orientation = 'vertical')\r\n# Tick labels for x axis\r\nplt.xticks(x_values, feature_list, rotation='vertical')\r\n# Axis labels and title\r\nplt.ylabel('Importance'); plt.xlabel('Variable'); plt.title('Variable Importances')\r\nplt.show()\r\n\r\n\r\n#decision tree\r\ndecisiontreereg = DecisionTreeRegressor(max_depth=10)\r\ndecisiontreereg.fit(xtrain, ytrain)\r\npredictions = decisiontreereg.predict(xtest) # Use the forest's predict method on the test data\r\nmsedt = mean_squared_error(ytest,predictions)\r\nrmsedt = np.sqrt(mserf)\r\nr2dt = metrics.r2_score(ytest,predictions)\r\nprint('Mean Absolute Error of DT :', metrics.mean_absolute_error(ytest, predictions))\r\nprint(\"MSE OF DT model:\", msedt)\r\nprint(\"RMSE OF DT model:\", rmsedt)\r\nprint(\"R-Squared of DT model:\",r2dt)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"modifiecations.py","file_name":"modifiecations.py","file_ext":"py","file_size_in_byte":11364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597877903","text":"import os\nimport sqlite3\n\nfrom cs50 import SQL\nfrom flask import Flask, flash, redirect, render_template, request, session, url_for\nfrom flask_session import Session\nfrom tempfile import mkdtemp\nfrom werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError\nfrom werkzeug.security import check_password_hash, generate_password_hash\n\nfrom helpers import apology, login_required, lookup, usd\n\n# Configure application\napp = Flask(__name__)\n\n# Ensure templates are auto-reloaded\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n\n# Ensure responses aren't cached\n@app.after_request\ndef after_request(response):\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n\n# Custom filter\napp.jinja_env.filters[\"usd\"] = usd\n\n# Configure session to use filesystem (instead of signed cookies)\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n# Configure CS50 Library to use SQLite database\ndb = SQL(\"sqlite:///finance.db\")\n\n# For Heroku PostgreSQL\n# uri = os.getenv(\"DATABASE_URL\") # or other relevant config var\n# if uri.startswith(\"postgres://\"):\n# uri = uri.replace(\"postgres://\", \"postgresql://\", 1)\n# db = SQL(uri)\n\n# Make sure API key is set\n# if not os.environ.get(\"API_KEY\"):\n# raise RuntimeError(\"API_KEY not set\")\n\n\n@app.route(\"/\")\n@login_required\ndef index():\n \"\"\"Show portfolio of stocks\"\"\"\n\n # Show the sum of shares as 'totalShares', not individual one\n rows = db.execute(\"\"\"\n SELECT symbol, SUM(shares) as totalShares FROM transactions\n WHERE user_id = :user_id\n GROUP BY symbol\n HAVING totalShares > 0;\n \"\"\", user_id=session[\"user_id\"])\n\n # Create portfolio array\n portfolio = []\n grand_total = 0\n\n # add stock name to the table, using lookup function\n for row in rows:\n stock = lookup(row[\"symbol\"])\n\n # Add all tables we want to portfolio table\n portfolio.append({\n \"symbol\": stock[\"symbol\"],\n \"name\": stock[\"name\"],\n \"shares\": row[\"totalShares\"],\n \"price\": stock[\"price\"],\n \"total\": stock[\"price\"] * row[\"totalShares\"]\n })\n grand_total += stock[\"price\"] * row[\"totalShares\"]\n\n rows = db.execute(\"SELECT cash FROM users WHERE id=:user_id\", user_id=session[\"user_id\"])\n cash = round(rows[0][\"cash\"], 2)\n grand_total = round((grand_total + cash), 2)\n\n return render_template(\"index.html\", portfolio=portfolio, cash=cash, grand_total=grand_total)\n\n\n@app.route(\"/add_cash\", methods=[\"GET\", \"POST\"])\n@login_required\ndef add_cash():\n \"\"\"Add cash. Additional feature\"\"\"\n\n if request.method == \"POST\":\n if int(request.form.get(\"cash\")) < 0:\n return apology(\"Invalid amount of cash\")\n\n else:\n db.execute(\"\"\"UPDATE users\n SET cash = cash + :amount\n WHERE id = :user_id;\"\"\", amount=request.form.get(\"cash\"), user_id=session[\"user_id\"])\n\n flash(\"Added Cash!\")\n return redirect(\"/\")\n\n else:\n return render_template(\"add_cash.html\")\n\n\n@app.route(\"/buy\", methods=[\"GET\", \"POST\"])\n@login_required\ndef buy():\n \"\"\"Buy shares of stock\"\"\"\n\n if request.method == \"POST\":\n\n # Stock symbol or shares must be submitted\n if (not request.form.get(\"symbol\")) or (not request.form.get(\"shares\")):\n return apology(\"Must provide stock symbol and number of shares\")\n\n # Ensure shares are valid\n if not (request.form.get(\"shares\")).isnumeric():\n return apology(\"Must provide integer number of shares\")\n\n if int(request.form.get(\"shares\")) <= 0:\n return apology(\"Must provide valid number of shares\")\n\n if lookup(request.form.get(\"symbol\")) == None:\n return apology(\"Invalid symbol\")\n\n rows = db.execute(\"SELECT cash FROM users WHERE id=:id\", id=session[\"user_id\"])\n cash = rows[0][\"cash\"]\n\n symbol = request.form.get(\"symbol\").upper()\n shares = int(request.form.get(\"shares\"))\n stock = lookup(symbol)\n\n updated_cash = cash - shares * stock['price']\n if updated_cash < 0:\n return apology(\"Not enough cash for transaction\")\n\n else:\n # updated user's Cash\n db.execute(\"UPDATE users SET cash = :updated_cash WHERE id=:id\", updated_cash=updated_cash, id=session[\"user_id\"])\n\n # Update transaction table\n db.execute(\"\"\"INSERT INTO transactions (user_id, symbol, shares, price)\n VALUES (:user_id, :symbol, :shares, :price)\"\"\", user_id=session[\"user_id\"], symbol=stock[\"symbol\"], shares=shares, price=stock[\"price\"])\n\n # Shares bought successfully\n flash(\"Shares Bought!\")\n\n # Redirect to home page\n return redirect(url_for(\"index\"))\n\n else:\n return render_template(\"buy.html\")\n\n\n@app.route(\"/history\")\n@login_required\ndef history():\n \"\"\"Show history of transactions\"\"\"\n\n # pull from transactions table\n portfolio = db.execute(\"\"\"\n SELECT symbol, shares, price, transacted\n FROM transactions\n WHERE user_id = :user_id\n ORDER BY transacted DESC;\n \"\"\", user_id=session[\"user_id\"])\n\n if not portfolio:\n return apology(\"Sorry, you have no transaction records\")\n\n return render_template(\"history.html\", portfolio=portfolio)\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n \"\"\"Log user in\"\"\"\n\n # Forget any user_id\n session.clear()\n\n # User reached route via POST (as by submitting a form via POST)\n if request.method == \"POST\":\n\n # Ensure username was submitted\n if not request.form.get(\"username\"):\n return apology(\"must provide username\")\n\n # Ensure password was submitted\n elif not request.form.get(\"password\"):\n return apology(\"must provide password\")\n\n # Query database for username\n rows = db.execute(\"SELECT * FROM users WHERE username = ?\", request.form.get(\"username\"))\n\n # Ensure username exists and password is correct\n if len(rows) != 1 or not check_password_hash(rows[0][\"hash\"], request.form.get(\"password\")):\n return apology(\"invalid username and/or password\")\n\n # Remember which user has logged in\n session[\"user_id\"] = rows[0][\"id\"]\n\n # Redirect user to home page\n return redirect(\"/\")\n\n # User reached route via GET (as by clicking a link or via redirect)\n else:\n return render_template(\"login.html\")\n\n\n@app.route(\"/logout\")\ndef logout():\n \"\"\"Log user out\"\"\"\n\n # Forget any user_id\n session.clear()\n\n # Redirect user to login form\n return redirect(\"/\")\n\n\n@app.route(\"/quote\", methods=[\"GET\", \"POST\"])\n@login_required\ndef quote():\n \"\"\"Get stock quote.\"\"\"\n\n if request.method == \"POST\":\n\n # Ensure name of stock submitted\n if not request.form.get(\"symbol\"):\n return apology(\"must provide stock symbol\", 400)\n\n # lookup quote symbol\n stock = lookup(request.form.get(\"symbol\").upper())\n\n # check if stock provided is valid\n if stock == None:\n return apology(\"Invalid symbol\", 400)\n\n # All checks valid. Pass in variable \"stock\" from lookup function\n else:\n return render_template(\"quoted.html\", stock=stock)\n\n else:\n return render_template(\"quote.html\")\n\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n\n if request.method == \"POST\":\n # Ensure username was submitted\n if not request.form.get(\"username\"):\n return apology(\"must provide username\")\n\n # Ensure password was submitted\n elif not request.form.get(\"password\"):\n return apology(\"must provide password\")\n\n # Ensure password confirmation matches\n elif request.form.get(\"password\") != request.form.get(\"confirmation\"):\n return apology(\"Passwords confirmation did not match\")\n\n # Insert new user into database\n else:\n try:\n # self-note: placeholder ':'' supports one-line function, '?' have to use separate lines\n result = db.execute(\"INSERT INTO users (username, hash) VALUES (:username, :hash)\",\n username=request.form.get(\"username\"),\n hash=generate_password_hash(request.form.get(\"password\"))\n )\n\n # Ensure username is unique, ie. insertion fail if errors occurs.\n except:\n return apology(\"Username is already registered\")\n\n # All other errors\n if not result:\n return apology(\"Registration error\")\n\n # Remember session ID\n session[\"user_id\"] = result\n\n # Redirect to home page\n return redirect(\"/login\")\n\n else:\n return render_template(\"register.html\")\n\n\n@app.route(\"/sell\", methods=[\"GET\", \"POST\"])\n@login_required\ndef sell():\n \"\"\"Sell shares of stock\"\"\"\n print(request.method)\n\n # if user reach route via POST eg. submit a form via POST\n if request.method == \"POST\":\n\n # Stock symbol or shares must be submitted\n if (not request.form.get(\"symbol\")) or (not request.form.get(\"shares\")):\n return apology(\"Must provide stock symbol and number of shares\")\n\n # Ensure shares are valid\n if int(request.form.get(\"shares\")) <= 0:\n return apology(\"Must provide valid number of shares\")\n\n if lookup(request.form.get(\"symbol\")) == None:\n return apology(\"Invalid symbol\")\n\n # Query for user's Cash\n rows = db.execute(\"SELECT cash FROM users WHERE id=:id\", id=session[\"user_id\"])\n cash = rows[0][\"cash\"]\n\n symbol = request.form.get(\"symbol\").upper()\n shares = int(request.form.get(\"shares\"))\n stock = lookup(symbol)\n\n # Query for user's shares holding\n rows = db.execute(\"\"\"\n SELECT symbol, SUM(shares) as totalShares\n FROM transactions\n WHERE user_id = :user_id\n GROUP BY symbol\n HAVING totalShares > 0;\n \"\"\", user_id=session[\"user_id\"])\n\n # check if users have sufficient shares to sell\n for row in rows:\n if row[\"symbol\"] == symbol:\n if shares > row[\"totalShares\"]:\n return apology(\"Insufficient shares for transaction\")\n\n updated_cash = cash + shares * stock['price']\n\n # updated user's Cash\n db.execute(\"UPDATE users SET cash = :updated_cash WHERE id=:id\", updated_cash=updated_cash, id=session[\"user_id\"])\n\n # Update transaction table\n db.execute(\"\"\"INSERT INTO transactions (user_id, symbol, shares, price)\n VALUES (:user_id, :symbol, :shares, :price)\"\"\", user_id=session[\"user_id\"], symbol=stock[\"symbol\"], shares=-shares, price=stock[\"price\"])\n\n # Shares bought successfully\n flash(\"Shares Sold!\")\n\n # Redirect to home page\n return redirect(url_for(\"index\"))\n\n # if user reached via GET (by clicking on a link to reach this page)\n else:\n symbols = db.execute(\"\"\"\n SELECT symbol\n FROM transactions\n WHERE user_id=:user_id\n GROUP BY symbol\n HAVING SUM(shares) > 0;\n \"\"\", user_id=session[\"user_id\"])\n\n # to simplify [{symbol: APPL}, {}]... etc to [{AAPL}, {}]...\n\n return render_template(\"sell.html\", symbols=symbols)\n\n\ndef errorhandler(e):\n \"\"\"Handle error\"\"\"\n if not isinstance(e, HTTPException):\n e = InternalServerError()\n return apology(e.name, e.code)\n\n\n# Listen for errors\nfor code in default_exceptions:\n app.errorhandler(code)(errorhandler)\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":11929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33433208","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom zuul import model\nfrom zuul.lib.logutil import get_annotated_logger\nfrom zuul.manager import PipelineManager, StaticChangeQueueContextManager\nfrom zuul.manager import DynamicChangeQueueContextManager\n\n\nclass DependentPipelineManager(PipelineManager):\n \"\"\"PipelineManager for handling interrelated Changes.\n\n The DependentPipelineManager puts Changes that share a Pipeline\n into a shared :py:class:`~zuul.model.ChangeQueue`. It then processes them\n using the Optimistic Branch Prediction logic with Nearest Non-Failing Item\n reparenting algorithm for handling errors.\n \"\"\"\n changes_merge = True\n\n def __init__(self, *args, **kwargs):\n super(DependentPipelineManager, self).__init__(*args, **kwargs)\n\n def buildChangeQueues(self, layout):\n self.log.debug(\"Building shared change queues\")\n change_queues = {}\n tenant = self.pipeline.tenant\n layout_project_configs = layout.project_configs\n\n for project_name, project_configs in layout_project_configs.items():\n (trusted, project) = tenant.getProject(project_name)\n queue_name = None\n project_in_pipeline = False\n for project_config in layout.getAllProjectConfigs(project_name):\n project_pipeline_config = project_config.pipelines.get(\n self.pipeline.name)\n if project_pipeline_config is None:\n continue\n project_in_pipeline = True\n queue_name = project_pipeline_config.queue_name\n if queue_name:\n break\n if not project_in_pipeline:\n continue\n if queue_name and queue_name in change_queues:\n change_queue = change_queues[queue_name]\n else:\n p = self.pipeline\n change_queue = model.ChangeQueue(\n p,\n window=p.window,\n window_floor=p.window_floor,\n window_increase_type=p.window_increase_type,\n window_increase_factor=p.window_increase_factor,\n window_decrease_type=p.window_decrease_type,\n window_decrease_factor=p.window_decrease_factor,\n name=queue_name)\n if queue_name:\n # If this is a named queue, keep track of it in\n # case it is referenced again. Otherwise, it will\n # have a name automatically generated from its\n # constituent projects.\n change_queues[queue_name] = change_queue\n self.pipeline.addQueue(change_queue)\n self.log.debug(\"Created queue: %s\" % change_queue)\n change_queue.addProject(project)\n self.log.debug(\"Added project %s to queue: %s\" %\n (project, change_queue))\n\n def getChangeQueue(self, change, event, existing=None):\n log = get_annotated_logger(self.log, event)\n\n if existing:\n return StaticChangeQueueContextManager(existing)\n queue = self.pipeline.getQueue(change.project)\n if queue:\n return StaticChangeQueueContextManager(queue)\n else:\n # There is no existing queue for this change. Create a\n # dynamic one for this one change's use\n change_queue = model.ChangeQueue(self.pipeline, dynamic=True)\n change_queue.addProject(change.project)\n self.pipeline.addQueue(change_queue)\n log.debug(\"Dynamically created queue %s\", change_queue)\n return DynamicChangeQueueContextManager(change_queue)\n\n def getNodePriority(self, item):\n with self.getChangeQueue(item.change, item.event) as change_queue:\n items = change_queue.queue\n return items.index(item)\n\n def isChangeReadyToBeEnqueued(self, change, event):\n log = get_annotated_logger(self.log, event)\n source = change.project.source\n if not source.canMerge(change, self.getSubmitAllowNeeds(),\n event=event):\n log.debug(\"Change %s can not merge, ignoring\", change)\n return False\n return True\n\n def enqueueChangesBehind(self, change, event, quiet, ignore_requirements,\n change_queue):\n log = get_annotated_logger(self.log, event)\n\n log.debug(\"Checking for changes needing %s:\" % change)\n if not hasattr(change, 'needed_by_changes'):\n log.debug(\" %s does not support dependencies\" % type(change))\n return\n\n # for project in change_queue, project.source get changes, then dedup.\n sources = set()\n for project in change_queue.projects:\n sources.add(project.source)\n\n seen = set(change.needed_by_changes)\n needed_by_changes = change.needed_by_changes[:]\n for source in sources:\n log.debug(\" Checking source: %s\", source)\n for c in source.getChangesDependingOn(change,\n change_queue.projects,\n self.pipeline.tenant):\n if c not in seen:\n seen.add(c)\n needed_by_changes.append(c)\n\n log.debug(\" Following changes: %s\", needed_by_changes)\n\n to_enqueue = []\n for other_change in needed_by_changes:\n with self.getChangeQueue(other_change,\n event) as other_change_queue:\n if other_change_queue != change_queue:\n log.debug(\" Change %s in project %s can not be \"\n \"enqueued in the target queue %s\" %\n (other_change, other_change.project,\n change_queue))\n continue\n source = other_change.project.source\n if source.canMerge(other_change, self.getSubmitAllowNeeds()):\n log.debug(\" Change %s needs %s and is ready to merge\",\n other_change, change)\n to_enqueue.append(other_change)\n\n if not to_enqueue:\n log.debug(\" No changes need %s\" % change)\n\n for other_change in to_enqueue:\n self.addChange(other_change, event, quiet=quiet,\n ignore_requirements=ignore_requirements,\n change_queue=change_queue)\n\n def enqueueChangesAhead(self, change, event, quiet, ignore_requirements,\n change_queue, history=None):\n log = get_annotated_logger(self.log, event)\n\n if hasattr(change, 'number'):\n history = history or []\n history = history + [change]\n else:\n # Don't enqueue dependencies ahead of a non-change ref.\n return True\n\n ret = self.checkForChangesNeededBy(change, change_queue, event)\n if ret in [True, False]:\n return ret\n log.debug(\" Changes %s must be merged ahead of %s\", ret, change)\n for needed_change in ret:\n r = self.addChange(needed_change, event, quiet=quiet,\n ignore_requirements=ignore_requirements,\n change_queue=change_queue, history=history)\n if not r:\n return False\n return True\n\n def checkForChangesNeededBy(self, change, change_queue, event):\n log = get_annotated_logger(self.log, event)\n\n # Return true if okay to proceed enqueing this change,\n # false if the change should not be enqueued.\n log.debug(\"Checking for changes needed by %s:\" % change)\n if (hasattr(change, 'commit_needs_changes') and\n (change.refresh_deps or change.commit_needs_changes is None)):\n self.updateCommitDependencies(change, change_queue, event)\n if not hasattr(change, 'needs_changes'):\n log.debug(\" %s does not support dependencies\", type(change))\n return True\n if not change.needs_changes:\n log.debug(\" No changes needed\")\n return True\n changes_needed = []\n # Ignore supplied change_queue\n with self.getChangeQueue(change, event) as change_queue:\n for needed_change in change.needs_changes:\n log.debug(\" Change %s needs change %s:\" % (\n change, needed_change))\n if needed_change.is_merged:\n log.debug(\" Needed change is merged\")\n continue\n with self.getChangeQueue(needed_change,\n event) as needed_change_queue:\n if needed_change_queue != change_queue:\n log.debug(\" Change %s in project %s does not \"\n \"share a change queue with %s \"\n \"in project %s\",\n needed_change, needed_change.project,\n change, change.project)\n return False\n if not needed_change.is_current_patchset:\n log.debug(\" Needed change is not the current patchset\")\n return False\n if self.isChangeAlreadyInQueue(needed_change, change_queue):\n log.debug(\" Needed change is already ahead in the queue\")\n continue\n if needed_change.project.source.canMerge(\n needed_change, self.getSubmitAllowNeeds()):\n log.debug(\" Change %s is needed\", needed_change)\n if needed_change not in changes_needed:\n changes_needed.append(needed_change)\n continue\n # The needed change can't be merged.\n log.debug(\" Change %s is needed but can not be merged\",\n needed_change)\n return False\n if changes_needed:\n return changes_needed\n return True\n\n def getFailingDependentItems(self, item):\n if not hasattr(item.change, 'needs_changes'):\n return None\n if not item.change.needs_changes:\n return None\n failing_items = set()\n for needed_change in item.change.needs_changes:\n needed_item = self.getItemForChange(needed_change)\n if not needed_item:\n continue\n if needed_item.current_build_set.failing_reasons:\n failing_items.add(needed_item)\n if failing_items:\n return failing_items\n return None\n\n def dequeueItem(self, item):\n super(DependentPipelineManager, self).dequeueItem(item)\n # If this was a dynamic queue from a speculative change,\n # remove the queue (if empty)\n if item.queue.dynamic:\n if not item.queue.queue:\n self.pipeline.removeQueue(item.queue)\n","sub_path":"zuul/manager/dependent.py","file_name":"dependent.py","file_ext":"py","file_size_in_byte":11606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"642810667","text":"#!/usr/bin/env python\n\n\"\"\"\ngds_tools based catabot realtime plot\n\"\"\"\nimport rospy\nimport rospkg\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport message_filters\nimport matplotlib.animation as animation\nfrom matplotlib import style\n\nfrom ysi_exo.msg import Sonde\nfrom sensor_msgs.msg import NavSatFix, Range, Temperature\nfrom mavros_msgs.msg import VFR_HUD, WaypointReached, StatusText\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import TwistStamped\nfrom timeit import default_timer as timer\nfrom std_msgs.msg import Float64\n\nimport os.path\nfrom os import path\n\n# designation of csv file\n#global CSV_FILE_PATH\nCSV_FILE_PATH = ''\n#global data_read\ndata_read = False\ninitial_time = None\ndelta_time = None\n\nyour_list = []\nrow = None\n\n# initialization of compass (original msg some error)\ncur_compass = Range()\n#path = None\n\n\n# csv file save\ndef append_file(data_array):\n with open(CSV_FILE_PATH, 'a') as csv_file:\n global data_read\n writer = csv.writer(csv_file)\n writer.writerow(data_array)\n data_read = True\n #print(\"csv file saved!\", data_read, CSV_FILE_PATH)\n\n\ndef gps_sonde_callback(sonde_msg, gps_msg, local_velocity_msg):\n data_array = [gps_msg.header.stamp.to_sec(), cur_compass.header.stamp.to_sec(), float(cur_compass.range),\n float(local_velocity_msg.header.stamp.to_sec()),\n float(local_velocity_msg.twist.twist.linear.x), float(local_velocity_msg.twist.twist.linear.y), float(local_velocity_msg.twist.twist.linear.z),\n float(local_velocity_msg.twist.twist.angular.x), float(local_velocity_msg.twist.twist.angular.y), float(local_velocity_msg.twist.twist.angular.z),\n float(sonde_msg.header.stamp.to_sec())]\n data_array.extend(sonde_msg.data)\n append_file(data_array)\n\ndef compass_callback(compass_msg):\n cur_compass.header.stamp = rospy.Time.now()\n cur_compass.range = compass_msg.data\n\ndef spin(fig,ax1):\n \"\"\"ROS node to listen to robot global position, depth, and EXO sonde measurements and write to csv file.\"\"\"\n global CSV_FILE_PATH\n CSV_FILE_PATH = r'//home/minkbrook/Desktop/boat-house-turning.csv'\n # ROS nitialization and parameters.\n\n #rospack = rospkg.RosPack()\n #CSV_FILE_PATH = rospack.get_path('gds_tools') + \"/data/\" + rospy.get_param('~csv_file_name')\n\n data_plot(fig,ax1)\n #rospy.spin()\n\n\n\ndef data_plot(fig,ax):\n \"\"\"\n data plotting function\n \"\"\"\n global data_read\n global initial_time\n global delta_time\n global time\n global heading\n global angular_z\n #global ODO\n #global your_list\n global row\n global path\n\n #print(\"Here\")\n ax1 = ax[0]\n ax2 = ax[1]\n ax3 = ax[2]\n #print(\"here2\", data_read)\n\n path_check = path.exists(\"/home/minkbrook/Desktop/boat-house-turning.csv\")\n\n if path_check:\n print(\"now data exist\")\n\n # initialization process\n \"\"\"wb for fast processing if there are too many\"\"\"\n # if it is \"a\" it should be here; otherwise 'wb', it should be above\n time = []\n heading = []\n angular_z = []\n ODO = []\n\n with open(CSV_FILE_PATH, 'r') as csv_file:\n reader = csv.reader(csv_file)\n your_list = np.array(list(reader))\n # initial time setup\n #time = your_list[:, 1].astype('float32')\n #heading = your_list[:,2].astype('float32')\n\n # numpy and list thing separate (Both didn't work at the same time)\n with open(CSV_FILE_PATH, 'r') as csv_file2:\n\n another_reader = csv.reader(csv_file2)\n for row in another_reader:\n if initial_time is None:\n initial_time = float(row[1])\n print(\"initial time set up\", initial_time)\n\n else:\n current_time = float(row[1])\n delta_time = float(current_time-initial_time)\n time.append(delta_time)\n heading.append(float(row[2]))\n angular_z.append(float(row[9]))\n ODO.append(float(row[22]))\n\n\n #print(\"initial time\", initial_time)\n #print(\"your list\", your_list)\n #print(\"time\", time)\n #print(\"heading\", heading)\n\n ax1.clear() # not that necessary if we fix the color\n ax1.plot(time, heading, color='green')\n ax1.set_ylim([0,360])\n ax1.tick_params(axis='y', labelsize=20)\n ax1.tick_params(labelbottom=False)\n ax1.set_ylabel('Heading (degree)', fontsize=20)\n ax1.yaxis.set_ticks(np.arange(0, 361,100))\n\n ax2.clear()\n ax2.plot(time, angular_z, color ='blueviolet')\n ax2.set_ylim([-1.6,1.6])\n ax2.set_ylabel('Yaw velocity (rad/sec)', fontsize=20)\n ax2.set_xlabel('Time (sec)', fontsize=20)\n #ax2.tick_params(axis='both', which='major', labelsize=20)\n ax2.tick_params(axis='x', labelsize=20)\n ax2.tick_params(axis='y', labelsize=20)\n\n ax3.clear()\n ax3.set_ylim([7.565,7.614])\n ax3.plot(time, ODO, color='red')\n ax3.set_ylabel('Dissolved Oxygen (mg/L)', fontsize=20)\n ax3.set_xlabel('Time (sec)', fontsize=20)\n ax3.tick_params(axis='both', which='major', labelsize=20)\n ax3.tick_params(axis='x', labelsize=20)\n ax3.tick_params(axis='y', labelsize=20)\n\n if delta_time >= 10:\n for each in ax:\n each.axvline(x=10, color='gray', linestyle='--')\n\n if delta_time >= 72:\n for each in ax:\n each.axvline(x=72, color='orange', linestyle='--', LineWidth=3)\n\n\n plt.show()\n plt.pause(0.00001)\n\n\n\nif __name__ == \"__main__\":\n try:\n\n rospy.init_node(\"real_time_plotter\", anonymous=False)\n rospy.sleep(1)\n \"\"\"\n definition of the figures\n \"\"\"\n #boundary of plot\n #style.use('fivethirtyeight')\n global fig, ax1\n fig = plt.figure()\n ax1 = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=1)\n ax2 = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=1)\n ax3 = plt.subplot2grid((2, 2), (0, 1), rowspan=2, colspan=1)\n #ax1 = fig.add_subplot(1,1,1)\n plt.ion()\n mng = plt.get_current_fig_manager()\n #mng.full_screen_toggle()\n ax = (ax1, ax2, ax3)\n \"\"\"\n main plotter\n \"\"\"\n while not rospy.is_shutdown():\n #data_plot(fig,ax)\n spin(fig, ax)\n\n except rospy.ROSInterruptException:\n pass\n","sub_path":"scripts/ISER2021-turn-boat-house-plotter.py","file_name":"ISER2021-turn-boat-house-plotter.py","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"436931319","text":"import decimal\nimport uuid\n\nfrom flask import request\n\nfrom flask_restplus import Resource, reqparse\nfrom ..models.mines import MineIdentity, MineDetail, MineralTenureXref\nfrom ..models.location import MineLocation\nfrom ..utils.random import generate_mine_no\nfrom app.extensions import jwt\n\n\nclass Mine(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('name', type=str)\n parser.add_argument('tenure_number_id', type=str)\n parser.add_argument('longitude', type=decimal.Decimal)\n parser.add_argument('latitude', type=decimal.Decimal)\n\n @jwt.requires_roles([\"mds-mine-view\"])\n def get(self, mine_no):\n mine = MineIdentity.find_by_mine_no(mine_no) or MineIdentity.find_by_mine_guid(mine_no)\n if mine:\n return mine.json()\n return {'message': 'Mine not found'}, 404\n\n @jwt.requires_roles([\"mds-mine-create\"])\n def post(self, mine_no=None):\n if mine_no:\n return {'error': 'Unexpected mine number in Url.'}, 400\n\n data = Mine.parser.parse_args()\n name = data['name']\n lat = data['latitude']\n lon = data['longitude']\n location = None\n if not name:\n return {'error': 'Must specify a name.'}, 400\n if len(name) > 60:\n return {'error': 'Specified name exceeds 60 characters.'}, 400\n # Dummy User for now\n dummy_user = 'DummyUser'\n dummy_user_kwargs = {'create_user': dummy_user, 'update_user': dummy_user}\n mine_identity = MineIdentity(mine_guid=uuid.uuid4(), **dummy_user_kwargs)\n mine_identity.save()\n mine_detail = MineDetail(\n mine_detail_guid=uuid.uuid4(),\n mine_guid=mine_identity.mine_guid,\n mine_no=generate_mine_no(),\n mine_name=name,\n **dummy_user_kwargs\n )\n mine_detail.save()\n if lat and lon:\n location = MineLocation(\n mine_location_guid=uuid.uuid4(),\n mine_guid=mine_identity.mine_guid,\n latitude=lat,\n longitude=lon,\n **dummy_user_kwargs\n )\n location.save()\n\n return {\n 'mine_guid': str(mine_detail.mine_guid),\n 'mine_no': mine_detail.mine_no,\n 'mine_name': mine_detail.mine_name,\n 'latitude': str(location.latitude) if location else None,\n 'longitude': str(location.longitude) if location else None\n }\n\n @jwt.requires_roles([\"mds-mine-create\"])\n def put(self, mine_no):\n data = Mine.parser.parse_args()\n tenure = data['tenure_number_id']\n lat = data['latitude']\n lon = data['longitude']\n if not tenure and not (lat and lon):\n return {'error': 'No fields filled.'}, 400\n mine = MineIdentity.find_by_mine_no(mine_no) or MineIdentity.find_by_mine_guid(mine_no)\n if not mine:\n return {'message': 'Mine not found'}, 404\n dummy_user = 'DummyUser'\n dummy_user_kwargs = {'create_user': dummy_user, 'update_user': dummy_user}\n # Tenure validation\n if tenure:\n if not tenure.isdigit():\n return {'error': 'Field tenure_id must contain only digits.'}, 400\n if len(tenure) != 7:\n return {'error': 'Field tenure_id must be exactly 7 digits long.'}, 400\n tenure_exists = MineralTenureXref.find_by_tenure(tenure)\n if tenure_exists:\n return {'error': 'Field tenure_id already exists for this mine'}, 400\n tenure = MineralTenureXref(\n mineral_tenure_xref_guid=uuid.uuid4(),\n mine_guid=mine.mine_guid,\n tenure_number_id=tenure,\n **dummy_user_kwargs\n )\n tenure.save()\n # Location validation\n if lat and lon:\n location = MineLocation(\n mine_location_guid=uuid.uuid4(),\n mine_guid=mine.mine_guid,\n latitude=lat,\n longitude=lon,\n **dummy_user_kwargs\n )\n location.save()\n\n return mine.json()\n\n\nclass MineList(Resource):\n @jwt.requires_roles([\"mds-mine-view\"])\n def get(self):\n items_per_page = request.args.get('per_page', 50, type=int)\n page = request.args.get('page', 1, type=int)\n mines = MineIdentity.query.join(MineDetail).order_by(MineDetail.mine_name).paginate(page, items_per_page, False)\n return {\n 'mines': list(map(lambda x: x.json(), mines.items)),\n 'has_next': mines.has_next,\n 'has_prev': mines.has_prev,\n 'next_num': mines.next_num,\n 'prev_num': mines.prev_num,\n 'current_page': mines.page,\n 'total_pages': mines.pages,\n 'items_per_page': mines.per_page,\n 'total': mines.total,\n }\n\n\nclass MineListByName(Resource):\n @jwt.requires_roles([\"mds-mine-view\"])\n def get(self):\n return {'mines': list(map(lambda x: x.json_by_name(), MineIdentity.query.all()))}\n","sub_path":"python-backend/app/mines/resources/mine.py","file_name":"mine.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462327693","text":"# -*- encoding: utf-8 -*-\nimport glob\nimport pandas as pd\n\nfile_list = glob.glob('results_for_analysis/*.csv')\n# writer = pd.ExcelWriter('output.xlsx')\ndata_li=[]\nfor num,na in enumerate(file_list):\n raw_data = pd.read_csv(na, low_memory=False)\n sheet_name = na.split('\\\\')[1].split('.')[0]\n raw_data['SubID'] = sheet_name.split('-')[0]\n raw_data['Pro'] = sheet_name.split('-')[1]\n raw_data['Kind'] = sheet_name.split('-')[2]\n raw_data['Order'] = sheet_name.split('-')[3].split('_')[0]\n raw_data['ED'] = \"\"\n raw_data.insert(0, 'SubID', raw_data.pop('SubID'))\n raw_data.insert(1, 'Pro', raw_data.pop('Pro'))\n raw_data.insert(2, 'Kind', raw_data.pop('Kind'))\n raw_data.insert(3, 'Order', raw_data.pop('Order'))\n raw_data.iloc[4, 9] = (raw_data.iloc[:, 8].sum()+raw_data.iloc[5:-1, 8].sum())*3/2\n data_li.append(raw_data)\n if (num+1) % (len(file_list)//5) == 0:\n print('进度:{}%'.format((num+1)*100/len(file_list)))\nmid_ware = pd.concat(data_li)\nmid_ware.to_csv('output1.csv', index=False)\n# mid_ware.to_excel(writer, 'Sheet1', index=False)\nprint('>>>>>Done!<<<<<<')","sub_path":"Extract_info/mesh.py","file_name":"mesh.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538200940","text":"import io\nimport os\nfrom flask import Flask, Response, render_template, flash, request, redirect, url_for\nimport json\nimport tensorflow as tf\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom werkzeug.utils import secure_filename\nfrom numpy import asarray\nimport numpy as np\nimport time\n\n\nUPLOAD_FOLDER = 'uploads'\nALLOWED_EXTENSIONS = {'jpg'}\n\napp = Flask(__name__)\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\ndef load_labels(filename):\n # with open(filename, 'r') as f:\n # return [line.strip() for line in f.readlines()]\n with open('./annotations/instances_val2017.txt', 'r') as handle:\n annotate_json = json.load(handle)\n\n return [line.strip() for line in annotate_json.readlines()]\n\n\ndef create_figure():\n # launch predictor and run inference on an arbitrary image in the validation dataset\n graph_def_file = \"ssdlite_mobiledet_cpu_320x320_coco_2020_05_19/frozen_graph.pb\"\n\n input_arrays = [\"normalized_input_image_tensor\"]\n output_arrays = [\"raw_outputs/box_encodings\", \"raw_outputs/class_predictions\"]\n input_shapes = {\"normalized_input_image_tensor\": [1, 320, 320, 3]}\n\n converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(graph_def_file,\n input_arrays,\n output_arrays,\n input_shapes)\n tflite_model = converter.convert()\n\n with open('ssdlite_mobiledet_cpu_320x320_coco_2020_05_19/model.tflite', 'wb') as f:\n f.write(tflite_model)\n\n image = 'static/2ca98d21a076b2ce.jpg'\n\n # launch predictor and run inference on an arbitrary image in the validation dataset\n # with Image.open(image) as img:\n # (width, height) = (320, 320)\n # img_resized = img.resize((width, height))\n # img_array = asarray(img_resized, dtype=np.float32) # first convert to a numpy array\n\n # Load the TFLite model and allocate tensors.\n interpreter = tf.compat.v1.lite.Interpreter(\n model_path=\"ssdlite_mobiledet_cpu_320x320_coco_2020_05_19/model.tflite\"\n )\n interpreter.allocate_tensors()\n\n # Get input and output tensors.\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n # check the type of the input tensor\n # floating_model = input_details[0]['dtype'] == np.float32\n\n print(f'output_details: {output_details}')\n\n height = input_details[0]['shape'][1]\n width = input_details[0]['shape'][2]\n img = Image.open(image).resize((width, height))\n\n # add N dim\n input_data = np.expand_dims(img, axis=0, dtype=np.float32)\n\n # Test the model on random input data.\n input_shape = input_details[0]['shape']\n # input_data = tf.compat.v1.expand_dims(img_array, axis=0)\n interpreter.set_tensor(input_details[0]['index'], input_data)\n\n start_time = time.time()\n interpreter.invoke()\n stop_time = time.time()\n\n # The function `get_tensor()` returns a copy of the tensor data.\n # Use `tensor()` in order to get a pointer to the tensor.\n output_data = interpreter.get_tensor(output_details[0]['index'])\n results = np.squeeze(output_data, dtype=np.float32)\n\n top_k = results.argsort()[-5:][::-1]\n labels = load_labels('./annotations/instances_val2017.txt')\n\n for i in top_k:\n # if floating_model:\n # print('{:08.6f}: {}'.format(float(results[i]), labels[i]))\n # else:\n print('{:08.6f}: {}'.format(float(results[i] / 255.0), labels[i]))\n\n PIL_image = Image.fromarray(np.uint8(results)).convert('RGB')\n\n print('time: {:.3f}ms'.format((stop_time - start_time) * 1000))\n\n print(f'results: {results}')\n print(f'results_shape: {results.shape}')\n\n # # load annotations to decode classification result\n # with open('./annotations/instances_val2017.txt', 'r') as handle:\n # annotate_json = json.load(handle)\n # label_info = {idx + 1: cat['name'] for idx, cat in enumerate(annotate_json['categories'])}\n\n return PIL_image\n\n\n@app.route('/')\ndef hello_world():\n figure = create_figure()\n output = io.BytesIO()\n FigureCanvas(figure).print_jpg(output)\n processed_image = Response(output.getvalue(), mimetype='image/jpeg')\n return render_template('index.html', processed_image=processed_image)\n\n\n@app.route('/upload_file', 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('uploaded_file',\n filename=filename))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56000193","text":"\"\"\"Perform SVM with descriptors\"\"\"\n\nimport os\nimport pandas as pd\nfrom Kmeans import Kmeans\n\nroot = {\n \"root\": \"/home/babs/Documents/DIFACQUIM/PPI_classifier/phase-2_a/Databases/\",\n \"root_Info\": \"/home/babs/Documents/DIFACQUIM/PPI_classifier/phase-2_a/Supervised_Models/SVM/Info\",\n \"root_ROC\": \"/home/babs/Documents/DIFACQUIM/PPI_classifier/phase-2_a/Supervised_Models/SVM/ROC\",\n \"trained_models\": \"/home/babs/Documents/DIFACQUIM/PPI_classifier/phase-2_a/trained_models\",\n}\n\n\nprint(str(root[\"root\"]))\ndata = pd.read_csv(str(root[\"root\"]) + str(\"dataset_descriptors_p2.csv\"))\n\nnumerical_data = data.drop(\n [\"Unnamed: 0\", \"ipp_id\", \"chembl_id\", \"SMILES\", \"library\", \"PPI family\", \"PPI\"],\n axis=1,\n)\ndescriptors = numerical_data.columns.to_list()\nprint(\"number of descriptors: \", len(descriptors))\n\n\ndef execute(\n root, input_file, target, descriptors, fraction, kernel, balanced, ref_output\n):\n a = Kmeans(root, input_file, target, descriptors, fraction)\n a.eda()\n a.train_model()\n # a.report(ref_output)\n # print(\"report \", str(ref_output), \"is done\")\n\n\nexecute(\n root,\n \"dataset_descriptors_p2.csv\",\n \"PPI\",\n descriptors,\n 0.2,\n \"linear\",\n \"balanced\",\n \"p2_D11L6P3SVM1A\",\n)\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.2,\n# \"poly\",\n# \"balanced\",\n# \"p2_D11L6P3SVM2A\",\n# )\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.2,\n# \"rbf\",\n# \"balanced\",\n# \"p2_D11L6P3SVM3A\",\n# )\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.2,\n# \"sigmoid\",\n# \"balanced\",\n# \"p2_D11L6P3SVM4A\",\n# )\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.3,\n# \"linear\",\n# \"balanced\",\n# \"p2_D11L6P5SVM1A\",\n# )\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.3,\n# \"poly\",\n# \"balanced\",\n# \"p2_D11L6P5SVM2A\",\n# )\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.3,\n# \"rbf\",\n# \"balanced\",\n# \"p2_D11L6P5SVM3A\",\n# )\n# execute(\n# root,\n# \"dataset_descriptors_p2.csv\",\n# \"PPI\",\n# descriptors,\n# 0.3,\n# \"sigmoid\",\n# \"balanced\",\n# \"p2_D11L6P5SVM4A\",\n# )\n\n","sub_path":"phase-2_a/Unsupervised_Models/Kmeans/descriptors_instructions.py","file_name":"descriptors_instructions.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"632673429","text":"#import tensorflow.compat.v1 as tf\r\n#tf.disable_v2_behavior()\r\nimport logging, os \r\nos.system('clear')\r\nlogging.disable(logging.WARNING) \r\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\r\nimport tensorflow as tf\r\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\r\nimport numpy as np \r\nimport pandas as pd \r\nimport time\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n#from keras import backend as K\r\n\r\n\r\nclass nnpde_informed():\r\n def __init__(self,linearTerm,advection_z,advection_f,diffusion_z,diffusion_f,cross_term,J0,X,layers,X_f,dt,tb,learning_rate,adam_iter):\r\n \r\n self.linearTerm = linearTerm\r\n self.advection_z = advection_z\r\n self.advection_y = advection_f\r\n self.diffusion_z = diffusion_z\r\n self.diffusion_y = diffusion_f\r\n self.cross_term = cross_term\r\n self.u = J0\r\n self.X = X\r\n self.layers = layers\r\n self.t_b = tb\r\n self.X_f = X_f\r\n self.dt = dt\r\n self.learning_rate = learning_rate\r\n self.adam_iter = adam_iter\r\n \r\n self.z_u = self.X[:,0:1]\r\n self.t_u = self.X[:,2:3]\r\n self.z_f = self.X_f[:,0:1]\r\n self.t_f = self.X_f[:,2:3]\r\n self.y_u = self.X[:,1:2]\r\n self.y_f = self.X_f[:,1:2]\r\n \r\n self.lb = np.array([0,self.y_u[0][0], self.dt])\r\n self.ub = np.array([1,self.y_u[-1][0], 0])\r\n #self.lb = 0\r\n #self.ub = 1\r\n \r\n self.X_b = np.array([[self.z_u[0][0],self.y_u[0][0], 0],[self.z_u[0][0],self.y_u[0][0], self.dt],[self.z_u[-1][0],self.y_u[-1][0],0.],[self.z_u[-1][0],self.y_u[-1][0],self.dt]])\r\n self.z_b = np.array(self.X_b[:,0]).reshape(-1,1)\r\n self.y_b = np.array(self.X_b[:,1]).reshape(-1,1)\r\n self.t_b = np.array(self.X_b[:,2]).reshape(-1,1)\r\n #Initialize NNs\r\n self.weights, self.biases = self.initialize_nn(layers)\r\n \r\n #tf placeholders and computational graph\r\n self.sess = tf.Session(config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = True))\r\n self.z_u_tf = tf.placeholder(tf.float32,shape=[None,self.z_u.shape[1]])\r\n self.y_u_tf = tf.placeholder(tf.float32,shape=[None,self.y_u.shape[1]])\r\n self.t_u_tf = tf.placeholder(tf.float32,shape=[None,self.t_u.shape[1]])\r\n self.u_tf = tf.placeholder(tf.float32, shape=[None,self.u.shape[1]])\r\n \r\n \r\n self.z_b_tf = tf.placeholder(tf.float32, shape=[None,self.z_b.shape[1]])\r\n self.y_b_tf = tf.placeholder(tf.float32, shape=[None,self.y_b.shape[1]])\r\n self.t_b_tf = tf.placeholder(tf.float32, shape=[None,self.t_b.shape[1]])\r\n \r\n self.z_f_tf = tf.placeholder(tf.float32, shape=[None,self.z_f.shape[1]])\r\n self.y_f_tf = tf.placeholder(tf.float32, shape=[None,self.y_f.shape[1]])\r\n self.t_f_tf = tf.placeholder(tf.float32, shape=[None,self.t_f.shape[1]])\r\n \r\n \r\n self.u_pred,_,_ = self.net_u(self.z_u_tf,self.y_u_tf,self.t_u_tf)\r\n self.f_pred = self.net_f(self.z_f_tf, self.y_f_tf,self.t_f_tf)\r\n _, self.ub_z_pred, self.ub_y_pred = self.net_u(self.z_b_tf,self.y_b_tf,self.t_b_tf)\r\n \r\n \r\n \r\n self.loss = tf.reduce_mean(tf.square(self.u_tf-self.u_pred)) + \\\r\n tf.reduce_mean(tf.square(self.f_pred)) #+\\\r\n #tf.reduce_mean(tf.square(self.ub_y_pred)) #+\\\r\n #tf.reduce_mean(tf.square(self.ub_z_pred)) #works even without this line for ies1 case\r\n \r\n \r\n \r\n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss,method='L-BFGS-B',\r\n options = {'maxiter': 50000,\r\n 'maxfun': 50000,\r\n 'maxcor': 50,\r\n 'maxls': 50,\r\n 'ftol': 1e-08})\r\n \r\n \r\n self.optimizer_Adam = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\r\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss)\r\n \r\n init = tf.global_variables_initializer()\r\n self.sess.run(init)\r\n\r\n \r\n def initialize_nn(self,layers):\r\n weights = []\r\n biases = []\r\n num_layers = len(layers)\r\n for l in range(num_layers-1):\r\n W = self.xavier_init(size = [layers[l],layers[l+1]])\r\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype = tf.float32)\r\n weights.append(W)\r\n biases.append(b)\r\n \r\n return weights,biases\r\n\r\n \r\n def xavier_init(self,size):\r\n in_dim = size[0]\r\n out_dim = size[1]\r\n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\r\n try:\r\n val = tf.Variable(tf.random.truncated_normal([in_dim,out_dim], stddev = xavier_stddev), dtype = tf.float32)\r\n except:\r\n val = tf.Variable(tf.truncated_normal([in_dim,out_dim], stddev = xavier_stddev), dtype = tf.float32)\r\n return val\r\n \r\n def neural_net(self,X,weights,biases):\r\n num_layers = len(weights) +1\r\n H = 2.0*(X - self.lb)/(self.ub - self.lb) -1\r\n #H=X\r\n for l in range(num_layers-2):\r\n W = weights[l]\r\n b = biases[l]\r\n H = tf.tanh(tf.add(tf.matmul(H,W),b))\r\n W = weights[-1]\r\n b = biases[-1]\r\n Y = tf.add(tf.matmul(H,W),b)\r\n\r\n return Y\r\n\r\n def net_u(self,z,y,t):\r\n X = tf.concat([z,y,t],1)\r\n u = self.neural_net(X,self.weights,self.biases)\r\n u_z = tf.gradients(u,z)[0]\r\n u_y = tf.gradients(u,y)[0]\r\n return u,u_z,u_y\r\n \r\n def net_f(self,z,y,t):\r\n u,u_z,u_y = self.net_u(z,y,t)\r\n u_t = tf.gradients(u,t)[0]\r\n u_zz = tf.gradients(u_z,z)[0]\r\n u_yy = tf.gradients(u_y,y)[0]\r\n u_zy = tf.gradients(u_z,y)[0]\r\n f = u_t + self.diffusion_z * u_zz + self.diffusion_y * u_yy + self.advection_y * u_y + self.advection_z * u_z + self.cross_term * u_zy - self.linearTerm *u\r\n #f = u_t + self.diffusion_z * u_zz + self.advection_z * u_z - self.linearTerm*u\r\n return f\r\n \r\n def callback(self,loss):\r\n print('Loss: ',loss)\r\n \r\n def train(self):\r\n #K.clear_session()\r\n tf_dict = {self.z_u_tf: self.z_u, self.y_u_tf: self.y_u, self.t_u_tf: self.t_u, self.u_tf:self.u,\r\n self.z_f_tf: self.z_f,self.y_f_tf: self.y_f, self.t_f_tf: self.t_f,\r\n self.z_b_tf: self.z_b,\r\n self.y_b_tf: self.y_b,\r\n self.t_b_tf: self.t_b}\r\n \r\n start_time = time.time()\r\n \r\n if True: #set this to true if you want adam to run \r\n for it in range(self.adam_iter):\r\n self.sess.run(self.train_op_Adam, tf_dict)\r\n # Print\r\n if it % 1000 == 0:\r\n elapsed = time.time() - start_time\r\n loss_value = self.sess.run(self.loss, tf_dict)\r\n print('It: %d, Loss: %.3e, Time: %.2f' % \r\n (it, loss_value, elapsed))\r\n start_time = time.time()\r\n \r\n start_time = time.time()\r\n self.optimizer.minimize(self.sess,feed_dict = tf_dict)\r\n elapsed = time.time() - start_time\r\n print('Time: %.2f' % elapsed)\r\n #self.sess.close()\r\n\r\n\r\n def predict(self, X_star):\r\n u_star = self.sess.run(self.u_pred, {self.z_u_tf: X_star[:,0:1],self.y_u_tf: X_star[:,1:2], self.t_u_tf: X_star[:,2:3]})\r\n #f_star = self.sess.run(self.f_pred, {self.z_f_tf: X_star[:,0:1],self.y_f_tf: X_star[:,1:2], self.t_f_tf: X_star[:,2:3]})\r\n tf.reset_default_graph()\r\n return u_star\r\n\r\n\r\n\r\nif __name__ =='__main__':\r\n J0 = Je0.astype(np.float32).reshape(-1,1)\r\n linearTerm = linearTermE_tile\r\n advection_z,advection_f,diffusion_z,diffusion_f,cross_term = advection_z_tile,advection_f_tile,diffusion_z_tile,diffusion_f_tile,cross_term_tile\r\n model_ = nnpde_informed(linearTerm,advection_z,advection_f,diffusion_z,diffusion_f,cross_term,J0,X,layers,X_f,dt,tb)\r\n model_.train()\r\n \r\n Jnew, Jnew_error = model_.predict(x_star)\r\n #plt.plot(z, Jnew)\r\n #plt.plot(z, Je)\r\n \r\n \r\n \r\n \r\n","sub_path":"Models/Extended/nnpde.py","file_name":"nnpde.py","file_ext":"py","file_size_in_byte":8638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130537893","text":"from typing import Dict\nfrom playhouse.sqlite_ext import *\n\nDB_NAME = \"someone.sqlite3\"\nDATABASE = SqliteExtDatabase(DB_NAME)\n\n\ndef initialize_db():\n DATABASE.connect()\n DATABASE.create_tables([Post])\n DATABASE.close()\n\n\nclass BaseModel(Model):\n class Meta:\n database = DATABASE\n\n\nclass Post(BaseModel):\n # Manual append\n identifier = CharField(index=True, primary_key=True)\n title = CharField()\n subtitle = CharField(default=\"\")\n is_public = BooleanField(default=False)\n is_top = BooleanField(default=False)\n on_index = BooleanField(default=False)\n index = IntegerField(index=True, default=0)\n cover_img = CharField(default=\"\")\n trim_abstract = BooleanField(default=True)\n # Auto append by reader\n source_fp = TextField(default=\"\")\n update_dt = DateTimeField()\n html = TextField(default=\"\")\n related_idfs = JSONField(default=[])\n abstract = CharField(default=\"\")\n\n @classmethod\n def insert_replace_all(cls, post_list: [Dict]):\n \"\"\"create a list of posts in transaction, return length of the list if transaction is correctly executed\"\"\"\n # insert\n try:\n cls.replace_many(post_list).execute()\n except (KeyError, ValueError, DatabaseError):\n raise DatabaseError(\"fail to generate new database file\")\n\n @classmethod\n def get_public_posts(cls):\n \"\"\"select and order all posts in database\"\"\"\n fields = [\"identifier\", \"title\", \"subtitle\", \"on_index\",\n \"cover_img\", \"update_dt\", \"html\", \"related_idfs\", \"abstract\"]\n fields = [getattr(cls, v) for v in fields]\n query = cls.select(*fields).where(cls.is_public == True).order_by(cls.is_top.desc(),\n cls.index.desc(),\n cls.update_dt.desc())\n return query\n\n @classmethod\n def get_one(cls, identifier: str, public_only: bool = True):\n \"\"\"get a single post by identifier\"\"\"\n fields = (\"identifier\", \"title\", \"subtitle\", \"abstract\",\n \"cover_img\", \"update_dt\", \"html\", \"related_idfs\")\n fields = (getattr(cls, v) for v in fields)\n query = cls.select(*fields).where(cls.identifier == identifier, cls.is_public == True)\n if len(query) != 1:\n raise DatabaseError(\"Invalid identifier: {}.\".format(identifier))\n return query[0]\n\n\nclass DatabaseError(Exception):\n pass\n","sub_path":"someone_console/someone_console/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570032482","text":"# coding = utf8\nimport os\nimport sys\n\nfrom poco.exceptions import PocoNoSuchNodeException\n\nfrom page.system.system import System, sleep\nfrom toolsbar.excel_tools import read_excel_for_page_element\n\nos.path.abspath(\".\")\n\"\"\"\n @File:calendar_page.py\n @Author:Bruce\n @Date:2021/1/13\n @Description:Calendar page,控制设备Calendar应用的函数、控件\n @param:继承System,传入Main_Page实例完成设备Device、Poco初始化\n\"\"\"\n\n\n# 该函数用于简化元素获取操作\ndef get_element_parametrize(element_name=\"guide_page_text\"):\n form_name = \"./page/page_sheet.xlsx\"\n element_data = read_excel_for_page_element(form=form_name, sheet_name=\"calendar_page\",\n element_name=element_name)\n return element_data\n\n\nclass Calendar_Page(System):\n \"\"\"\n @param:main_page:传入Main_Page实例完成设备的Device、Poco的初始化\n \"\"\"\n\n def __init__(self, main_page):\n System.__init__(self, main_page)\n\n self.guide_page_text = self.poco(text=get_element_parametrize(\"guide_page_text\"))\n self.guide_next_arrow = self.poco(get_element_parametrize(\"guide_next_arrow\"))\n self.guide_got_it = self.poco(get_element_parametrize(\"guide_got_it\"))\n self.create_calendar_button = self.poco(get_element_parametrize(\"create_calendar_button\"))\n self.create_event_button = self.poco(text=get_element_parametrize(\"create_event_button\"))\n self.add_title_edittext = self.poco(get_element_parametrize(\"add_title_edittext\"))\n self.save_button = self.poco(get_element_parametrize(\"save_button\"))\n\n \"\"\"\n @description:启动calendar应用\n \"\"\"\n\n def start_calendar(self):\n self.logger.info(\"function:\" + sys._getframe().f_code.co_name + \":启动calendar app:\")\n self.device.start_app(\"com.google.android.calendar\")\n sleep(1)\n\n \"\"\"\n @description:关闭calendar应用\n \"\"\"\n\n def stop_calendar(self):\n self.logger.info(\"function:\" + sys._getframe().f_code.co_name + \":关闭calendar app:\")\n sleep(1)\n self.device.stop_app(\"com.google.android.calendar\")\n\n \"\"\"\n @description:跳过calendar向导页\n \"\"\"\n\n def skip_guide(self):\n self.logger.info(\"function:\" + sys._getframe().f_code.co_name + \":跳过设置向导:\")\n try:\n if self.guide_page_text.wait().exists():\n for i in range(2):\n guide_next = self.guide_next_arrow.wait()\n guide_next.click()\n self.guide_got_it.wait().click()\n except PocoNoSuchNodeException as ex:\n self.logger.warning(\"function:\" + sys._getframe().f_code.co_name +\n \":无需跳过calendar设置向导:\" + str(ex))\n\n \"\"\"\n @description:创建日历事件\n @param:\n title:传入title指定创建的日历事件的名称\n \"\"\"\n\n def create_calendar(self, title=\"Test\"):\n result = \"\"\n try:\n self.logger.info(\"function:\" + sys._getframe().f_code.co_name + \":创建一个名为{}的calendar:\".format(title))\n self.create_calendar_button.wait().click()\n try:\n self.create_event_button.wait().click()\n except PocoNoSuchNodeException as ex:\n self.logger.warning(\"function:\" + sys._getframe().f_code.co_name +\n \":无需点击event按钮:\" + str(ex))\n sleep(1)\n self.add_title_edittext.wait().set_text(title)\n self.save_button.wait().click()\n created_calendar = self.poco(\n \"com.google.android.calendar:id/alternate_timeline_fragment_container\").children()[0].wait().children()[\n 2].attr(\"desc\")\n result = created_calendar\n except Exception as ex:\n self.logger.error(\"function:\" + sys._getframe().f_code.co_name + \":创建日历出现问题:\" + str(ex))\n return result\n","sub_path":"page/calendar/calendar_page.py","file_name":"calendar_page.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109187690","text":"# -*- coding: utf-8 -*-\nfrom time import sleep, time\nfrom Queue import Queue, Empty\nfrom threading import Thread\nfrom .vnpy import CtpGateway, CtpTdApi, CtpMdApi, posiDirectionMapReverse\nfrom .vnpy import VtBaseData\nfrom .vnpy import EMPTY_FLOAT, EMPTY_STRING\nfrom .vnpy import Event\nfrom .vnpy import EventEngine2\n\nEVENT_POSITION_EXTRA = 'ePositionExtra'\nEVENT_CONTRACT_EXTRA = 'eContractExtra'\nEVENT_ACCOUNT_EXTRA = 'eAccountExtra'\nEVENT_COMMISSION = 'eCommission'\nEVENT_INIT_ACCOUNT = 'eAccountInit'\n\n\n# ------------------------------------ 自定义或扩展数据类型 ------------------------------------\nclass PositionExtra(VtBaseData):\n def __init__(self):\n super(PositionExtra, self).__init__()\n self.symbol = EMPTY_STRING\n self.direction = EMPTY_STRING\n\n self.commission = EMPTY_FLOAT\n self.closeProfit = EMPTY_FLOAT\n self.openCost = EMPTY_FLOAT\n self.preSettlementPrice = EMPTY_FLOAT\n\n\nclass ContractExtra(VtBaseData):\n def __init__(self):\n super(ContractExtra, self).__init__()\n\n self.symbol = EMPTY_STRING\n\n self.openDate = EMPTY_STRING\n self.expireDate = EMPTY_STRING\n self.longMarginRatio = EMPTY_FLOAT\n self.shortMarginRatio = EMPTY_FLOAT\n\n\nclass CommissionData(VtBaseData):\n def __init__(self):\n super(CommissionData, self).__init__()\n\n self.symbol = EMPTY_STRING\n\n self.OpenRatioByMoney = EMPTY_FLOAT\n self.CloseRatioByMoney = EMPTY_FLOAT\n self.OpenRatioByVolume = EMPTY_FLOAT\n self.CloseRatioByVolume = EMPTY_FLOAT\n self.CloseTodayRatioByMoney = EMPTY_FLOAT\n self.CloseTodayRatioByVolume = EMPTY_FLOAT\n\n\nclass AccountExtra(VtBaseData):\n def __init__(self):\n super(AccountExtra, self).__init__()\n\n self.accountID = EMPTY_STRING\n self.vtAccountID = EMPTY_STRING\n\n self.preBalance = EMPTY_FLOAT\n\n\n# ------------------------------------ 扩展事件引擎 ------------------------------------\nclass RQVNEventEngine(EventEngine2):\n def __init__(self):\n super(RQVNEventEngine, self).__init__()\n\n def __run(self):\n \"\"\"引擎运行\"\"\"\n while self.__active == True:\n try:\n event = self.__queue.get(block=True, timeout=10) # 获取事件的阻塞时间设为1秒\n self.__process(event)\n except Empty:\n pass\n except Exception as e:\n system_log.exception(\"event engine process fail\")\n system_log.error(\"We can not handle this exception exiting.\")\n os._exit(-1)\n\n\n# ------------------------------------ 扩展CTPApi ------------------------------------\nclass RQCTPTdApi(CtpTdApi):\n def __init__(self, gateway):\n super(RQCTPTdApi, self).__init__(gateway)\n self.posExtraDict = {}\n\n def onRspQryTradingAccount(self, data, error, n, last):\n super(RQCTPTdApi, self).onRspQryTradingAccount(data, error, n, last)\n\n accountExtra = AccountExtra()\n accountExtra.accountID = data['AccountID']\n accountExtra.vtAccountID = '.'.join([self.gatewayName, accountExtra.accountID])\n\n accountExtra.preBalance = data['PreBalance']\n self.gateway.onAccountExtra(accountExtra)\n\n self.gateway.status.account_success()\n\n def onRspQryInvestorPosition(self, data, error, n, last):\n super(RQCTPTdApi, self).onRspQryInvestorPosition(data, error, n, last)\n\n positionName = '.'.join([data['InstrumentID'], data['PosiDirection']])\n posExtra = PositionExtra()\n posExtra.symbol = data['InstrumentID']\n posExtra.direction = posiDirectionMapReverse.get(data['PosiDirection'])\n posExtra.commission = data['Commission']\n posExtra.closeProfit = data[\"CloseProfit\"]\n posExtra.openCost = data[\"OpenCost\"]\n posExtra.preSettlementPrice = data['PreSettlementPrice']\n\n self.posExtraDict[positionName] = posExtra\n\n if last:\n for posExtra in self.posExtraDict.values():\n self.gateway.onPositionExtra(posExtra)\n\n self.gateway.status.position_success()\n\n def onRspQryInstrument(self, data, error, n, last):\n super(RQCTPTdApi, self).onRspQryInstrument(data, error, n, last)\n\n contractExtra = ContractExtra()\n contractExtra.symbol = data['InstrumentID']\n\n contractExtra.expireDate = data['ExpireDate']\n contractExtra.openDate = data['OpenDate']\n contractExtra.longMarginRatio = data['LongMarginRatio']\n contractExtra.shortMarginRatio = data['ShortMarginRatio']\n\n self.gateway.onContractExtra(contractExtra)\n if last:\n self.gateway.status.contract_success()\n\n def reqCommission(self, instrumentId, exchangeId, userId, brokerId):\n self.reqID += 1\n req = {\n 'InstrumentID': instrumentId,\n 'InvestorID': userId,\n 'BrokerID': brokerId,\n 'ExchangeID': exchangeId\n }\n self.reqQryInstrumentCommissionRate(req, self.reqID)\n\n def onRspQryInstrumentCommissionRate(self, data, error, n, last):\n commissionData = CommissionData()\n commissionData.symbol = data['InstrumentID']\n\n commissionData.OpenRatioByMoney = data['OpenRatioByMoney']\n commissionData.OpenRatioByVolume = data['OpenRatioByVolume']\n commissionData.CloseRatioByMoney = data['CloseRatioByMoney']\n commissionData.CloseRatioByVolume = data['CloseRatioByVolume']\n commissionData.CloseTodayRatioByMoney = data['CloseTodayRatioByMoney']\n commissionData.CloseTodayRatioByVolume = data['CloseTodayRatioByVolume']\n\n self.gateway.onCommission(commissionData)\n\n\nclass RQCTPMdApi(CtpMdApi):\n def __init__(self, gateway):\n super(RQCTPMdApi, self).__init__(gateway)\n\n\n# ------------------------------------ 扩展gateway ------------------------------------\nclass RQVNCTPGateway(CtpGateway):\n def __init__(self, event_engine, gateway_name, login_dict):\n super(CtpGateway, self).__init__(event_engine, gateway_name)\n\n self.mdApi = RQCTPMdApi(self)\n self.tdApi = RQCTPTdApi(self)\n\n self.mdConnected = False\n self.tdConnected = False\n\n self.qryEnabled = False\n\n self.inited = False\n\n self.status = InitStatus()\n\n self.login_dict = login_dict\n\n self.query_que = Queue()\n self._activate = True\n self._query_thread = Thread(target=self._process)\n\n def connect_and_init_contract(self):\n self.put_query(self.connect)\n # self.connect(self.login_dict)\n self.status.wait_until_contract(timeout=100)\n self.wait_until_query_que_empty()\n\n def connect(self):\n userID = str(self.login_dict['userID'])\n password = str(self.login_dict['password'])\n brokerID = str(self.login_dict['brokerID'])\n tdAddress = str(self.login_dict['tdAddress'])\n mdAddress = str(self.login_dict['mdAddress'])\n\n self.mdApi.connect(userID, password, brokerID, mdAddress)\n self.tdApi.connect(userID, password, brokerID, tdAddress, None, None)\n self.initQuery()\n\n def init_account(self):\n # TODO: 加入超时重试功能\n self.put_query(self.qryAccount)\n self.status.wait_until_account(timeout=10)\n self.put_query(self.qryPosition)\n self.status.wait_until_position(timeout=10)\n self.wait_until_query_que_empty()\n event = Event(type_=EVENT_INIT_ACCOUNT)\n self.eventEngine.put(event)\n\n def qryCommission(self, symbol, exchange):\n self.tdApi.reqCommission(symbol, exchange, self.login_dict['userID'], self.login_dict['brokerID'])\n\n def onPositionExtra(self, positionExtra):\n event = Event(type_=EVENT_POSITION_EXTRA)\n event.dict_['data'] = positionExtra\n self.eventEngine.put(event)\n\n def onContractExtra(self, contractExtra):\n event = Event(type_=EVENT_CONTRACT_EXTRA)\n event.dict_['data'] = contractExtra\n self.eventEngine.put(event)\n\n def onAccountExtra(self, accountExtra):\n event = Event(type_=EVENT_ACCOUNT_EXTRA)\n event.dict_['data'] = accountExtra\n self.eventEngine.put(event)\n\n def onCommission(self, commissionData):\n event = Event(type_=EVENT_COMMISSION)\n event.dict_['data'] = commissionData\n self.eventEngine.put(event)\n\n def put_query(self, query_name, **kwargs):\n self.query_que.put((query_name, kwargs))\n\n def _process(self):\n while self._activate:\n try:\n query = self.query_que.get(block=True, timeout=1)\n except Empty:\n continue\n query[0](**query[1])\n sleep(0.8)\n\n def start(self):\n self._activate = True\n self._query_thread.start()\n\n def wait_until_query_que_empty(self):\n while True:\n if self.query_que.empty():\n break\n\n\nclass InitStatus(object):\n def __init__(self):\n self._login = False\n self._contract = False\n self._account = False\n self._position = False\n\n def _wait_until(self, which, timeout):\n start_time = time()\n while True:\n which_dict = {\n 'login': self._login,\n 'contract': self._contract,\n 'account': self._account,\n 'position': self._position,\n }\n if which_dict[which]:\n break\n else:\n if timeout is not None:\n if time() - start_time > timeout:\n break\n\n def wait_until_login(self, timeout=None):\n self._wait_until('login', timeout)\n\n def login_success(self):\n self._login = True\n\n def wait_until_contract(self, timeout=None):\n self._wait_until('contract', timeout)\n\n def contract_success(self):\n self._contract = True\n\n def wait_until_account(self, timeout=None):\n self._wait_until('account', timeout)\n\n def account_success(self):\n self._account = True\n\n def wait_until_position(self, timeout=None):\n self._wait_until('position', timeout)\n\n def position_success(self):\n self._position = True\n\n","sub_path":"rqalpha_mod_vnpy/vnpy_gateway.py","file_name":"vnpy_gateway.py","file_ext":"py","file_size_in_byte":10220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"541955227","text":"\"\"\" Copyright 2012, 2013 UW Information Technology, University of Washington\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 Changes\n =================================================================\n\n sbutler1@illinois.edu: add support for filtering search params\n before sending to spotseeker server.\n\"\"\"\nfrom django.http import HttpResponse\nimport simplejson\nfrom spacescout_web.spot import Spot, SpotException\nfrom spacescout_web.org_filters import SearchFilterChain\n\n\ndef SearchView(request):\n\n chain = SearchFilterChain(request)\n\n search_args = {}\n\n for key in request.GET:\n if not chain.filters_key(key):\n search_args[key] = request.GET.getlist(key)\n\n search_args = chain.filter_args(search_args)\n\n json = Spot(None, request=request).search(search_args)\n json = simplejson.dumps(json)\n\n return HttpResponse(json, content_type='application/json')\n","sub_path":"views/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"428557598","text":"import paho.mqtt.client as mqtt\n\nUPDATE_RATE = 1 # seconds\nCLIENT_ID = \"eac9c9686e75475c3286f5c7224ef3d359b30cf3\"\nDEFAULT_PORT = 1883\nDEFAULT_KEEPALIVE = 60\n\n\nclass MqttBroker:\n def __init__(self, ip, port=DEFAULT_PORT, keepalive=DEFAULT_KEEPALIVE):\n self.client = mqtt.Client(client_id=CLIENT_ID)\n self.client.on_connect = self.__on_connect\n self.client.connect(ip, port, keepalive)\n self.client.loop_start()\n\n def __on_connect(self, client, userdata, flags, rc):\n print(\"Connected with result code \" + str(rc))\n\n def publish(self, topic, data):\n self.client.publish(topic, data)\n\n\n# client = mqtt.Client(client_id=CLIENT_ID)\n# client.on_connect = on_connect\n# client.connect(MQTT_IP, 1883, 60)\n# client.loop_start()\n\n# starttime = time.time()\n# while True:\n# client.publish(\"home/env/raw/something\", data)\n#\n# time.sleep(UPDATE_RATE - ((time.time() - starttime) % UPDATE_RATE))","sub_path":"air-pi/ble2mqtt/mqtt.py","file_name":"mqtt.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"631396990","text":"#!/usr/bin/python3\n# author: xaled (https://github.com/xaled)\n# credits: https://github.com/pradyumnac/AliexpressOrders\nimport time\nfrom pyquery import PyQuery as pq\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.common.exceptions import TimeoutException\nfrom xaled_utils.json_min_db import JsonMinConnexion\nfrom xaled_utils.logs import configure_logging\nfrom xaled_scrapers.selenium import get_display\nimport logging\nfrom xaled_scrapers.args import parse_args, get_additional_argument\n\n\nlogger = logging.getLogger(__name__)\nUA_STRING = \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0\"\n# EMAIL = 'XXXXXX'\n# PASS = 'YYYYYYY'\n# DRIVER_TYPE = \"Chrome\"\n# DRIVER_PATH = \"./chromedriver\"\n\nDEFAULT_ORDERS_DB_PATH = 'orders.data.json'\nDEFAULT_PROTECTION_EXTENSION_MSG = \"please extend protection for another 30 days\"\n\n\n# PROTECTION_EXTENSION = True\n\n\ndef update_order(order):\n global data\n data['orders'][order['order_id']] = order\n # if not order['order_id'] in data['order_ids']:\n # data['order_ids'].append(order['order_id'])\n data.save()\n\n\ndef still_non_finished(order_id):\n order_ids = sorted(data['orders'].keys(), reverse=True)\n if len(order_ids) == 0:\n return True\n if not order_id in order_ids:\n return True\n if len(order_ids[order_ids.index(order_id) + 1:]) == 0:\n return True\n for oi in order_ids[order_ids.index(order_id) + 1:]:\n o = data['orders'][oi]\n if o['status'] == 'Awaiting delivery':\n return True\n return False\n\n\ndef parse_orders_page(src):\n node = pq(src)\n l_orders = []\n for e in node('.order-item-wraper'):\n try:\n order = {\n \"order_id\": pq(e)('.order-head .order-info .first-row .info-body')[0].text,\n \"order_url\": pq(e)('.order-head .order-info .first-row .view-detail-link')[0].attrib['href'],\n \"order_dt\": pq(e)('.order-head .order-info .second-row .info-body')[0].text,\n \"order_store\": pq(e)('.order-head .store-info .first-row .info-body')[0].text,\n \"order_store_url\": pq(e)('.order-head .store-info .second-row a')[0].attrib['href'],\n \"order_amount\": pq(e)('.order-head .order-amount .amount-body .amount-num')[0].text,\n \"product_list\": [{\n \"title\": pq(f)('.product-right .product-title a').attr['title'],\n \"url\": pq(f)('.product-right .product-title a').attr['href'],\n \"amount\": pq(f)('.product-right .product-amount').text().strip(),\n \"property\": pq(f)('.product-right .product-policy a').attr['title'],\n } for f in pq(e)('.order-body .product-sets')],\n \"status\": pq(e)('.order-body .order-status .f-left').text(),\n \"status_days_left\": pq(e)('.order-body .order-status .left-sendgoods-day').text().strip()\n }\n\n try:\n # TODO - handle not found exception\n t_button = driver.find_element_by_xpath(\n '//*[@button_action=\"logisticsTracking\" and @orderid=\"{}\"]'.format(order['order_id']))\n hover = ActionChains(driver).move_to_element(t_button).perform()\n time.sleep(5)\n\n order['tracking_id'] = driver.find_element_by_css_selector('.ui-balloon b').text.strip().split(':')[\n 1].strip()\n try:\n # if present, It means, tracking has begun\n order['tracking_status'] = driver.find_element_by_css_selector('.ui-balloon .event-line-key').text\n order['tracking_desc'] = driver.find_element_by_css_selector('.ui-balloon .event-line-desc').text\n except:\n # Check for no event which means tracking has nto started or has not begun\n try:\n order['tracking_status'] = driver.find_element_by_css_selector(\n '.ui-balloon .no-event').text.strip()\n # If above passed, copy the tracking link and past for manual tracking\n order['tracking_status'] = \"Manual Tracking: \" + driver.find_element_by_css_selector(\n '.ui-balloon .no-event a').get_attribute('href').strip()\n order['tracking_desc'] = \"\"\n except:\n order['tracking_status'] = ''\n order['tracking_desc'] = \"\"\n except:\n order['tracking_id'] = ''\n order['tracking_status'] = ''\n order['tracking_desc'] = \"\"\n print(\"Tracking id retrieval failed for order:\" + order['order_id'])\n pass\n update_order(order)\n l_orders.append(order)\n except:\n print(\"failed parsing 1 order\")\n pass\n\n return l_orders\n\n\ndef parse_orders():\n orders = []\n source = driver.find_element_by_id(\"buyer-ordertable\").get_attribute(\"innerHTML\")\n\n # break_loop = False\n try:\n cur_page, total_page = (int(i) for i in\n driver.find_element_by_xpath('//*[@id=\"simple-pager\"]/div/label').text.split('/'))\n print(cur_page, '/', total_page)\n while (1):\n try:\n source = driver.find_element_by_id(\"buyer-ordertable\").get_attribute(\"innerHTML\")\n page_orders = parse_orders_page(source)\n orders.extend(page_orders)\n try:\n if not still_non_finished(page_orders[-1]['order_id']):\n break\n except:\n break\n except:\n print(\"failed parsing page %d/%d\" % (cur_page, total_page))\n try:\n if cur_page < total_page:\n link_next = driver.find_element_by_xpath('//*[@id=\"simple-pager\"]/div/a[text()=\"Next \"]')\n link_next.click()\n cur_page, total_page = (int(i) for i in driver.find_element_by_xpath(\n '//*[@id=\"simple-pager\"]/div/label').text.split('/'))\n print(\"Page:%d/%d\" % (cur_page, total_page))\n except:\n print(\"failed getting next link from page %d/%d\" % (cur_page, total_page))\n break\n if cur_page == total_page:\n break # break_loop = True # to break after parsing the next time\n return orders\n except Exception as e:\n print(e)\n return ([])\n\n\ndef login(email, passwd):\n # driver.get(\n # \"https://login.aliexpress.com/express/mulSiteLogin.htm?spm=2114.11010108.1000002.7.9c5Rcg&return=http%3A%2F%2Fwww.aliexpress.com%2F\")\n driver.get(\"https://www.aliexpress.com/\")\n # driver.find_element_by_class_name(\"sign-btn\").click()\n driver.execute_script(\"document.getElementsByClassName('sign-btn')[0].click()\")\n driver.get(\"https://login.aliexpress.com/express/mulSiteLogin.htm?return=https%3A%2F%2Fwww.aliexpress.com%2F\")\n driver.switch_to_frame(driver.find_element_by_id(\"alibaba-login-box\"))\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"fm-login-id\"))\n )\n element.send_keys(email)\n driver.find_element_by_xpath(\"//*[@id=\\\"fm-login-password\\\"]\").send_keys(passwd)\n driver.find_element_by_id(\"fm-login-submit\").click()\n try:\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"search-key\"))\n )\n except TimeoutException:\n print(\"Automatic log failed\")\n if args.manual_login:\n element = WebDriverWait(driver, 60).until(\n EC.presence_of_element_located((By.ID, \"search-key\"))\n )\n else:\n raise\n print(\"Login success!\")\n\n\ndef get_orders():\n driver.get(\"http://trade.aliexpress.com/orderList.htm?spm=2114.11010108.1000002.18.bT7Uae\")\n orders = parse_orders()\n return (orders)\n\n\ndef send_protection_extension_request(order_id):\n try:\n order_url = \"https://trade.aliexpress.com/order_detail.htm?orderId=%s\" % (order_id)\n driver.get(order_url)\n driver.switch_to_frame(driver.find_element_by_id(\"msgDetailFrame\"))\n driver.find_element_by_xpath(\"//*[@id=\\\"message-detail-textarea\\\"]\").send_keys(\n args.protection_message)\n # driver.find_element_by_id(\"message-detail-textarea\").send_keys(PROTECTION_EXTENSION_MSG)\n driver.find_element_by_id(\"send-message\").click()\n print(\"sent protection extension requests for order_id: \", order_id)\n except:\n print(\"could not send protection extension request for order_id: \", order_id)\n\n\ndef parse_days_lefts(status_days_left):\n if status_days_left == '':\n return 3153600000.0\n arr = status_days_left.split(':')[1].split()\n sum = 0.0\n for i in range(len(arr) // 2):\n u, c = arr[-1 - i * 2], float(arr[-2 - i * 2])\n if 'second' in u:\n sum += c\n elif 'minute' in u:\n sum += c * 60.0\n elif 'hour' in u:\n sum += c * 3600.0\n elif 'day' in u:\n sum += c * 86400.0\n return sum\n\n\ndef init_driver_(drivertype=\"Chrome\", driver_path=\"./chromedriver\"):\n if drivertype == \"Chrome\":\n from selenium.webdriver.chrome.options import Options\n opts = Options()\n opts.add_argument(\"user-agent=\" + UA_STRING)\n if driver_path is None:\n driver = webdriver.Chrome(chrome_options=opts)\n else:\n driver = webdriver.Chrome(driver_path, chrome_options=opts)\n elif drivertype == \"PhantomJS\":\n dcap = dict(DesiredCapabilities.PHANTOMJS)\n dcap[\"phantomjs.page.settings.userAgent\"] = (UA_STRING)\n driver = webdriver.PhantomJS(desired_capabilities=dcap)\n else:\n raise Exception(\"Invalid Driver Type:\" + drivertype)\n driver.set_window_size(1366, 680)\n return driver\n\n\ndef resize_string(obj, size):\n if len(obj) < size:\n return obj + \" \"*(size - len(obj))\n return obj[:size]\n\ndef parse_days_left(days_left):\n try:\n return \" \".join(days_left.split(\":\")[1].split()[:2])\n except:\n return days_left\n\n\nif __name__ == \"__main__\":\n configure_logging(modules=['xaled_scrapers', 'xaled_utils'])\n additional_arguments = list()\n additional_arguments.append(get_additional_argument('-u', '--user', required=True))\n additional_arguments.append(get_additional_argument('-p', '--password', required=True))\n additional_arguments.append(get_additional_argument('--db-path', default=DEFAULT_ORDERS_DB_PATH))\n additional_arguments.append(get_additional_argument('-P', '--protection', action='store_true'))\n additional_arguments.append(get_additional_argument('-m', '--manual-login', action='store_true'))\n additional_arguments.append(\n get_additional_argument('--protection-message', default=DEFAULT_PROTECTION_EXTENSION_MSG))\n args = parse_args(additional_argument=additional_arguments)\n\n data = JsonMinConnexion(args.db_path, template={'order_ids': [], 'orders': {}})\n try:\n if args.headless:\n display = get_display(size=(1500, 800))\n driver = init_driver_()\n # driver = init_driver(drivertype=args.driver_type, driver_path=args.driver_path)\n login(args.user, args.password)\n\n orders = get_orders()\n for o in orders:\n if o['status'].strip() in ['Awaiting Shipment', 'Finished', 'Fund Processing']:\n continue # ignore non shipped and finished orders\n tt = parse_days_lefts(o[\"status_days_left\"])\n if 86400 < tt < 14 * 86400: # 2 weeks\n if args.protection:\n print(\"- SENDING PROECTECTION EXTENSION REQUEST FOR ORDER: #%s %s (%s)\"%\n (o['order_id'], o['product_list'][0]['title'][:50], o['status_days_left']))\n else:\n print(\"- NOT SENDING PROECTECTION EXTENSION REQUEST FOR ORDER: #%s %s (%s)\"%\n (o['order_id'], o['product_list'][0]['title'][:50], o['status_days_left']))\n elif 0 < tt <= 86400:\n print(\"- ORDER ABOUT TO EXPIRE; %s (%s)\" % (o['product_list'][0]['title'][:50], o['status_days_left']))\n if o['tracking_status'] == 'Delivered' and o['status'] != 'Finished':\n print(\"- ORDER DELIVERED: #%s %s (%s)\" %\n (o['order_id'], o['product_list'][0]['title'][:50], o['status_days_left']))\n\n if args.verbose:\n print(\"\\nlist of retrieved orders:\")\n print(\"%s | %s | %s | %s | %s | %s\" %\n (resize_string('order_id', 15), resize_string('product title', 40),\n resize_string('status', 20), resize_string('days left', 10),\n resize_string('tracking_status', 25), resize_string('tracking_desc', 25)))\n for o in orders:\n print(\"%s | %s | %s | %s | %s | %s\" %\n (resize_string(o['order_id'], 15), resize_string(o['product_list'][0]['title'], 40),\n resize_string(o['status'],20), resize_string(parse_days_left(o['status_days_left']), 10),\n resize_string(o['tracking_status'],25), resize_string(o['tracking_desc'],25)))\n finally:\n try: driver.quit()\n except: pass\n if args.headless:\n try: display.stop()\n except: pass\n","sub_path":"aliexpress.py","file_name":"aliexpress.py","file_ext":"py","file_size_in_byte":13901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"565198425","text":"## https://scikit-learn.org/stable/\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n\n# 觀察資料\nX = [[6], [8], [10], [14], [18]]\ny = [[7], [9], [13], [17.5], [18]]\nplt.figure()\nplt.title('Pizza Price with diameter.')\nplt.xlabel('diameter(inch)')\nplt.ylabel('price($)')\nplt.axis([0, 25, 0, 25])\nplt.grid(True)\nplt.plot(X, y, 'k.')\n# pyplot.plot 第3個參數是format string \n# https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.plot.html\nplt.show()\n\n\n# 建立模型與評量\nreg = LinearRegression()\n# X and y is the data in previous code.\nreg.fit(X, y)\nprint(u'係數', reg.coef_)\nprint (u'截距', reg.intercept_)\nprint (u'評分函式', reg.score(X, y))\nX2 = [[1], [10], [14], [25]]\ny2 = reg.predict(X2)\nprint(y2)\n\n\n# 資料預測\nX2 = [[1], [10], [14], [25]]\ny2 = reg.predict(X2)\nprint(y2)\n#繪製線性迴歸圖形\nplt.figure()\nplt.title(u'Pizza Price with diameter.') #標題\nplt.xlabel(u'diameter') #x軸座標\nplt.ylabel(u'price') #y軸座標\nplt.axis([0, 25, 0, 25]) #區間\nplt.grid(True) #顯示網格\nplt.plot(X, y, 'k.') #繪製訓練資料集散點圖\nplt.plot(X2, y2, '-g.') #繪製預測資料集直線\n","sub_path":"1_1.py","file_name":"1_1.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"594594012","text":"a, b, c = int( input() ), int( input() ), int( input() )\nd = True\nif a % 2 == 1 and b % 2 == 1 and c % 2 == 1:\n print( 'Все числа не четные' )\nelif a % 2 == 1 and b % 2 == 0 and c % 2 == 0 \\\n or a % 2 == 0 and b % 2 == 1 and c % 2 == 0 \\\n or a % 2 == 0 and b % 2 == 0 and c % 2 == 1:\n print( 'Есть одно не четное число' )\nelif a % 2 == 1 and b % 2 == 1 and c % 2 == 0 \\\n or a % 2 == 0 and b % 2 == 1 and c % 2 == 1 \\\n or a % 2 == 1 and b % 2 == 0 and c % 2 == 1:\n print( 'Есть два не четных числа' )\nelse:\n print( 'Все числа четные' )\n\ntype( d )\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42016631","text":"import os\nimport re\nimport argparse\nfrom collections import defaultdict\n\nimport cv2\nimport numpy as np\nfrom tqdm.auto import tqdm\nfrom pycocotools.coco import COCO\n\nfrom utils.writer import get_coco_writer\nfrom utils.image import pad_img, draw_text\nfrom utils.get_image_info import get_image_size\nfrom utils.path import get_subfolders_with_files, is_image\n\n\ndef get_crop(image, x, y, w,h):\n height, width, _ = image.shape\n\n ymin = np.clip(y-10, 0, height)\n ymax = np.clip(y+h+10, 0, height)\n xmin = np.clip(x-10, 0, width)\n xmax = np.clip(x+w+10, 0 , width) \n crop = image[ymin:ymax,xmin:xmax]\n crop = cv2.resize(crop, (-1,-1), fx=5, fy=5)\n return crop\n\n\ndef display_crop(image, bbox, target_window_sizes, cat_id):\n image = image.copy()\n crop_size, image_size = target_window_sizes\n\n crop = get_crop(image, *bbox)\n crop = cv2.resize(crop, crop_size)\n (label_width, label_height), baseline = cv2.getTextSize(str(cat_id), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n crop = cv2.copyMakeBorder(crop, label_height + baseline, 0, 0, 0, cv2.BORDER_CONSTANT, value=(0, 0, 0))\n cv2.putText(crop, str(cat_id), (0, label_height), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))\n cv2.imshow(f'crop', crop)\n\n x, y, w, h = bbox\n cv2.rectangle(image, (x, y), (x+w, y+h), (22, 48, 163), 2)\n cv2.imshow(f'full_image', cv2.resize(image, image_size))\n\n\ndef write_results(images, annotations, save_path):\n writer = get_coco_writer()\n for i, anns in annotations.items():\n img_h, img_w, img_path = images[i]\n if len(anns):\n image_id, _ = writer.add_frame(img_h, img_w, filename=img_path)\n for (bbox, category_id) in anns.values():\n writer.add_annotation(image_id, bbox, category_id)\n writer.write_result(save_path, verbose=True)\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('data_path', type=str, help='path to the output folder of `super_download_script`')\n parser.add_argument('--min_size', type=int, default=-1, help='min_size_to_classify')\n parser.add_argument('--auto', action='store_true', help='skip manual work')\n args = parser.parse_args()\n return args\n\ndef is_changed_folder(root_path:str, crop_name: str, annotation_num: int, class_num: int) -> bool:\n \"\"\"Check if folder is changed for image.\"\"\"\n image_name = f'{crop_name}_{annotation_num}.jpg'\n image_name_2 = f'{crop_name}_{annotation_num}..jpg'\n changed_dir_path = os.path.join(root_path, f'misclass_{class_num}')\n return (os.path.isfile(os.path.join(changed_dir_path, image_name)) or \n os.path.isfile(os.path.join(changed_dir_path, image_name_2)))\n\n\ndef in_which_folder(root_path:str, crop_name: str, annotation_num: int) -> int:\n \"\"\"Return class number based on detection location\"\"\"\n image_name = f'{crop_name}_{annotation_num}.jpg'\n image_name_2 = f'{crop_name}_{annotation_num}..jpg'\n for cat_id, folder_name in zip([0, 0, 1, 1], ['classified_0', 'misclass_1', 'classified_1', 'misclass_0']):\n infer_dir_path = os.path.join(root_path, folder_name)\n if (os.path.isfile(os.path.join(infer_dir_path, image_name)) or \n os.path.isfile(os.path.join(infer_dir_path, image_name_2))):\n return cat_id\n return -1\n\n\nif __name__ == \"__main__\":\n\n args = get_args()\n print(args)\n \n target_window_sizes = [\n ((64, 64), (640, 360)), \n ((128, 128), (1280, 720)), \n ((256, 256), (1920, 1080)),\n ]\n target_size_marker = 2\n\n coco = COCO(os.path.join(args.data_path, 'hor_crops_annotations.json'))\n hor_crops_path = os.path.join(args.data_path, 'hor_crops')\n hor_crops_infer_path = os.path.join(args.data_path, 'hor_crops_infer')\n save_path = os.path.join(args.data_path, 'human_checked_hor_crop_annotations.json')\n anns = coco.anns\n imgs = coco.imgs\n\n keys = np.array(list(imgs.keys()))\n image_num = 0\n prev_image_num = -1\n annotation_num = 0\n \n images, annotations = dict(), defaultdict(dict)\n pbar = tqdm(total=len(keys))\n while image_num < len(keys):\n pbar.update(image_num - pbar.n)\n # Load image and it's annotations\n if image_num != prev_image_num:\n img_info = imgs.get(keys[image_num])\n crop_name = os.path.splitext(os.path.split(img_info['file_name'])[1])[0]\n ann_ids = coco.getAnnIds(imgIds=img_info['id'], iscrowd=None)\n anns = coco.loadAnns(ann_ids)\n # Skip if no annotations\n if len(anns) == 0:\n prev_image_num = image_num\n image_num += 1\n continue\n annotation_num = 0\n # Load image, if none, skip\n image = cv2.imread(img_info['file_name'])\n if image is None:\n print('Image not found at: ', img_info['file_name'])\n prev_image_num = image_num\n image_num += 1\n continue\n # Get image id\n images[image_num] = (*image.shape[:2], img_info['file_name'])\n \n # If no more object in frame, go to next frame\n if annotation_num >= len(anns):\n prev_image_num = image_num\n image_num += 1\n continue\n # If annotation_num < 0, go to previous image\n elif annotation_num < 0:\n prev_image_num = image_num\n image_num -= 1\n continue\n \n # Get bbox and annotation\n bbox = np.array(anns[annotation_num]['bbox'], dtype=int)\n # Check if already classified\n if annotations[image_num].get(annotation_num):\n cat_id = annotations[image_num][annotation_num][1]\n else:\n # Check if already mapped as different class\n cat_id = in_which_folder(hor_crops_infer_path, crop_name, annotation_num)\n # Don't store if deleted\n if not cat_id == -1:\n annotations[image_num][annotation_num] = (bbox, cat_id)\n\n # Skip displaying if in auto mode\n if args.auto:\n prev_image_num = image_num\n annotation_num += 1\n continue\n\n # Display bbox\n display_crop(image, bbox, target_window_sizes[target_size_marker], cat_id)\n \n isBadKey = True\n while isBadKey:\n key = cv2.waitKey()\n isBadKey = False\n print(key)\n # Increase window size\n if key == ord('+'):\n target_size_marker = min(target_size_marker+1, 2)\n # Decrease window size\n elif key == ord('-'):\n target_size_marker = max(target_size_marker-1, 0)\n # Go to previous object\n elif key == ord(','):\n annotation_num -= 1\n # Go to next object\n elif key == ord('.'):\n annotation_num += 1\n # TP\n elif key == ord('j'):\n annotations[image_num][annotation_num] = (bbox, 1)\n annotation_num += 1\n # FP\n elif key == ord('o'):\n annotations[image_num][annotation_num] = (bbox, 0)\n annotation_num += 1\n # Save result\n elif key == 13:\n write_results(images, annotations, save_path)\n # Exit on q\n elif key == ord('q'):\n break\n else:\n isBadKey = True\n \n prev_image_num = image_num\n # Exit on q\n if key == ord('q'):\n cv2.destroyAllWindows()\n break\n write_results(images, annotations, save_path)\n","sub_path":"annotate_vino_output.py","file_name":"annotate_vino_output.py","file_ext":"py","file_size_in_byte":7620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380178444","text":"#-*- coding:utf-8 -*-\n#网址:http://www.ccgp-dalian.gov.cn\n#文件名:ccgp_dalian.py\n#作者: huanghong\n#创建日期: 2017-12-05\n#功能描述: 大连政府采购网\n#完成状况:完��\nimport logging\nfrom ccgp.Auxiliary import Saving\nimport time,datetime\n# import requests\nfrom pymongo import MongoClient\nfrom bson.binary import Binary\nimport sys\nimport codecs,csv\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib \nimport json\nfrom requests import Request, Session\nreload(sys)\nsys.setdefaultencoding('utf-8')\nheaders={\n\t'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n\t'Accept-Encoding':'gzip, deflate',\n\t'Accept-Language':'zh-CN,zh;q=0.9',\n\t'Cache-Control':'max-age=0',\n\t'Connection':'keep-alive',\n\t'Cookie':'yunsuo_session_verify=c280372dadcf36e45342a1f1e828d79b; ASP.NET_SessionId=hlmyqmyknzygwmymdbam3k45',\n\t'Host':'www.ccgp-dalian.gov.cn',\n\t'Referer':'http://www.ccgp-dalian.gov.cn/dlweb/Template/Default/pagehead.htm',\n\t'Upgrade-Insecure-Requests':'1',\n\t'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36'\n}\ndef get_link(nd,keyword):\n\t\tass=json.dumps(keyword)\n\t\tjsonObj =[(i and \"%\"+i) for i in ass.split('\\\\')]\n\t\tworld=(jsonObj[1]+jsonObj[2]).strip('\"').upper().replace('%U', '%u')\n\t\tdatas=[]\n\t\ts = Session()\n\t\turl=\"http://www.ccgp-dalian.gov.cn/dlweb/showinfo/searchresult.aspx?EpStr3=%s&searchtype=title\"%world\n\t\treq = Request('GET', url)\n\t\tprepped = s.prepare_request(req)\n\t\tprepped.url = prepped.url.replace('%25', '%')\n\t\tresp = s.send(prepped)\n\t\thtml=resp.content.decode('gb2312')\n\t\tsoup=BeautifulSoup(html,'lxml')\n\t\ttable=soup.find_all('table',id=\"SearchResult2_DataGrid1\")[0]\n\t\ttr=table.find_all('tr',valign=\"top\")\n\t\tfor i in tr:\n\t\t\ttis=i.find_all('td',align=\"right\")[0]\n\t\t\tti=re.findall('(\\d+.\\d+.\\d+)',tis.text)[0].replace('.','-')\t\t\t\t\n\t\t\tdatime=datetime.datetime.strptime(str(ti),'%Y-%m-%d')\n\t\t\tnowtime=time.strftime('%Y-%m-%d',time.localtime(time.time()))\n\t\t\tntime=datetime.datetime.strptime(nowtime,'%Y-%m-%d')\n\t\t\tif abs((ntime-datime).days)<=nd:\t\n\t\t\t\tem=i.find_all('a')[0]\n\t\t\t\ttitle=em.text.replace(' ','')\n\t\t\t\tlink='http://www.ccgp-dalian.gov.cn'+em.get('href')\n\t\t\t\tdatas.append({'url':link,'title':title,'updatetime':datime})\n\t\t\t\n\t\treturn datas\n\t\t\n\n\n\nclass Crawler():\n\tdef __init__(self):\n\t\tself.url = 'http://www.ccgp-dalian.gov.cn'\n\t\tself.mongo=Saving()\n\t\t\n\tdef __call__(self,nd,keyword):\n\t\tself.nd=nd\t\n\t\tself.keyword=keyword\n\t\t\t\t\t\n\t\ttry:\n\t\t\tupdatelists=get_link(self.nd,self.keyword)\n\t\texcept Exception as e:\n\t\t\tlogging.error(e)\n\t\t# print len(updatelists)\n\t\tself.mongo.save(self.url,updatelists)\n\t\tlogging.info(u'大连政府采购网,更新:(%s)'%len(updatelists))\n\t\treturn True\ndef main():\n\ttest = Crawler()\n\tresult =test(10,'智慧')\t\n\tlogging.info(result)\nif __name__ == '__main__':\n\tmain()\t\n","sub_path":"gov1/ccgp_dalian.py","file_name":"ccgp_dalian.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115714574","text":"# -*- coding: utf-8 -*-\nimport mydb\nimport sqls\nimport metadata.rule as rule\n\nplay_type = ['pplay', 'play', 'pause', 'resume', 'drag', 'stop', 'qplay', 'gflow', 'load', 'buffer', 'heartbeat']\n\n\ndef check_play_records(records, result):\n\n item = dict()\n item['check_point'] = 'check_play_act_num'\n item['type'] = 'report_number'\n item['result'] = ''\n item['reason'] = {}\n item['data'] = {}\n\n item['result'] = 'failure' if len(records) == 0 else 'success'\n item['reason'] = {'number': 'query no data'} if len(records) == 0 else {}\n result['items'].append(item)\n\n item2 = dict()\n item2['check_point'] = 'check_play_act_miss'\n item2['type'] = 'report_number'\n item2['result'] = ''\n item2['reason'] = {}\n item2['data'] = {}\n result['items'].append(item2)\n\n query_acts = []\n miss_list = []\n if len(records) != 0:\n for record in records:\n query_acts.append(record['act'])\n for act in play_type:\n if act not in query_acts:\n miss_list.append(act)\n\n if len(miss_list) == 0:\n item2['result'] = 'success'\n else:\n item2['result'] = 'failure'\n item2['reason']['miss'] = str(miss_list)\n\n return\n\n\ndef check(records, result):\n check_play_records(records, result)\n i = 0\n for r in records:\n check_play_record(r, result)\n\n\ndef check_play_record(record, result):\n rowid = record['rowid']\n bid = record['bid']\n\n act = record['act']\n item = dict()\n item['check_point'] = act\n item['type'] = 'field_check'\n item['result'] = ''\n item['reason'] = {}\n item['data'] = {}\n result['items'].append(item)\n\n # event_type indicate the the current record whether contains all columns\n sql = sqls.event_sql.format(mydb.tables[bid])\n r = mydb.get_one_data(sql, tuple([rowid]))\n\n tool = rule.CheckTool(act, 'play', 'v')\n tool.check_common(r, item['reason'])\n tool.check_service(r, item['reason'])\n rule.get_data(r, item['data'])\n\n if len(item['reason']) == 0:\n item['result'] = 'success'\n else:\n item['result'] = 'failure'\n\n item2 = dict()\n item2['check_point'] = act + '_report_time'\n item2['type'] = 'report_time'\n item2['result'] = 'success'\n item2['reason'] = {}\n item2['data'] = {}\n result['items'].append(item2)\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"uitest/check/checkdata_play.py","file_name":"checkdata_play.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"160359274","text":"#!/usr/bin/env python3\n\nimport email\nimport os\nimport dmarc\n\ndef save_file(attachment):\n f_name = attachment.get_filename()\n dest = os.path.join('./reports', f_name)\n with open(dest, 'wb') as f:\n f.write(attachment.get_payload(decode=True))\n\nif not os.path.isdir('./reports'):\n os.mkdir('./reports')\n\nfor root, dirs, files in os.walk('./mails/INBOX/'):\n for f in files:\n mail_file = os.path.join(root, f)\n msg = email.message_from_file(open(mail_file))\n if msg.is_multipart():\n attachment = msg.get_payload()[1]\n save_file(attachment)\n else:\n save_file(msg)\n\ni_dmarc = dmarc.dmarc()\ni_dmarc.parse()\ni_dmarc.render()\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398643229","text":"#!/usr/bin/env python2.6\n# -*- coding : utf-8 -*-\n\nimport urllib2\nimport sys,os\nsys.path.append(os.path.dirname(os.path.abspath(__file__))+'/lib')\nimport tornado.escape\n\ndef check(server,t,k,**partitions):\n post=[{\"type\":t,\"key\":k,\"partitions\":partitions}]\n print(\"[client] Post data:{0}\".format(post))\n try:\n request = urllib2.Request(server,tornado.escape.json_encode(post),{\"Content-type\":\"application/json\"})\n response = urllib2.urlopen(request)\n dependention = tornado.escape.json_decode(response.read())\n response.close()\n if dependention[\"status\"] == 0 and dependention[\"data\"][k]:\n exit(0)\n else:\n print(\"[WARN] response:{0}\".format(dependention))\n exit(1)\n except urllib2.HTTPError as e:\n print(\"[EXCEPT] query error with code:{0}\".format(e.code))\n response.close()\n exit(255)\n except urllib2.URLError as e:\n print(\"[EXCEPT] url is not correct with exception:{0}\".format(e.reason))\n exit(255)\n except KeyError as e:\n print(\"[EXCEPT] response:{0} error with exception:{1}\".format(response,e.message))\n response.close()\n exit(255)\n\nif __name__ == \"__main__\":\n # import os,sys\n# if len(sys.argv) < 4: # client.py url type key **partitions\n# print(\"[ERROR] parameters is less than 4\")\n# exit(255)\n# else:\n# partitions = {}\n# for i in range(4,len(sys.argv)):\n# (k,v) = argv[i].split(\"=\")\n# partitions[k] = v\n# check(sys.argv[1],sys.argv[2],sys.argv[3],partitions)\n# else:\n import pdb\n pdb.set_trace()\n check(\"http://10.39.0.99:8000/check\",\"hdfs\",\"/user/zeus\")\n","sub_path":"Server/src/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"17142308","text":"from functools import reduce\nfrom itertools import permutations as prm\nfrom negotiator_base import BaseNegotiator\n\nclass AccommodatingNegotiator(BaseNegotiator):\n def __init__(self):\n self.preferences = []\n self.offer = []\n self.iter_limit = 0\n\n self.is_first = False\n self.iter = 0\n self.max_util = 0.0\n self.offer_index = 0\n self.offer_step_size = 1\n\n #Four thresholds:\n self.offer_thresh = 0.6\n self.accept_thresh = 0.4\n self.last_offer_thresh = 0.3\n self.last_accept_thresh = 0.2\n self.highest_opp_offer = [] #best offer the opponents give that are above last_offer_thresh but below accept_thresh\n self.highest_opp_offer_util = 0.0 #highest utility of best offer from opponent\n self.accepted_midway = False\n\n self.opp_preference = []\n self.opp_max_util = -1.0\n self.opp_offers = []\n\n #For abuse caving\n self.caving_count = 0\n self.caving = False\n\n\n def find_util(self, order):\n tmp = self.offer[:]\n self.offer = order[:]\n i = self.utility()\n self.offer = tmp\n return i\n\n def find_possibilities(self):\n #return sorted([(a,self.find_util(a)) for a in prm(self.preferences)],key=lambda x:x[1])\n L = [self.preferences[:]]\n outlist = []\n while True:\n tmp = L.pop(0)\n tmputil = self.find_util(tmp)\n if tmputil < self.offer_thresh * self.find_util(self.preferences):\n break\n outlist.append((tmp,tmputil))\n\n for i in range(len(tmp)):\n for j in range(len(tmp)):\n if i != j:\n swapt = tmp[:]\n swapt[i], swapt[j] = swapt[j], swapt[i]\n if swapt not in L:\n L.append(swapt)\n\n return sorted(outlist,key=lambda x: x[1])\n\n def initialize(self, preferences, iter_limit):\n self.__init__()\n self.preferences = preferences\n self.iter_limit = iter_limit\n self.iter = 0\n self.sp = self.find_possibilities() \n self.sp = self.sp[::-1]\n self.max_util = self.sp[0][1]\n\n def make_offer(self, offer):\n #check if first in first iteration\n # assume no agent ever gives an offer of None\n if offer == None:\n self.is_first = True\n else:\n self.iter += 1\n #Save opponent offer\n opp_util = self.find_util(offer)\n if opp_util >= self.last_offer_thresh * self.max_util and opp_util > self.highest_opp_offer_util:\n self.highest_opp_offer = offer\n self.highest_opp_offer_util = opp_util\n\n #If opponent caves and you make last offer, only demand \n #if self.caving and not self.is_first:\n # self.offer = self.sp[0][0]\n # return self.offer\n\n #if last offer\n if self.iter == self.iter_limit:\n #Give final offer\n if not self.is_first:\n #If opponent hasn't given reasonable offer, spit back preferences\n if self.highest_opp_offer == []:\n self.offer = self.sp[0][0]\n return self.offer\n #If opponent has given us reasonable offer prior, offer back\n else:\n self.offer = self.highest_opp_offer[:]\n return self.offer\n \n #Final accept\n elif self.find_util(offer) >= self.last_accept_thresh * self.max_util:\n self.offer = offer[:]\n return offer\n #Final decline\n else:\n self.offer = self.sp[0][0]\n return self.offer\n\n # sorted possibilities\n if offer is None or self.find_util(offer) < self.accept_thresh * self.max_util:\n self.offer = self.sp[self.offer_index][0]\n self.offer_index = (self.offer_index + self.offer_step_size) % len(self.sp) \n if self.sp[self.offer_index][1] < self.offer_thresh * self.max_util:\n self.offer_index = 0\n return self.offer\n\n self.offer = offer\n self.accepted_midway = True\n return self.offer\n\n def receive_utility(self, utility):\n if utility > self.opp_max_util:\n self.opp_max_util = utility\n self.opp_offering_pref = True\n\n # receive_results(self : BaseNegotiator, results : (Boolean, Float, Float, Int))\n # Store the results of the last series of negotiation (points won, success, etc.)\n def receive_results(self, results):\n self.iter = 0\n self.offer_index = 0\n self.opp_offers = []\n self.accepted_midway = False\n \n #If negotiation SUCCEEDED\n if results[0]:\n #If I went FIRST\n if self.is_first:\n my_score = results[1]\n opp_score = results[2]\n\n #If I LOST\n if my_score < opp_score:\n #If negotiation dragged to last round = accepted last offer\n if results[3] == self.iter_limit:\n if my_score < 0.8 * opp_score:\n self.last_accept_thresh = float(my_score) / float(self.max_util) + 0.05\n else:\n self.last_accept_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and we accepted\n elif self.accepted_midway:\n if my_score < 0.8 * opp_score:\n self.accept_thresh = float(my_score) / float(self.max_util) + 0.05\n else:\n self.accept_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and opponent accepted\n else:\n if my_score < 0.8 * opp_score:\n self.offer_thresh = float(my_score) / float(self.max_util) + 0.05\n else:\n self.offer_thresh = float(my_score) / float(self.max_util)\n #If I WON or DREW\n elif my_score >= opp_score:\n #If negotiation dragged to last round = accepted last offer\n if results[3] == self.iter_limit:\n self.last_accept_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and we accepted\n elif self.accepted_midway:\n self.accept_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and opponent accepted\n else:\n self.offer_thresh = float(my_score) / float(self.max_util)\n #If I went SECOND\n else:\n my_score = results[2]\n opp_score = results[1]\n\n #If I LOST\n if my_score < opp_score:\n #If negotiation dragged to last round = made the last offer\n if results[3] == self.iter_limit:\n #self.caving_count = 0\n #self.caving = False\n if my_score < 0.8 * opp_score:\n self.last_offer_thresh = float(my_score) / float(self.max_util) + 0.05\n else:\n self.last_offer_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and we accepted\n elif self.accepted_midway:\n if my_score < 0.8 * opp_score:\n self.accept_thresh = float(my_score) / float(self.max_util) + 0.05\n else:\n self.accept_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and opponent accepted\n else:\n if my_score < 0.8 * opp_score:\n self.offer_thresh = float(my_score) / float(self.max_util) + 0.05\n else:\n self.offer_thresh = float(my_score) / float(self.max_util)\n #If I WON or DREW\n elif my_score >= opp_score:\n #If negotiation dragged to last round = opponent accepted last offer\n if results[3] == self.iter_limit:\n #self.caving_count += 1\n #if self.caving_count > 1:\n # self.caving = True\n self.last_offer_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and we accepted\n elif self.accepted_midway:\n self.accept_thresh = float(my_score) / float(self.max_util)\n #If negotiation aggreed midway and opponent accepted\n else:\n self.offer_thresh = float(my_score) / float(self.max_util)\n \n #If negotiation FAILED\n else:\n #self.caving = False\n #self.caving_count = 0\n #self.offer_step_size += 1\n if self.last_accept_thresh > 0.0:\n self.last_accept_thresh -= 0.05\n","sub_path":"accommodating_negotiator.py","file_name":"accommodating_negotiator.py","file_ext":"py","file_size_in_byte":9434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"404491918","text":"\"\"\"\nPer session GetMute() SetMute() GetMasterVolume() SetMasterVolume() using\nSimpleAudioVolume.\nhttps://github.com/AndreMiras/pycaw/blob/develop/examples/audio_controller_class_example.py\n\"\"\"\n\nfrom __future__ import print_function\n\nimport keyboard\nfrom pycaw.pycaw import AudioUtilities\n\nstate = 0\n\n\nclass AudioController(object):\n def __init__(self, process_name):\n self.process_name = process_name\n self.volume = self.process_volume()\n\n def mute(self):\n sessions = AudioUtilities.GetAllSessions()\n for session in sessions:\n interface = session.SimpleAudioVolume\n if session.Process and session.Process.name() == self.process_name:\n interface.SetMute(1, None)\n print(self.process_name, 'has been muted.') # debug\n\n def unmute(self):\n sessions = AudioUtilities.GetAllSessions()\n for session in sessions:\n interface = session.SimpleAudioVolume\n if session.Process and session.Process.name() == self.process_name:\n interface.SetMute(0, None)\n print(self.process_name, 'has been unmuted.') # debug\n\n def process_volume(self):\n sessions = AudioUtilities.GetAllSessions()\n for session in sessions:\n interface = session.SimpleAudioVolume\n if session.Process and session.Process.name() == self.process_name:\n print('Volume:', interface.GetMasterVolume()) # debug\n return interface.GetMasterVolume()\n\n\ndef main():\n audio_controller = AudioController('chrome.exe')\n audio_controller.mute()\n audio_controller.unmute()\n\n\ndef run():\n global state\n if state == 0:\n audio_controller.mute()\n keyboard.send(\"play/pause media\")\n state = 1\n else:\n keyboard.send(\"play/pause media\")\n audio_controller.unmute()\n state = 0\n\n\nif __name__ == \"__main__\":\n audio_controller = AudioController('chrome.exe')\n keyboard.add_hotkey('alt+q', run)\n\n recorded = keyboard.record(until='shift+alt+f1')\n","sub_path":"python小工具/从游戏到网课/HearClass(keyboard监听不可用).py","file_name":"HearClass(keyboard监听不可用).py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472699923","text":"\nimport os\nimport sys\nfrom unittest import TestLoader, TestSuite, TextTestRunner\n\n# The service only works on python >= 2.5\nif sys.version_info >= (2, 5):\n test_service = True\nelse:\n test_service = False\n\n# Try to import the dependencies to make sure they exist\ntry:\n import Pegasus\n import sqlalchemy\n if sys.version_info >= (2, 5):\n import sqlite3\n import boto\n import requests\n import flask\n import Pegasus.service\n else:\n import pysqlite2\nexcept ImportError as e:\n print(e)\n print(\"Unable to import Pegasus modules\")\n print(\"Make sure dependencies are available\")\n print(\"Set PYTHONPATH or run: python setup.py develop\")\n sys.exit(1)\n\n\ndef discoverTestModules(dirpath):\n modules = []\n for name in os.listdir(dirpath):\n path = os.path.join(dirpath, name)\n if os.path.isdir(path):\n modules += discoverTestModules(path)\n elif name.endswith(\".py\") and name.startswith(\"test_\"):\n modules.append(path.replace(\".py\", \"\").replace(\"/\", \".\"))\n return modules\n\n\nloader = TestLoader()\nalltests = TestSuite()\n\nfor module in discoverTestModules(\"Pegasus/test\"):\n # If not testing service, skip service test modules\n if not test_service and module.startswith(\"Pegasus.test.service\"):\n continue\n\n # First, try importing the module to make sure it works\n __import__(module)\n\n # Now load the tests from the module\n suite = loader.loadTestsFromName(module)\n alltests.addTest(suite)\n\nrunner = TextTestRunner(verbosity=2)\nresult = runner.run(alltests)\n\nif result.wasSuccessful():\n sys.exit(0)\nelse:\n sys.exit(1)\n","sub_path":"lib/pegasus/python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264862198","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom dateutil import relativedelta\nfrom odoo import http, models, fields, api, _\nfrom cStringIO import StringIO\nimport base64\nfrom decimal import *\nimport time\nfrom . import VATReport_wizard\nimport string\nimport re\nimport unicodedata\n\ndef remove_accents(input_str):\n nfkd_form = unicodedata.normalize('NFKD', input_str)\n printable = set(string.printable)\n res = u\"\".join([c for c in nfkd_form if not unicodedata.combining(c)])[:30]\n return filter(lambda x: x in printable, res)\n\nclass inventory_excel_extended(models.TransientModel):\n _name= \"sicore.extended\"\n excel_file = fields.Binary('Download TXT')\n file_name = fields.Char('TXT File', size=64)\n excel_file2 = fields.Binary('Download TXT')\n file_name2 = fields.Char('TXT File', size=64)\n\nclass sire_report(models.TransientModel):\n _name = 'vitt_sales_reports.reportsicore'\n\n wh_code = fields.Many2many('account.tax', 'pre_prop_rel', 'sicore_tax_code_id', 'wh_code_id',\n string='Cod Retencion',\n ondelete='cascade',\n domain=\"[('sicore_tax_code', '!=', False)]\")\n date_from = fields.Date(string='Date From', required=True,\n default=datetime.now().strftime('%Y-%m-01'))\n date_to = fields.Date(string='Date To', required=True,\n default=str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10])\n\n def _get_paym_amount(self,paym):\n matched_amount = 0.0\n for line in paym.payment_group_id.matched_move_line_ids:\n if paym.vendorbill.id == line.invoice_id.id:\n payment_group_id = self._context.get('payment_group_id')\n if not payment_group_id:\n payments = paym.payment_group_id.payment_ids\n payment_move_lines = payments.mapped('move_line_ids')\n payment_partial_lines = self.env['account.partial.reconcile'].search(\n ['|',('credit_move_id', 'in', payment_move_lines.ids),('debit_move_id', 'in', payment_move_lines.ids),\n ])\n for rec in line:\n for pl in (rec.matched_debit_ids + rec.matched_credit_ids):\n if pl in payment_partial_lines:\n matched_amount += pl.amount\n return matched_amount\n\n def sicore_to_txt(self):\n context = self._context\n filename= 'SICORE_SUJETOS.txt'\n filename2= 'SICORE_RETENCIONES.txt'\n\n #data\n whcode = list(self.wh_code._ids)\n domain = [\n ('payment_date', '>=', self.date_from), ('payment_date', '<=', self.date_to), ('state', 'not in', ['draft','cancel'])\n ]\n\n invoiceModel = self.env['account.payment']\n payments = invoiceModel.search(domain,order=\"payment_date\")\n\n tstr = ''\n tstr2 = ''\n for pay in payments:\n if pay.tax_withholding_id:\n if (pay.tax_withholding_id.id in whcode) or (whcode == []):\n tstr += \"{:<11}\".format(pay.partner_id.main_id_number)\n\n\n if pay.partner_id.name:\n tmpstr = remove_accents(pay.partner_id.name[0:20])\n else:\n tmpstr = \"\"\n\n tstr += \"{:<20}\".format(tmpstr)\n street = \"\"\n if pay.partner_id.street:\n street = pay.partner_id.street\n if pay.partner_id.street2:\n street += pay.partner_id.street2\n\n if street:\n tmpstr = remove_accents(street[0:20])\n else:\n tmpstr = \"\"\n\n tstr += \"{:<20}\".format(tmpstr)\n tmp = pay.partner_id.city\n\n if tmp:\n tmpstr = remove_accents(tmp[0:20])\n else:\n tmpstr = \"\"\n\n tstr += \"{:<20}\".format(tmpstr)\n tstr += \"{:0>2}\".format(pay.partner_id.state_id.afip_code)\n tstr += \"{:<8}\".format(pay.partner_id.zip)\n tstr += \"{:0>2}\".format(pay.partner_id.main_id_category_id.afip_code)\n\n tstr += '\\r\\n'\n\n for pay in payments:\n if pay.tax_withholding_id:\n if ((pay.tax_withholding_id.id in whcode) or (whcode == [])) and (pay.partner_id.supplier == True) and \\\n (pay.payment_group_id.retencion_ganancias != 'no_aplica'):\n tstr2 += \"{:0<2}\".format('06')\n tstr2 += pay.payment_date[8:10] + '/' + pay.payment_date[5:7] + '/' + pay.payment_date[0:4]\n tstr2 += \"{:<16}\".format(pay.display_name)\n tstr2 += \"{:0>16.2f}\".format(float(self._get_paym_amount(pay)))\n tstr2 += \"{:0>3}\".format(pay.sicore_tax_code)\n tstr2 += \"{:0>3}\".format(pay.regcode)\n whtype = pay.payment_group_id.retencion_ganancias\n if whtype == 'nro_regimen':\n tstr2 += \"{:0>1}\".format('1')\n elif whtype == 'imposibilidad_retencion':\n tstr2 += \"{:0>1}\".format('4')\n else:\n tstr2 += \"{:0>1}\".format('?')\n\n if pay.withholdable_invoiced_amount2 > 0:\n tstr2 += \"{:0>14.2f}\".format(pay.withholdable_invoiced_amount2)\n else:\n tstr2 += \"{:0>14.2f}\".format(pay.withholdable_invoiced_amount)\n tstr2 += pay.payment_date[8:10] + '/' + pay.payment_date[5:7] + '/' + pay.payment_date[0:4]\n tstr2 += \"{:0>2}\".format(pay.partner_id.afip_responsability_type_id.code)\n tstr2 += \"{:0>1}\".format('0')\n tstr2 += \"{:0>14.2f}\".format(pay.amount)\n tstr2 += \"{:0>6}\".format('0')\n tstr2 += pay.payment_date[8:10] + '/' + pay.payment_date[5:7] + '/' + pay.payment_date[0:4]\n if pay.partner_id.main_id_category_id.afip_code in [80, 86, 83, 87, 84]:\n tstr2 += \"{:0>2}\".format(pay.partner_id.main_id_category_id.afip_code)\n else:\n tstr2 += \"{:0>2}\".format('??')\n tmpstr = pay.partner_id.main_id_number\n tstr2 += \"{:0>20}\".format(tmpstr.replace('-', '0'))\n tmpstr = re.sub(\"\\D\", \"\", pay.withholding_number)\n if not pay.withholding_number:\n tmpstr = '??????????????'\n tstr2 += \"{:0>14}\".format(tmpstr.replace('-', '0'))\n if pay.partner_id.main_id_category_id.afip_code in [83, 84] and pay.partner_id.state_id.afip_code == '99':\n\n tmpstr = remove_accents(pay.partner_id.name[0:30])\n\n tstr2 += \"{:>30}\".format(tmpstr)\n tstr2 += \"{:0>1}\".format('0')\n tstr2 += \"{:0>11}\".format(pay.partner_id.Country.cuit_juridica[0:11])\n tstr2 += \"{:0>11}\".format(pay.partner_id.main_id_number[0:11])\n else:\n tstr2 += \"{:>30}\".format(' ')\n tstr2 += \"{:0>1}\".format('0')\n tstr2 += \"{:0>11}\".format('0')\n tstr2 += \"{:0>11}\".format('0')\n tstr2 += '\\r\\n'\n\n fp = StringIO()\n fp2 = StringIO()\n fp.write(tstr)\n fp2.write(tstr2)\n export_id = self.env['sicore.extended'].create({'excel_file': base64.encodestring(fp.getvalue()), 'file_name': filename,\n 'excel_file2': base64.encodestring(fp2.getvalue()),'file_name2': filename2}).id\n fp.close()\n fp2.close()\n return{\n 'view_mode': 'form',\n 'res_id': export_id,\n 'res_model': 'sicore.extended',\n 'view_type': 'form',\n 'type': 'ir.actions.act_window',\n 'context': context,\n 'target': 'new',\n }\n\n","sub_path":"odoo-argentina-vitt/vitt_sales_reports/wizard/SicoreReportWizard.py","file_name":"SicoreReportWizard.py","file_ext":"py","file_size_in_byte":8271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36678689","text":"\"\"\"This module is to make updated classes of certain Tkinter classes that do certain functions on their own,\nsuch as set the default font and pack at the end of the parent __init__ function.\"\"\"\n\nimport tkinter\n\nfrom Countdown import create_logger\n\nlogger = create_logger('SK')\n\n\nclass LoggingGrid(tkinter.Grid):\n \"\"\"A Grid system that logs all of it's arguments.\"\"\"\n\n def grid(self, cnf=None, **kw):\n \"\"\"The grid function. Logs the creation of a gris to DEBUG.\"\"\"\n s = ''\n if cnf is None:\n cnf = {}\n for a, b in kw.items():\n s += '%s = %s,' % (a, b)\n logger.debug('Grid ran with arguments %s' % s)\n super().grid_configure(cnf, **kw)\n\n\nclass SmartLabel(tkinter.Label, LoggingGrid):\n \"\"\"A Smart Tkinter Label. Automatically packs the label and sets the font to the given font, which also defaults\n to font size 24.\"\"\"\n\n def __init__(self, master=None, FONT='Courier New', font_size: int = 20, **kw) -> None:\n \"\"\"Initializes the class\"\"\"\n self.kw = kw\n logger.debug(kw)\n super().__init__(master, font=(FONT, font_size), **kw)\n if kw.get('text') is not None:\n logger.debug('Label with text %s was created', kw.get('text'))\n else:\n logger.debug('Label was created')\n\n\nclass SmartButton(tkinter.Button, LoggingGrid):\n \"\"\"A Smart Button. Automatically sets the button text font and packs it. The default font size is 16. The setup\n for it is essentially identical to the setup of the SmartLabel. \"\"\"\n\n def __init__(self, master=None, FONT='Courier New', font_size: int = 12, **kw) -> None:\n \"\"\"Initializes the class\"\"\"\n self.kw = kw\n if kw.get('command') is None:\n raise ValueError('No command for SmartButton. Keyword is command.')\n super().__init__(master, font=(FONT, font_size), **kw)\n if kw.get('text') is not None:\n logger.debug('Button with text %s and command with name %s was created', kw.get('text'),\n kw.get('command').__name__)\n else:\n logger.debug('Button with command with name %s was created was created', kw.get('command').__name__)\n\n\nclass SmartEntry(tkinter.Entry, LoggingGrid):\n \"\"\"A Smart Entry. Automatically sets font.\"\"\"\n\n def __init__(self, master=None, FONT='Courier New', font_size: int = 12, **kw) -> None:\n \"\"\"Initializes the class\"\"\"\n self.kw = kw\n super().__init__(master, font=(FONT, font_size), **kw)\n logger.debug('A field was created.')\n\n def grid(self, **kwargs):\n super().grid(padx=2, **kwargs)","sub_path":"Countdown/SmartKinter.py","file_name":"SmartKinter.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"648551285","text":"import datetime\nimport math\nimport numpy as np\n\n#base_date = datetime.datetime(2019, 3, 8)\nprint(\"基準日を入力してください\")\nyear = int(input('Enter a year'))\nmonth = int(input('Enter a month'))\nday = int(input('Enter a day'))\nbase_date = datetime.datetime(year, month, day)\nprint(base_date)\n\n\n#maturity_date = datetime.datetime(2028, 11, 8)\nprint(\"満期日を入力してください\")\nyear = int(input('Enter a year'))\nmonth = int(input('Enter a month'))\nday = int(input('Enter a day'))\nmaturity_date = datetime.datetime(year, month, day)\nprint(maturity_date)\n\n\nprint(\"クーポンを入力してください\")\ncoupon = float(input())\n#coupon = 0.454\n\nprint(\"利払い回数を入力してください\")\nfreq = int(input())\n#freq = 2 # 利払い回数\n\nzanzon = (maturity_date - base_date).days / 365\n\n# 残存年数から利払い頻度に応じた期間を引いていく\ncashflow = []\ni = 0\nwhile zanzon - (1 / freq) * i > 0:\n cashflow.append(\n (zanzon - (1 / freq) * i, coupon / freq + (100 if i == 0 else 0))\n )\n i += 1\n# 文法メモ\"100 if i == 0 else 0\"→iが0ならば100 iが0でなければ0\n\n\n# バケットの中心時点を設定\nbuckets_timing = [0.0028, 0.0417, 0.1667, 0.375, 0.625, 0.875, 1.25, 1.75, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 12.5, 17.5, 25]\n\n# バケットへの割当金額を初期化\nbuckets_amount = [0 for t in buckets_timing]\n\nfor t, a in cashflow:\n # CFの発生時期を元に前後のバケット時点を取得する\n prev_timing = max([b for b in buckets_timing if b < t])\n next_timing = min([b for b in buckets_timing if b > t])\n\n # tとの距離に比例して配分率を決める(近いほど配分率が大きい)\n prev_bucket_ratio = 1 - (t - prev_timing) / (next_timing - prev_timing)\n next_bucket_ratio = 1 - (next_timing - t) / (next_timing - prev_timing)\n\n prev_bucket_cf = a * prev_bucket_ratio\n next_bucket_cf = a * next_bucket_ratio\n\n # 前後のバケットに割当CF金額を加算する\n buckets_amount[buckets_timing.index(prev_timing)] += prev_bucket_cf\n buckets_amount[buckets_timing.index(next_timing)] += next_bucket_cf\n\n\n# イールドカーブ上の金利を求める関数を作成\n# べき乗分母\nx = 4.0\n\n# パラレルシフトシナリオ\ndef change_parallel(parallel):\n return parallel\n\n# スティープ化シナリオ\ndef change_steepner(t, rshort, rlong):\n return -0.65 * (rshort * math.e ** (-t / x)) + 0.9 * (rlong * (1 - math.e ** (-t / x)))\n\n# フラット化シナリオ\ndef change_flattener(t, rshort, rlong):\n return 0.8 * (rshort * math.e ** (-t / x)) - 0.6 * (rlong * (1 - math.e ** (-t / x)))\n\n# 短期金利変化シナリオ\ndef change_short(t, rshort):\n return rshort * math.e ** (-t / x)\n\n\nbase_rate = -0.00035\n\n# 長短金利とパラレル変動幅\nparallel = 0.01\nrshort = 0.01\nrlong = 0.01\n\n# 変化量を取得する\nsenario = [\n [(t, 0) for t in buckets_timing], # 変化なし\n [(t, change_parallel(parallel)) for t in buckets_timing], # 上方パラレルシフト\n [(t, change_parallel(parallel * -1)) for t in buckets_timing], # 下方パラレルシフト\n [(t, change_steepner(t, rshort, rlong)) for t in buckets_timing], # スティープ化\n [(t, change_flattener(t, rshort, rlong)) for t in buckets_timing], # フラット化\n [(t, change_short(t, rshort)) for t in buckets_timing], # 短期金利上昇\n [(t, change_short(t, rshort * -1)) for t in buckets_timing] #短期金利低下\n]\n\ndiscount_factors = [[ 1 / ((1 + r / freq) ** (t * freq)) for t, r in change ] for change in senario]\n\npvs = [ sum(buckets_amount * np.array(df)) for df in discount_factors ]\n\nfor i, pv in enumerate(pvs):\n print(i, pv - pvs[0])","sub_path":"IRRBB/irrbb(success).py","file_name":"irrbb(success).py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"307203414","text":"\"\"\"\nA module that preprocesses readmissions data to be ready for xgboost training.\n\"\"\"\n\nimport json\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\n#import modin.pandas as pd\nimport torch\nimport torchtext\nfrom collections import OrderedDict\n\n\ndef get_frequent_features(vocab, num_features, codes_only=True, exclusion_list=[]): \n \"\"\"\n Get the most frequent codes/features.\n Args:\n vocab(Object): Vocab object\n num_features(int): # of features\n codes_only(bool): Wether to use ICD codes as features\n exclution_list(list): List of events/keys to excluded from features\n Returns:\n List of most frequent features\n \"\"\"\n num_exc = len(exclusion_list) + 100\n features = vocab.freqs.most_common(num_features + num_exc)\n if codes_only:\n features = [word[0] for word in features if word[0] not in exclusion_list and ('_' in word[0])]\n else:\n features = [word[0] for word in features if word[0] not in exclusion_list]\n features = [word for word in features if 'day' not in word] #Exclude day features\n features = features[:num_features]\n return features\n\n\ndef get_one_hot_frequent_features(row, frequent_features):\n \"\"\"Gets one-hot encoding of the most frequent features of a given patient data\n Args:\n row(pd.Series): row to specify patient's specific adverse event\n Returns:\n Returns 0 if max value is 0 otherwise 1\n \"\"\"\n features = set(row.tolist())\n one_hot = [int(ft in features) for ft in frequent_features] \n return one_hot\n\n\ndef read_labels(labels_path):\n \"\"\"Read list of labels from path.\n Args:\n labels_path(str): Classes path\n Returns:\n List of classes\n \"\"\"\n with open(labels_path, 'r') as fp:\n labels = fp.readlines()\n labels = [label.strip() for label in labels]\n return labels\n\n\ndef get_class_imbalance(df_y):\n \"\"\"Get class imbalance for all the target variables.\n Args:\n df_y(DataFrame): Dataframe of class imbalances\n Returns:\n Dictionary of class imbalances\n \"\"\"\n imbalance = df_y.apply(lambda x: x.value_counts()).transpose().values.tolist()\n imbalance = dict(zip(df_y.columns.tolist(), imbalance))\n return imbalance\n\n\ndef preprocess(df, features, label, fold, split, output_dir, class_imbalance_fname=None):\n \"\"\"Transform the predictor data to one-hot encoding and aggregate with target data.\n Args:\n df(DataFrame): Data to be preprocessed\n features(list): List of features\n label(str): Class/label name\n split(str): Dataset split\n output_dir(str): Output directory\n class_imbalance_fname(str): Class imbalance filename\n Returns:\n Preprocessed data in dataframe\n \"\"\"\n print('Preprocessing and saving fold={} and split={} data...'.format(fold, split))\n df = df[df[label].notna()]\n \n df_x = df.iloc[:, :1000]\n df_y = df[[label]]\n df_y = df_y.astype(int)\n \n df_x = df_x.apply(get_one_hot_frequent_features, axis=1, args=(features,))\n df_x = pd.DataFrame(df_x.tolist(), columns=features)\n df = pd.concat([df_x, df_y], axis=1)\n\n my_output_dir = os.path.join(output_dir, fold)\n if not os.path.exists(my_output_dir):\n os.makedirs(my_output_dir)\n \n if split=='train':\n imb = get_class_imbalance(df_y)\n class_imbalance_path = os.path.join(my_output_dir, class_imbalance_fname)\n with open(class_imbalance_path, 'w') as fp:\n json.dump(imb, fp)\n \n output_path = os.path.join(my_output_dir, split+'.csv')\n df.to_csv(output_path, index=False)\n print('{} data successfully preprocessed!'.format(split))\n return df\n\n\ndef prepare(df, num_features_list, label, output_dir, fold, split='train'):\n \"\"\"Prepares data for model training.\n Args:\n df(DataFrame): Data to be ready for training\n num_features_list(list): List of number of features\n label(str): Class/label name\n output_dir(str): Output directory\n fold: Data fold number\n split(str): Dataset split\n Returns:\n None\n \"\"\"\n num_targets = 1\n features = df.columns.tolist()[:-num_targets]\n for num_features in num_features_list:\n print('Preparing data with {} features...'.format(num_features))\n columns = [label] + features[:num_features]\n my_output_dir = os.path.join(output_dir, fold, str(num_features))\n \n if not os.path.exists(my_output_dir):\n os.makedirs(my_output_dir)\n \n output_path = os.path.join(my_output_dir, split+'.csv')\n df[columns].to_csv(output_path, index=False, header=None)\n print('Successfully prepared data for training!')\n\n\ndef get_all_data_from_folds(data_root_dir, folds, data_all):\n \"\"\"\n Integrate all the data from folds to be used for final training.\n Args:\n data_root_dir(str): Root data dir\n folds(list): List of data folds\n data_all(str): Name of all data folder\n Returns:\n All data in dataframe format\n \"\"\"\n output_dir = os.path.join(data_root_dir, data_all)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n \n df_all = None\n for fold in folds:\n data_path = os.path.join(data_root_dir, fold, 'test', 'raw_test_data_1000_30days_anony.csv')\n df = pd.read_csv(data_path)\n if df_all is None:\n df_all = df.copy(deep=True)\n else:\n df_all = pd.concat([df_all, df], ignore_index=True, axis=0)\n output_path = os.path.join(output_dir, 'train.csv')\n df_all.to_csv(output_path, index=False)\n return df_all\n\n\ndef combine_all_vocabs(data_dir, folds, data_all= 'all', vocab_fname='vocab_1000_vall_30days'):\n \"\"\"\n Combine all vocabularies and save to disk.\n Args:\n data_dir(str): Data directory\n folds(list): List of dataset folds\n data_all(str): All data folder\n vocab_fname(str): Vocab filename\n Returns:\n Combined vocab output file path\n \"\"\"\n def combine_vocabs(vocab1, vocab2):\n \"\"\"Combine two vocabularies.\"\"\"\n freqs = vocab1.freqs + vocab2.freqs\n vocab = torchtext.vocab.Vocab(freqs)\n return vocab\n\n output_dir = os.path.join(data_dir, data_all, 'vocab')\n output_path = os.path.join(output_dir, vocab_fname)\n if os.path.exists(output_path):\n print('Aggregated Vocab already saved to {}!'.format(output_path))\n return output_path\n\n print('Aggregating vocabularies...')\n vocab_all = None \n for fold in folds:\n vocab_path = os.path.join(data_dir, fold, 'vocab', vocab_fname)\n if vocab_all is None:\n vocab_all = torch.load(vocab_path)\n else:\n vocab = torch.load(vocab_path)\n vocab_all = combine_vocabs(vocab_all, vocab)\n \n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n \n torch.save(vocab_all, output_path)\n print('[SUCCESS] Aggregated Vocab saved to {}!'.format(output_path))\n \n return output_path\n\n\nif __name__ == \"__main__\":\n ROOT_DIR = '/home/ec2-user/SageMaker/CMSAI/modeling/tes/data/final-global/re/1000/'\n RAW_DATA_DIR = os.path.join(ROOT_DIR, 'raw')\n \n SPLITS_FNAMES = OrderedDict({'train': ['train', 'raw_train_data_1000_30days_anony.csv'],\n 'val': ['test', 'raw_test_data_1000_30days_anony.csv']\n })\n VOCAB_FNAME = 'vocab_1000_vall_30days'\n LABEL = 'unplanned_readmission'\n CLASS_IMBALANCE_FNAME = 'class_imbalances.json'\n\n PREPROCESSED_DATA_DIR = os.path.join(ROOT_DIR, 'preprocessed')\n TRAIN_DATA_DIR = os.path.join(ROOT_DIR, 'training', 'data')\n S3_PREPROCESSED_OUTPUT_DIR = 's3://cmsai-mrk-amzn/FinalData/RE/Models/XGBoost/1000/preprocessed/'\n S3_TRAIN_OUTPUT_DIR = 's3://cmsai-mrk-amzn/FinalData/RE/Models/XGBoost/1000/training/data/'\n \n FOLDS = ['fold_'+str(i) for i in range(5)]\n DATA_ALL = 'all'\n NUM_FREQUENT_FEATURES = 300\n NUM_FEATURES_LIST = [100, 200]\n MEDICAL_CODES_ONLY = True\n\n EXCLUSION_LIST = ['nan', 'pad', 'unk'] + [LABEL]\n \n #[START] Integrate all cross-val data and process it.\n print('Aggregating, processing and preparing all data from folds...')\n vocab_path = combine_all_vocabs(RAW_DATA_DIR, FOLDS, DATA_ALL, VOCAB_FNAME)\n vocab = torch.load(vocab_path)\n \n features = get_frequent_features(vocab, \n NUM_FREQUENT_FEATURES, \n MEDICAL_CODES_ONLY, \n EXCLUSION_LIST) \n df = get_all_data_from_folds(RAW_DATA_DIR, FOLDS, DATA_ALL)\n df = preprocess(df, features, LABEL, DATA_ALL, 'train', PREPROCESSED_DATA_DIR, CLASS_IMBALANCE_FNAME)\n \n prepare(df, NUM_FEATURES_LIST, LABEL, TRAIN_DATA_DIR, DATA_ALL, 'train')\n\n for fold in FOLDS:\n print('Processing and preparing data for {}...'.format(fold))\n vocab_path = os.path.join(RAW_DATA_DIR, fold, 'vocab', VOCAB_FNAME)\n vocab = torch.load(vocab_path)\n \n features = get_frequent_features(vocab, \n NUM_FREQUENT_FEATURES, \n MEDICAL_CODES_ONLY, \n EXCLUSION_LIST) \n\n for split, fnames in SPLITS_FNAMES.items():\n data_path = os.path.join(RAW_DATA_DIR, fold, fnames[0], fnames[1])\n df = pd.read_csv(data_path)\n\n df = preprocess(df, features, LABEL, fold, split, PREPROCESSED_DATA_DIR, CLASS_IMBALANCE_FNAME)\n prepare(df, NUM_FEATURES_LIST, LABEL, TRAIN_DATA_DIR, fold, split)\n del df\n\n print('Copying preprocessed data to {}...'.format(S3_PREPROCESSED_OUTPUT_DIR))\n command = 'aws s3 cp --recursive --quiet {} {}'.format(PREPROCESSED_DATA_DIR, S3_PREPROCESSED_OUTPUT_DIR)\n os.system(command)\n print('[SUCCESS] All preprocessed data is copied {}!'.format(S3_PREPROCESSED_OUTPUT_DIR))\n \n print('Copying training data to {}...'.format(S3_TRAIN_OUTPUT_DIR))\n command = 'aws s3 cp --recursive --quiet {} {}'.format(TRAIN_DATA_DIR, S3_TRAIN_OUTPUT_DIR)\n os.system(command) \n print('[SUCCESS] All data ready for model training is copied {}!'.format(S3_TRAIN_OUTPUT_DIR))\n","sub_path":"model/readmission/xgboost/xgboost_re_preprocess.py","file_name":"xgboost_re_preprocess.py","file_ext":"py","file_size_in_byte":10284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128920224","text":"##########################################################################\n# MediPy - Copyright (C) Universite de Strasbourg, 2011-2012\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\nimport datetime\n\nimport wx\n\nimport medipy.base\n\nclass Date(wx.PyPanel, medipy.base.Observable) :\n \"\"\" Control to enter a date.\n \"\"\"\n \n def __init__(self, parent, value=None, *args, **kwargs):\n self._value = None\n \n wx.PyPanel.__init__(self, parent, *args, **kwargs)\n medipy.base.Observable.__init__(self, [\"value\"])\n \n self._date = wx.DatePickerCtrl(self, style=wx.DP_DEFAULT|wx.DP_ALLOWNONE)\n \n sizer = wx.BoxSizer(wx.HORIZONTAL)\n sizer.Add(self._date, 1, wx.EXPAND)\n \n self._date.Bind(wx.EVT_DATE_CHANGED, self.OnDate)\n \n self.value = value or datetime.datetime.now()\n \n def validate(self):\n return self._date.GetValue().IsValid()\n \n ##############\n # Properties #\n ##############\n \n def _get_value(self):\n \"\"\" Date stored in the control\n \"\"\"\n \n return self._value\n \n def _set_value(self, value):\n self._value = value\n \n time_tuple = value.timetuple()\n \n wx_date = wx.DateTimeFromDMY(\n time_tuple[2], time_tuple[1]-1, time_tuple[0])\n \n self._date.SetValue(wx_date)\n \n self.notify_observers(\"value\")\n \n value = property(_get_value, _set_value)\n \n ##################\n # Event handlers #\n ##################\n \n def OnDate(self, event) :\n wx_date = event.GetDate()\n \n if wx_date.IsValid() :\n ymd = map(int, wx_date.FormatISODate().split('-'))\n value = datetime.date(*ymd)\n else :\n value = None\n \n self.value = value\n","sub_path":"lib/medipy/gui/control/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"615122527","text":"# max mix简单玩法\n# l = [1, 2, 3]\n# print(max(l))\n# print(min(l))\n# 3\n# 1\n# max mix高端玩法\n# 先比较第一个值第一个比较出来后直接出结果无须在比较,max会for循环遍历每个元素在比较\npeople = [\n {'name': 'fg', 'age': 1000},\n {'name': 'hh', 'age': 1000}\n]\nprint(max(people, key=lambda item: item['age']))\n# max(people)会对people进行for循环然后将值传给item,lambda将age值取出来进行比较\n","sub_path":"python/chapter-V-5/ch5-V-07.py","file_name":"ch5-V-07.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390390344","text":"from abc import ABC, abstractmethod\nfrom typing import Type, Optional\n\nfrom bson import ObjectId\nfrom motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorClientSession\nfrom pydantic import BaseModel\n\nfrom core.config import database_name\nfrom db.exceptions import DatabaseResultException\n\n\nclass AbstractCRUD(ABC):\n \"\"\"Describes abstract CRUD class for database interaction\"\"\"\n\n _collection_name: str\n _model: Type[BaseModel]\n\n def __init__(self, client: AsyncIOMotorClient):\n self._db = client[database_name]\n\n async def get(self, *args, **kwargs):\n \"\"\"\n Retrieve document from the DB by parameters passed as key arguments\n :return: BaseModel subclass instance filled with document data\n \"\"\"\n data = await self._db[self._collection_name].find_one(kwargs)\n\n if data is None:\n raise DatabaseResultException(f'There are no {self._collection_name} by \"{kwargs}\"')\n\n return self._model(**data)\n\n async def get_many(self, *args, **kwargs) -> list:\n \"\"\"\n Retrieve many documents from the DB by parameters passed as key arguments\n :return: list of BaseModel subclass instance filled with document data\n \"\"\"\n cursor = self._db[self._collection_name].find(kwargs)\n result = [self._model(**document) for document in await cursor.to_list(length=None)]\n\n return result\n\n @abstractmethod\n async def create(self, document_data: dict, session: Optional[AsyncIOMotorClientSession] = None) -> BaseModel:\n \"\"\"\n Insert a document to the DB\n :param document_data: BaseModel subclass instance filled with document data\n :param session: AsyncIOMotorClientSession instance to make a transaction\n :return: BaseModel subclass instance filled with document data\n \"\"\"\n pass\n\n async def delete(self, document_id: ObjectId, session: Optional[AsyncIOMotorClientSession] = None) -> None:\n \"\"\"\n Delete document from the DB by _id\n :param document_id: ObjectId instance\n :param session: AsyncIOMotorClientSession instance to make a transaction\n \"\"\"\n result = await self._db[self._collection_name].delete_one({'_id': document_id}, session=session)\n if result.deleted_count == 0:\n raise DatabaseResultException(f'There are no {self._collection_name} with {document_id}')\n","sub_path":"app/crud/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"336868163","text":"from Module import AbstractModule\n\nclass Module(AbstractModule):\n def __init__(self):\n AbstractModule.__init__(self)\n\n def run(\n self, network, antecedents, out_attributes, user_options, num_cores,\n outfile):\n import os\n import shutil\n from genomicode import filelib\n in_data = antecedents\n result_files = os.listdir(in_data.identifier)\n for result_file in result_files:\n if '-controls' in result_file:\n goal_file = os.path.join(in_data.identifier, result_file)\n shutil.copyfile(goal_file, outfile)\n \n \n assert filelib.exists_nz(outfile), (\n 'the output file %s for illu_control fails' % outfile\n )\n\n\n def name_outfile(self, antecedents, user_options):\n from Betsy import module_utils\n original_file = module_utils.get_inputid(antecedents.identifier)\n filename = 'control_illumina_' + original_file + '.gct'\n return filename\n\n\n\n","sub_path":"Betsy/Betsy/modules/get_illumina_control.py","file_name":"get_illumina_control.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"530697527","text":"\"\"\"\n二叉树的实现\n\n思路分析:\n 1.使用链式存储\n 节点类设计出两个属性,包括左孩子和右孩子\n\"\"\"\nfrom day02.s_queue import SQueue\n#节点类\nclass TreeNode(object):\n def __init__(self, data=None, left=None, right=None):\n self.data = data\n self.left = left\n self.right = right\n\n# 二叉树操作类\nclass Bitree:\n \"\"\"\n 完成二叉树的遍历\n \"\"\"\n def __init__(self, root=None):\n self.root = root\n self.list = []\n\n # 先序遍历\n def pre_order(self,node):\n if node is None:\n return\n print(node.data,end=\" \")\n self.pre_order(node.left)\n self.pre_order(node.right)\n\n\n #中序遍历\n def in_order(self, node):\n if node is None:\n return\n self.in_order(node.left)\n print(node.data, end=\" \")\n self.in_order(node.right)\n\n\n\n # 后序遍历\n def be_order(self, node):\n if node is None:\n return\n self.be_order(node.left)\n self.be_order(node.right)\n print(node.data, end=\" \")\n\n # 层次遍历\n # def level_order(self,node):\n # self.list.append(node)\n # while not self.list == []:\n # code = self.list.pop(0)\n # print(code.data, end=\" \")\n # if code.left:\n # self.list.append(code.left)\n # if code.right:\n # self.list.append(code.right)\n\n # 层次遍历\n def level_order(self,node):\n st = SQueue()\n st.enquene(node)\n while not st.is_empty():\n code = st.dequene()\n print(code.data, end=\" \")\n if code.left:\n st.enquene(code.left)\n if code.right:\n st.enquene(code.right)\n\n\nif __name__ == \"__main__\":\n # 后续遍历 B F G D I H E C A\n b = TreeNode(\"B\")\n f = TreeNode(\"F\")\n g = TreeNode(\"G\")\n d = TreeNode(\"D\",f,g)\n i = TreeNode(\"I\")\n h = TreeNode(\"H\")\n e = TreeNode(\"E\",i,h)\n c = TreeNode(\"C\",d,e)\n a = TreeNode(\"A\",b,c)\n #初始化对象得到树根\n bt = Bitree(a)\n # bt.pre_order(bt.root)\n # print()\n # bt.in_order(bt.root)\n # print()\n # bt.be_order(bt.root)\n # print()\n bt.level_order(bt.root)\n print()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"xiaojian/second_phase/day03/bit_tree.py","file_name":"bit_tree.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"272010470","text":"# https://gist.github.com/anonymous/26a01b934ea7e522c497\n\nfrom scene import *\nfrom random import randint\n\n#A simple function to return the ratio of two integers or floats\ndef ratios(item1,item2):\n\tif item1 > item2: \n\t\treturn float(item1)/item2 \n\treturn float(item2)/item1\n\n#Hit test function. Tests a point to see if it's hitting a square.\n#Used for controls. Minimap uses a hittest when you click, for example.\ndef hit(loc1, loc2, size2):\n\tif loc1.x>loc2.x and loc1.xloc2.y and loc1.y self.grid_count*self.map_size: \n\t\t\tself.circle_vel.x = randint(-10,10)\n\t\t\tself.circle_pos.x = 0\n\t\tif self.circle_pos.y < 0 or self.circle_pos.y > self.grid_count*self.map_size: \n\t\t\tself.circle_vel.y = randint(-10,10)\n\t\t\tself.circle_pos.y = 0\n\t\tself.circle_vel.y += .1\n\t\tself.circle_vel.x += .1\n\t\t\n\t\tif self.drag: #Drag and drop\n\t\t\tfill(1,1,1,.4)\n\t\t\trect(self.drag[0].x, self.drag[0].y, self.drag[1].x, self.drag[1].y)\n\t\n\tdef touch_began(self, touch):\n\t\tif not self.drag and not hit(touch.location, self.minimap_position, Point(200,200)):\n\t\t\tself.drag = [touch.location, Point(0,0)]\n\t\n\tdef touch_moved(self, touch):\n\t\tif self.drag:\n\t\t\tself.drag[1] = Point(touch.location.x-self.drag[0].x, touch.location.y-self.drag[0].y)\n\n\tdef touch_ended(self, touch):\n\t\t#When you touch the minimap, the screen moves.\n\t\tif self.drag:\n\t\t\tself.drag = False\n\t\t\treturn\n\t\tif hit(touch.location, self.minimap_position, Point(200,200)):\n\t\t\ttempPoint=Point(self.minimap_position.x-touch.location.x,\n\t\t\t self.minimap_position.y-touch.location.y)\n\t\t\tself.map_position = Point(tempPoint.x*self.ratio+self.size.w/2, \n\t\t\t tempPoint.y*self.ratio+self.size.h/2)\n\nrun(MyScene())","sub_path":"scenes/a_rts.py","file_name":"a_rts.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"257937812","text":"#! python3\n# -*- coding: utf-8 -*-\n\n\n# import logging\n# logging.disable(logging.CRITICAL)\n# logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')\n# logging.debug(\"Start of program.\")\n\n\ndef test_list_pre():\n prepare_list = locals()\n for i in range(16):\n prepare_list['list_' + str(i)] = []\n prepare_list['list_' + str(i)].append('I\\'m the ' + str(i) + 'th list.')\n for i in prepare_list:\n print(i, prepare_list[i])\n\n\nif __name__ == '__main__':\n test_list_pre()\n","sub_path":"Program/function_locals.py","file_name":"function_locals.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191523107","text":"\"\"\"\nMIT License\n-----------\n\nCopyright (c) 2021 University of Malaga\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nAuthors: J. Ricardo Sánchez Ibáñez, Carlos J. Pérez del Pulgar\nAffiliation: Department of Systems Engineering and Automation\nSpace Robotics Lab (www.uma.es/space-robotics)\n\"\"\"\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom context import camis\nimport copy\nimport zipfile\nimport yaml\nfrom matplotlib.ticker import FormatStrFormatter\ntry:\n from scipy import signal\nexcept:\n raise ImportError('ERROR: scipy module could not be imported')\nimport plotly.graph_objects as go\nfrom matplotlib.colors import LightSource\n\n# =============================================================================\n## LOADING DEM\n# =============================================================================\n\n#v = x.*exp(-x.^2-y.^2-z.^2);\n\nxx = np.linspace(-3.0,3.0,50)\nyy = np.linspace(-4.5,4.5,50)\nxmesh, ymesh = np.meshgrid(xx,yy)\n\nz = np.ones_like(xmesh)\nfor j,y in enumerate(yy):\n for i,x in enumerate(xx):\n z[j,i] = 3*(1-x)**2*np.exp(-(x**2)/1.0 - (y+1)**2/1.0) - \\\n 10*(x/5 - x**3 - y**5)*np.exp(-x**2-y**2) - \\\n 1/3*np.exp(-(x+1)**2 - y**2) \n\nxmesh *= 10.0\nymesh *= 10.0\nz = z/9.0\n\nplt.style.use('default')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig, ax1 = plt.subplots(figsize=(3, 4),nrows = 1, ncols = 1, constrained_layout=True)\ncc = ax1.scatter(xmesh, ymesh, c = z, \n cmap=cm.gist_earth,s=16.0)\ncbar = fig.colorbar(cc, ax=ax1,shrink=0.6, location = 'top')\ncbar.set_label('Elevation [deg]')\nax1.set_xlabel('X [m]')\nax1.set_ylabel('Y [m]')\nax1.set_aspect('equal')\n\nhiRes = 1.0\nhexRes = 0.5\noffset = (0,0)\noccupancy_radius = 0.5\ntracking_error = 0.5\n#posA = np.asarray([20,45])\n#posB = np.asarray([30,5])\nposA = np.asarray([27,5])\nposB = np.asarray([20,45])\nenv = camis.AnisotropicMap(z, hiRes, hexRes,\\\n offset, occupancy_radius, tracking_error)\nplt.style.use('default')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig, ax1 = plt.subplots(figsize=(3.2, 3.9),nrows = 1, ncols = 1, constrained_layout=True)\ncc = ax1.scatter(env.hexXmap, env.hexYmap, c = 180/np.pi*env.hexSlopeMap, \n cmap=\"nipy_spectral\",s=16.0, vmin = 0.0, vmax = 25.0, rasterized=True)\ncbar = fig.colorbar(cc, ax=ax1,shrink=0.6, location = 'top', \\\n ticks=[0,5,10,15,20,25])\n#cc.set_clim(0,50.0)\ncbar.set_label('Steepness α [deg]')\nax1.set_xlim([0,48.0])\nax1.set_ylim([0,48.0])\nax1.set_xlabel('X [m]')\nax1.set_ylabel('Y [m]')\nax1.set_aspect('equal')\nplt.savefig('numerical_tests_steepnessMap_reduced.pdf',dpi=300)\n\n\nplt.style.use('default')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig, ax1 = plt.subplots(figsize=(3.2, 3.9),nrows = 1, ncols = 1, constrained_layout=True)\ncc = ax1.scatter(env.hexXmap, env.hexYmap, c = 180/np.pi*np.arctan2(env.hexAspectMap[1],env.hexAspectMap[0]),\n cmap=\"gist_rainbow\",s=16.0, vmin = -180.0, vmax = 180.0, rasterized=True)\ncbar = fig.colorbar(cc, ax=ax1,shrink=0.6, location = 'top', ticks=[-180, -90, 0, 90, 180])\ncbar.set_label('Aspect Angle [deg]')\nax1.set_xlim([0,48.0])\nax1.set_ylim([0,48.0])\nax1.set_xlabel('X [m]')\nax1.set_ylabel('Y [m]')\nax1.set_aspect('equal')\nplt.savefig('numerical_tests_aspectMap_reduced.pdf',dpi=300)\n\n\n#cc.set_clim(0,50.0)\n#cbar.set_label('Steepness (deg)')\n\n\n\n\n\nhiRes_elevationMap = np.loadtxt(\\\n open(\"data/umaRescueArea/UMARescueArea_1mDEM.csv\",\\\n \"rb\"), delimiter=\" \", skiprows=0)\noffset = np.loadtxt(\\\n open(\"data/umaRescueArea/UMARescueArea_1mOffset.csv\",\\\n \"rb\"), delimiter=\" \", skiprows=0)\n\n\n\nhiRes = 1.0\noccupancy_radius = 0.5\ntracking_error = 0.5\n\nprint('TEST_DEMO: DEM is loaded')\n\n\n\n#r = 3\n#y,x = np.ogrid[-r: r+1, -r: r+1]\n#convMatrix = x**2+y**2 <= r**2\n#convMatrix = convMatrix.astype(float)\n#convMatrix = convMatrix/convMatrix.sum()\n#for i in range(5):\n# hiRes_elevationMap = signal.convolve2d(hiRes_elevationMap, \\\n# convMatrix, \\\n# mode='same', boundary='symm')\n\n##elevationMap = hiRes_elevationMap[:70,60:140]\n##posA = np.asarray([6,10])\n##posB = np.asarray([70,10])\n##posC = np.asarray([70,50])\n##hexRes = 1.0\n#\n#elevationMap = hiRes_elevationMap[:50,80:140]\n#posA = np.asarray([25,5])\n#posB = np.asarray([10,40])\n#posC = np.asarray([50,20])\n#hexRes = 1.0\n# \n##elevationMap = hiRes_elevationMap[-70:,-80:]\n##posA = np.asarray([45,10])\n##posB = np.asarray([70,60])\n##posC = np.asarray([10,60])\n##hexRes = 1.0\n# \n##elevationMap = hiRes_elevationMap[20:60,140:]\n##posA = np.asarray([10,5])\n##posB = np.asarray([50,30])\n##posC = np.asarray([50,5])\n##hexRes = 1.0\n#\n#XX,YY = np.meshgrid(range(elevationMap.shape[1]), range(elevationMap.shape[0]))\n##elevationMap = elevationMap - 0.1*YY\n##elevationMap = elevationMap - 0.1*XX - 0.1*YY\n#\n#env = camis.AnisotropicMap(elevationMap, hiRes, hexRes,\\\n# offset, occupancy_radius, tracking_error)\n\n#plt.style.use('default')\n#plt.rcParams[\"font.family\"] = \"Constantia\"\n#plt.rcParams['mathtext.fontset'] = 'cm'\n#plt.rcParams['mathtext.rm'] = 'serif'\n#fig, ax1 = plt.subplots(figsize=(5, 4),nrows = 1, ncols = 1, constrained_layout=True)\n#cc = ax1.scatter(env.hexXmap, env.hexYmap, c = 180/np.pi*env.hexSlopeMap, \n# cmap=\"nipy_spectral\",s=16.0)\n#cbar = fig.colorbar(cc, ax=ax1,shrink=0.6)\n#cc.set_clim(0,50.0)\n#cbar.set_label('Steepness (deg)')\n\ndef computeAllPlannings(anisoMapList):\n anisoMapList[0].executeBiPlanning(posB,posA)\n# anisoMapList[1].executeBiPlanning(posC,posB)\n# anisoMapList[2].executeBiPlanning(posA,posC)\n# anisoMapList[3].executeBiPlanning(posC,posA)\n# anisoMapList[4].executeBiPlanning(posB,posC)\n anisoMapList[1].executeBiPlanning(posA,posB)\n\ndef getMapLists(camisInput):\n iso_model = copy.deepcopy(camisInput)\n iso_model.setAsIsotropic()\n env_aniso = [None] * 2\n env_iso = [None] * 2\n env.computeVecCostMap(camisInput)\n enviso = copy.deepcopy(env)\n enviso.computeVecCostMap(iso_model)\n for i in range(2):\n env_aniso[i] = copy.deepcopy(env)\n env_iso[i] = copy.deepcopy(enviso)\n return env_aniso, env_iso\n\n\n\nwith open(\"data/sim01/cuadriga_aniso_01.yml\", 'r') as file:\n cuadriga_data = yaml.full_load(file)\naniso_01 = camis.CamisDrivingModel(cuadriga_data)\naniso_01.showCAMIS(25)\nenv_CUAD01_scene01, env_isoCUAD01_scene01 = getMapLists(aniso_01)\ncomputeAllPlannings(env_CUAD01_scene01)\ncomputeAllPlannings(env_isoCUAD01_scene01)\n\nwith open(\"data/sim01/cuadriga_aniso_02.yml\", 'r') as file:\n cuadriga_data = yaml.full_load(file)\naniso_02 = camis.CamisDrivingModel(cuadriga_data)\naniso_02.showCAMIS(25)\nenv_CUAD02_scene01, env_isoCUAD02_scene01 = getMapLists(aniso_02)\ncomputeAllPlannings(env_CUAD02_scene01)\ncomputeAllPlannings(env_isoCUAD02_scene01)\n\nwith open(\"data/sim01/cuadriga_aniso_03.yml\", 'r') as file:\n cuadriga_data = yaml.full_load(file)\naniso_03 = camis.CamisDrivingModel(cuadriga_data)\naniso_03.showCAMIS(25)\nenv_CUAD03_scene01, env_isoCUAD03_scene01 = getMapLists(aniso_03)\ncomputeAllPlannings(env_CUAD03_scene01)\ncomputeAllPlannings(env_isoCUAD03_scene01)\n\nwith open(\"data/sim01/cuadriga_aniso_04.yml\", 'r') as file:\n cuadriga_data = yaml.full_load(file)\naniso_04 = camis.CamisDrivingModel(cuadriga_data)\naniso_04.showCAMIS(25)\nenv_CUAD04_scene01, env_isoCUAD04_scene01 = getMapLists(aniso_04)\ncomputeAllPlannings(env_CUAD04_scene01)\ncomputeAllPlannings(env_isoCUAD04_scene01)\n\nwith open(\"data/sim01/cuadriga_aniso_05.yml\", 'r') as file:\n cuadriga_data = yaml.full_load(file)\naniso_05 = camis.CamisDrivingModel(cuadriga_data)\naniso_05.showCAMIS(25)\nenv_CUAD05_scene01, env_isoCUAD05_scene01 = getMapLists(aniso_05)\ncomputeAllPlannings(env_CUAD05_scene01)\ncomputeAllPlannings(env_isoCUAD05_scene01)\n\nwith open(\"data/sim01/cuadriga_aniso_06.yml\", 'r') as file:\n cuadriga_data = yaml.full_load(file)\naniso_06 = camis.CamisDrivingModel(cuadriga_data)\naniso_06.showCAMIS(25)\nenv_CUAD06_scene01, env_isoCUAD06_scene01 = getMapLists(aniso_06)\ncomputeAllPlannings(env_CUAD06_scene01)\ncomputeAllPlannings(env_isoCUAD06_scene01)\n\nplt.style.use('seaborn-darkgrid')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig, ax = plt.subplots(figsize=(5,2.5),constrained_layout=True)\np1 = aniso_01.showModelData('anisotropy',fig,ax,'r','solid',25)\np2 = aniso_02.showModelData('anisotropy',fig,ax,'m','solid',25)\np3 = aniso_03.showModelData('anisotropy',fig,ax,'orange','solid',25)\np4 = aniso_04.showModelData('anisotropy',fig,ax,'b','solid',25)\np5 = aniso_05.showModelData('anisotropy',fig,ax,'c','solid',25)\np6 = aniso_06.showModelData('anisotropy',fig,ax,'lime','solid',25)\np7, = ax.plot([0], marker='None',\n linestyle='None', label='Wheel Model')\nax.set_xlabel('Steepness α [degrees]', fontsize = 12)\nax.set_ylabel('Anisotropy', fontsize = 12)\nax.text(-1.8,5.7,'ϒ',{'family':'DejaVu Sans'},rotation = 'vertical', fontsize = 12)\nl1 = ax.legend([p7,p1,p2,p3,p7,p7,p4,p5,p6], [r'$Wheel \\ Model$'] + \\\n ['$ρ = 0.3$', '$ρ = 0.6$', \\\n '$ρ = 0.9$'] + [''] + \\\n [r'$Track \\ Model$'] + \\\n [r'$ρ = 0.3$', r'$ρ = 0.6$', \\\n r'$ρ = 0.9$'], ncol = 2, fontsize = 10)\nax.set_xlim([0,25])\nplt.minorticks_on()\nplt.grid(b=True,which='minor', linestyle = '--')\nplt.grid(b=True,which='major', linewidth = 1)\nplt.show()\n\n\ndef plotModels(model, fig, axes,label,modelname):\n axes.plot(0,0,alpha = 0.0)\n model.showModelData('ascent-cost',fig,axes,'m','dashed',25)\n model.showModelData('lateral-cost',fig,axes,'g','dashed',25)\n model.showModelData('descent-cost',fig,axes,'b','dashed',25)\n model.showModelData('nominal-cost',fig,axes,'orange','dashed',25)\n axes.legend((modelname,'$C(α, β = \\pm π)$','$C(α, β = \\pm π/2)$',\\\n '$C(α, β = 0)$', '$C_n(α)$'), loc = 2, ncol = 2, fontsize = 10)\n# axes.set_ylabel(label)\n# axes.text(0.05, 0.35, modelname, horizontalalignment='left', \\\n# verticalalignment='bottom', transform=axes.transAxes, fontsize = 10,\\\n# color = 'k')\nplt.style.use('seaborn-darkgrid')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig,(axes1, axes2, axes3) = plt.subplots(figsize=(7, 6), \\\n nrows = 3, ncols = 2)\nplotModels(aniso_01,fig,axes1[0],'Power/Speed [As/m]','$\\mathbf{ρ = 0.3}$')\naxes1[0].grid(b=True,which='minor', linestyle = '--')\naxes1[0].grid(b=True,which='major', linewidth = 1)\naxes1[0].minorticks_on() \nplotModels(aniso_02,fig,axes2[0],'Power/Speed [As/m]','$\\mathbf{ρ = 0.6}$')\naxes2[0].grid(b=True,which='minor', linestyle = '--')\naxes2[0].grid(b=True,which='major', linewidth = 1)\naxes2[0].minorticks_on() \nplotModels(aniso_03,fig,axes3[0],'Power/Speed [As/m]','$\\mathbf{ρ = 0.9}$')\naxes3[0].grid(b=True,which='minor', linestyle = '--')\naxes3[0].grid(b=True,which='major', linewidth = 1)\naxes3[0].minorticks_on() \nplotModels(aniso_04,fig,axes1[1],'Power/Speed [As/m]','$\\mathbf{ρ = 0.3}$')\naxes1[1].grid(b=True,which='minor', linestyle = '--')\naxes1[1].grid(b=True,which='major', linewidth = 1)\naxes1[1].minorticks_on() \nplotModels(aniso_05,fig,axes2[1],'Power/Speed [As/m]','$\\mathbf{ρ = 0.6}$')\naxes2[1].grid(b=True,which='minor', linestyle = '--')\naxes2[1].grid(b=True,which='major', linewidth = 1)\naxes2[1].minorticks_on() \nplotModels(aniso_06,fig,axes3[1],'Power/Speed [As/m]','$\\mathbf{ρ = 0.9}$')\naxes3[1].grid(b=True,which='minor', linestyle = '--')\naxes3[1].grid(b=True,which='major', linewidth = 1)\naxes3[1].minorticks_on() \nfor ax in (axes1, axes2, axes3):\n# ax.set_ylim([0,300])\n ax[0].grid(True, which='both')\n ax[1].grid(True, which='both')\n ax[0].set_xlim([0,25])\n ax[1].set_xlim([0,25])\n# ax[0].set_ylim([0,9.0])\n ax[1].set_ylim([0, 25.0])\naxes1[0].set_title('Wheel Model', fontsize = 14)\naxes1[1].set_title('Track Model', fontsize = 14)\nplt.subplots_adjust(left = 0.07, right = 0.99, bottom = 0.075, top = 0.95, \\\n wspace = 0.15, hspace = 0.15)\nfig.text(0.5, 0.0075, 'Steepness α [deg]', ha='center', fontsize = 14)\naxes2[0].set_ylabel('Energy per Distance [J/m]', fontsize = 14)\nplt.grid(b=True,which='minor', linestyle = '--')\nplt.grid(b=True,which='major', linewidth = 1)\nplt.minorticks_on() \n#axes.set_xlabel('Steepness [deg]')\n\n#\n#with open(\"data/sim01/cuadriga_aniso_07.yml\", 'r') as file:\n# cuadriga_data = yaml.full_load(file)\n#aniso_07 = camis.CamisDrivingModel(cuadriga_data)\n#env_CUAD07_scene01, env_isoCUAD07_scene01 = getMapLists(aniso_07)\n#computeAllPlannings(env_CUAD07_scene01)\n#computeAllPlannings(env_isoCUAD07_scene01)\n#\n#with open(\"data/sim01/cuadriga_aniso_08.yml\", 'r') as file:\n# cuadriga_data = yaml.full_load(file)\n#aniso_08 = camis.CamisDrivingModel(cuadriga_data)\n#env_CUAD08_scene01, env_isoCUAD08_scene01 = getMapLists(aniso_08)\n#computeAllPlannings(env_CUAD08_scene01)\n#computeAllPlannings(env_isoCUAD08_scene01)\n#\n#with open(\"data/sim01/cuadriga_aniso_09.yml\", 'r') as file:\n# cuadriga_data = yaml.full_load(file)\n#aniso_09 = camis.CamisDrivingModel(cuadriga_data)\n#env_CUAD09_scene01, env_isoCUAD09_scene01 = getMapLists(aniso_09)\n#computeAllPlannings(env_CUAD09_scene01)\n#computeAllPlannings(env_isoCUAD09_scene01)\n#\n#\n#env.show3dDEM()\n#\nplt.style.use('default')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig, (ax1,ax2) = plt.subplots(figsize=(5, 4),nrows = 1, ncols = 2, constrained_layout=True)\ncc = ax1.scatter(env.hexXmap, env.hexYmap, c = 180/np.pi*env.hexSlopeMap, \n cmap=\"nipy_spectral\",s=4.0)\ncbar = fig.colorbar(cc, ax=ax1,shrink=0.6)\ncbar.set_label('Steepness (deg)')\n\nfig, ax = plt.subplots(constrained_layout=True)\ngradient = np.linspace(0,25,26)\nslipRatio = 0.07 * np.exp(0.1*gradient)\nslipFactorParallel = 1.0 / (1 - slipRatio)\nslipAngle = 1.32 * np.exp(0.16*gradient)\nslipFactorPerp = 1 / np.cos(slipAngle*3.1416/180.0)\n#ax.plot(gradient, slipRatio)\n#ax.plot(gradient, slipAngle)\nax.plot(gradient, slipFactorParallel)\nax.plot(gradient, slipFactorPerp)\n\ndef showAnisoPath(mapList, color, ax1, ax2, mode):\n for i,anisomap in enumerate(mapList):\n if i < 1:\n anisomap.showPath(fig,ax1,color,mode)\n else:\n anisomap.showPath(fig,ax2,color,mode)\ndef showIsoPath(mapList, color, ax1, ax2, mode):\n for i,anisomap in enumerate(mapList):\n if i < 1:\n anisomap.showPath(fig,ax1,color,mode)\n else:\n anisomap.showPath(fig,ax2,color,mode)\n \nplt.style.use('default')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig, axes = plt.subplots(figsize=(8, 8), \\\n nrows = 1, ncols = 3, \\\n sharex = 'all', sharey = 'all')\nax1 = axes[0]\nax2 = axes[1]\nax3 = axes[2]\n\n\nplt.subplots_adjust(left = 0.1, right = 0.9, bottom = 0.5, top = 1.0, wspace = 0.01, hspace = 0.05)\nfig.text(0.5, 0.005, 'X-axis [m]', ha='center')\nfig.text(0.005, 0.5, 'Y-axis [m]', va='center', rotation='vertical')\n\nshowAnisoPath(env_CUAD01_scene01, 'r', ax1, ax2,'solid')\nshowIsoPath(env_isoCUAD01_scene01, 'r', ax3, ax3,'dashed')\nshowAnisoPath(env_CUAD02_scene01, 'm', ax1, ax2,'solid')\nshowIsoPath(env_isoCUAD02_scene01, 'm', ax3, ax3,'dashed')\nshowAnisoPath(env_CUAD03_scene01, 'orange', ax1, ax2,'solid')\nshowIsoPath(env_isoCUAD03_scene01, 'orange', ax3, ax3,'dashed')\nshowAnisoPath(env_CUAD04_scene01, 'b', ax1, ax2,'solid')\nshowIsoPath(env_isoCUAD04_scene01, 'b', ax3, ax3,'dashed')\nshowAnisoPath(env_CUAD05_scene01, 'c', ax1, ax2,'dashed')\nshowIsoPath(env_isoCUAD05_scene01, 'c', ax3, ax3,'dashed')\nshowAnisoPath(env_CUAD06_scene01, 'g', ax1, ax2,'dashed')\nshowIsoPath(env_isoCUAD06_scene01, 'g', ax3, ax3,'dashed')\n#showAnisoPath(env_CUAD07_scene01, 'orange', ax1, ax2,'dotted')\n#showIsoPath(env_isoCUAD07_scene01, 'orange', ax3, ax3,'dotted')\n#showAnisoPath(env_CUAD08_scene01, 'm', ax1, ax2,'dotted')\n#showIsoPath(env_isoCUAD08_scene01, 'm', ax3, ax3,'dotted') \n#showAnisoPath(env_CUAD09_scene01, 'k', ax1, ax2,'dotted')\n#showIsoPath(env_isoCUAD09_scene01, 'k', ax3, ax3,'dotted')\n#ax1.text(0.5, 0.95, 'Go traverses \\n (CAMIS models)', horizontalalignment='center', \\\n# verticalalignment='center', transform=ax1.transAxes, fontsize = 12,\\\n# color = 'white')\n#ax2.text(0.5, 0.95, 'Return traverses \\n (CAMIS models)', horizontalalignment='center', \\\n# verticalalignment='center', transform=ax2.transAxes, fontsize = 12,\\\n# color = 'white')\n#ax3.text(0.5, 0.95, 'Go and Return traverses \\n (isotropic equivalent models)', horizontalalignment='center', \\\n# verticalalignment='center', transform=ax3.transAxes, fontsize = 12,\\\n# color = 'white')\n##ax1.legend()\n# \nfor ax in axes:\n cc = ax.scatter(env.hexXmap, env.hexYmap, c = env.hexElevationMap, cmap = cm.gist_earth,s=20)\n ax.scatter(posA[0], posA[1], facecolor = 'r', edgecolor='black', s=60)\n ax.scatter(posB[0], posB[1], facecolor = 'r', edgecolor='black', s=60)\n ax.set_xlim([env.xMap[0,2], env.xMap[-1,-4]])\n ax.set_ylim([env.yMap[0,0], env.yMap[-1,-1]])\n ax.set_aspect('equal')\nfig.tight_layout()\n\n\n\n#\n#env.executeBiPlanning(posB,posA)\n#\n#plt.style.use('default')\n#plt.rcParams[\"font.family\"] = \"Constantia\"\n#plt.rcParams['mathtext.fontset'] = 'cm'\n#plt.rcParams['mathtext.rm'] = 'serif'\n#fig, ax = plt.subplots(figsize=(8, 8), \\\n# nrows = 1, ncols = 1, \\\n# sharex = 'all', sharey = 'all')\n#plt.subplots_adjust(left = 0.1, right = 0.9, bottom = 0.5, top = 1.0, wspace = 0.01, hspace = 0.05)\n#fig.text(0.5, 0.005, 'X-axis [m]', ha='center')\n#fig.text(0.005, 0.5, 'Y-axis [m]', va='center', rotation='vertical')\n#\n#\n#env.showPath(fig,ax,'r','solid')\n#\n#cc = ax.scatter(env.hexXmap, env.hexYmap, c = env.hexElevationMap, cmap = cm.gist_earth,s=20)\n#ax.scatter(posA[0], posA[1], facecolor = 'r', edgecolor='black', s=60)\n#ax.scatter(posB[0], posB[1], facecolor = 'r', edgecolor='black', s=60)\n#ax.set_xlim([env.xMap[0,2], env.xMap[-1,-4]])\n#ax.set_ylim([env.yMap[0,0], env.yMap[-1,-1]])\n#ax.set_aspect('equal')\n#fig.tight_layout()\n\n\n################ ENERGY PLOT ##################\nplt.style.use('seaborn-darkgrid')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\ncoeffsLabels = ['Wheel\\nModel\\n$ρ= 0.3$','Wheel\\nModel\\n$ρ = 0.6$',\\\n 'Wheel\\nModel\\n$ρ = 0.9$','Track\\nModel\\n$ρ = 0.3$',\\\n 'Track\\nModel\\n$ρ = 0.6$','Track\\nModel\\n$ρ = 0.9$']\nanisoTotalCost = [0,0,0,0,0,0]\nisoTotalCost = [0,0,0,0,0,0]\nanisoTR = [0,0]\nisoTR = [0,0]\nfor i in range(2):\n anisoTotalCost[0] = anisoTotalCost[0] + env_CUAD01_scene01[i].pathComputedTotalCost[-1]#/3600.0\n anisoTotalCost[1] = anisoTotalCost[1] + env_CUAD02_scene01[i].pathComputedTotalCost[-1]#/3600.0\n anisoTotalCost[2] = anisoTotalCost[2] + env_CUAD03_scene01[i].pathComputedTotalCost[-1]#/3600.0\n anisoTotalCost[3] = anisoTotalCost[3] + env_CUAD04_scene01[i].pathComputedTotalCost[-1]#/3600.0\n anisoTotalCost[4] = anisoTotalCost[4] + env_CUAD05_scene01[i].pathComputedTotalCost[-1]#/3600.0\n anisoTotalCost[5] = anisoTotalCost[5] + env_CUAD06_scene01[i].pathComputedTotalCost[-1]#/3600.0\n isoTotalCost[0] = isoTotalCost[0] + env_isoCUAD01_scene01[i].pathComputedTotalCost[-1]#/3600.0\n isoTotalCost[1] = isoTotalCost[1] + env_isoCUAD02_scene01[i].pathComputedTotalCost[-1]#/3600.0\n isoTotalCost[2] = isoTotalCost[2] + env_isoCUAD03_scene01[i].pathComputedTotalCost[-1]#/3600.0\n isoTotalCost[3] = isoTotalCost[3] + env_isoCUAD04_scene01[i].pathComputedTotalCost[-1]#/3600.0\n isoTotalCost[4] = isoTotalCost[4] + env_isoCUAD05_scene01[i].pathComputedTotalCost[-1]#/3600.0\n isoTotalCost[5] = isoTotalCost[5] + env_isoCUAD06_scene01[i].pathComputedTotalCost[-1]#/3600.0\n# anisoTR[0] = anisoTR[0] + env_CUAD02_scene01[i].pathComputedTotalCostwithRisk[-1]/3600.0\n# anisoTR[1] = anisoTR[1] + env_CUAD03_scene01[i].pathComputedTotalCostwithRisk[-1]/3600.0\n# isoTR[0] = isoTR[0] + env_isoCUAD02_scene01[i].pathComputedTotalCostwithRisk[-1]/3600.0\n# isoTR[1] = isoTR[1] + env_isoCUAD03_scene01[i].pathComputedTotalCostwithRisk[-1]/3600.0\n\nx = np.arange(len(coeffsLabels)) # the label locations\nx2 = np.arange(2)+1\nwidth = 0.48 # the width of the bars\n\nfig, ax = plt.subplots(figsize=(7,3), constrained_layout=True)\n#rects3 = ax.bar(x2 - 0.45/2, anisoTR, 0.45, label='Isotropic (ρ = 0.8)', color='lime')\n#rects4 = ax.bar(x2 + 0.45/2, isoTR, 0.45, label='Isotropic (ρ = 0.8)', color='g')\nrects1 = ax.bar(x - width/2, anisoTotalCost, width, label='Isotropic (ρ = 0.8)', color='r')\nrects2 = ax.bar(x + width/2, isoTotalCost, width, label='Isotropic (ρ = 0.8)', color = 'b')\n\nfor i,rect in enumerate(rects1):\n T = rect.get_height()\n ax.annotate('{0:.2f}'.format(T),\n xy=(rect.get_x() + rect.get_width() / 2, T),\n xytext=(0, -3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='top',color = 'w', fontsize = 12)\nfor i,rect in enumerate(rects2):\n T = rect.get_height()\n ax.annotate('{0:.2f}'.format(T),\n xy=(rect.get_x() + rect.get_width() / 2, T),\n xytext=(0, -3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='top',color = 'w', fontsize = 12)\nfor i,rect in enumerate(rects2):\n isoT = rect.get_height()\n anisoT = rects1[i].get_height()\n gain = (isoT - anisoT)/isoT * 100\n ax.annotate('{0:.2f}'.format(gain) + '%',\n xy=(rect.get_x(), isoT),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom', fontsize = 12)\n#for i,rect in enumerate(rects3):\n# T = rect.get_height()\n# ax.annotate('{0:.2f}'.format(T) + '\\nAh',\n# xy=(rect.get_x() + rect.get_width() / 2, T),\n# xytext=(0, 3), # 3 points vertical offset\n# textcoords=\"offset points\",\n# ha='center', va='bottom',color = 'k')\n#for i,rect in enumerate(rects4):\n# T = rect.get_height()\n# ax.annotate('{0:.2f}'.format(T) + '\\nAh',\n# xy=(rect.get_x() + rect.get_width() / 2, T),\n# xytext=(0, 3), # 3 points vertical offset\n# textcoords=\"offset points\",\n# ha='center', va='bottom',color = 'k')\n#for i,rect in enumerate(rects4):\n# isoT = rect.get_height()\n# anisoT = rects3[i].get_height()\n# gain = (isoT - anisoT)/isoT * 100\n# ax.annotate('Gain = ' + '{0:.2f}'.format(gain) + '%',\n# xy=(rect.get_x(), isoT),\n# xytext=(0, 25), # 3 points vertical offset\n# textcoords=\"offset points\",\n# ha='center', va='bottom') \n \nax.grid(True, which='both') \n#autolabel(rects1)\n#autolabel(rects2)\nax.set_ylabel('Total Cost [J]', fontsize = 12)\nax.set_ylim([0,1000])\n#ax.set_xlabel('CAMIS')\nax.set_xticks(x)\nax.set_xticklabels(coeffsLabels, fontsize = 12)\nax.legend(('Anisotropic','Isotropic'), fontsize = 12)\nplt.minorticks_on() \nplt.show()\n\n\n####3d PATHS###\nXX = np.zeros_like(z)\nYY = np.zeros_like(z)\nfor i in range(50):\n for j in range(50):\n XX[j,i] = i\n YY[j,i] = j\n \nfig = plt.figure()\nax1 = fig.add_subplot(1, 1, 1)\ncc = ax1.scatter(env.hexXmap, env.hexYmap, c = env.hexElevationMap, \\\n cmap = cm.gist_earth,s=20,vmin = -1.0, vmax = 1.0)\n\nplt.style.use('seaborn-darkgrid')\nplt.rcParams[\"font.family\"] = \"Constantia\"\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['mathtext.rm'] = 'serif'\nfig = plt.figure(figsize=(13.2, 4.5))\nax1 = fig.add_subplot(1, 3, 1, projection='3d')\nax2 = fig.add_subplot(1, 3, 2, projection='3d')\nax3 = fig.add_subplot(1, 3, 3, projection='3d')\n\n\nls = LightSource(270, 45)\nrgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')\nsurf1 = ax1.plot_surface(XX,YY,z, rstride=1, cstride=1, facecolors=rgb,\\\n linewidth=0, antialiased=False, shade=False,\\\n vmin = -1.0, vmax = 1.0, rasterized=True)\nsurf2 = ax2.plot_surface(XX,YY,z, rstride=1, cstride=1, facecolors=rgb,\\\n linewidth=0, antialiased=False, shade=False,\\\n vmin = -1.0, vmax = 1.0, rasterized=True)\nsurf3 = ax3.plot_surface(XX,YY,z, rstride=1, cstride=1, facecolors=rgb,\\\n linewidth=0, antialiased=False, shade=False,\\\n vmin = -1.0, vmax = 1.0, rasterized=True)\nax1.plot(env_CUAD01_scene01[0].path[:,0], env_CUAD01_scene01[0].path[:,1], \\\n env_CUAD01_scene01[0].pathElevation,linestyle='dashed',color = 'r')\nax1.plot(env_CUAD02_scene01[0].path[:,0], env_CUAD02_scene01[0].path[:,1], \\\n env_CUAD02_scene01[0].pathElevation,linestyle='dashed',color = 'm')\nax1.plot(env_CUAD03_scene01[0].path[:,0], env_CUAD03_scene01[0].path[:,1], \\\n env_CUAD03_scene01[0].pathElevation,linestyle='dashed',color = 'orange')\nax1.plot(env_CUAD04_scene01[0].path[:,0], env_CUAD04_scene01[0].path[:,1], \\\n env_CUAD04_scene01[0].pathElevation,linestyle='dashed',color = 'b')\nax1.plot(env_CUAD05_scene01[0].path[:,0], env_CUAD05_scene01[0].path[:,1], \\\n env_CUAD05_scene01[0].pathElevation,linestyle='dashed',color = 'c')\nax1.plot(env_CUAD06_scene01[0].path[:,0], env_CUAD06_scene01[0].path[:,1], \\\n env_CUAD06_scene01[0].pathElevation,linestyle='dashed',color = 'lime')\nax1.set_xlabel('X [m]',labelpad=-8)\nax1.set_ylabel('Y [m]',labelpad=-8)\nax1.set_zlabel('Z [m]',labelpad=-6)\nax1.tick_params(axis=\"x\",direction=\"in\", pad=-5)\nax1.tick_params(axis=\"y\",direction=\"in\", pad=-5)\nax1.tick_params(axis=\"z\",direction=\"in\", pad=-2)\nax1.set_zticks([-0.6, 0.1, 0.8])\nax1.view_init(78.0, -150.0)\nax1.set_xlim([0,50])\nax1.set_ylim([0,50])\nax1.set_facecolor('w')\nax2.plot(env_CUAD01_scene01[1].path[:,0], env_CUAD01_scene01[1].path[:,1], \\\n env_CUAD01_scene01[1].pathElevation,linestyle='dashed',color = 'r')\nax2.plot(env_CUAD02_scene01[1].path[:,0], env_CUAD02_scene01[1].path[:,1], \\\n env_CUAD02_scene01[1].pathElevation,linestyle='dashed',color = 'm')\nax2.plot(env_CUAD03_scene01[1].path[:,0], env_CUAD03_scene01[1].path[:,1], \\\n env_CUAD03_scene01[1].pathElevation,linestyle='dashed',color = 'orange')\nax2.plot(env_CUAD04_scene01[1].path[:,0], env_CUAD04_scene01[1].path[:,1], \\\n env_CUAD04_scene01[1].pathElevation,linestyle='dashed',color = 'b')\nax2.plot(env_CUAD05_scene01[1].path[:,0], env_CUAD05_scene01[1].path[:,1], \\\n env_CUAD05_scene01[1].pathElevation,linestyle='dashed',color = 'c')\nax2.plot(env_CUAD06_scene01[1].path[:,0], env_CUAD06_scene01[1].path[:,1], \\\n env_CUAD06_scene01[1].pathElevation,linestyle='dashed',color = 'lime')\nax2.set_xlabel('X [m]',labelpad=-8)\nax2.set_ylabel('Y [m]',labelpad=-8)\nax2.set_zlabel('Z [m]',labelpad=-6)\nax2.tick_params(axis=\"x\",direction=\"in\", pad=-5)\nax2.tick_params(axis=\"y\",direction=\"in\", pad=-5)\nax2.tick_params(axis=\"z\",direction=\"in\", pad=-2)\nax2.set_zticks([-0.6, 0.1, 0.8])\nax2.view_init(78.0, -150.0)\nax2.set_xlim([0,50])\nax2.set_ylim([0,50])\nax2.set_facecolor('w')\n\nax3.plot(env_isoCUAD01_scene01[0].path[:,0], env_isoCUAD01_scene01[0].path[:,1], \\\n env_isoCUAD01_scene01[0].pathElevation,linestyle='dashed',color = 'r')\nax3.plot(env_isoCUAD02_scene01[0].path[:,0], env_isoCUAD02_scene01[0].path[:,1], \\\n env_isoCUAD02_scene01[0].pathElevation,linestyle='dashed',color = 'm')\nax3.plot(env_isoCUAD03_scene01[0].path[:,0], env_isoCUAD03_scene01[0].path[:,1], \\\n env_isoCUAD03_scene01[0].pathElevation,linestyle='dashed',color = 'orange')\nax3.plot(env_isoCUAD04_scene01[0].path[:,0], env_isoCUAD04_scene01[0].path[:,1], \\\n env_isoCUAD04_scene01[0].pathElevation,linestyle='dashed',color = 'b')\nax3.plot(env_isoCUAD05_scene01[0].path[:,0], env_isoCUAD05_scene01[0].path[:,1], \\\n env_isoCUAD05_scene01[0].pathElevation,linestyle='dashed',color = 'c')\nax3.plot(env_isoCUAD06_scene01[0].path[:,0], env_isoCUAD06_scene01[0].path[:,1], \\\n env_isoCUAD06_scene01[0].pathElevation,linestyle='dashed',color = 'lime')\nax3.set_xlabel('X [m]',labelpad=-8)\nax3.set_ylabel('Y [m]',labelpad=-8)\nax3.set_zlabel('Z [m]',labelpad=-6)\nax3.tick_params(axis=\"x\",direction=\"in\", pad=-5)\nax3.tick_params(axis=\"y\",direction=\"in\", pad=-5)\nax3.tick_params(axis=\"z\",direction=\"in\", pad=-2)\nax3.set_zticks([-0.6, 0.1, 0.8])\nax3.view_init(78.0, -150.0)\nax3.set_xlim([0,50])\nax3.set_ylim([0,50])\nax3.set_facecolor('w')\n\nax1.text(posA[0],posA[1],0.2,'$X_o$',color='w', size=15)\nax2.text(posA[0],posA[1],0.2,'$X_o$',color='w', size=15)\nax3.text(posA[0],posA[1],0.2,'$X_o$',color='w', size=15)\nax1.text(posB[0],posB[1],0.2,'$X_g$',color='w', size=15)\nax2.text(posB[0],posB[1],0.2,'$X_g$',color='w', size=15)\nax3.text(posB[0],posB[1],0.2,'$X_g$',color='w', size=15)\n\nax1.text(50,35,0.8,'$Anisotropic$\\n $X_o \\Rightarrow X_g$',color='k', size=14)\nax2.text(50,35,0.8,'$Anisotropic$\\n $X_g \\Rightarrow X_o$',color='k', size=14)\nax3.text(50,35,0.8,'$Isotropic$\\n $Both \\ ways$',color='k', size=14)\n\n\nfig.tight_layout()\nplt.subplots_adjust(left = 0.01, right = 1.0, bottom = 0.0, top = 1.0, \\\n wspace = 0.0, hspace = 0.0)\ncbar_ax = fig.add_axes([0.01, 0.05, 0.15, 0.025])\nlegend_ax1 = fig.add_axes([0.1, 0.18, 0.3, 0.1])\nlegend_ax2 = fig.add_axes([0.1, 0.18, 0.63, 0.1])\nlegend_ax1.plot(0,0, alpha = 0, label = '$\\mathbf{Wheel \\ Model}$')\nlegend_ax1.plot(0,0,'r', linestyle = 'dashed', label='$ρ = 0.3$')\nlegend_ax1.plot(0,0,'m', linestyle = 'dashed', label='$ρ = 0.6$')\nlegend_ax1.plot(0,0,'orange', linestyle = 'dashed', label='$ρ = 0.9$')\nlegend_ax1.grid(b=False)\nlegend_ax1.axis('off')\nlegend_ax1.legend(fontsize=12)\nlegend_ax2.plot(0,0, alpha = 0, label = '$\\mathbf{Track \\ Model}$')\nlegend_ax2.plot(0,0,'b', linestyle = 'dashed', label='$ρ = 0.3$')\nlegend_ax2.plot(0,0,'c', linestyle = 'dashed', label='$ρ = 0.6$')\nlegend_ax2.plot(0,0,'lime', linestyle = 'dashed', label='$ρ = 0.9$')\nlegend_ax2.grid(b=False)\nlegend_ax2.axis('off')\nlegend_ax2.legend(fontsize=12)\n#plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n#plt.grid(b=False)\n#plt.axis('off')\ncbar = fig.colorbar(cc, cax=cbar_ax, orientation = 'horizontal')\ncbar.set_alpha(1.0)\ncbar.set_label('Elevation [m]',color='k', labelpad=-40,x = 0.4,fontsize=14)\ncbar.ax.tick_params(colors='k', size = 2)\ncbar.outline.set_visible(True)\n#cbar.outline.set_edgecolor('k')\ncbar.ax.yaxis.set_tick_params(color='k')\ncbar.set_ticks([-1.0, -0.5, 0.0, 0.5, 1.0])\n#cbar.outline.set_linewidth(0.5)\nplt.savefig('numerical_tests_paths_reduced.pdf',dpi=300)\n#MAX = 6\n#for direction in (-1, 1):\n# for point in np.diag(direction * MAX * np.array([1,1,1])):\n# ax1.plot([point[0]+12.5], [point[1]+12.5], [point[2]+2.0], 'w')\n#plt.show()\n\n \n##### COMPUTATIONAL TIMES ###\ncoeffsLabels = ['Wheel\\nModel\\n$ρ= 0.3$','Wheel\\nModel\\n$ρ = 0.6$',\\\n 'Wheel\\nModel\\n$ρ = 0.9$','Track\\nModel\\n$ρ = 0.3$',\\\n 'Track\\nModel\\n$ρ = 0.6$','Track\\nModel\\n$ρ = 0.9$']\nanisoTime = [0,0,0,0,0,0]\nisoTime = [0,0,0,0,0,0]\nfor i in range(2):\n anisoTime[0] = anisoTime[0] + env_CUAD01_scene01[i].elapsedTime\n anisoTime[1] = anisoTime[1] + env_CUAD02_scene01[i].elapsedTime\n anisoTime[2] = anisoTime[2] + env_CUAD03_scene01[i].elapsedTime\n anisoTime[3] = anisoTime[3] + env_CUAD04_scene01[i].elapsedTime\n anisoTime[4] = anisoTime[4] + env_CUAD05_scene01[i].elapsedTime\n anisoTime[5] = anisoTime[5] + env_CUAD06_scene01[i].elapsedTime\n isoTime[0] = isoTime[0] + env_isoCUAD01_scene01[i].elapsedTime\n isoTime[1] = isoTime[1] + env_isoCUAD02_scene01[i].elapsedTime\n isoTime[2] = isoTime[2] + env_isoCUAD03_scene01[i].elapsedTime \n isoTime[3] = isoTime[3] + env_isoCUAD04_scene01[i].elapsedTime \n isoTime[4] = isoTime[4] + env_isoCUAD05_scene01[i].elapsedTime\n isoTime[5] = isoTime[5] + env_isoCUAD06_scene01[i].elapsedTime\n\nx = np.arange(len(coeffsLabels)) # the label locations\nx2 = np.arange(2)+1\nwidth = 0.4 # the width of the bars\n\nfig, ax = plt.subplots(figsize=(7,3), constrained_layout=True)\n#rects3 = ax.bar(x2 - 0.45/2, anisoTR, 0.45, label='Isotropic (ρ = 0.8)', color='lime')\n#rects4 = ax.bar(x2 + 0.45/2, isoTR, 0.45, label='Isotropic (ρ = 0.8)', color='g')\nrects1 = ax.bar(x - width/2, anisoTime, width, label='Isotropic (ρ = 0.8)', color='r')\nrects2 = ax.bar(x + width/2, isoTime, width, label='Isotropic (ρ = 0.8)', color = 'b')\n\nfor i,rect in enumerate(rects1):\n T = rect.get_height()\n ax.annotate('{0:.2f}'.format(T),\n xy=(rect.get_x() + rect.get_width() / 2, T),\n xytext=(0, -3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='top',color = 'w', fontsize = 12)\nfor i,rect in enumerate(rects2):\n T = rect.get_height()\n ax.annotate('{0:.2f}'.format(T),\n xy=(rect.get_x() + rect.get_width() / 2, T),\n xytext=(0, -3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='top',color = 'w', fontsize = 12)\nfor i,rect in enumerate(rects1):\n anisoT = rect.get_height()\n isoT = rects2[i].get_height()\n gain = (isoT - anisoT)/isoT * 100\n ax.annotate('{0:.2f}'.format(gain) + '%',\n xy=(rects2[i].get_x(), anisoT),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom', fontsize = 12)\nax.grid(True, which='both') \n#autolabel(rects1)\n#autolabel(rects2)\nax.set_ylabel('Computational Time [s]', fontsize = 12)\n#ax.set_xlabel('CAMIS')\nax.set_xticks(x)\nax.set_xticklabels(coeffsLabels, fontsize = 12)\nax.set_ylim([0,40])\nax.legend(('Anisotropic','Isotropic'), fontsize = 12)\nplt.minorticks_on() \nplt.show()\n\n\nfig = go.Figure(data=[go.Surface(contours = {\"z\": {\"show\": True, \"size\": 0.01, \"color\":\"white\"}},\\\n z=z, colorscale = 'haline'), \\\n go.Scatter3d(\n x=env_CUAD01_scene01[0].path[:,0], y=env_CUAD01_scene01[0].path[:,1], \\\n z=env_CUAD01_scene01[0].pathElevation,\n marker=dict(\n size=2,\n color='red'\n )), \\\n go.Scatter3d(\n x=env_CUAD01_scene01[1].path[:,0], y=env_CUAD01_scene01[1].path[:,1], \\\n z=env_CUAD01_scene01[1].pathElevation,\n marker=dict(\n size=2,\n color='red'\n )), \\\n go.Scatter3d(\n x=env_CUAD02_scene01[0].path[:,0], y=env_CUAD02_scene01[0].path[:,1], \\\n z=env_CUAD02_scene01[0].pathElevation,\n marker=dict(\n size=2,\n color='magenta'\n )), \\\n go.Scatter3d(\n x=env_CUAD02_scene01[1].path[:,0], y=env_CUAD02_scene01[1].path[:,1], \\\n z=env_CUAD02_scene01[1].pathElevation,\n marker=dict(\n size=2,\n color='magenta'\n )), \\\n go.Scatter3d(\n x=env_CUAD03_scene01[0].path[:,0], y=env_CUAD03_scene01[0].path[:,1], \\\n z=env_CUAD03_scene01[0].pathElevation,\n marker=dict(\n size=2,\n color='orange'\n )), \\\n go.Scatter3d(\n x=env_CUAD03_scene01[1].path[:,0], y=env_CUAD03_scene01[1].path[:,1], \\\n z=env_CUAD03_scene01[1].pathElevation,\n marker=dict(\n size=2,\n color='orange'\n )), \\\n go.Scatter3d(\n x=env_CUAD04_scene01[0].path[:,0], y=env_CUAD04_scene01[0].path[:,1], \\\n z=env_CUAD04_scene01[0].pathElevation,\n marker=dict(\n size=2,\n color='blue'\n )), \\\n go.Scatter3d(\n x=env_CUAD04_scene01[1].path[:,0], y=env_CUAD04_scene01[1].path[:,1], \\\n z=env_CUAD04_scene01[1].pathElevation,\n marker=dict(\n size=2,\n color='blue'\n )), \\\n go.Scatter3d(\n x=env_CUAD05_scene01[0].path[:,0], y=env_CUAD05_scene01[0].path[:,1], \\\n z=env_CUAD05_scene01[0].pathElevation,\n marker=dict(\n size=2,\n color='cyan'\n )), \\\n go.Scatter3d(\n x=env_CUAD05_scene01[1].path[:,0], y=env_CUAD05_scene01[1].path[:,1], \\\n z=env_CUAD05_scene01[1].pathElevation,\n marker=dict(\n size=2,\n color='cyan'\n )), \\\n go.Scatter3d(\n x=env_CUAD06_scene01[0].path[:,0], y=env_CUAD06_scene01[0].path[:,1], \\\n z=env_CUAD06_scene01[0].pathElevation,\n marker=dict(\n size=2,\n color='green'\n )), \\\n go.Scatter3d(\n x=env_CUAD06_scene01[1].path[:,0], y=env_CUAD06_scene01[1].path[:,1], \\\n z=env_CUAD06_scene01[1].pathElevation,\n marker=dict(\n size=2,\n color='green'\n )) \n])\n\nscene=dict(camera=dict(up=dict(x=0, y=0, z=1),\\\n center=dict(x=0, y=0, z=-0.2),\\\n eye=dict(x=1.5, y=-1.5, z=0.7)), #the default values are 1.25, 1.25, 1.25\n xaxis=dict(),\n yaxis=dict(),\n zaxis=dict(),\n aspectmode='data', #this string can be 'data', 'cube', 'auto', 'manual'\n #a custom aspectratio is defined as follows:\n aspectratio=dict(x=1, y=1, z=1)\n )\n\nfig.update_layout(autosize=False,\n width=2048, height=512,\n margin=dict(l=0, r=0, b=0, t=0), scene = scene)\n#fig.show(renderer=\"iframe\")\nfig.write_image(\"elevation_map.pdf\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tests/simulation_test_numerical.py","file_name":"simulation_test_numerical.py","file_ext":"py","file_size_in_byte":38862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"511582952","text":"from multiprocessing import Pool\nfrom PIL import Image\nimport glob\nimport os\nimport time\nimport json\nimport urllib.request\nimport urllib\nimport http\nimport base64\n\nfrom apiKeys import apiKeys\n\n\ndef cleanResult(result):\n\treplaceArray = [\n\t\t['-', ' ']\n\t]\n\tfor a in replaceArray:\n\t\tresult = result.replace(a[0], a[1])\n\n\tif result[len(result)-1] == ' ':\n\t\tresult = result[:-1]\n\n\treturn result.lower()\n\ndef BingWebSearch(search):\n\n\tbingKey = apiKeys['bing']\n\thost = \"api.cognitive.microsoft.com\"\n\tpath = \"/bing/v7.0/search\"\n\n\tterm = \"Microsoft Cognitive Services\"\n\n\theaders = {'Ocp-Apim-Subscription-Key': bingKey}\n\tconn = http.client.HTTPSConnection(host)\n\tquery = urllib.parse.quote(search)\n\tconn.request(\"GET\", path + \"?q=\" + query, headers=headers)\n\tresponse = conn.getresponse()\n\treturn response\n\n\ndef BingCheck(query, answers, keyword):\n\n\tresult = BingWebSearch(query).read().decode('utf-8').encode('ascii', 'ignore').decode('ascii')\n\ta = json.loads(result)\n\n\t# f = open('abc', 'w')\n\t# f.write(result)\n\t# f.close()\n\n\n\tif isinstance(answers, list):\n\t\tanswerScore = [0,0,0]\n\t\tfor result in a['webPages']['value']:\n\n\t\t\tname = result['name'].encode('ascii', 'ignore').decode('ascii')\n\t\t\tsnippet = result['snippet'].encode('ascii', 'ignore').decode('ascii')\n\n\n\t\t\ti = 0\n\n\n\t\t\twhile i < 3:\n\t\t\t\tif answers[i].lower() in cleanResult(name):\n\t\t\t\t\tanswerScore[i] += 1\n\t\t\t\tif answers[i].lower() in cleanResult(snippet):\n\t\t\t\t\tanswerScore[i] += 1\n\n\t\t\t\ti += 1\n\n\n\telse:\n\t\tanswerScore = 0\n\t\tfor result in a['webPages']['value']:\n\n\t\t\tname = result['name'].encode('ascii', 'ignore').decode('ascii')\n\t\t\tsnippet = result['snippet'].encode('ascii', 'ignore').decode('ascii')\n\n\t\t\tif answers.lower() in snippet.lower():\n\t\t\t\tanswerScore += 1\n\t\t\tif answers.lower() in name.lower():\n\t\t\t\tanswerScore += 1\n\n\n\n\n\treturn answerScore\n\n\ndef GoogleCheck(questionString, answers, keyword):\n\tapiKey = apiKeys['googleapi']\n\tcx = apiKeys['googlecx']\n\n\tquestionString = urllib.parse.quote_plus(questionString)\n\turlString = \"https://www.googleapis.com/customsearch/v1?q={}&cx={}&key={}\".format(questionString, cx, apiKey)\n\n\twith urllib.request.urlopen(urlString) as url:\n\t\tencJson = json.loads(url.read().decode())\n\n\tanswerScore = [0, 0, 0]\n\n\tif 'items' in encJson:\n\t\tfor result in encJson['items']:\n\t\t\ti = 0\n\t\t\twhile i < 3:\n\t\t\t\tif answers[i] in cleanResult(result['snippet']):\n\t\t\t\t\tanswerScore[i] += 1\n\t\t\t\tif answers[i] in cleanResult(result['title']):\n\t\t\t\t\tanswerScore[i] += 1\n\n\t\t\t\ti += 1\n\n\t\treturn answerScore\n\telse:\n\t\treturn ['Error', 'Error', 'Error']\n\n\ndef NegativeCheck(questionString, answers):\n\tpreNoun = ['for', 'are', 'an', 'a']\n\tqWords = questionString.split(' ')\n\tqLength = len(qWords)\n\n\tfor sep in preNoun:\n\t\tif sep in qWords:\n\t\t\tsIndex = qWords.index(sep)\n\t\t\tkeyword = qWords[sIndex + 1].replace('?', '')\n\n\ndef GetWikiScore(questionString, answer, keyword):\n\n\tkeyword = keyword.lower()\n\n\tpAnswer = urllib.parse.quote(answer)\n\n\turlString = \"https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch={}&utf8=\".format(\n\t\tpAnswer)\n\n\twith urllib.request.urlopen(urlString) as url:\n\t\twikiText = url.read().decode()\n\n\tencJson = encJson = json.loads(wikiText)\n\n\n\n\tif encJson['query']['searchinfo']['totalhits'] > 0:\n\t\twikiPageName = encJson['query']['search'][0]['title']\n\t\tpWikiName = urllib.parse.quote(wikiPageName)\n\t\turlString = \"https://en.wikipedia.org/w/api.php?action=query&titles={}&format=json&prop=revisions&rvprop=content&formatversion=2\".format(\n\t\t\tpWikiName)\n\n\t\twith urllib.request.urlopen(urlString) as url:\n\t\t\twikiContent = url.read().decode()\n\n\t\tencJson2 = json.loads(wikiContent)\n\n\t\ttext = cleanResult(encJson2['query']['pages'][0]['revisions'][0]['content'])\n\n\t\t# f = open('abc', 'w')\n\t\t# f.write(text.encode('ascii', 'ignore').decode('ascii'))\n\t\t# f.close()\n\n\t\treturn text.count(keyword)\n\n\telse:\n\t\treturn 0\n\ndef getLatest():\n\tlist_of_files = glob.glob('/home/david/Downloads/*')\n\tlatest_file = max(list_of_files, key=os.path.getctime)\n\treturn latest_file\n\n\ndef getText(file):\n\n\tim = Image.open(file)\n\n\tleft = 44\n\ttop = 310\n\twidth = 1000\n\theight = 1000\n\tbox = (left, top, left+width, top+height)\n\tim = im.crop(box)\n\n\tGrayImg = im.convert('L')\n\tBlackWhite = GrayImg.point(lambda x: 0 if x<220 else 255, '1')\n\n\tBlackWhite.save('testbw.jpg', 'jpeg')\n\n\ttext = ocrImage('testbw.jpg')\n\n\ttext2 = text.split('\\n')\n\n\tleng = len(text2)\n\n\ti = 0\n\tii = 0\n\n\tquestionString = ''\n\n\twhile i < leng:\n\t\tquestionString += text2[i]\n\t\tif('?' in text2[i]):\n\t\t\tii = i + 1\n\t\t\ti = leng\n\t\telse:\n\t\t\tquestionString += ' '\n\t\ti+=1\n\tquestionString = questionString.encode('ascii', 'ignore').decode('ascii')\n\n\tanswers = []\n\twhile ii < leng and len(answers) < 3:\n\t\tif len(text2[ii]) > 0 and \"prize\" not in text2[ii].encode('ascii', 'ignore').decode('ascii').lower():\n\t\t\tanswers.append(cleanResult(text2[ii].encode('ascii', 'ignore').decode('ascii')))\n\t\tii += 1\n\n\tdata = {}\n\tdata['questionString'] = questionString\n\tdata['answers'] = answers\n\n\treturn data\n\n\ncheck_types = {\n\t\"google\": GoogleCheck,\n\t\"bing\": BingCheck,\n\t# \"negative\": NegativeCheck,\n\t\"wiki\": GetWikiScore,\n\t\"wikipage\": GetWikiScore,\n}\n\ndef check_method(params):\n\tcheck_type, questionString, answers, keyword = params\n\tresult = { 'type' : check_type, 'answers' : answers, 'data' : check_types.get(check_type)(questionString, answers, keyword), 'keyword': keyword }\n\treturn result\n\n\ndef searchFor(data):\n\tos.system('clear')\n\tquestionString = data['questionString'].encode('ascii', 'ignore').decode('ascii')\n\tanswers = data['answers']\n\n\tchecks_to_run = check_types.keys()\n\tp = Pool(len(check_types.keys()))\n\n\tcheck_params = []\n\n\t\n\tprint(questionString)\n\tprint(answers[0])\n\tprint(answers[1])\n\tprint(answers[2])\n\n\tkeyword = input('keyword: ')\n\tsplitword = input('split word: ')\n\twikiPageSearch = input('wiki page search: ')\n\n\ti = 0\n\tif splitword: \n\t\twhile i <3:\n\t\t\tanswers[i] = answers[i].split(splitword)[0]\n\t\t\ti += 1\n\n\tfor check in checks_to_run:\n\t\tif check != 'wiki' and check != 'wikipage':\n\t\t\tcheck_params.append((check, questionString, answers, keyword))\n\n\tif keyword:\n\t\ti = 0\n\t\twhile i < 3:\n\t\t\tcheck_params.append(['wiki', questionString, answers[i], keyword])\n\t\t\ti += 1\n\n\tif wikiPageSearch:\n\t\ti = 0\n\t\twhile i < 3:\n\t\t\tcheck_params.append(['wikipage', questionString, wikiPageSearch, answers[i]])\n\t\t\ti += 1\n\n\tresult = p.map(check_method, check_params)\n\n\tPrintData(result)\n\n\n\n\ndef Go():\n\tos.system('adb shell screencap -p > image.png')\n\tsearchFor(getText('image.png'))\n\n\ndef PrintData(data):\n\n\twikiAnswers = {}\n\twikiPageAnswers = {}\n\n\tfor entry in data:\n\t\tif entry['type'] == 'google':\n\t\t\tanswers = entry['answers']\n\t\t\tgoogle = entry['data']\n\t\t\t# google\n\n\t\telif entry['type'] == 'bing':\n\t\t\tbing = entry['data']\n\n\t\telif entry['type'] == 'wiki':\n\t\t\twikiAnswers[entry['answers']] = entry['data']\n\t\t\t# wiki\n\n\t\telif entry['type'] == 'wikipage':\n\t\t\twikiPageAnswers[entry['keyword']] = entry['data']\n\n\t\n\tprint('--------Bing---------')\n\ti = 0\n\twhile i < 3:\n\t\tprint(answers[i] + \": \" + str(bing[i]))\n\t\ti += 1\n\n\tprint('')\n\n\n\tprint('--------Google---------')\n\ti = 0\n\twhile i < 3:\n\t\tprint(answers[i] + \": \" + str(google[i]))\n\t\ti += 1\n\n\n\tprint('')\n\t\n\tif wikiAnswers:\n\t\tprint('--------Wiki Keyword Check---------')\n\t\ti = 0\n\t\twhile i < 3:\n\t\t\tprint(answers[i] + \": \" + str(wikiAnswers[answers[i]]))\n\t\t\ti += 1\n\t\n\tif wikiPageAnswers:\n\t\tprint('------ Wiki Page Check ---------')\n\t\ti = 0\n\t\twhile i < 3:\n\t\t\tprint(answers[i] + \": \" + str(wikiPageAnswers[answers[i]]))\n\t\t\ti += 1\n\n\n\ndef encode_image(image_path, charset):\n\twith open(image_path, 'rb') as image:\n\t\tb64_img = base64.b64encode(image.read())\n\n\treturn b64_img.decode(charset)\n\n\ndef get_response(b64encoded_image):\n\treq_url = '/v1/images:annotate?key=' + apiKeys['googlevision']\n\n\treq_body = {\n\t \"requests\": [\n\t\t{\n\t\t \"image\": {\n\t\t\t\"content\": b64encoded_image\n\t\t },\n\t\t \"features\": [\n\t\t\t{\n\t\t\t \"type\": \"TEXT_DETECTION\"\n\t\t\t}\n\t\t ]\n\t\t}\n\t ]\n\t}\n\n\treq_headers = {\"Content-Type\": \"application/json; charset=utf-8\"}\n\n\n\thost = 'vision.googleapis.com'\n\n\tconn = http.client.HTTPSConnection(host)\n\t# query = urllib.parse.quote(search)\n\tconn.request(\"POST\", req_url, headers=req_headers, body=json.dumps(req_body))\n\tresponse = conn.getresponse()\n\n\treturn response\n\n\ndef ocrImage(local_image_path):\n\tbody = get_response(encode_image(local_image_path, 'ascii')).read().decode('utf-8').encode('ascii', 'ignore').decode('ascii')\n\n\ta = json.loads(body)\n\n\treturn a['responses'][0]['textAnnotations'][0]['description']","sub_path":"triviaBot.py","file_name":"triviaBot.py","file_ext":"py","file_size_in_byte":8375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"533343549","text":"import numpy as np\nfrom forcepho.likelihood import negative_lnlike_multistamp, make_image\nfrom forcepho.data import PostageStamp\nfrom forcepho import psf as pointspread\n\n\nclass Scene(object):\n \"\"\"The Scene holds the sources and provides the mapping between a giant 1-d\n array of parameters and the parameters of each source in each band/image\n \"\"\"\n\n filterloc = {'F090W': 0}\n\n def __init__(self, galaxy=False, nfilters=1):\n\n self.nfilters = nfilters\n if galaxy:\n self.nshape = 4 #ra, dec, q, pa\n self.use_gradients = slice(0, 5)\n else:\n self.nshape = 2 #ra, dec\n self.use_gradients = slice(0, 3)\n \n \n def param_indices(self, sourceid, filterid):\n \"\"\"Get the indices of the relevant parameters in the giant Theta\n vector, which is assumed to be\n [(fluxes_1), (shape_1), (fluxes_2), (shape_2), ..., (fluxes_n), (shape_n)]\n \n :returns theta:\n An array with elements [flux, (shape_params)]\n \"\"\"\n start = sourceid * (self.nshape + self.nfilters)\n # get all the shape parameters\n # TODO: nshape (and use_gradients) should probably be an attribute of the source\n inds = range(start + self.nfilters, start + self.nfilters + self.nshape)\n # put in the flux for this source in this band\n inds.insert(0, start + filterid)\n return inds\n\n def set_source_params(self, theta, source, filterid=None):\n \"\"\"Set the parameters of a source\n \"\"\"\n t = np.array(theta).copy()\n if len(t) == 3:\n # Star\n t = np.append(t, np.array([1., 0., 0., 0.]))\n elif len(t) == 5:\n # Galaxy\n t = np.append(np.array(t), np.array([0., 0.]))\n else:\n print(\"theta vector {} not a valid length: {}\".format(theta, len(theta)))\n flux, ra, dec, q, pa, sersic, rh = t\n # if allowing sources to hold the multiband fluxes you'd do this line\n # instead. Or something even smarter since probably want to update all\n # sources and fluxes at once.\n #source.flux[filterid] = flux\n source.flux = flux\n source.ra = ra\n source.dec = dec\n source.q = q\n source.pa = pa\n source.sersic = sersic\n source.rh = rh\n\n def set_params(self, Theta, filterid=0):\n \"\"\"Set all source parameters at once.\n \"\"\"\n for source in self.sources:\n inds = self.param_indices(source.id, filterid)\n print(inds)\n self.set_source_params(Theta[inds], source, filterid)\n\n\ndef negative_lnlike_stamp(theta, scene=None, stamp=None):\n nll, nll_grad = negative_lnlike_multistamp(theta, scene=scene, stamps=[stamp])\n return nll, nll_grad\n\n\ndef negative_lnlike_nograd(theta, scene=None, stamp=None):\n nll, nll_grad = negative_lnlike_multistamp(theta, scene=scene, stamps=[stamp])\n return nll\n\n\ndef chi_vector(theta, scene=None, stamp=None):\n stamp.residual = stamp.pixel_values.flatten()\n scene.set_params(theta)\n sources, thetas = scene.sources, scene.params\n residual, partials = model_image(thetas, sources, stamp)\n chi = residual * stamp.ierr\n return chi\n\n\ndef numerical_image_gradients(theta0, delta, scene=None, stamp=None):\n\n dI_dp = []\n for i, (p, dp) in enumerate(zip(theta0, delta)):\n theta = theta0.copy()\n imlo, _ = make_image(theta, scene, stamp)\n theta[i] += dp\n imhi, _ = make_image(theta, scene, stamp)\n dI_dp.append((imhi - imlo) / (dp))\n\n return np.array(dI_dp)\n\n \ndef make_stamp(size=(100, 100), fwhm=1.0, psfname=None, offset=0.):\n \"\"\"Make a postage stamp of the given size, including a PSF\n\n :param size:\n The size in pixels, 2-element tuple\n\n :param fwhm:\n For a single gaussian PSF, the FWHM of the PSF in pixels\n\n :param offset:\n The offset of the position of the object from the stamp center. Useful\n for playing with subpixel offsets.\n\n :param psfname:\n The path and filename of the gaussian mixture PSF parameters.\n \"\"\"\n\n # --- Get a stamp with a give size ----\n stamp = PostageStamp()\n size = np.array(size).astype(int)\n stamp.nx, stamp.ny = size\n stamp.npix = int(stamp.nx * stamp.ny)\n # note the inversion of x and y order in the meshgrid call here\n stamp.ypix, stamp.xpix = np.meshgrid(np.arange(stamp.ny), np.arange(stamp.nx))\n\n # --- Add WCS info to Stamp ---\n # override the WCS so coordinates are in pixels\n # The scale matrix D\n stamp.scale = np.eye(2)\n # The sky coordinates of the reference pixel\n stamp.crval = np.zeros([2]) + offset\n # The pixel coordinates of the reference pixel\n stamp.crpix = np.zeros([2])\n\n\n # --- Add the PSF ---\n if psfname is not None:\n import pickle\n with open(psfname, 'rb') as pf:\n pdat = pickle.load(pf)\n\n oversample, pcenter = 8, 504 - 400\n answer = pdat[6][2]\n stamp.psf = pointspread.make_psf(answer, oversample=oversample, center=pcenter)\n else:\n stamp.psf = pointspread.PointSpreadFunction()\n stamp.psf.covariances *= fwhm / 2.355\n \n # --- Add extra information ---\n #stamp.full_header = dict(hdr)\n \n return stamp\n","sub_path":"demo/demo_utils.py","file_name":"demo_utils.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587028619","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 29 09:20:28 2018\n\n@author: william\n\"\"\"\n\nimport obspy\nfrom obspy import read\nimport numpy as np\nfrom numpy import genfromtxt\nimport matplotlib.pyplot as plt\nfrom obspy import Stream\nfrom obspy.signal.trigger import classic_sta_lta, recursive_sta_lta\nfrom obspy.signal.trigger import plot_trigger, trigger_onset\nfrom obspy import UTCDateTime\n\n\n#%% import data\nstre = read(\"/Users/william/Documents/scanner/output_data/EXP_all_data_stream_month_1.mseed\")\nper_day = genfromtxt(\"/Users/william/Documents/scanner/all_stations/Explosions_per_day_v2.csv\", delimiter=',',skip_header=1,skip_footer=1)\ndata = genfromtxt(\"/Users/william/Documents/scanner/all_stations/EXP_all_coincidence_month_1.csv\", delimiter=',',skip_header=1)\n\n#%% Events per day and per week\nplt.figure(10001)\nplt.plot(per_day[:,1],per_day[:,0])\nplt.ylim([0,max(per_day[:,0])+10])\nplt.xlabel('Day Number')\nplt.ylabel('Number of Explosions')\nplt.title('Explosions per Day')\n\nepw=np.zeros(shape=(1,2))\nday=0\nweek=0\nnepw=0\nfor x in range(0,len(per_day)):\n nepw += per_day[x,0]\n day += 1\n if day == 7:\n epw[week][0] = nepw\n epw[week][1] = week\n week +=1\n day=0\n nepw=0\n if len(per_day)-x > 7:\n epw = np.lib.pad(epw, ((0,1),(0,0)), 'constant', constant_values=(0))\nplt.figure(10002)\nplt.plot(epw[:,1],epw[:,0])\nplt.ylim([0,max(epw[:,0])+50])\nplt.xlabel('Week Number')\nplt.ylabel('Number of Explosions')\nplt.title('Explosions per Week')\n#\n\n\n\n#%% \"Energy\" of each event\n\nevent_stream = Stream()\nevent_list=np.zeros(shape=(1,1))\nevent_count=0\n\nevent_stream.append(stre[0])\nevent_list[event_count]=stre[0].stats.starttime.timestamp\nevent_list = np.lib.pad(event_list, ((0,1),(0,0)), 'constant', constant_values=(0))\nevent_count +=1 \nfor x in range(1,len(stre)):\n if stre[x].stats.station == \"LB01\":\n event_stream.append(stre[x])\n event_list[event_count]=stre[x].stats.starttime.timestamp\n event_list = np.lib.pad(event_list, ((0,1),(0,0)), 'constant', constant_values=(0))\n event_count +=1 \n else:\n rt=stre[x].stats.starttime.timestamp\n near,ix=find_nearest(event_list[:,0], rt)\n if abs(near-rt) > 60:\n event_stream.append(stre[x])\n event_list[event_count]=stre[x].stats.starttime.timestamp\n event_list = np.lib.pad(event_list, ((0,1),(0,0)), 'constant', constant_values=(0))\n event_count +=1 \n\n\n#print(len(data_stream))\n\nsr = 100\nnsta=int(1*sr) \nnlta=int(10*sr) \ntrig_on=2.5 \ntrig_off=0.05\n\n#for x in range(0,len(data_stream)):\nfor x in range(0,10):\n data_s=event_stream[x].data\n max_a = data_s.max()\n min_a = data_s.min()\n p2p= max_a-min_a\n cft=recursive_sta_lta(data_s, nsta, nlta)\n# plot_trigger(sq_stream[x], cft, trig_on, trig_off) \n on_off = trigger_onset(cft,trig_on,trig_off) \n start = event_stream[x].stats.starttime\n tr = event_stream[x].slice(starttime=start+(on_off[0,0]/sr) , endtime=start+(on_off[0,1]/sr)) \n print('event:',event_stream[x].stats.starttime ,'from station: ',stre[x].stats.station,', has energy: ',sum(np.square(tr.data)),' and peak to peak:', p2p)\n plt.figure(x)\n plt.plot(tr) \n plt.figure(x+20)\n plt.plot(np.square(tr.data)) \n \n#%% energy information\n \n \nday_one = 1416787200.0\nday_energy=0\nday_count=0\ne_count=0\ndays=0\nenergy_each_event = av_energy_list =np.zeros(shape=(1,1))\nav_energy_list =np.zeros(shape=(1,1))\ntotal_energy_list =np.zeros(shape=(1,1))\n\nfor x in range(0,len(per_day)):#len(per_day)\n day_start = day_one + x*24*60*60\n day_end = day_start + 24*60*60 - 0.01\n# print(UTCDateTime(day_start),' to', UTCDateTime(day_end))\n for p in range(0,len(event_stream)):\n if day_start < event_stream[p].stats.starttime.timestamp < day_end :\n # ADD IN CALIBRATIONS ########################################################\n day_count += 1\n data_s=event_stream[p].data\n max_a = data_s.max()\n min_a = data_s.min()\n p2p= max_a-min_a\n cft=recursive_sta_lta(data_s, nsta, nlta)\n # plot_trigger(sq_stream[x], cft, trig_on, trig_off) \n on_off = trigger_onset(cft,trig_on,trig_off) \n start = event_stream[p].stats.starttime\n tr = event_stream[p].slice(starttime=start+(on_off[0,0]/sr) , endtime=start+(on_off[0,1]/sr)) \n event_energy = sum(np.square(tr.data))\n day_energy += event_energy\n# print('event:',event_stream[p].stats.starttime ,'station: ',event_stream[p].stats.station,', energy: ',event_energy,', peak to peak:', p2p)\n energy_each_event[e_count] = event_energy\n energy_each_event = np.lib.pad(energy_each_event, ((0,1),(0,0)), 'constant', constant_values=(0))\n e_count += 1\n \n# if event_energy > 1e16:\n# tr.plot()\n \n print('total energy in the day:',UTCDateTime(day_start),'=', day_energy)\n av_day_energy = day_energy/day_count\n print('average energy in day:',UTCDateTime(day_start),'=', av_day_energy)\n \n av_energy_list[days]= av_day_energy\n total_energy_list[days] = day_energy \n av_energy_list = np.lib.pad(av_energy_list, ((0,1),(0,0)), 'constant', constant_values=(0))\n total_energy_list = np.lib.pad(total_energy_list, ((0,1),(0,0)), 'constant', constant_values=(0))\n day_count = 0\n day_energy=0\n days += 1\n \n \n\n\nplt.figure(2001)\nplt.plot(av_energy_list)\n\nplt.figure(2002)\nplt.plot(total_energy_list)\n\nplt.figure(2003)\nplt.plot(energy_each_event)\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":"size_and_occurance.py","file_name":"size_and_occurance.py","file_ext":"py","file_size_in_byte":5866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"341188532","text":"\n\nfrom xai.brain.wordbase.nouns._thinner import _THINNER\n\n#calss header\nclass _THINNERS(_THINNER, ):\n\tdef __init__(self,): \n\t\t_THINNER.__init__(self)\n\t\tself.name = \"THINNERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"thinner\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_thinners.py","file_name":"_thinners.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347235742","text":"import sys\nimport os\npath = os.path.dirname(os.path.realpath(__file__)) # path to this directory\nsys.path.append(os.path.abspath(path + \"/../..\"))\n\nimport numpy as np\nfrom envs.cartpole import CartPoleEnv\nfrom approximators.mlp import MLPQFunction\nfrom operators.mellow import MellowBellmanOperator\nfrom algorithms.nt import learn\nfrom misc import utils\nimport argparse\nfrom joblib import Parallel, delayed\nimport datetime\n\n# Global parameters\nrender = False\nverbose = True\n\n# Command line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--kappa\", default=100.)\nparser.add_argument(\"--xi\", default=0.5)\nparser.add_argument(\"--tau\", default=0.0)\nparser.add_argument(\"--batch_size\", default=50)\nparser.add_argument(\"--max_iter\", default=5000)\nparser.add_argument(\"--buffer_size\", default=10000)\nparser.add_argument(\"--random_episodes\", default=0)\nparser.add_argument(\"--exploration_fraction\", default=0.2)\nparser.add_argument(\"--eps_start\", default=1.0)\nparser.add_argument(\"--eps_end\", default=0.02)\nparser.add_argument(\"--train_freq\", default=1)\nparser.add_argument(\"--eval_freq\", default=100)\nparser.add_argument(\"--mean_episodes\", default=20)\nparser.add_argument(\"--l1\", default=32)\nparser.add_argument(\"--l2\", default=0)\nparser.add_argument(\"--alpha\", default=0.001)\nparser.add_argument(\"--env\", default=\"cartpole\")\n# Cartpole parameters (default = randomize)\nparser.add_argument(\"--cart_mass\", default=-1)\nparser.add_argument(\"--pole_mass\", default=-1)\nparser.add_argument(\"--pole_length\", default=-1)\nparser.add_argument(\"--n_jobs\", default=1)\nparser.add_argument(\"--n_runs\", default=1)\nparser.add_argument(\"--file_name\", default=\"nt_{}\".format(datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")))\n\n# Read arguments\nargs = parser.parse_args()\nkappa = float(args.kappa)\nxi = float(args.xi)\ntau = float(args.tau)\nbatch_size = int(args.batch_size)\nmax_iter = int(args.max_iter)\nbuffer_size = int(args.buffer_size)\nrandom_episodes = int(args.random_episodes)\nexploration_fraction = float(args.exploration_fraction)\neps_start = float(args.eps_start)\neps_end = float(args.eps_end)\ntrain_freq = int(args.train_freq)\neval_freq = int(args.eval_freq)\nmean_episodes = int(args.mean_episodes)\nl1 = int(args.l1)\nl2 = int(args.l2)\nalpha = float(args.alpha)\nenv = str(args.env)\ncart_mass = float(args.cart_mass)\npole_mass = float(args.pole_mass)\npole_length = float(args.pole_length)\nn_jobs = int(args.n_jobs)\nn_runs = int(args.n_runs)\nfile_name = str(args.file_name)\n\n# Seed to get reproducible results\nnp.random.seed(485)\n\n# Generate tasks\nmc = [np.random.uniform(0.5, 1.5) if cart_mass < 0 else cart_mass for _ in range(n_runs)]\nmp = [np.random.uniform(0.1, 0.2) if pole_mass < 0 else pole_mass for _ in range(n_runs)]\nl = [np.random.uniform(0.2, 0.8) if pole_length < 0 else pole_length for _ in range(n_runs)]\nmdps = [CartPoleEnv(a,b,c) for a,b,c in zip(mc,mp,l)]\nn_eval_episodes = 5\n\nstate_dim = mdps[0].state_dim\naction_dim = 1\nn_actions = mdps[0].action_space.n\n\n# Create BellmanOperator\noperator = MellowBellmanOperator(kappa, tau, xi, mdps[0].gamma, state_dim, action_dim)\n# Create Q Function\nlayers = [l1]\nif l2 > 0:\n layers.append(l2)\nQ = MLPQFunction(state_dim, n_actions, layers=layers)\n\n\ndef run(mdp, seed=None):\n return learn(mdp,\n Q,\n operator,\n max_iter=max_iter,\n buffer_size=buffer_size,\n batch_size=batch_size,\n alpha=alpha,\n train_freq=train_freq,\n eval_freq=eval_freq,\n eps_start=eps_start,\n eps_end=eps_end,\n exploration_fraction=exploration_fraction,\n random_episodes=random_episodes,\n eval_episodes=n_eval_episodes,\n mean_episodes=mean_episodes,\n seed=seed,\n render=render,\n verbose=verbose)\n\n\nseeds = [9, 44, 404, 240, 259, 141, 371, 794, 41, 507, 819, 959, 829, 558, 638, 127, 672, 4, 635, 687]\nseeds = seeds[:n_runs]\nif n_jobs == 1:\n results = [run(mdp,seed) for (mdp,seed) in zip(mdps,seeds)]\nelif n_jobs > 1:\n results = Parallel(n_jobs=n_jobs)(delayed(run)(mdp,seed) for (mdp,seed) in zip(mdps,seeds))\n\nutils.save_object(results, file_name)\n","sub_path":"experiments/cartpole/run_nt.py","file_name":"run_nt.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432269951","text":"import pytest\nimport logging\nfrom dateutil.parser import ParserError\nfrom datetime import datetime\nfrom importers.common.helpers import _date_parser\nfrom importers.common.keywords_extracted import _trim_location, _create_employer_name_keywords, add_keywords_extracted\nfrom importers.platsannons import converter\n\nlog = logging.getLogger(__name__)\ncurrent_year = datetime.now().strftime('%Y')\ncurrent_month = datetime.now().strftime('%m')\ncurrent_day = datetime.now().strftime('%d')\n\n\n@pytest.mark.unit\n@pytest.mark.parametrize(\"input_date, expected_result, expected_error\",\n [('180924-00:00', '2024-09-18T00:00:00', None),\n ('20180924T', '2018-09-24T00:00:00', None),\n ('mon sep 24', f'{current_year}-09-24T00:00:00', None),\n ('sep 24', f'{current_year}-09-24T00:00:00', None),\n ('24', f'{current_year}-{current_month}-24T00:00:00', None),\n ('00:00:00', f'{current_year}-{current_month}-{current_day}T00:00:00',\n None),\n ('20180101f', None, ParserError),\n ('2099-13-32', None, ParserError),\n ('18-09-24:01:01', None, ParserError),\n (' ', None, ParserError),\n (None, None, TypeError),\n ([' '], None, TypeError),\n ([], None, TypeError),\n ({}, None, TypeError),\n ('XYZ', None, ParserError)\n ])\ndef test_date_conversion(input_date, expected_result, expected_error):\n import dateutil\n try:\n converted_date = _date_parser(input_date)\n except dateutil.parser.ParserError as e:\n if expected_error == type(e):\n return\n else:\n raise e\n except TypeError as e:\n if expected_error == type(e):\n return\n else:\n raise e\n else:\n assert converted_date == expected_result\n\n\n@pytest.mark.unit\n@pytest.mark.parametrize(\"location, expected\", [(\"Solna\", \"solna\"),\n (\"Upplands Väsby\", \"upplands väsby\"),\n (\"Upplands-Bro\", \"upplands-bro\"),\n (\"Malmö (huvudkontor)\", \"malmö\"),\n (\"12345 Danderyd\", \"danderyd\"),\n (\"34-5 Sundsvall\", \"sundsvall\"),\n (\"34-5 Sundsvall\", \"sundsvall\"),\n (\"Stockholm 8\", \"stockholm\"),\n (\"Gävle (avd.8)\", \"gävle\"),\n (\"Gävle (avd. 8)\", \"gävle\"),\n (\"Liljeholmen ()\", \"liljeholmen\"),\n (\"dk-5000 odense\", \"odense\"),\n (\"d02 r299 dublin\", \"dublin\"),\n (\"02d 299r dublin\", \"dublin\"),\n (\"campanillas, málaga\", \"málaga\"),\n (\"box 215, se-251 helsingborg\",\n \"helsingborg\"),\n (\"bromma stockholm\", \"bromma stockholm\"),\n ])\ndef test_trim_location(location, expected):\n assert _trim_location(location) == expected\n\n\n@pytest.mark.unit\n@pytest.mark.parametrize(\"employer, expected\", [([\"Logopedbyrån Dynamica AB\",\n \"Logopedbyrån Dynamica Stockholm AB\"],\n [\"logopedbyrån dynamica\"]),\n ([\"Logopedbyrån Dynamica Stockholm AB\",\n \"AB Logopedbyrån Dynamica\"],\n [\"logopedbyrån dynamica\"]),\n ([\"AB Foo\", \"Foo\"], [\"foo\"]),\n ([\" AB Foo\", \"AB Foo\"], [\"foo\"]),\n ([\"Foo Bar AB\", \"Foo Bar\"], [\"foo bar\"]),\n ([\" Foo Bar AB\"], [\"foo bar\"]),\n ([\" Foo Bar AB \"], [\"foo bar\"]),\n ([\"Fazer AB\", \"Gateau\"],\n [\"fazer\", \"gateau\"]),\n ([\"Fazer Stockholm AB\", \"Gateau\"],\n [\"gateau\", \"fazer stockholm\"]),\n ([\"Fazer Stockholm AB\", \"Gateau\", \"Foo\"],\n [\"foo\", \"gateau\", \"fazer stockholm\"]),\n ([\"Fazer Stockholm AB\", \"Gateau\",\n \"Gateau\"],\n [\"gateau\", \"fazer stockholm\"]),\n (None, [])\n ])\ndef test_create_employer_name(employer, expected):\n assert _create_employer_name_keywords(employer) == expected\n\n\n@pytest.mark.unit\n@pytest.mark.parametrize(\"fake_ad, expected_location_count, expected_locations, \\\n expected_employer_count, expected_employers\",\n [\n ({\n \"workplace_address\": {\n \"city\": \"Stockholm\",\n \"municipality\": \"Stockholm\",\n \"region\": \"Stockholms län\",\n \"country\": \"Sverige\"\n },\n \"employer\": {\n \"name\": \"TestByrån Obfuscatica Stockholm AB\",\n \"workplace\": \"TestByrån Obfuscatica AB\"\n }\n }, 3, ['stockholm', 'stockholms län', 'sverige'],\n 1, ['testbyrån obfuscatica']),\n ({\n \"workplace_address\": {\n \"city\": \"\",\n \"municipality\": \"Stockholm\",\n \"region\": \"Stockholms län\",\n \"country\": \"Sverige\"\n },\n \"employer\": {\n \"name\": \"TestByrån Obfuscatica Stockholm AB\",\n \"workplace\": \"AB TestByrån Obfuscatica\"\n }\n }, 3, ['stockholm', 'stockholms län', 'sverige'],\n 1, ['testbyrån obfuscatica']),\n ])\ndef test_extract_keywords(fake_ad, expected_location_count, expected_locations,\n expected_employer_count, expected_employers):\n enriched_ad = add_keywords_extracted(fake_ad)\n\n for location in expected_locations:\n assert location in enriched_ad['keywords']['extracted']['location']\n assert len(enriched_ad['keywords']['extracted']['location']) == expected_location_count\n\n for employer in expected_employers:\n assert employer in enriched_ad['keywords']['extracted']['employer']\n assert len(enriched_ad['keywords']['extracted']['employer']) == expected_employer_count\n\n\n@pytest.mark.parametrize('annons, expected_error', [([], AttributeError),\n (None, TypeError),\n ('', AttributeError)\n ])\ndef test_converter_error(annons, expected_error):\n with pytest.raises(expected_error):\n converter.convert_ad(annons)\n\n\ndef test_set_occupations_empty():\n annons = {}\n with pytest.raises(KeyError):\n converter._set_occupations(annons, {})\n\n\n@pytest.mark.parametrize(\"annons\", [{\"id\": 23483261}])\n@pytest.mark.parametrize(\"message\", [{\"annonsId\": 23483261, \"NOT_yrkesroll\": {\"värde\": \"no_roll\"}}])\ndef test_set_occupations(annons, message):\n converter._set_occupations(annons, message)\n assert annons['id'] == message['annonsId']\n\n","sub_path":"tests/unit_tests/test_converter.py","file_name":"test_converter.py","file_ext":"py","file_size_in_byte":8751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"227168613","text":"import re\nfrom functools import wraps\n\n\nfrom flask import jsonify, request\nimport connexion\n# from flask_jwt_extended import get_jwt_identity\nimport jwt\n\nfrom application.models.account import AccountPost # noqa: E501\nimport application.exceptions as exceptions\n\nfrom application.db.mongo import MongoWrappers\nfrom application.db.models import AccountModel, UserModel\n\ndef token_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = None\n\n if 'x-access-token' in request.headers:\n token = request.headers['x-access-token']\n print(token)\n\n if not token:\n return jsonify({'message' : 'Token is missing!'}), 401\n\n try: \n data = jwt.decode(token, \"a123B456cC@!#123\")\n spec = {\n UserModel.Attr.username: data['username']\n }\n print('spec: ', spec)\n user_collection = MongoWrappers(UserModel.db, UserModel.table_name)\n current_user = user_collection.find_one(spec=spec)\n print('current_user: ', current_user)\n except:\n return jsonify({'message' : 'Token is invalid!'}), 401\n\n return f(current_user,*args, **kwargs)\n\n return decorated\n\n\n\ndef get_account_list(_size=None, _from=None, _counting=None, _sort=None, name=None):\n\n\n # Collection\n account_collection = MongoWrappers(AccountModel.db, AccountModel.table_name)\n\n # query\n _filter = {}\n\n if not name is None:\n columns = [\"account_number\", \"firstname\", \"lastname\", \"gender\", \"age\", \"email\", \"address\", \"city\", \"state\",\n \"employer\", \"balance\"]\n _filter = {}\n # the term put into search is logically concatenated with 'or' between all columns\n and_filter_on_all_columns = []\n for i in range(len(columns)):\n column_filter = {}\n if i == 0 or i == 4 or i == 10:\n try:\n column_filter[columns[i]] = int(name)\n except ValueError:\n continue\n else:\n column_filter[columns[i]] = {'$regex': name, '$options': 'i'}\n and_filter_on_all_columns.append(column_filter)\n if len(and_filter_on_all_columns) > 0:\n _filter['$or'] = and_filter_on_all_columns\n if not _from:\n _from = 0\n\n if not _size or _size < 0:\n _size = 10\n\n if _size > 100:\n _size = 100\n\n sort = AccountModel.bin_sort(AccountModel, _sort)\n fields = {'_id': False}\n results = account_collection.find(spec=_filter, fields=fields, limit=_size, skip=_from, sort=sort)\n count = 0\n\n if _counting:\n count = results.count()\n\n ret = {\n 'code': 200,\n 'data': [],\n 'count': count\n }\n\n for r in results:\n ret['data'].append(r)\n\n return jsonify(ret)\n\n\ndef get_one_account(account_number):\n\n _filter = {'account_number': account_number}\n fields = {'_id': False}\n\n account_collection = MongoWrappers(AccountModel.db, AccountModel.table_name)\n results = account_collection.find_one(spec=_filter, fields=fields)\n\n if results is None:\n ret = {\n 'code': 400,\n 'data': \"account not found\",\n }\n else:\n ret = {\n 'code': 200,\n 'data': results,\n }\n\n return jsonify(ret)\n\n@token_required\ndef create_one_account(current_user, person):\n\n if current_user['roles'] != 'admin':\n return jsonify({'failed': 'wrong permission'})\n\n account_collection = MongoWrappers(AccountModel.db, AccountModel.table_name)\n account_number = person.get('account_number')\n _filter = {'account_number': account_number}\n results = account_collection.find_one(spec=_filter)\n\n if results is not None:\n ret = {\n 'code': 400,\n 'data': \"account exists!\",\n }\n return jsonify(ret)\n\n person_info = {\n 'account_number': person.get('account_number'),\n 'firstname': person.get('firstname'),\n 'lastname': person.get('lastname'),\n 'gender': person.get('gender'),\n 'age': person.get('age'),\n 'email': person.get('email'),\n 'address': person.get('address'),\n 'city': person.get('city'),\n 'state': person.get('state'),\n 'employer': person.get('employer'),\n 'balance': person.get('balance')\n }\n _result = account_collection.insert(**person_info)\n new_account = account_collection.find_one(\n spec={'_id': _result}\n )\n\n ret = {\n 'code': 200,\n 'inserted_info': {\n 'account_number': new_account.get('account_number'),\n 'firstname': new_account.get('firstname'),\n 'lastname': new_account.get('lastname'),\n 'gender': new_account.get('gender'),\n 'age': new_account.get('age'),\n 'email': new_account.get('email'),\n 'address': new_account.get('address'),\n 'city': new_account.get('city'),\n 'state': new_account.get('state'),\n 'employer': new_account.get('employer'),\n 'balance': new_account.get('balance')\n }\n }\n return jsonify(ret)\n\n@token_required\ndef update_one_account(current_user, account_number, person):\n\n if current_user['roles'] != 'admin':\n return jsonify({'failed': 'wrong permission'})\n\n # spec, set_doc=None\n _filter = {'account_number': account_number}\n fields = {'_id': False}\n\n account_collection = MongoWrappers(AccountModel.db, AccountModel.table_name)\n _sample = account_collection.find_one(spec=_filter, fields=fields)\n\n if _sample is None:\n ret = {\n 'code': 400,\n 'data': \"account not found\",\n }\n return jsonify(ret)\n else:\n person_info = {\n 'account_number': person.get('account_number'),\n 'firstname': person.get('firstname'),\n 'lastname': person.get('lastname'),\n 'gender': person.get('gender'),\n 'age': person.get('age'),\n 'email': person.get('email'),\n 'address': person.get('address'),\n 'city': person.get('city'),\n 'state': person.get('state'),\n 'employer': person.get('employer'),\n 'balance': person.get('balance')\n }\n account_collection.update(spec=_filter, set_doc=person_info)\n ret = {\n 'code': 200,\n 'data': \"update success\",\n }\n return jsonify(ret)\n\n@token_required\ndef delete_one_account(current_user, account_number):\n\n if current_user['roles'] != 'admin':\n return jsonify({'failed': 'wrong permission'})\n\n _filter = {'account_number': account_number}\n fields = {'_id': False}\n\n account_collection = MongoWrappers(AccountModel.db, AccountModel.table_name)\n _sample = account_collection.find_one(spec=_filter, fields=fields)\n\n if _sample is None:\n ret = {\n 'code': 400,\n 'data': \"account not found\",\n }\n return jsonify(ret)\n else:\n account_collection.remove(spec=_filter)\n ret = {\n 'code': 200,\n 'data': \"delete success\",\n }\n return jsonify(ret)","sub_path":"backend/application/controllers/account_controller.py","file_name":"account_controller.py","file_ext":"py","file_size_in_byte":7219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11993937","text":"from __future__ import annotations\nfrom snapflow.storage.data_formats.records import RecordsFormat\nfrom snapflow.core.execution import RunContext\nfrom snapflow.storage.data_records import as_records\nfrom snapflow.storage.data_formats.database_table import DatabaseTableFormat\nfrom snapflow.storage.db.utils import get_tmp_sqlite_db_url\nfrom snapflow.core import data_block\n\nfrom snapflow.core.data_block import DataBlockMetadata, StoredDataBlockMetadata, get_datablock_id\nfrom snapflow.core.graph import Graph\nfrom snapflow.core.node import DataBlockLog, Direction, PipeLog\nfrom snapflow.core.operators import filter, latest, operator\nfrom snapflow.core.streams import DataBlockStream, StreamBuilder\nfrom tests.utils import (\n TestSchema1, TestSchema2, TestSchema3, make_test_env, make_test_run_context,\n pipe_generic,\n pipe_t1_sink,\n pipe_t1_source,\n pipe_t1_to_t2,\n)\n\ndef test_data_block_methods():\n env = make_test_env()\n db = DataBlockMetadata(\n id=get_datablock_id(),\n inferred_schema_key=\"_test.TestSchema1\",\n nominal_schema_key=\"_test.TestSchema2\",\n realized_schema_key=\"_test.TestSchema3\",\n )\n strg = env.get_default_local_python_storage()\n records = [{\"a\":1}]\n mdr = as_records(records)\n sdb = StoredDataBlockMetadata(\n id=get_datablock_id(),\n data_block_id=db.id,\n data_block=db,\n storage_url=strg.url,\n data_format=RecordsFormat,\n )\n with env.session_scope() as sess:\n sess.add(db)\n sess.add(sdb)\n assert sdb.name is None\n name = sdb.get_name()\n assert len(name) > 10\n assert sdb.name == name\n strg.get_api().put(sdb.name, mdr)\n assert db.inferred_schema(env, sess) == TestSchema1\n assert db.nominal_schema(env, sess) == TestSchema2\n assert db.realized_schema(env, sess) == TestSchema3\n db.compute_record_count()\n assert db.record_count == 1","sub_path":"tests/test_data_block.py","file_name":"test_data_block.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"647215000","text":"\"\"\"This file is a ERecruit_Sub spider created on top of the ERecruit Spider.\n\n scrapy crawl erecruit_sub -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://erecruit.jarden.com/psc/erecruit/EMPLOYEE/HRMS/c/HRS_HRAM.HRS_CE.GBL\"\n scrapy crawl erecruit_sub -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://erecruit.sandvik.com/psc/sandvik/EMPLOYEE/HRMS/c/HRS_HRAM.HRS_CE.GBL\"\n\nsample urls:\n \"https://erecruit.jarden.com/psc/erecruit/EMPLOYEE/HRMS/c/HRS_HRAM.HRS_CE.GBL\"\n\"\"\"\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import FormRequest\n\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin\nfrom brightcorp.base.atsspiders import ATSSpider\n\n\nclass ERecruitSub(ATSSpider):\n\n name = 'erecruit_sub'\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath('//tr[contains(@id, \"trHRS_CE_JO_EXT_I$0_row\")]/td/div/span[@class=\"PSHYPERLINK\"]/a/@id').extract()\n if not self.expected_job_count_set:\n self.expected_job_count = len(jobs)\n for job in jobs:\n yield FormRequest(\n callback=self.parse_job_callback(),\n formdata={\n 'ICType': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICType\"]/@value').extract()[0],\n 'ICElementNum': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICElementNum\"]/@value').extract()[0],\n 'ICStateNum': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICStateNum\"]/@value').extract()[0],\n 'ICAction': job,\n 'ICXPos': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICXPos\"]/@value').extract()[0],\n 'ICYPos': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICYPos\"]/@value').extract()[0],\n 'ResponsetoDiffFrame': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ResponsetoDiffFrame\"]/@value').extract()[0],\n 'TargetFrameName': sel.xpath('//form[@name=\"win0\"]/input[@name=\"TargetFrameName\"]/@value').extract()[0],\n 'ICFocus': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICFocus\"]/@value').extract()[0],\n 'ICSaveWarningFilter': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICSaveWarningFilter\"]/@value').extract()[0],\n 'ICChanged': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICChanged\"]/@value').extract()[0],\n 'ICResubmit': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICResubmit\"]/@value').extract()[0],\n 'ICSID': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICSID\"]/@value').extract()[0],\n 'ICModalWidget': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICModalWidget\"]/@value').extract()[0],\n 'ICZoomGrid': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICZoomGrid\"]/@value').extract()[0],\n 'ICZoomGridRt': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICZoomGridRt\"]/@value').extract()[0],\n 'ICModalLongClosed': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICModalLongClosed\"]/@value').extract()[0],\n 'ICActionPrompt': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICActionPrompt\"]/@value').extract()[0],\n 'ICFind': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICFind\"]/@value').extract()[0],\n 'ICAddCount': sel.xpath('//form[@name=\"win0\"]/input[@name=\"ICAddCount\"]/@value').extract()[0],\n 'HRS_CE_JO_EXT_I$hnewpers$0': sel.xpath('//form[@name=\"win0\"]/input[@name=\"HRS_CE_JO_EXT_I$hnewpers$0\"]/@value').extract()[0],\n },\n url=response.url\n )\n\n def parse_job(self, response):\n selector = Selector(response)\n loader = BrightcorpItemLoader(selector=selector)\n loader.add_xpath(\n 'description',\n '//tr/td/div[contains(@id, \"win0div$ICField25\")]//text()[following::*[contains(text(), \"Responsibilities\") or contains(text(), \"RESPONSIBILITIES\")]]',\n NormalizedJoin())\n if not loader.get_output_value('description'):\n loader.add_xpath(\n 'description',\n '//tr/td/div[contains(@id, \"win0div$ICField25\")]//text()[following::*[contains(text(), \"QUALIFICATIONS\")]]')\n\n loader.add_xpath(\n 'jobtype',\n '//tr/td/div[contains(@id, \"WRK2_HRS_REG_TEMP\")]/span/text()')\n\n loader.add_xpath(\n 'location',\n '//tr/td//child::node()[contains(text(), \"Location\")]/following::td//span[contains(@id, \"JO_LCTN\")]/text()')\n\n loader.add_xpath(\n 'qualifications',\n '//*[contains(text(), \"Qualifications\") or contains(text(), \"QUALIFICATIONS\")]/following::*[1]//text()[not(contains(., \"\\r\\n\"))]',\n NormalizedJoin())\n\n loader.add_xpath(\n 'referencenumber',\n '//tr/td//child::node()[contains(text(), \"Job ID\")]/following::td//span[contains(@id, \"OPENING_ID\")]/text()',\n Prefix('%s-' % self.name))\n\n loader.add_xpath(\n 'responsibilities',\n '//*[contains(text(), \"Responsibilities\") or contains(text(), \"RESPONSIBILITIES\")]/following::*[1]//text()[not(contains(., \"\\r\\n\"))]',\n NormalizedJoin())\n\n loader.add_xpath(\n 'title',\n '//tr/td//child::node()[contains(text(), \"Job Title\")]/following::td//span[contains(@id, \"POSTING_TITLE\")]/text()')\n\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/erecruit_sub.py","file_name":"erecruit_sub.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323704985","text":"# Large Shirts: Modify the make_shirt() function so that shirts are\n# large by default with a message that reads I love Python. Make a large\n# shirt and a medium shirt with the default message, and a shirt of any\n# size with a different message.\n\ndef make_shirt(size = 'l', text = 'I love Python'):\n \"\"\"Display information about the size and text on the t-shirt.\"\"\"\n print(\"\\nI want a size \" + size.upper() + \" t-shirt.\")\n print(\"The text should read: \" + text + \".\")\n\nmake_shirt()\n\nmake_shirt('xxl', 'Man Utd')\n\nmake_shirt(text = 'Forza Juve', size = 'm')","sub_path":"Chapter 8 - Functions/large_shirt.py","file_name":"large_shirt.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"379609338","text":"from collections import defaultdict, Counter\nfrom pprint import pprint\n\nimport pandas as pd\n\nfrom count_incidents import count_borough_incidents, count_zip_incidents\nfrom util import clean_string, verify_clean_zip, string_similarity, get_jsons_list, attempt_borough_from_zip, \\\n\tdownload_jsons\n\n\ndef json_url_to_dataframe():\n\tdfs = []\n\tjson_files = get_jsons_list()\n\tprint(\"One moment please - master dataframe is being constructed.\\n\")\n\t# Iterate JSONs into dataframes and append into list\n\tfor file in json_files:\n\t\tdataframe = pd.read_json(file, orient=\"columns\", dtype={'incident_zip': int}) # Help to ensure int for zip\n\t\tdfs.append(dataframe)\n\n\t# Dataframes from the list concat'd into one\n\tdataframe = pd.concat(dfs)\n\tdataframe = pd.DataFrame.from_records(dataframe)\n\tprint(\"Shape of df: \", dataframe.shape)\n\treturn dataframe\n\n\n# Helper function for option 5 (dev)\ndef handle_similarity_debug( set_tmp ):\n\tif len(set_tmp) > 0:\n\t\tstring_similarity(set_tmp)\n\n\n# Primary counting logic of the user's chosen attribute.\ndef counter_processing( dataframe, is_zip_root, sanitize_dev=False ):\n\tword_set_diff = set() # Used for storing words/phrases to later be similarilty checked\n\td = dataframe\n\n\t# Dict to aggregate counts\n\tnested_dict = defaultdict(Counter)\n\n\tcross_ref_fix = 0 # Option 2 related only, cross-ref counter\n\n\t# Primary loop to locate, and increment. Cleanse functions are used here.\n\tfor row in range(len(d)):\n\n\t\t# Yank\n\t\tzip = d.loc[row, 'incident_zip']\n\t\tcomplaint = d.loc[row, 'complaint_type']\n\t\tborough = d.loc[row, 'borough']\n\n\t\t# Clean\n\t\tzip = verify_clean_zip(zip)\n\t\tcomplaint = clean_string(complaint)\n\t\tborough = clean_string(borough)\n\n\t\t# Dev - String Similarity sets\n\t\tword_set_diff.add(borough)\n\t\tword_set_diff.add(complaint)\n\n\t\tprint(borough, \" - \", complaint, \" - \", zip) # Raw print as rows iterate\n\n\t\tif (is_zip_root): # Option 1 at menu (Zip is parent/root)\n\t\t\tnested_dict[zip][complaint] += 1\n\t\telif ('unspecified' not in borough): # Option 2 always - with unspecified check\n\t\t\tnested_dict[borough][complaint] += 1\n\t\telif (\"unspecified\" in borough and zip is not None): # Option 2 but bad borough string\n\t\t\tprint(borough, zip)\n\t\t\tif attempt_borough_from_zip(zip):\n\t\t\t\tborough = attempt_borough_from_zip(zip) # Attempting cross reference to find borough\n\t\t\t\tif borough:\n\t\t\t\t\tcross_ref_fix += 1\n\t\t\t\t\tnested_dict[clean_string(borough)][complaint] += 1 # Success on cross reference!\n\t\t\telse:\n\t\t\t\tprint(\"No Cross Reference Found\")\n\n\tprint(\"\\n\" * 5, \" -------- \\n\")\n\tpprint(dict(nested_dict)) # Print out final structure\n\tif (not is_zip_root):\n\t\tprint(\"FIXED CROSS REFERENCED:\", cross_ref_fix)\n\t# Kicks off fuzzy-wuzzy checking (Option 5)\n\tif sanitize_dev:\n\t\tprint(\"\\n\\n-- FUZZY CHECKING --\")\n\t\thandle_similarity_debug(word_set_diff)\n\n\n# Start the program and menu system, main call\nif __name__ == \"__main__\":\n\tis_zip_root = None\n\tprint(\"\\n---Written by Alan Steinberg---\\n\")\n\n\t# Dataframe being generated from the numerous JSONs to be passed throughout\n\n\tdf = json_url_to_dataframe()\n\n\twhile (True):\n\t\tprint(\"\\n1. Aggregate incidents per zip code\")\n\t\tprint(\"2. Aggregate incidents per boroughs\")\n\t\tprint(\"3. Analyze incidents per 10k capita by zip\")\n\t\tprint(\"4. Analyze incidents per 10k capita by Borough\")\n\t\tprint(\"5. (DEV) - String Similarity Comparison FuzzyWuzzy\")\n\t\tprint(\"6. (DEV) - Force JSON download\")\n\n\t\tkb_user = input(\"Enter Choice: \").lower().strip() # Menu needs some cleaning up, too much redundnacy.\n\t\tif (kb_user == \"1\"):\n\t\t\tis_zip_root = True\n\t\t\tcounter_processing(df, is_zip_root)\n\t\telif (kb_user == \"2\"):\n\t\t\tis_zip_root = False\n\t\t\tcounter_processing(df, is_zip_root)\n\t\telif (kb_user == \"3\"):\n\t\t\tcount_zip_incidents(df)\n\t\telif (kb_user == \"4\"):\n\t\t\tcount_borough_incidents(df)\n\t\telif (kb_user == \"5\"):\n\t\t\tcounter_processing(df, is_zip_root, sanitize_dev=True)\n\t\telif (kb_user == \"6\"):\n\t\t\tdownload_jsons()\n\t\telse:\n\t\t\tprint(\"Bad input! Either (1,2,3,4,5) are to be chosen.\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432217464","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\n\n\n# show the distribution of features selected by model\ndef show_model_features_hist(model_path):\n feature_data_path = os.path.join(model_path, 'selected_feature.csv')\n\n features_data = pd.read_csv(feature_data_path)\n feature_list = features_data.columns.values[2:]\n\n for feature in feature_list:\n ran = (min(features_data[feature]),max(features_data[feature]))\n feature_label_0_distribution = features_data[features_data['label'] == 0][feature]\n feature_label_1_distribution = features_data[features_data['label'] == 1][feature]\n\n # plt.style.use('ggplot')\n plt.hist(feature_label_0_distribution, edgecolor='black', color='red', alpha=0.7, bins=50, range=ran)\n plt.hist(feature_label_1_distribution, edgecolor='black', color='blue', alpha=0.7, bins=50, range=ran)\n plt.title(feature)\n plt.show()\n\n\n# show distribution of features selected by you\ndef show_feature_hist(data_path, feature_list=None):\n data = pd.read_csv(data_path)\n\n features_data = pd.read_csv(data_path)\n if feature_list is None:\n feature_list = features_data.columns.values[2:]\n\n for feature in feature_list:\n ran = (min(features_data[feature]), max(features_data[feature]))\n feature_label_0_distribution = features_data[features_data['label'] == 0][feature]\n feature_label_1_distribution = features_data[features_data['label'] == 1][feature]\n\n # plt.style.use('ggplot')\n plt.hist(feature_label_0_distribution, edgecolor='black', color='red', alpha=0.6, bins=50, range=ran)\n plt.hist(feature_label_1_distribution, edgecolor='black', color='green', alpha=0.6, bins=50, range=ran)\n plt.title(feature)\n plt.show()\n\nif __name__ == '__main__':\n # model_path = r'F:\\SHZL\\model\\3d\\ISUP\\arterial\\9.18\\model\\NormUnit_PCC_ANOVA_2_LR'\n # show_model_features_hist(model_path)\n\n data_path = r'F:\\SHZL\\model\\3d\\ISUP\\data_3\\test_data.csv'\n show_feature_hist(data_path,['venous.nii_wavelet-HHH_glrlm_ShortRunHighGrayLevelEmphasis'])\n","sub_path":"problem/show_feature_speciality.py","file_name":"show_feature_speciality.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"442313205","text":"import flask\nimport flask_principal\nimport flask_saml\n\napp = flask.Flask(__name__)\nprincipals = flask_principal.Principal(app)\napp.config.update({\n 'SECRET_KEY': 'soverysecret',\n 'SAML_METADATA_URL': 'https://metadata-url',\n})\nsaml = flask_saml.FlaskSAML(app)\n\n# Create a permission with a single Need, in this case a RoleNeed.\nadmin_permission = flask_principal.Permission(flask_principal.RoleNeed('admin'))\n\n#\n# Connect SAML & Principal\n#\n\n@flask_saml.saml_authenticated.connect_via(app)\ndef on_saml_authenticated(sender, subject, attributes, auth):\n # We have a logged in user, inform Flask-Principal\n flask_principal.identity_changed.send(\n flask.current_app._get_current_object(),\n identity=get_identity(),\n )\n\n\n@flask_saml.saml_log_out.connect_via(app)\ndef on_saml_logout(sender):\n # Let Flask-Principal know the user is gone\n flask_principal.identity_changed.send(\n flask.current_app._get_current_object(),\n identity=get_identity(),\n )\n\n\n# This provides the users' identity in the application\n@principals.identity_loader\ndef get_identity():\n if 'saml' in flask.session:\n return flask_principal.Identity(flask.session['saml']['subject'])\n else:\n return flask_principal.AnonymousIdentity()\n\n\n@flask_principal.identity_loaded.connect_via(app)\ndef on_identity_loaded(sender, identity):\n # If authenticated, you're an admin - yay!\n if not isinstance(identity, flask_principal.AnonymousIdentity):\n identity.provides.add(flask_principal.RoleNeed('admin'))\n\n\n# protect a view with a principal for that need\n@app.route('/admin')\n@admin_permission.require()\ndef do_admin_index():\n return flask.Response('Only if you are an admin')\n\n# this time protect with a context manager\n@app.route('/articles')\ndef do_articles():\n with admin_permission.require():\n return flask.Response('Only if you are admin')\n\n\n@app.errorhandler(flask_principal.PermissionDenied)\ndef handle_permission_denied(error):\n deny = 'Permission Denied', 403\n redirect = flask.redirect(flask.url_for('login', next=flask.request.url))\n if isinstance(flask.g.identity, flask_principal.AnonymousIdentity):\n return redirect\n else:\n return deny\n\n\nif __name__ == '__main__':\n app.run(port=8000, debug=True)\n","sub_path":"examples/flask_principal_recipe.py","file_name":"flask_principal_recipe.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"442120860","text":"import json\nfrom pprint import pprint\n\nfrom ci._internal_utils import (\n parse_csv,\n split_by_comma,\n update_gps_coordinates,\n strip_unsupported_schema,\n perform_kv_transforms,\n)\n\n\ndef main():\n SCHEMA = {\n \"zip\": {\"public\": \"zip_code\"},\n \"type\": {\"public\": \"zip_code_type\"},\n \"decommissioned\": {\"public\": \"active\", \"transform\": lambda v: not bool(int(v))},\n \"primary_city\": {\"public\": \"city\"},\n \"acceptable_cities\": {\n \"public\": \"acceptable_cities\",\n \"transform\": split_by_comma,\n },\n \"unacceptable_cities\": {\n \"public\": \"unacceptable_cities\",\n \"transform\": split_by_comma,\n },\n \"state\": {\"public\": \"state\"},\n \"county\": {\"public\": \"county\"},\n \"timezone\": {\"public\": \"timezone\"},\n \"area_codes\": {\"public\": \"area_codes\", \"transform\": split_by_comma},\n \"world_region\": {\"public\": \"world_region\"},\n \"country\": {\"public\": \"country\"},\n \"latitude\": {\"public\": \"lat\"},\n \"longitude\": {\"public\": \"long\"},\n }\n\n gps_zipcodes_filename = \"ci/data/zip-codes-database-FREE.csv\"\n base_zipcodes_filename = \"ci/data/zip_code_database.csv\"\n\n gps_data = parse_csv(gps_zipcodes_filename)\n base_data = parse_csv(base_zipcodes_filename)\n\n pprint(\"GPS Keys: {}\".format(list(gps_data[0].keys())))\n pprint(\"Base Keys: {}\".format(list(base_data[0].keys())))\n\n # Begin transforming base place data.\n base_data = update_gps_coordinates(gps_data, base_data)\n base_data = strip_unsupported_schema(base_data, SCHEMA)\n base_data = perform_kv_transforms(base_data, SCHEMA)\n\n print(\"Writing zipcode information for {} places\".format(len(base_data)))\n\n with open(\"zips.json\", \"w\") as f:\n json.dump(base_data, f)\n\n print(\"To zip for production, run:\\n$ bzip2 zips.json\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ci/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"508051827","text":"\nclass Publisher(TimeStampedModel, IndestructibleModel):\n\n \"\"\"\n A publisher that displays advertising from the ad server.\n\n A publisher represents a site or collection of sites that displays advertising.\n Advertisers can opt-in to displaying ads on different publishers.\n\n An example of a publisher would be Read the Docs, our first publisher.\n \"\"\"\n\n name = models.CharField(_(\"Name\"), max_length=200)\n slug = models.SlugField(_(\"Publisher Slug\"), max_length=200, unique=True)\n\n revenue_share_percentage = models.FloatField(\n default=70.0,\n validators=[MinValueValidator(0), MaxValueValidator(100)],\n help_text=_(\"Percentage of advertising revenue shared with this publisher\"),\n )\n\n default_keywords = models.CharField(\n _(\"Default keywords\"),\n max_length=250,\n help_text=_(\"A CSV of default keywords for this property. Used for targeting.\"),\n default=\"\",\n blank=True,\n )\n\n unauthed_ad_decisions = models.BooleanField(\n default=True,\n help_text=_(\n \"Whether this publisher allows unauthenticated ad decision API requests (eg. JSONP)\"\n ),\n )\n disabled = models.BooleanField(\n default=False,\n help_text=_(\"Completely disable this publisher\"),\n )\n\n saas = models.BooleanField(\n default=False,\n help_text=_(\n \"This published is configured as a SaaS customer. They will be billed by usage instead of paid out.\"\n ),\n )\n\n # Default to False so that we can use this as an \"approved\" flag for publishers\n allow_paid_campaigns = models.BooleanField(_(\"Allow paid campaigns\"), default=False)\n allow_affiliate_campaigns = models.BooleanField(\n _(\"Allow affiliate campaigns\"), default=False\n )\n allow_community_campaigns = models.BooleanField(\n _(\"Allow community campaigns\"),\n default=True,\n help_text=\"These are unpaid campaigns that support non-profit projects in our community. Shown only when no paid ads are available\",\n )\n allow_house_campaigns = models.BooleanField(\n _(\"Allow house campaigns\"),\n default=True,\n help_text=\"These are ads for EthicalAds itself. Shown only when no paid ads are available.\",\n )\n\n # Payout information\n skip_payouts = models.BooleanField(\n _(\"Skip payouts\"),\n default=False,\n help_text=_(\n \"Enable this to temporarily disable payouts. They will be processed again once you uncheck this.\"\n ),\n )\n payout_method = models.CharField(\n max_length=100,\n choices=PUBLISHER_PAYOUT_METHODS,\n blank=True,\n null=True,\n default=None,\n )\n djstripe_account = models.ForeignKey(\n djstripe_models.Account,\n verbose_name=_(\"Stripe connected account\"),\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n default=None,\n )\n\n # Deprecated - migrate to `stripe_account`\n stripe_connected_account_id = models.CharField(\n _(\"Stripe connected account ID\"),\n max_length=200,\n blank=True,\n null=True,\n default=None,\n )\n open_collective_name = models.CharField(\n _(\"Open Collective name\"), max_length=200, blank=True, null=True, default=None\n )\n paypal_email = models.EmailField(\n _(\"PayPal email address\"), blank=True, null=True, default=None\n )\n\n # This overrides settings.ADSERVER_RECORD_VIEWS for a specific publisher\n # Details of each ad view are written to the database.\n # Setting this can result in some performance degradation and a bloated database,\n # but note that all Offers are stored by default.\n record_views = models.BooleanField(\n default=False,\n help_text=_(\"Record each ad view from this publisher to the database\"),\n )\n record_placements = models.BooleanField(\n default=False, help_text=_(\"Record placement impressions for this publisher\")\n )\n # This defaults to False, so publishers have to ask for it.\n render_pixel = models.BooleanField(\n default=False,\n help_text=_(\n \"Render ethical-pixel in ad templates. This is needed for users not using the ad client.\"\n ),\n )\n cache_ads = models.BooleanField(\n default=True,\n help_text=_(\n \"Cache this publishers ad requests. Disable for special cases (eg. SaaS users)\"\n ),\n )\n\n # Denormalized fields\n sampled_ctr = models.FloatField(\n default=0.0,\n help_text=_(\n \"A periodically calculated CTR from a sample of ads on this publisher.\"\n ),\n )\n\n history = HistoricalRecords()\n\n class Meta:\n ordering = (\"name\",)\n\n permissions = [\n (\"staff_publisher_fields\", \"Can view staff publisher fields in reports\"),\n ]\n\n def __str__(self):\n \"\"\"Simple override.\"\"\"\n return self.name\n\n def get_absolute_url(self):\n return reverse(\"publisher_report\", kwargs={\"publisher_slug\": self.slug})\n\n @property\n def keywords(self):\n \"\"\"\n Parses database keywords and ensures consistency.\n\n - Lowercases all tags\n - Converts underscores to hyphens\n - Slugifies tags\n - Removes empty tags\n\n Similar logic to RTD ``readthedocs.projects.tag_utils.rtd_parse_tags``.\n \"\"\"\n if self.default_keywords:\n return_keywords = []\n keyword_list = self.default_keywords.split(\",\")\n for keyword in keyword_list:\n keyword = keyword.lower().replace(\"_\", \"-\")\n keyword = slugify(keyword)\n if keyword:\n return_keywords.append(keyword)\n return return_keywords\n return []\n\n def total_payout_sum(self):\n \"\"\"The total amount ever paid out to this publisher.\"\"\"\n total = self.payouts.filter(status=PAID).aggregate(\n total=models.Sum(\"amount\", output_field=models.DecimalField())\n )[\"total\"]\n if total:\n return total\n return 0\n\n def payout_url(self):\n if self.payout_method == PAYOUT_STRIPE and self.djstripe_account.id:\n return f\"https://dashboard.stripe.com/connect/accounts/{self.djstripe_account.id}\"\n if self.payout_method == PAYOUT_OPENCOLLECTIVE and self.open_collective_name:\n return f\"https://opencollective.com/{self.open_collective_name}\"\n if self.payout_method == PAYOUT_PAYPAL and self.paypal_email:\n return \"https://www.paypal.com/myaccount/transfer/homepage/pay\"\n return \"\"\n\n\nclass PublisherGroup(TimeStampedModel):\n\n \"\"\"Group of publishers that can be targeted by advertiser's campaigns.\"\"\"\n\n name = models.CharField(\n _(\"Name\"), max_length=200, help_text=_(\"Visible to advertisers\")\n )\n slug = models.SlugField(_(\"Publisher group slug\"), max_length=200, unique=True)\n\n publishers = models.ManyToManyField(\n Publisher,\n related_name=\"publisher_groups\",\n blank=True,\n help_text=_(\"A group of publishers that can be targeted by advertisers\"),\n )\n\n history = HistoricalRecords()\n\n class Meta:\n ordering = (\"name\",)\n\n def __str__(self):\n \"\"\"Simple override.\"\"\"\n return self.name\n","sub_path":"ads/modelz/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":7291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146192551","text":"import smbl\nimport os\nimport numpy\nimport gzip\n\nfrom .Consensus import Consensus\n\n#\n# REMARKS:\n# - pileup must have matches with \".\" and \",\"\n#\n\nclass Consensus_BcfTools(Consensus):\n\n\tdef __init__(self,\n\t\t\t):\n\t\tpass\n\n\n\t@property\n\tdef required(self):\n\t\treturn [\n\t\t\t\tsmbl.prog.BCFTOOLS,\n\t\t\t\tsmbl.prog.SAMTOOLS,\n\t\t\t\tsmbl.prog.BGZIP,\n\t\t\t\tsmbl.prog.TABIX,\n\t\t\t]\n\n\tdef create_consensus(self,\n\t\t\t\tfasta_fn,\n\t\t\t\tsorted_bam_fn,\n\t\t\t\tcompressed_vcf_fn,\n\t\t\t\t**kwargs\n\t\t\t):\n\n\t\tvcf_fn=compressed_vcf_fn[:-3]\n\t\tfilter_bcftools_consensus_fn=os.path.join(os.path.dirname(__file__),'filter_bcftools_consensus.pl')\n\n\t\t# ~/.smbl/bin/bcftools call -c | ~/github/dymas/dymas/dymas/filter_bcftools_consensus.pl\n\t\tsmbl.utils.shell(\n\t\t\t\t\"\"\"\n\t\t\t\t\"{SAMTOOLS}\" mpileup -uf \"{fasta_fn}\" \"{sorted_bam_fn}\" \\\n\t\t\t\t| \\\n\t\t\t\t\"{BCFTOOLS}\" call -c \\\n\t\t\t\t| \\\n\t\t\t\t\"{FILTER_BCFTOOLS_CONSENSUS}\" \\\n\t\t\t\t\\\n\t\t\t\t> \"{vcf_fn}\" \\\n\t\t\t\t\"\"\".format(\n\t\t\t\t\t\tSAMTOOLS=smbl.prog.SAMTOOLS,\n\t\t\t\t\t\tBCFTOOLS=smbl.prog.BCFTOOLS,\n\t\t\t\t\t\tFILTER_BCFTOOLS_CONSENSUS=filter_bcftools_consensus_fn,\n\t\t\t\t\t\tfasta_fn=fasta_fn,\n\t\t\t\t\t\tsorted_bam_fn=sorted_bam_fn,\n\t\t\t\t\t\tvcf_fn=vcf_fn,\n\t\t\t\t\t)\n\t\t\t)\n\n\t\tsmbl.utils.shell(\n\t\t\t\t\"\"\"\n\t\t\t\t\"{BGZIP}\" -f \"{vcf_fn}\"\n\t\t\t\t\"\"\".format(\n\t\t\t\t\t\tBGZIP=smbl.prog.BGZIP,\n\t\t\t\t\t\tvcf_fn=vcf_fn,\n\t\t\t\t\t)\n\t\t\t)\n\n\t\tsmbl.utils.shell(\n\t\t\t\t\"\"\"\n\t\t\t\t\"{TABIX}\" -f \"{compressed_vcf_fn}\"\n\t\t\t\t\"\"\".format(\n\t\t\t\t\t\tTABIX=smbl.prog.TABIX,\n\t\t\t\t\t\tcompressed_vcf_fn=compressed_vcf_fn,\n\t\t\t\t\t)\n\t\t\t)\n","sub_path":"dymas/dymas/Consensus_BcfTools.py","file_name":"Consensus_BcfTools.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376640912","text":"#!/usr/bin/env python\n#author: qinlin@andrew.cmu.edu\nimport math\nimport numpy as np\n\ndef normalize_angle(angle):\n \"\"\"\n Normalize angle from [-pi, pi].\n \"\"\"\n angle = angle % (2*np.pi)\n if (angle >= np.pi):\n angle -= 2*np.pi\n return angle\n\n\ndef rotate_state(state, angle):\n \"\"\"\n Rotate a state [x, y, yaw, x_dot, y_dot, yaw_dot] by a specified angle\n in radians.\n \"\"\"\n if len(state) != 6:\n raise ValueError('Invalid state; dimension mismatch')\n\n x = state[0]\n y = state[1]\n yaw = state[2]\n\n new_state = np.array(state)\n\n new_state[0] = x*np.cos(angle) - y*np.sin(angle)\n new_state[1] = y*np.cos(angle) + x*np.sin(angle)\n new_state[2] = normalize_angle(yaw + angle)\n\n return new_state\n\n\ndef translate_state(state, translation):\n \"\"\"\n Translate a state [x, y, yaw, x_dot, y_dot, yaw_dot] by a translation\n [dx, dy].\n \"\"\"\n if len(state) != 6:\n raise ValueError('Invalid state; dimension mismatch')\n if len(translation) != 2:\n raise ValueError('Invalid translation amount; dimension mismatch')\n\n state = np.array(state)\n state[0] += translation[0]\n state[1] += translation[1]\n return state\nclass state:\n def __init__(self, a=0, k=0, t=0, v=0, vh=0, vl=0, xg=0, yg=0):\n self.a = a\n self.k = k\n self.t = t\n self.v = v\n self.vh = vh\n self.vl =vl\n self.xg = xg\n self.yg =yg\n\nclass parameters:\n def __init__(self, A=0, B=0, T=0, eps=0):\n self.A = A\n self.B = B\n self.T = T\n self.eps = eps\n\nclass plantparameters:\n def __init__(self, A=0, B=0, T=0, a=0, eps=0, k=0, vh=0, vl=0): \n self.A = A\n self.B = B\n self.T = T\n self.a = a\n self.eps = eps\n self.k = k\n self.vh = vh\n self.vl = vl\n \nclass plantstate:\n def __init__(self,t=0, t_0=0, v=0, v_0=0, xg=0, xg_0=0, yg=0, yg_0=0):\n self.t = t\n self.t_0 = t_0\n self.v = v\n self.v_0 = v_0\n self.xg = xg\n self.xg_0 = xg_0\n self.yg = yg\n self.yg_0 = yg_0\n\ndef convertState(current_state):\n '''\n Function: converting current robot's state, the resulting state will be used for modelplex's state\n Output: converted state will be used for modelplex's state\n '''\n xr = current_state[0]\n yr = current_state[1]\n zt = current_state[3]\n xg = current_state[7]\n yg = current_state[8]\n k = current_state[9]\n\n coord_trafo_state = list()\n coord_trafo_state.append(0.0)\n coord_trafo_state.append(0.0)\n coord_trafo_state.append(0.0)\n coord_trafo_state.append(0.0)\n coord_trafo_state.append(current_state[4])\n coord_trafo_state.append(current_state[5])\n coord_trafo_state.append(current_state[6])\n convxg = (xg-xr)*math.cos(zt) + (yg-yr)*math.sin(zt)\n convyg = -(xg-xr)*math.sin(zt) + (yg-yr)*math.cos(zt)\n #print(\"x-y: \", xr, yr)\n #print(\"convxg-convyg: \", convxg, convyg)\n #/* Car Monitor\n # * x y\n # * ^ ^\n # * | |\n # * y <---+ +---> x\n # */\n coord_trafo_state.append(-convyg)\n coord_trafo_state.append(convxg)\n coord_trafo_state.append(-k) \n\n converted_state = convertUnits(coord_trafo_state)\n\n return converted_state\n\ndef convertUnits(coord_trafo_state):\n '''\n Function: converting units\n '''\n converted_state = list()\n converted_state.append(coord_trafo_state[0]*10.0) #xr [dm] @note = 0\n converted_state.append(coord_trafo_state[1]*10.0) #yr [dm] @note = 0\n converted_state.append(coord_trafo_state[2]*10.0) #zr [dm] @note = 0\n converted_state.append(coord_trafo_state[3]) #orientation radians (unused in monitor)\n converted_state.append(coord_trafo_state[4]*10.0) #vx [dm/s]\n converted_state.append(coord_trafo_state[5]*10.0) #vy [dm/s] @note = 0\n converted_state.append(coord_trafo_state[6]*10.0) #vz [dm/s] @note = 0\n converted_state.append(coord_trafo_state[7]*10.0) #xg [dm]\n converted_state.append(coord_trafo_state[8]*10.0) #yg [dm]\n converted_state.append(coord_trafo_state[9]*100.0) #k [centi-(meters^-1)]\n\n return converted_state\n\ndef convertAction(proposed_action):\n '''\n Function: converting proposed action to future state\n Input: robot's standard control action from ROS\n Output: converted future state\n '''\n vset = proposed_action[0]\n steer = proposed_action[1]\n \n wheelbase = 0.257\n d_com_rear = 0.1294\n \n # sanity check: is steering angle roughly planned curvature\n # convert steering angle into curve radius (bicycle model)\n # simpler alternative: double r = wheelbase/tan(steer);\n cot = 1.0/math.tan(steer) if steer != 0 else 0.0\n r = math.sqrt(d_com_rear*d_com_rear + wheelbase*wheelbase*cot*cot) if steer != 0 else 0.0\n if steer > 0:\n ksteer = 100.0/r\n elif steer < 0:\n ksteer = -100.0/r\n else:\n ksteer = 0\n \n ksteer2 = 100.0/(wheelbase*cot) if steer != 0 else 0.0\n \n # actual acceleration profile to compute acceleration from vset unavailable, so we pretend to reach vset from current v within T_CYCLE_TIME \n a = proposed_action[2] #[dm/s^2]\n t = 0.0 #timer expected to be reset [ds]\n vh = proposed_action[3] #[dm/s] \n vl = proposed_action[4] #[dm/s]\n xg = proposed_action[5] #[dm]\n yg = proposed_action[6] #[dm]\n k = proposed_action[7] #curvature [centi-(meters^-1)]\n \n \n converted_action = list()\n converted_action.append(a)\n converted_action.append(k)\n converted_action.append(t)\n converted_action.append(vh)\n converted_action.append(vl)\n converted_action.append(xg)\n converted_action.append(yg)\n return converted_action\n\ndef extCtrl(pre, proposed_action):\n '''\n Function: converting proposed action and current state to future state\n Input:\n pre: current modelplex state\n proposed_action: robot's standard control action from ROS\n Output: converted future state\n '''\n ctrl_action = proposed_action[:]\n ctrl_action.append(pre.a)\n ctrl_action.append(pre.vh)\n ctrl_action.append(pre.vl)\n ctrl_action.append(pre.xg)\n ctrl_action.append(pre.yg)\n ctrl_action.append(pre.k)\n converted_action = convertAction(ctrl_action)\n \n result = state()\n result.a = converted_action[0]\n result.k = converted_action[1]\n result.t = converted_action[2]\n result.v = pre.v\n result.vh = converted_action[3]\n result.vl = converted_action[4]\n result.xg = converted_action[5]\n result.yg = converted_action[6]\n return result\n\ndef currConvert(curr, pre, current_state, current_waypoint, time):\n '''\n Function: convert robot's standard current state and waypoint to modelplex's state\n Input: \n curr (current modelplex state without values)\n pre (previous modelplex state)\n current_state (robot's standard current state from ROS)\n current_waypoint (robot's standard current waypoints from ROS)\n time: time elapsed from last control loop to the current one\n Output: curr with asigned values\n '''\n ctrl_state = current_state[:]\n ctrl_state.extend(current_waypoint)\n converted_state = convertState(ctrl_state)\n if time > 0:\n curr.a = (converted_state[4] - float(pre.v))/time\n else:\n curr.a = 0\n curr.k = converted_state[9]\n curr.t = time*10.0\n curr.v = converted_state[4]\n curr.vh = float(pre.vh)\n curr.vl = float(pre.vl)\n curr.xg = converted_state[7]\n curr.yg = converted_state[8]\n return curr\n\ndef plantParamsConvert(plantParams, params, curr):\n '''\n Function: getting modelplex's plant parameters\n Input: \n plantParams (plant parameters without values)\n params (modelplex's parameters)\n curr (current modelplex state)\n Output: plantParams with asigned values\n '''\n plantParams.A =float(params.A)\n plantParams.B = float(params.B)\n plantParams.T = float(params.T)\n plantParams.a = float(curr.a)\n plantParams.eps = float(params.eps)\n plantParams.k = float(curr.k)\n plantParams.vh = float(curr.vh)\n plantParams.vl = float(curr.vl)\n return plantParams\n\ndef plantcurrConvert(plantcurr, pre, curr):\n '''\n Function: getting modelplex's plant state\n Input: \n plantcurr (current plant state without values)\n pre (previous modelplex's state)\n curr (current modelplex's state)\n Output: plantcurr with asigned values\n '''\n plantcurr.t = float(curr.t)\n plantcurr.t_0 = float(pre.t)\n plantcurr.v = float(curr.v)\n plantcurr.v_0 = float(pre.v)\n plantcurr.xg = float(curr.xg)\n plantcurr.xg_0 = float(pre.xg)\n plantcurr.yg = float(curr.yg)\n plantcurr.yg_0 = float(pre.yg)\n return plantcurr\n\ndef postConvert(post, curr, proposed_action):\n '''\n Function: getting modelplex's future state\n Input: \n post (future state)\n curr (current modelplex's state)\n proposed_action (robot's standard control action from ROS)\n Output: post with asigned values\n '''\n ext_ctrl = extCtrl(curr, proposed_action)\n post.a = float(ext_ctrl.a)\n post.k = float(ext_ctrl.k)\n post.t = float(ext_ctrl.t)\n post.v = float(ext_ctrl.v)\n post.vh = float(ext_ctrl.vh)\n post.vl = float(ext_ctrl.vl)\n post.xg = float(ext_ctrl.xg)\n post.yg = float(ext_ctrl.yg)\n return post","sub_path":"utility/modelplex.py","file_name":"modelplex.py","file_ext":"py","file_size_in_byte":9601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}